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 sigc::signal<int> Session::AskAboutPendingState;
101 sigc::signal<void> Session::SendFeedback;
103 sigc::signal<void> Session::SMPTEOffsetChanged;
104 sigc::signal<void> Session::StartTimeChanged;
105 sigc::signal<void> Session::EndTimeChanged;
107 Session::Session (AudioEngine &eng,
109 string snapshot_name,
110 string* mix_template)
113 _scratch_buffers(new BufferSet()),
114 _silent_buffers(new BufferSet()),
115 _mix_buffers(new BufferSet()),
116 _mmc_port (default_mmc_port),
117 _mtc_port (default_mtc_port),
118 _midi_port (default_midi_port),
119 _session_dir (new SessionDirectory(fullpath)),
120 pending_events (2048),
121 //midi_requests (128), // the size of this should match the midi request pool size
122 _send_smpte_update (false),
123 diskstreams (new DiskstreamList),
124 routes (new RouteList),
125 auditioner ((Auditioner*) 0),
126 _bundle_xml_node (0),
130 if (!eng.connected()) {
131 throw failed_constructor();
134 n_physical_outputs = _engine.n_physical_outputs();
135 n_physical_inputs = _engine.n_physical_inputs();
137 first_stage_init (fullpath, snapshot_name);
139 initialize_start_and_end_locations(0, compute_initial_length ());
142 // try and create a new session directory
145 if(!_session_dir->create()) {
146 // an existing session.
147 // throw a_more_meaningful_exception()
149 throw failed_constructor ();
152 catch(sys::filesystem_error& ex)
155 throw failed_constructor ();
158 if(!create_session_file_from_template (*mix_template)) {
160 throw failed_constructor ();
163 cerr << "Creating session " << fullpath
164 <<" using template" << *mix_template
167 // must be an existing session
170 // ensure the necessary session subdirectories exist
171 // in case the directory structure has changed etc.
172 _session_dir->create();
174 catch(sys::filesystem_error& ex)
177 throw failed_constructor ();
180 cerr << "Loading session " << fullpath
181 << " using snapshot " << snapshot_name << " (1)"
185 if (second_stage_init (false)) {
187 throw failed_constructor ();
190 store_recent_sessions(_name, _path);
192 bool was_dirty = dirty();
194 _state_of_the_state = StateOfTheState (_state_of_the_state & ~Dirty);
196 Config->ParameterChanged.connect (mem_fun (*this, &Session::config_changed));
199 DirtyChanged (); /* EMIT SIGNAL */
203 Session::Session (AudioEngine &eng,
205 string snapshot_name,
206 AutoConnectOption input_ac,
207 AutoConnectOption output_ac,
208 uint32_t control_out_channels,
209 uint32_t master_out_channels,
210 uint32_t requested_physical_in,
211 uint32_t requested_physical_out,
212 nframes_t initial_length)
215 _scratch_buffers(new BufferSet()),
216 _silent_buffers(new BufferSet()),
217 _mix_buffers(new BufferSet()),
218 _mmc_port (default_mmc_port),
219 _mtc_port (default_mtc_port),
220 _midi_port (default_midi_port),
221 _session_dir ( new SessionDirectory(fullpath)),
222 pending_events (2048),
223 //midi_requests (16),
224 _send_smpte_update (false),
225 diskstreams (new DiskstreamList),
226 routes (new RouteList),
227 _bundle_xml_node (0),
231 if (!eng.connected()) {
232 throw failed_constructor();
235 cerr << "Loading session " << fullpath << " using snapshot " << snapshot_name << " (2)" << endl;
237 n_physical_outputs = _engine.n_physical_outputs();
238 n_physical_inputs = _engine.n_physical_inputs();
240 if (n_physical_inputs) {
241 n_physical_inputs = max (requested_physical_in, n_physical_inputs);
244 if (n_physical_outputs) {
245 n_physical_outputs = max (requested_physical_out, n_physical_outputs);
248 first_stage_init (fullpath, snapshot_name);
250 initialize_start_and_end_locations(0, initial_length);
252 if (!_session_dir->create () || !create_session_file ()) {
254 throw failed_constructor ();
258 /* set up Master Out and Control Out if necessary */
263 if (control_out_channels) {
264 shared_ptr<Route> r (new Route (*this, _("monitor"), -1, control_out_channels, -1, control_out_channels, Route::ControlOut));
265 r->set_remote_control_id (control_id++);
270 if (master_out_channels) {
271 shared_ptr<Route> r (new Route (*this, _("master"), -1, master_out_channels, -1, master_out_channels, Route::MasterOut));
272 r->set_remote_control_id (control_id);
276 /* prohibit auto-connect to master, because there isn't one */
277 output_ac = AutoConnectOption (output_ac & ~AutoConnectMaster);
286 Config->set_input_auto_connect (input_ac);
287 Config->set_output_auto_connect (output_ac);
289 if (second_stage_init (true)) {
291 throw failed_constructor ();
294 store_recent_sessions(_name, _path);
296 bool was_dirty = dirty ();
298 _state_of_the_state = StateOfTheState (_state_of_the_state & ~Dirty);
300 Config->ParameterChanged.connect (mem_fun (*this, &Session::config_changed));
303 DirtyChanged (); /* EMIT SIGNAL */
315 /* if we got to here, leaving pending capture state around
319 remove_pending_capture_state ();
321 _state_of_the_state = StateOfTheState (CannotSave|Deletion);
322 _engine.remove_session ();
324 GoingAway (); /* EMIT SIGNAL */
330 /* clear history so that no references to objects are held any more */
334 /* clear state tree so that no references to objects are held any more */
340 terminate_butler_thread ();
341 //terminate_midi_thread ();
343 if (click_data && click_data != default_click) {
344 delete [] click_data;
347 if (click_emphasis_data && click_emphasis_data != default_click_emphasis) {
348 delete [] click_emphasis_data;
353 delete _scratch_buffers;
354 delete _silent_buffers;
357 AudioDiskstream::free_working_buffers();
359 #undef TRACK_DESTRUCTION
360 #ifdef TRACK_DESTRUCTION
361 cerr << "delete named selections\n";
362 #endif /* TRACK_DESTRUCTION */
363 for (NamedSelectionList::iterator i = named_selections.begin(); i != named_selections.end(); ) {
364 NamedSelectionList::iterator tmp;
373 #ifdef TRACK_DESTRUCTION
374 cerr << "delete playlists\n";
375 #endif /* TRACK_DESTRUCTION */
376 for (PlaylistList::iterator i = playlists.begin(); i != playlists.end(); ) {
377 PlaylistList::iterator tmp;
382 (*i)->drop_references ();
387 for (PlaylistList::iterator i = unused_playlists.begin(); i != unused_playlists.end(); ) {
388 PlaylistList::iterator tmp;
393 (*i)->drop_references ();
399 unused_playlists.clear ();
401 #ifdef TRACK_DESTRUCTION
402 cerr << "delete regions\n";
403 #endif /* TRACK_DESTRUCTION */
405 for (RegionList::iterator i = regions.begin(); i != regions.end(); ) {
406 RegionList::iterator tmp;
411 i->second->drop_references ();
418 #ifdef TRACK_DESTRUCTION
419 cerr << "delete routes\n";
420 #endif /* TRACK_DESTRUCTION */
422 RCUWriter<RouteList> writer (routes);
423 boost::shared_ptr<RouteList> r = writer.get_copy ();
424 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
425 (*i)->drop_references ();
428 /* writer goes out of scope and updates master */
433 #ifdef TRACK_DESTRUCTION
434 cerr << "delete diskstreams\n";
435 #endif /* TRACK_DESTRUCTION */
437 RCUWriter<DiskstreamList> dwriter (diskstreams);
438 boost::shared_ptr<DiskstreamList> dsl = dwriter.get_copy();
439 for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
440 (*i)->drop_references ();
444 diskstreams.flush ();
446 #ifdef TRACK_DESTRUCTION
447 cerr << "delete audio sources\n";
448 #endif /* TRACK_DESTRUCTION */
449 for (SourceMap::iterator i = sources.begin(); i != sources.end(); ) {
450 SourceMap::iterator tmp;
455 i->second->drop_references ();
462 #ifdef TRACK_DESTRUCTION
463 cerr << "delete mix groups\n";
464 #endif /* TRACK_DESTRUCTION */
465 for (list<RouteGroup *>::iterator i = mix_groups.begin(); i != mix_groups.end(); ) {
466 list<RouteGroup*>::iterator tmp;
476 #ifdef TRACK_DESTRUCTION
477 cerr << "delete edit groups\n";
478 #endif /* TRACK_DESTRUCTION */
479 for (list<RouteGroup *>::iterator i = edit_groups.begin(); i != edit_groups.end(); ) {
480 list<RouteGroup*>::iterator tmp;
490 if (butler_mixdown_buffer) {
491 delete [] butler_mixdown_buffer;
494 if (butler_gain_buffer) {
495 delete [] butler_gain_buffer;
498 Crossfade::set_buffer_size (0);
506 Session::set_worst_io_latencies ()
508 _worst_output_latency = 0;
509 _worst_input_latency = 0;
511 if (!_engine.connected()) {
515 boost::shared_ptr<RouteList> r = routes.reader ();
517 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
518 _worst_output_latency = max (_worst_output_latency, (*i)->output_latency());
519 _worst_input_latency = max (_worst_input_latency, (*i)->input_latency());
524 Session::when_engine_running ()
526 string first_physical_output;
528 /* we don't want to run execute this again */
530 set_block_size (_engine.frames_per_cycle());
531 set_frame_rate (_engine.frame_rate());
533 Config->map_parameters (mem_fun (*this, &Session::config_changed));
535 /* every time we reconnect, recompute worst case output latencies */
537 _engine.Running.connect (mem_fun (*this, &Session::set_worst_io_latencies));
539 if (synced_to_jack()) {
540 _engine.transport_stop ();
543 if (Config->get_jack_time_master()) {
544 _engine.transport_locate (_transport_frame);
552 _click_io.reset (new ClickIO (*this, "click", 0, 0, -1, -1));
554 if (state_tree && (child = find_named_node (*state_tree->root(), "Click")) != 0) {
556 /* existing state for Click */
558 if (_click_io->set_state (*child->children().front()) == 0) {
560 _clicking = Config->get_clicking ();
564 error << _("could not setup Click I/O") << endmsg;
570 /* default state for Click */
572 first_physical_output = _engine.get_nth_physical_output (DataType::AUDIO, 0);
574 if (first_physical_output.length()) {
575 if (_click_io->add_output_port (first_physical_output, this)) {
576 // relax, even though its an error
578 _clicking = Config->get_clicking ();
584 catch (failed_constructor& err) {
585 error << _("cannot setup Click I/O") << endmsg;
588 set_worst_io_latencies ();
591 // XXX HOW TO ALERT UI TO THIS ? DO WE NEED TO?
594 /* Create a set of Bundle objects that map
595 to the physical outputs currently available
600 for (uint32_t np = 0; np < n_physical_outputs; ++np) {
602 snprintf (buf, sizeof (buf), _("out %" PRIu32), np+1);
604 shared_ptr<AutoBundle> c (new AutoBundle (buf, true));
606 c->set_port (0, _engine.get_nth_physical_output (DataType::AUDIO, np));
611 for (uint32_t np = 0; np < n_physical_inputs; ++np) {
613 snprintf (buf, sizeof (buf), _("in %" PRIu32), np+1);
615 shared_ptr<AutoBundle> c (new AutoBundle (buf, false));
617 c->set_port (0, _engine.get_nth_physical_input (DataType::AUDIO, np));
624 for (uint32_t np = 0; np < n_physical_outputs; np +=2) {
626 snprintf (buf, sizeof (buf), _("out %" PRIu32 "+%" PRIu32), np+1, np+2);
628 shared_ptr<AutoBundle> c (new AutoBundle (buf, true));
630 c->set_port (0, _engine.get_nth_physical_output (DataType::AUDIO, np));
631 c->set_port (1, _engine.get_nth_physical_output (DataType::AUDIO, np + 1));
636 for (uint32_t np = 0; np < n_physical_inputs; np +=2) {
638 snprintf (buf, sizeof (buf), _("in %" PRIu32 "+%" PRIu32), np+1, np+2);
640 shared_ptr<AutoBundle> c (new AutoBundle (buf, false));
642 c->set_port (0, _engine.get_nth_physical_input (DataType::AUDIO, np));
643 c->set_port (1, _engine.get_nth_physical_input (DataType::AUDIO, np + 1));
652 /* create master/control ports */
657 /* force the master to ignore any later call to this */
659 if (_master_out->pending_state_node) {
660 _master_out->ports_became_legal();
663 /* no panner resets till we are through */
665 _master_out->defer_pan_reset ();
667 while (_master_out->n_inputs().n_audio()
668 < _master_out->input_maximum().n_audio()) {
669 if (_master_out->add_input_port ("", this, DataType::AUDIO)) {
670 error << _("cannot setup master inputs")
676 while (_master_out->n_outputs().n_audio()
677 < _master_out->output_maximum().n_audio()) {
678 if (_master_out->add_output_port (_engine.get_nth_physical_output (DataType::AUDIO, n), this, DataType::AUDIO)) {
679 error << _("cannot setup master outputs")
686 _master_out->allow_pan_reset ();
690 shared_ptr<AutoBundle> c (new AutoBundle (_("Master Out"), true));
692 c->set_channels (_master_out->n_inputs().n_total());
693 for (uint32_t n = 0; n < _master_out->n_inputs ().n_total(); ++n) {
694 c->set_port (n, _master_out->input(n)->name());
701 /* catch up on send+insert cnts */
705 for (list<PortInsert*>::iterator i = _port_inserts.begin(); i != _port_inserts.end(); ++i) {
708 if (sscanf ((*i)->name().c_str(), "%*s %u", &id) == 1) {
709 if (id > insert_cnt) {
717 for (list<Send*>::iterator i = _sends.begin(); i != _sends.end(); ++i) {
720 if (sscanf ((*i)->name().c_str(), "%*s %u", &id) == 1) {
728 _state_of_the_state = StateOfTheState (_state_of_the_state & ~(CannotSave|Dirty));
730 /* hook us up to the engine */
732 _engine.set_session (this);
737 osc->set_session (*this);
740 _state_of_the_state = Clean;
742 DirtyChanged (); /* EMIT SIGNAL */
746 Session::hookup_io ()
748 /* stop graph reordering notifications from
749 causing resorts, etc.
752 _state_of_the_state = StateOfTheState (_state_of_the_state | InitialConnecting);
754 if (auditioner == 0) {
756 /* we delay creating the auditioner till now because
757 it makes its own connections to ports.
758 the engine has to be running for this to work.
762 auditioner.reset (new Auditioner (*this));
765 catch (failed_constructor& err) {
766 warning << _("cannot create Auditioner: no auditioning of regions possible") << endmsg;
770 /* Tell all IO objects to create their ports */
776 vector<string> cports;
778 while (_control_out->n_inputs().n_audio() < _control_out->input_maximum().n_audio()) {
779 if (_control_out->add_input_port ("", this)) {
780 error << _("cannot setup control inputs")
786 while (_control_out->n_outputs().n_audio() < _control_out->output_maximum().n_audio()) {
787 if (_control_out->add_output_port (_engine.get_nth_physical_output (DataType::AUDIO, n), this)) {
788 error << _("cannot set up master outputs")
796 uint32_t ni = _control_out->n_inputs().get (DataType::AUDIO);
798 for (n = 0; n < ni; ++n) {
799 cports.push_back (_control_out->input(n)->name());
802 boost::shared_ptr<RouteList> r = routes.reader ();
804 for (RouteList::iterator x = r->begin(); x != r->end(); ++x) {
805 (*x)->set_control_outs (cports);
809 /* load bundles, which we may have postponed earlier on */
810 if (_bundle_xml_node) {
811 load_bundles (*_bundle_xml_node);
812 delete _bundle_xml_node;
815 /* Tell all IO objects to connect themselves together */
817 IO::enable_connecting ();
819 /* Now reset all panners */
821 IO::reset_panners ();
823 /* Anyone who cares about input state, wake up and do something */
825 IOConnectionsComplete (); /* EMIT SIGNAL */
827 _state_of_the_state = StateOfTheState (_state_of_the_state & ~InitialConnecting);
829 /* now handle the whole enchilada as if it was one
835 /* update mixer solo state */
841 Session::playlist_length_changed ()
843 /* we can't just increase end_location->end() if pl->get_maximum_extent()
844 if larger. if the playlist used to be the longest playlist,
845 and its now shorter, we have to decrease end_location->end(). hence,
846 we have to iterate over all diskstreams and check the
847 playlists currently in use.
853 Session::diskstream_playlist_changed (boost::shared_ptr<Diskstream> dstream)
855 boost::shared_ptr<Playlist> playlist;
857 if ((playlist = dstream->playlist()) != 0) {
858 playlist->LengthChanged.connect (mem_fun (this, &Session::playlist_length_changed));
861 /* see comment in playlist_length_changed () */
866 Session::record_enabling_legal () const
868 /* this used to be in here, but survey says.... we don't need to restrict it */
869 // if (record_status() == Recording) {
873 if (Config->get_all_safe()) {
880 Session::reset_input_monitor_state ()
882 if (transport_rolling()) {
884 boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
886 for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
887 if ((*i)->record_enabled ()) {
888 //cerr << "switching to input = " << !auto_input << __FILE__ << __LINE__ << endl << endl;
889 (*i)->monitor_input (Config->get_monitoring_model() == HardwareMonitoring && !Config->get_auto_input());
893 boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
895 for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
896 if ((*i)->record_enabled ()) {
897 //cerr << "switching to input = " << !Config->get_auto_input() << __FILE__ << __LINE__ << endl << endl;
898 (*i)->monitor_input (Config->get_monitoring_model() == HardwareMonitoring);
905 Session::auto_punch_start_changed (Location* location)
907 replace_event (Event::PunchIn, location->start());
909 if (get_record_enabled() && Config->get_punch_in()) {
910 /* capture start has been changed, so save new pending state */
911 save_state ("", true);
916 Session::auto_punch_end_changed (Location* location)
918 nframes_t when_to_stop = location->end();
919 // when_to_stop += _worst_output_latency + _worst_input_latency;
920 replace_event (Event::PunchOut, when_to_stop);
924 Session::auto_punch_changed (Location* location)
926 nframes_t when_to_stop = location->end();
928 replace_event (Event::PunchIn, location->start());
929 //when_to_stop += _worst_output_latency + _worst_input_latency;
930 replace_event (Event::PunchOut, when_to_stop);
934 Session::auto_loop_changed (Location* location)
936 replace_event (Event::AutoLoop, location->end(), location->start());
938 if (transport_rolling() && play_loop) {
940 //if (_transport_frame < location->start() || _transport_frame > location->end()) {
942 if (_transport_frame > location->end()) {
943 // relocate to beginning of loop
944 clear_events (Event::LocateRoll);
946 request_locate (location->start(), true);
949 else if (Config->get_seamless_loop() && !loop_changing) {
951 // schedule a locate-roll to refill the diskstreams at the
953 loop_changing = true;
955 if (location->end() > last_loopend) {
956 clear_events (Event::LocateRoll);
957 Event *ev = new Event (Event::LocateRoll, Event::Add, last_loopend, last_loopend, 0, true);
964 last_loopend = location->end();
969 Session::set_auto_punch_location (Location* location)
973 if ((existing = _locations.auto_punch_location()) != 0 && existing != location) {
974 auto_punch_start_changed_connection.disconnect();
975 auto_punch_end_changed_connection.disconnect();
976 auto_punch_changed_connection.disconnect();
977 existing->set_auto_punch (false, this);
978 remove_event (existing->start(), Event::PunchIn);
979 clear_events (Event::PunchOut);
980 auto_punch_location_changed (0);
989 if (location->end() <= location->start()) {
990 error << _("Session: you can't use that location for auto punch (start <= end)") << endmsg;
994 auto_punch_start_changed_connection.disconnect();
995 auto_punch_end_changed_connection.disconnect();
996 auto_punch_changed_connection.disconnect();
998 auto_punch_start_changed_connection = location->start_changed.connect (mem_fun (this, &Session::auto_punch_start_changed));
999 auto_punch_end_changed_connection = location->end_changed.connect (mem_fun (this, &Session::auto_punch_end_changed));
1000 auto_punch_changed_connection = location->changed.connect (mem_fun (this, &Session::auto_punch_changed));
1002 location->set_auto_punch (true, this);
1003 auto_punch_location_changed (location);
1007 Session::set_auto_loop_location (Location* location)
1011 if ((existing = _locations.auto_loop_location()) != 0 && existing != location) {
1012 auto_loop_start_changed_connection.disconnect();
1013 auto_loop_end_changed_connection.disconnect();
1014 auto_loop_changed_connection.disconnect();
1015 existing->set_auto_loop (false, this);
1016 remove_event (existing->end(), Event::AutoLoop);
1017 auto_loop_location_changed (0);
1022 if (location == 0) {
1026 if (location->end() <= location->start()) {
1027 error << _("Session: you can't use a mark for auto loop") << endmsg;
1031 last_loopend = location->end();
1033 auto_loop_start_changed_connection.disconnect();
1034 auto_loop_end_changed_connection.disconnect();
1035 auto_loop_changed_connection.disconnect();
1037 auto_loop_start_changed_connection = location->start_changed.connect (mem_fun (this, &Session::auto_loop_changed));
1038 auto_loop_end_changed_connection = location->end_changed.connect (mem_fun (this, &Session::auto_loop_changed));
1039 auto_loop_changed_connection = location->changed.connect (mem_fun (this, &Session::auto_loop_changed));
1041 location->set_auto_loop (true, this);
1042 auto_loop_location_changed (location);
1046 Session::locations_added (Location* ignored)
1052 Session::locations_changed ()
1054 _locations.apply (*this, &Session::handle_locations_changed);
1058 Session::handle_locations_changed (Locations::LocationList& locations)
1060 Locations::LocationList::iterator i;
1062 bool set_loop = false;
1063 bool set_punch = false;
1065 for (i = locations.begin(); i != locations.end(); ++i) {
1069 if (location->is_auto_punch()) {
1070 set_auto_punch_location (location);
1073 if (location->is_auto_loop()) {
1074 set_auto_loop_location (location);
1081 set_auto_loop_location (0);
1084 set_auto_punch_location (0);
1091 Session::enable_record ()
1093 /* XXX really atomic compare+swap here */
1094 if (g_atomic_int_get (&_record_status) != Recording) {
1095 g_atomic_int_set (&_record_status, Recording);
1096 _last_record_location = _transport_frame;
1097 deliver_mmc(MIDI::MachineControl::cmdRecordStrobe, _last_record_location);
1099 if (Config->get_monitoring_model() == HardwareMonitoring && Config->get_auto_input()) {
1100 boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
1101 for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
1102 if ((*i)->record_enabled ()) {
1103 (*i)->monitor_input (true);
1108 RecordStateChanged ();
1113 Session::disable_record (bool rt_context, bool force)
1117 if ((rs = (RecordState) g_atomic_int_get (&_record_status)) != Disabled) {
1119 if ((!Config->get_latched_record_enable () && !play_loop) || force) {
1120 g_atomic_int_set (&_record_status, Disabled);
1122 if (rs == Recording) {
1123 g_atomic_int_set (&_record_status, Enabled);
1127 // FIXME: timestamp correct? [DR]
1128 // FIXME FIXME FIXME: rt_context? this must be called in the process thread.
1129 // does this /need/ to be sent in all cases?
1131 deliver_mmc (MIDI::MachineControl::cmdRecordExit, _transport_frame);
1133 if (Config->get_monitoring_model() == HardwareMonitoring && Config->get_auto_input()) {
1134 boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
1136 for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
1137 if ((*i)->record_enabled ()) {
1138 (*i)->monitor_input (false);
1143 RecordStateChanged (); /* emit signal */
1146 remove_pending_capture_state ();
1152 Session::step_back_from_record ()
1154 /* XXX really atomic compare+swap here */
1155 if (g_atomic_int_get (&_record_status) == Recording) {
1156 g_atomic_int_set (&_record_status, Enabled);
1158 if (Config->get_monitoring_model() == HardwareMonitoring) {
1159 boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
1161 for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
1162 if (Config->get_auto_input() && (*i)->record_enabled ()) {
1163 //cerr << "switching from input" << __FILE__ << __LINE__ << endl << endl;
1164 (*i)->monitor_input (false);
1172 Session::maybe_enable_record ()
1174 g_atomic_int_set (&_record_status, Enabled);
1176 /* this function is currently called from somewhere other than an RT thread.
1177 this save_state() call therefore doesn't impact anything.
1180 save_state ("", true);
1182 if (_transport_speed) {
1183 if (!Config->get_punch_in()) {
1187 deliver_mmc (MIDI::MachineControl::cmdRecordPause, _transport_frame);
1188 RecordStateChanged (); /* EMIT SIGNAL */
1195 Session::audible_frame () const
1201 /* the first of these two possible settings for "offset"
1202 mean that the audible frame is stationary until
1203 audio emerges from the latency compensation
1206 the second means that the audible frame is stationary
1207 until audio would emerge from a physical port
1208 in the absence of any plugin latency compensation
1211 offset = _worst_output_latency;
1213 if (offset > current_block_size) {
1214 offset -= current_block_size;
1216 /* XXX is this correct? if we have no external
1217 physical connections and everything is internal
1218 then surely this is zero? still, how
1219 likely is that anyway?
1221 offset = current_block_size;
1224 if (synced_to_jack()) {
1225 tf = _engine.transport_frame();
1227 tf = _transport_frame;
1230 if (_transport_speed == 0) {
1240 if (!non_realtime_work_pending()) {
1244 /* take latency into account */
1253 Session::set_frame_rate (nframes_t frames_per_second)
1255 /** \fn void Session::set_frame_size(nframes_t)
1256 the AudioEngine object that calls this guarantees
1257 that it will not be called while we are also in
1258 ::process(). Its fine to do things that block
1262 _base_frame_rate = frames_per_second;
1266 Automatable::set_automation_interval ((jack_nframes_t) ceil ((double) frames_per_second * (0.001 * Config->get_automation_interval())));
1270 // XXX we need some equivalent to this, somehow
1271 // SndFileSource::setup_standard_crossfades (frames_per_second);
1275 /* XXX need to reset/reinstantiate all LADSPA plugins */
1279 Session::set_block_size (nframes_t nframes)
1281 /* the AudioEngine guarantees
1282 that it will not be called while we are also in
1283 ::process(). It is therefore fine to do things that block
1289 current_block_size = nframes;
1291 ensure_buffers(_scratch_buffers->available());
1293 if (_gain_automation_buffer) {
1294 delete [] _gain_automation_buffer;
1296 _gain_automation_buffer = new gain_t[nframes];
1298 allocate_pan_automation_buffers (nframes, _npan_buffers, true);
1300 boost::shared_ptr<RouteList> r = routes.reader ();
1302 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
1303 (*i)->set_block_size (nframes);
1306 boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
1307 for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
1308 (*i)->set_block_size (nframes);
1311 set_worst_io_latencies ();
1316 Session::set_default_fade (float steepness, float fade_msecs)
1319 nframes_t fade_frames;
1321 /* Don't allow fade of less 1 frame */
1323 if (fade_msecs < (1000.0 * (1.0/_current_frame_rate))) {
1330 fade_frames = (nframes_t) floor (fade_msecs * _current_frame_rate * 0.001);
1334 default_fade_msecs = fade_msecs;
1335 default_fade_steepness = steepness;
1338 // jlc, WTF is this!
1339 Glib::RWLock::ReaderLock lm (route_lock);
1340 AudioRegion::set_default_fade (steepness, fade_frames);
1345 /* XXX have to do this at some point */
1346 /* foreach region using default fade, reset, then
1347 refill_all_diskstream_buffers ();
1352 struct RouteSorter {
1353 bool operator() (boost::shared_ptr<Route> r1, boost::shared_ptr<Route> r2) {
1354 if (r1->fed_by.find (r2) != r1->fed_by.end()) {
1356 } else if (r2->fed_by.find (r1) != r2->fed_by.end()) {
1359 if (r1->fed_by.empty()) {
1360 if (r2->fed_by.empty()) {
1361 /* no ardour-based connections inbound to either route. just use signal order */
1362 return r1->order_key(N_("signal")) < r2->order_key(N_("signal"));
1364 /* r2 has connections, r1 does not; run r1 early */
1368 return r1->order_key(N_("signal")) < r2->order_key(N_("signal"));
1375 trace_terminal (shared_ptr<Route> r1, shared_ptr<Route> rbase)
1377 shared_ptr<Route> r2;
1379 if ((r1->fed_by.find (rbase) != r1->fed_by.end()) && (rbase->fed_by.find (r1) != rbase->fed_by.end())) {
1380 info << string_compose(_("feedback loop setup between %1 and %2"), r1->name(), rbase->name()) << endmsg;
1384 /* make a copy of the existing list of routes that feed r1 */
1386 set<shared_ptr<Route> > existing = r1->fed_by;
1388 /* for each route that feeds r1, recurse, marking it as feeding
1392 for (set<shared_ptr<Route> >::iterator i = existing.begin(); i != existing.end(); ++i) {
1395 /* r2 is a route that feeds r1 which somehow feeds base. mark
1396 base as being fed by r2
1399 rbase->fed_by.insert (r2);
1403 /* 2nd level feedback loop detection. if r1 feeds or is fed by r2,
1407 if ((r1->fed_by.find (r2) != r1->fed_by.end()) && (r2->fed_by.find (r1) != r2->fed_by.end())) {
1411 /* now recurse, so that we can mark base as being fed by
1412 all routes that feed r2
1415 trace_terminal (r2, rbase);
1422 Session::resort_routes ()
1424 /* don't do anything here with signals emitted
1425 by Routes while we are being destroyed.
1428 if (_state_of_the_state & Deletion) {
1435 RCUWriter<RouteList> writer (routes);
1436 shared_ptr<RouteList> r = writer.get_copy ();
1437 resort_routes_using (r);
1438 /* writer goes out of scope and forces update */
1443 Session::resort_routes_using (shared_ptr<RouteList> r)
1445 RouteList::iterator i, j;
1447 for (i = r->begin(); i != r->end(); ++i) {
1449 (*i)->fed_by.clear ();
1451 for (j = r->begin(); j != r->end(); ++j) {
1453 /* although routes can feed themselves, it will
1454 cause an endless recursive descent if we
1455 detect it. so don't bother checking for
1463 if ((*j)->feeds (*i)) {
1464 (*i)->fed_by.insert (*j);
1469 for (i = r->begin(); i != r->end(); ++i) {
1470 trace_terminal (*i, *i);
1477 cerr << "finished route resort\n";
1479 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
1480 cerr << " " << (*i)->name() << " signal order = " << (*i)->order_key ("signal") << endl;
1487 list<boost::shared_ptr<MidiTrack> >
1488 Session::new_midi_track (TrackMode mode, uint32_t how_many)
1490 char track_name[32];
1491 uint32_t track_id = 0;
1494 RouteList new_routes;
1495 list<boost::shared_ptr<MidiTrack> > ret;
1496 //uint32_t control_id;
1498 // FIXME: need physical I/O and autoconnect stuff for MIDI
1500 /* count existing midi tracks */
1503 shared_ptr<RouteList> r = routes.reader ();
1505 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
1506 if (dynamic_cast<MidiTrack*>((*i).get()) != 0) {
1507 if (!(*i)->is_hidden()) {
1509 //channels_used += (*i)->n_inputs().n_midi();
1516 vector<string> physinputs;
1517 vector<string> physoutputs;
1518 uint32_t nphysical_in;
1519 uint32_t nphysical_out;
1521 _engine.get_physical_outputs (physoutputs);
1522 _engine.get_physical_inputs (physinputs);
1523 control_id = ntracks() + nbusses() + 1;
1528 /* check for duplicate route names, since we might have pre-existing
1529 routes with this name (e.g. create Audio1, Audio2, delete Audio1,
1530 save, close,restart,add new route - first named route is now
1538 snprintf (track_name, sizeof(track_name), "Midi %" PRIu32, track_id);
1540 if (route_by_name (track_name) == 0) {
1544 } while (track_id < (UINT_MAX-1));
1547 if (Config->get_input_auto_connect() & AutoConnectPhysical) {
1548 nphysical_in = min (n_physical_inputs, (uint32_t) physinputs.size());
1553 if (Config->get_output_auto_connect() & AutoConnectPhysical) {
1554 nphysical_out = min (n_physical_outputs, (uint32_t) physinputs.size());
1560 shared_ptr<MidiTrack> track;
1563 track = boost::shared_ptr<MidiTrack>((new MidiTrack (*this, track_name, Route::Flag (0), mode)));
1565 if (track->ensure_io (ChanCount(DataType::MIDI, 1), ChanCount(DataType::AUDIO, 1), false, this)) {
1566 error << "cannot configure 1 in/1 out configuration for new midi track" << endmsg;
1572 for (uint32_t x = 0; x < track->n_inputs().n_midi() && x < nphysical_in; ++x) {
1576 if (Config->get_input_auto_connect() & AutoConnectPhysical) {
1577 port = physinputs[(channels_used+x)%nphysical_in];
1580 if (port.length() && track->connect_input (track->input (x), port, this)) {
1586 for (uint32_t x = 0; x < track->n_outputs().n_midi(); ++x) {
1590 if (nphysical_out && (Config->get_output_auto_connect() & AutoConnectPhysical)) {
1591 port = physoutputs[(channels_used+x)%nphysical_out];
1592 } else if (Config->get_output_auto_connect() & AutoConnectMaster) {
1594 port = _master_out->input (x%_master_out->n_inputs().n_midi())->name();
1598 if (port.length() && track->connect_output (track->output (x), port, this)) {
1603 channels_used += track->n_inputs ().n_midi();
1607 track->midi_diskstream()->non_realtime_input_change();
1609 track->DiskstreamChanged.connect (mem_fun (this, &Session::resort_routes));
1610 //track->set_remote_control_id (control_id);
1612 new_routes.push_back (track);
1613 ret.push_back (track);
1616 catch (failed_constructor &err) {
1617 error << _("Session: could not create new midi track.") << endmsg;
1620 /* we need to get rid of this, since the track failed to be created */
1621 /* XXX arguably, AudioTrack::AudioTrack should not do the Session::add_diskstream() */
1624 RCUWriter<DiskstreamList> writer (diskstreams);
1625 boost::shared_ptr<DiskstreamList> ds = writer.get_copy();
1626 ds->remove (track->midi_diskstream());
1633 catch (AudioEngine::PortRegistrationFailure& pfe) {
1635 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;
1638 /* we need to get rid of this, since the track failed to be created */
1639 /* XXX arguably, MidiTrack::MidiTrack should not do the Session::add_diskstream() */
1642 RCUWriter<DiskstreamList> writer (diskstreams);
1643 boost::shared_ptr<DiskstreamList> ds = writer.get_copy();
1644 ds->remove (track->midi_diskstream());
1655 if (!new_routes.empty()) {
1656 add_routes (new_routes, false);
1657 save_state (_current_snapshot_name);
1663 list<boost::shared_ptr<AudioTrack> >
1664 Session::new_audio_track (int input_channels, int output_channels, TrackMode mode, uint32_t how_many)
1666 char track_name[32];
1667 uint32_t track_id = 0;
1669 uint32_t channels_used = 0;
1671 RouteList new_routes;
1672 list<boost::shared_ptr<AudioTrack> > ret;
1673 uint32_t control_id;
1675 /* count existing audio tracks */
1678 shared_ptr<RouteList> r = routes.reader ();
1680 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
1681 if (dynamic_cast<AudioTrack*>((*i).get()) != 0) {
1682 if (!(*i)->is_hidden()) {
1684 channels_used += (*i)->n_inputs().n_audio();
1690 vector<string> physinputs;
1691 vector<string> physoutputs;
1692 uint32_t nphysical_in;
1693 uint32_t nphysical_out;
1695 _engine.get_physical_outputs (physoutputs);
1696 _engine.get_physical_inputs (physinputs);
1697 control_id = ntracks() + nbusses() + 1;
1701 /* check for duplicate route names, since we might have pre-existing
1702 routes with this name (e.g. create Audio1, Audio2, delete Audio1,
1703 save, close,restart,add new route - first named route is now
1711 snprintf (track_name, sizeof(track_name), "Audio %" PRIu32, track_id);
1713 if (route_by_name (track_name) == 0) {
1717 } while (track_id < (UINT_MAX-1));
1719 if (Config->get_input_auto_connect() & AutoConnectPhysical) {
1720 nphysical_in = min (n_physical_inputs, (uint32_t) physinputs.size());
1725 if (Config->get_output_auto_connect() & AutoConnectPhysical) {
1726 nphysical_out = min (n_physical_outputs, (uint32_t) physinputs.size());
1731 shared_ptr<AudioTrack> track;
1734 track = boost::shared_ptr<AudioTrack>((new AudioTrack (*this, track_name, Route::Flag (0), mode)));
1736 if (track->ensure_io (ChanCount(DataType::AUDIO, input_channels), ChanCount(DataType::AUDIO, output_channels), false, this)) {
1737 error << string_compose (_("cannot configure %1 in/%2 out configuration for new audio track"),
1738 input_channels, output_channels)
1744 for (uint32_t x = 0; x < track->n_inputs().n_audio() && x < nphysical_in; ++x) {
1748 if (Config->get_input_auto_connect() & AutoConnectPhysical) {
1749 port = physinputs[(channels_used+x)%nphysical_in];
1752 if (port.length() && track->connect_input (track->input (x), port, this)) {
1758 for (uint32_t x = 0; x < track->n_outputs().n_midi(); ++x) {
1762 if (nphysical_out && (Config->get_output_auto_connect() & AutoConnectPhysical)) {
1763 port = physoutputs[(channels_used+x)%nphysical_out];
1764 } else if (Config->get_output_auto_connect() & AutoConnectMaster) {
1766 port = _master_out->input (x%_master_out->n_inputs().n_audio())->name();
1770 if (port.length() && track->connect_output (track->output (x), port, this)) {
1775 channels_used += track->n_inputs ().n_audio();
1777 track->audio_diskstream()->non_realtime_input_change();
1779 track->DiskstreamChanged.connect (mem_fun (this, &Session::resort_routes));
1780 track->set_remote_control_id (control_id);
1783 new_routes.push_back (track);
1784 ret.push_back (track);
1787 catch (failed_constructor &err) {
1788 error << _("Session: could not create new audio track.") << endmsg;
1791 /* we need to get rid of this, since the track failed to be created */
1792 /* XXX arguably, AudioTrack::AudioTrack should not do the Session::add_diskstream() */
1795 RCUWriter<DiskstreamList> writer (diskstreams);
1796 boost::shared_ptr<DiskstreamList> ds = writer.get_copy();
1797 ds->remove (track->audio_diskstream());
1804 catch (AudioEngine::PortRegistrationFailure& pfe) {
1806 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;
1809 /* we need to get rid of this, since the track failed to be created */
1810 /* XXX arguably, AudioTrack::AudioTrack should not do the Session::add_diskstream() */
1813 RCUWriter<DiskstreamList> writer (diskstreams);
1814 boost::shared_ptr<DiskstreamList> ds = writer.get_copy();
1815 ds->remove (track->audio_diskstream());
1826 if (!new_routes.empty()) {
1827 add_routes (new_routes, false);
1828 save_state (_current_snapshot_name);
1835 Session::set_remote_control_ids ()
1837 RemoteModel m = Config->get_remote_model();
1839 shared_ptr<RouteList> r = routes.reader ();
1841 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
1842 if ( MixerOrdered == m) {
1843 long order = (*i)->order_key(N_("signal"));
1844 (*i)->set_remote_control_id( order+1 );
1845 } else if ( EditorOrdered == m) {
1846 long order = (*i)->order_key(N_("editor"));
1847 (*i)->set_remote_control_id( order+1 );
1848 } else if ( UserOrdered == m) {
1849 //do nothing ... only changes to remote id's are initiated by user
1856 Session::new_audio_route (int input_channels, int output_channels, uint32_t how_many)
1859 uint32_t bus_id = 1;
1863 uint32_t control_id;
1865 /* count existing audio busses */
1868 shared_ptr<RouteList> r = routes.reader ();
1870 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
1871 if (dynamic_cast<AudioTrack*>((*i).get()) == 0) {
1872 if (!(*i)->is_hidden() && (*i)->name() != _("master")) {
1879 vector<string> physinputs;
1880 vector<string> physoutputs;
1882 _engine.get_physical_outputs (physoutputs);
1883 _engine.get_physical_inputs (physinputs);
1884 control_id = ntracks() + nbusses() + 1;
1889 snprintf (bus_name, sizeof(bus_name), "Bus %" PRIu32, bus_id);
1893 if (route_by_name (bus_name) == 0) {
1897 } while (bus_id < (UINT_MAX-1));
1900 shared_ptr<Route> bus (new Route (*this, bus_name, -1, -1, -1, -1, Route::Flag(0), DataType::AUDIO));
1902 if (bus->ensure_io (ChanCount(DataType::AUDIO, input_channels), ChanCount(DataType::AUDIO, output_channels), false, this)) {
1903 error << string_compose (_("cannot configure %1 in/%2 out configuration for new audio track"),
1904 input_channels, output_channels)
1909 for (uint32_t x = 0; n_physical_inputs && x < bus->n_inputs().n_audio(); ++x) {
1913 if (Config->get_input_auto_connect() & AutoConnectPhysical) {
1914 port = physinputs[((n+x)%n_physical_inputs)];
1917 if (port.length() && bus->connect_input (bus->input (x), port, this)) {
1922 for (uint32_t x = 0; n_physical_outputs && x < bus->n_outputs().n_audio(); ++x) {
1926 if (Config->get_output_auto_connect() & AutoConnectPhysical) {
1927 port = physoutputs[((n+x)%n_physical_outputs)];
1928 } else if (Config->get_output_auto_connect() & AutoConnectMaster) {
1930 port = _master_out->input (x%_master_out->n_inputs().n_audio())->name();
1934 if (port.length() && bus->connect_output (bus->output (x), port, this)) {
1939 bus->set_remote_control_id (control_id);
1942 ret.push_back (bus);
1946 catch (failed_constructor &err) {
1947 error << _("Session: could not create new audio route.") << endmsg;
1951 catch (AudioEngine::PortRegistrationFailure& pfe) {
1952 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;
1962 add_routes (ret, false);
1963 save_state (_current_snapshot_name);
1971 Session::add_routes (RouteList& new_routes, bool save)
1974 RCUWriter<RouteList> writer (routes);
1975 shared_ptr<RouteList> r = writer.get_copy ();
1976 r->insert (r->end(), new_routes.begin(), new_routes.end());
1977 resort_routes_using (r);
1980 for (RouteList::iterator x = new_routes.begin(); x != new_routes.end(); ++x) {
1982 boost::weak_ptr<Route> wpr (*x);
1984 (*x)->solo_changed.connect (sigc::bind (mem_fun (*this, &Session::route_solo_changed), wpr));
1985 (*x)->mute_changed.connect (mem_fun (*this, &Session::route_mute_changed));
1986 (*x)->output_changed.connect (mem_fun (*this, &Session::set_worst_io_latencies_x));
1987 (*x)->processors_changed.connect (bind (mem_fun (*this, &Session::update_latency_compensation), false, false));
1989 if ((*x)->is_master()) {
1993 if ((*x)->is_control()) {
1994 _control_out = (*x);
1997 add_bundle ((*x)->bundle_for_inputs());
1998 add_bundle ((*x)->bundle_for_outputs());
2001 if (_control_out && IO::connecting_legal) {
2003 vector<string> cports;
2004 uint32_t ni = _control_out->n_inputs().n_audio();
2006 for (uint32_t n = 0; n < ni; ++n) {
2007 cports.push_back (_control_out->input(n)->name());
2010 for (RouteList::iterator x = new_routes.begin(); x != new_routes.end(); ++x) {
2011 (*x)->set_control_outs (cports);
2018 save_state (_current_snapshot_name);
2021 RouteAdded (new_routes); /* EMIT SIGNAL */
2025 Session::add_diskstream (boost::shared_ptr<Diskstream> dstream)
2027 /* need to do this in case we're rolling at the time, to prevent false underruns */
2028 dstream->do_refill_with_alloc ();
2030 dstream->set_block_size (current_block_size);
2033 RCUWriter<DiskstreamList> writer (diskstreams);
2034 boost::shared_ptr<DiskstreamList> ds = writer.get_copy();
2035 ds->push_back (dstream);
2036 /* writer goes out of scope, copies ds back to main */
2039 dstream->PlaylistChanged.connect (sigc::bind (mem_fun (*this, &Session::diskstream_playlist_changed), dstream));
2040 /* this will connect to future changes, and check the current length */
2041 diskstream_playlist_changed (dstream);
2043 dstream->prepare ();
2048 Session::remove_route (shared_ptr<Route> route)
2051 RCUWriter<RouteList> writer (routes);
2052 shared_ptr<RouteList> rs = writer.get_copy ();
2056 /* deleting the master out seems like a dumb
2057 idea, but its more of a UI policy issue
2061 if (route == _master_out) {
2062 _master_out = shared_ptr<Route> ();
2065 if (route == _control_out) {
2066 _control_out = shared_ptr<Route> ();
2068 /* cancel control outs for all routes */
2070 vector<string> empty;
2072 for (RouteList::iterator r = rs->begin(); r != rs->end(); ++r) {
2073 (*r)->set_control_outs (empty);
2077 update_route_solo_state ();
2079 /* writer goes out of scope, forces route list update */
2083 boost::shared_ptr<Diskstream> ds;
2085 if ((t = dynamic_cast<Track*>(route.get())) != 0) {
2086 ds = t->diskstream();
2092 RCUWriter<DiskstreamList> dsl (diskstreams);
2093 boost::shared_ptr<DiskstreamList> d = dsl.get_copy();
2098 find_current_end ();
2100 // We need to disconnect the routes inputs and outputs
2102 route->disconnect_inputs (0);
2103 route->disconnect_outputs (0);
2105 update_latency_compensation (false, false);
2108 /* get rid of it from the dead wood collection in the route list manager */
2110 /* XXX i think this is unsafe as it currently stands, but i am not sure. (pd, october 2nd, 2006) */
2114 /* try to cause everyone to drop their references */
2116 cerr << "pre drop, Route now has " << route.use_count() << " refs\n";
2117 cerr << "sig has " << route->GoingAway.size() << endl;
2119 route->drop_references ();
2121 cerr << "route dangling refs = " << route.use_count() << endl;
2123 /* save the new state of the world */
2125 if (save_state (_current_snapshot_name)) {
2126 save_history (_current_snapshot_name);
2131 Session::route_mute_changed (void* src)
2137 Session::route_solo_changed (void* src, boost::weak_ptr<Route> wpr)
2139 if (solo_update_disabled) {
2145 boost::shared_ptr<Route> route = wpr.lock ();
2148 /* should not happen */
2149 error << string_compose (_("programming error: %1"), X_("invalid route weak ptr passed to route_solo_changed")) << endmsg;
2153 is_track = (boost::dynamic_pointer_cast<AudioTrack>(route) != 0);
2155 shared_ptr<RouteList> r = routes.reader ();
2157 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2159 /* soloing a track mutes all other tracks, soloing a bus mutes all other busses */
2163 /* don't mess with busses */
2165 if (dynamic_cast<Track*>((*i).get()) == 0) {
2171 /* don't mess with tracks */
2173 if (dynamic_cast<Track*>((*i).get()) != 0) {
2178 if ((*i) != route &&
2179 ((*i)->mix_group () == 0 ||
2180 (*i)->mix_group () != route->mix_group () ||
2181 !route->mix_group ()->is_active())) {
2183 if ((*i)->soloed()) {
2185 /* if its already soloed, and solo latching is enabled,
2186 then leave it as it is.
2189 if (Config->get_solo_latched()) {
2196 solo_update_disabled = true;
2197 (*i)->set_solo (false, src);
2198 solo_update_disabled = false;
2202 bool something_soloed = false;
2203 bool same_thing_soloed = false;
2204 bool signal = false;
2206 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2207 if ((*i)->soloed()) {
2208 something_soloed = true;
2209 if (dynamic_cast<Track*>((*i).get())) {
2211 same_thing_soloed = true;
2216 same_thing_soloed = true;
2224 if (something_soloed != currently_soloing) {
2226 currently_soloing = something_soloed;
2229 modify_solo_mute (is_track, same_thing_soloed);
2232 SoloActive (currently_soloing); /* EMIT SIGNAL */
2235 SoloChanged (); /* EMIT SIGNAL */
2241 Session::update_route_solo_state ()
2244 bool is_track = false;
2245 bool signal = false;
2247 /* caller must hold RouteLock */
2249 /* this is where we actually implement solo by changing
2250 the solo mute setting of each track.
2253 shared_ptr<RouteList> r = routes.reader ();
2255 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2256 if ((*i)->soloed()) {
2258 if (dynamic_cast<Track*>((*i).get())) {
2265 if (mute != currently_soloing) {
2267 currently_soloing = mute;
2270 if (!is_track && !mute) {
2272 /* nothing is soloed */
2274 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2275 (*i)->set_solo_mute (false);
2285 modify_solo_mute (is_track, mute);
2288 SoloActive (currently_soloing);
2293 Session::modify_solo_mute (bool is_track, bool mute)
2295 shared_ptr<RouteList> r = routes.reader ();
2297 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2301 /* only alter track solo mute */
2303 if (dynamic_cast<Track*>((*i).get())) {
2304 if ((*i)->soloed()) {
2305 (*i)->set_solo_mute (!mute);
2307 (*i)->set_solo_mute (mute);
2313 /* only alter bus solo mute */
2315 if (!dynamic_cast<Track*>((*i).get())) {
2317 if ((*i)->soloed()) {
2319 (*i)->set_solo_mute (false);
2323 /* don't mute master or control outs
2324 in response to another bus solo
2327 if ((*i) != _master_out &&
2328 (*i) != _control_out) {
2329 (*i)->set_solo_mute (mute);
2340 Session::catch_up_on_solo ()
2342 /* this is called after set_state() to catch the full solo
2343 state, which can't be correctly determined on a per-route
2344 basis, but needs the global overview that only the session
2347 update_route_solo_state();
2351 Session::route_by_name (string name)
2353 shared_ptr<RouteList> r = routes.reader ();
2355 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2356 if ((*i)->name() == name) {
2361 return shared_ptr<Route> ((Route*) 0);
2365 Session::route_by_id (PBD::ID id)
2367 shared_ptr<RouteList> r = routes.reader ();
2369 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2370 if ((*i)->id() == id) {
2375 return shared_ptr<Route> ((Route*) 0);
2379 Session::route_by_remote_id (uint32_t id)
2381 shared_ptr<RouteList> r = routes.reader ();
2383 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2384 if ((*i)->remote_control_id() == id) {
2389 return shared_ptr<Route> ((Route*) 0);
2393 Session::find_current_end ()
2395 if (_state_of_the_state & Loading) {
2399 nframes_t max = get_maximum_extent ();
2401 if (max > end_location->end()) {
2402 end_location->set_end (max);
2404 DurationChanged(); /* EMIT SIGNAL */
2409 Session::get_maximum_extent () const
2414 boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
2416 for (DiskstreamList::const_iterator i = dsl->begin(); i != dsl->end(); ++i) {
2417 boost::shared_ptr<Playlist> pl = (*i)->playlist();
2418 if ((me = pl->get_maximum_extent()) > max) {
2426 boost::shared_ptr<Diskstream>
2427 Session::diskstream_by_name (string name)
2429 boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
2431 for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
2432 if ((*i)->name() == name) {
2437 return boost::shared_ptr<Diskstream>((Diskstream*) 0);
2440 boost::shared_ptr<Diskstream>
2441 Session::diskstream_by_id (const PBD::ID& id)
2443 boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
2445 for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
2446 if ((*i)->id() == id) {
2451 return boost::shared_ptr<Diskstream>((Diskstream*) 0);
2454 /* Region management */
2457 Session::new_region_name (string old)
2459 string::size_type last_period;
2461 string::size_type len = old.length() + 64;
2464 if ((last_period = old.find_last_of ('.')) == string::npos) {
2466 /* no period present - add one explicitly */
2469 last_period = old.length() - 1;
2474 number = atoi (old.substr (last_period+1).c_str());
2478 while (number < (UINT_MAX-1)) {
2480 RegionList::const_iterator i;
2485 snprintf (buf, len, "%s%" PRIu32, old.substr (0, last_period + 1).c_str(), number);
2488 for (i = regions.begin(); i != regions.end(); ++i) {
2489 if (i->second->name() == sbuf) {
2494 if (i == regions.end()) {
2499 if (number != (UINT_MAX-1)) {
2503 error << string_compose (_("cannot create new name for region \"%1\""), old) << endmsg;
2508 Session::region_name (string& result, string base, bool newlevel) const
2513 assert(base.find("/") == string::npos);
2517 Glib::Mutex::Lock lm (region_lock);
2519 snprintf (buf, sizeof (buf), "%d", (int)regions.size() + 1);
2527 /* XXX this is going to be slow. optimize me later */
2532 string::size_type pos;
2534 pos = base.find_last_of ('.');
2536 /* pos may be npos, but then we just use entire base */
2538 subbase = base.substr (0, pos);
2542 bool name_taken = true;
2545 Glib::Mutex::Lock lm (region_lock);
2547 for (int n = 1; n < 5000; ++n) {
2550 snprintf (buf, sizeof (buf), ".%d", n);
2555 for (RegionList::const_iterator i = regions.begin(); i != regions.end(); ++i) {
2556 if (i->second->name() == result) {
2569 fatal << string_compose(_("too many regions with names like %1"), base) << endmsg;
2577 Session::add_region (boost::shared_ptr<Region> region)
2579 boost::shared_ptr<Region> other;
2583 Glib::Mutex::Lock lm (region_lock);
2585 RegionList::iterator x;
2587 for (x = regions.begin(); x != regions.end(); ++x) {
2591 if (region->region_list_equivalent (other)) {
2596 if (x == regions.end()) {
2598 pair<RegionList::key_type,RegionList::mapped_type> entry;
2600 entry.first = region->id();
2601 entry.second = region;
2603 pair<RegionList::iterator,bool> x = regions.insert (entry);
2615 /* mark dirty because something has changed even if we didn't
2616 add the region to the region list.
2622 region->GoingAway.connect (sigc::bind (mem_fun (*this, &Session::remove_region), boost::weak_ptr<Region>(region)));
2623 region->StateChanged.connect (sigc::bind (mem_fun (*this, &Session::region_changed), boost::weak_ptr<Region>(region)));
2624 RegionAdded (region); /* EMIT SIGNAL */
2629 Session::region_changed (Change what_changed, boost::weak_ptr<Region> weak_region)
2631 boost::shared_ptr<Region> region (weak_region.lock ());
2637 if (what_changed & Region::HiddenChanged) {
2638 /* relay hidden changes */
2639 RegionHiddenChange (region);
2644 Session::remove_region (boost::weak_ptr<Region> weak_region)
2646 RegionList::iterator i;
2647 boost::shared_ptr<Region> region (weak_region.lock ());
2653 bool removed = false;
2656 Glib::Mutex::Lock lm (region_lock);
2658 if ((i = regions.find (region->id())) != regions.end()) {
2664 /* mark dirty because something has changed even if we didn't
2665 remove the region from the region list.
2671 RegionRemoved(region); /* EMIT SIGNAL */
2675 boost::shared_ptr<Region>
2676 Session::find_whole_file_parent (boost::shared_ptr<Region const> child)
2678 RegionList::iterator i;
2679 boost::shared_ptr<Region> region;
2681 Glib::Mutex::Lock lm (region_lock);
2683 for (i = regions.begin(); i != regions.end(); ++i) {
2687 if (region->whole_file()) {
2689 if (child->source_equivalent (region)) {
2695 return boost::shared_ptr<Region> ();
2699 Session::find_equivalent_playlist_regions (boost::shared_ptr<Region> region, vector<boost::shared_ptr<Region> >& result)
2701 for (PlaylistList::iterator i = playlists.begin(); i != playlists.end(); ++i)
2702 (*i)->get_region_list_equivalent_regions (region, result);
2706 Session::destroy_region (boost::shared_ptr<Region> region)
2708 vector<boost::shared_ptr<Source> > srcs;
2711 boost::shared_ptr<AudioRegion> aregion;
2713 if ((aregion = boost::dynamic_pointer_cast<AudioRegion> (region)) == 0) {
2717 if (aregion->playlist()) {
2718 aregion->playlist()->destroy_region (region);
2721 for (uint32_t n = 0; n < aregion->n_channels(); ++n) {
2722 srcs.push_back (aregion->source (n));
2726 region->drop_references ();
2728 for (vector<boost::shared_ptr<Source> >::iterator i = srcs.begin(); i != srcs.end(); ++i) {
2730 if (!(*i)->used()) {
2731 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*i);
2734 (afs)->mark_for_remove ();
2737 (*i)->drop_references ();
2739 cerr << "source was not used by any playlist\n";
2747 Session::destroy_regions (list<boost::shared_ptr<Region> > regions)
2749 for (list<boost::shared_ptr<Region> >::iterator i = regions.begin(); i != regions.end(); ++i) {
2750 destroy_region (*i);
2756 Session::remove_last_capture ()
2758 list<boost::shared_ptr<Region> > r;
2760 boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
2762 for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
2763 list<boost::shared_ptr<Region> >& l = (*i)->last_capture_regions();
2766 r.insert (r.end(), l.begin(), l.end());
2771 destroy_regions (r);
2773 save_state (_current_snapshot_name);
2779 Session::remove_region_from_region_list (boost::shared_ptr<Region> r)
2785 /* Source Management */
2787 Session::add_source (boost::shared_ptr<Source> source)
2789 pair<SourceMap::key_type, SourceMap::mapped_type> entry;
2790 pair<SourceMap::iterator,bool> result;
2792 entry.first = source->id();
2793 entry.second = source;
2796 Glib::Mutex::Lock lm (source_lock);
2797 result = sources.insert (entry);
2800 if (result.second) {
2801 source->GoingAway.connect (sigc::bind (mem_fun (this, &Session::remove_source), boost::weak_ptr<Source> (source)));
2807 Session::remove_source (boost::weak_ptr<Source> src)
2809 SourceMap::iterator i;
2810 boost::shared_ptr<Source> source = src.lock();
2817 Glib::Mutex::Lock lm (source_lock);
2819 if ((i = sources.find (source->id())) != sources.end()) {
2824 if (!_state_of_the_state & InCleanup) {
2826 /* save state so we don't end up with a session file
2827 referring to non-existent sources.
2830 save_state (_current_snapshot_name);
2834 boost::shared_ptr<Source>
2835 Session::source_by_id (const PBD::ID& id)
2837 Glib::Mutex::Lock lm (source_lock);
2838 SourceMap::iterator i;
2839 boost::shared_ptr<Source> source;
2841 if ((i = sources.find (id)) != sources.end()) {
2849 boost::shared_ptr<Source>
2850 Session::source_by_path_and_channel (const Glib::ustring& path, uint16_t chn)
2852 Glib::Mutex::Lock lm (source_lock);
2854 for (SourceMap::iterator i = sources.begin(); i != sources.end(); ++i) {
2855 cerr << "comparing " << path << " with " << i->second->name() << endl;
2856 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(i->second);
2858 if (afs && afs->path() == path && chn == afs->channel()) {
2863 return boost::shared_ptr<Source>();
2867 Session::peak_path (Glib::ustring base) const
2869 sys::path peakfile_path(_session_dir->peak_path());
2870 peakfile_path /= basename_nosuffix (base) + peakfile_suffix;
2871 return peakfile_path.to_string();
2875 Session::change_audio_path_by_name (string path, string oldname, string newname, bool destructive)
2878 string old_basename = PBD::basename_nosuffix (oldname);
2879 string new_legalized = legalize_for_path (newname);
2881 /* note: we know (or assume) the old path is already valid */
2885 /* destructive file sources have a name of the form:
2887 /path/to/Tnnnn-NAME(%[LR])?.wav
2889 the task here is to replace NAME with the new name.
2892 /* find last slash */
2896 string::size_type slash;
2897 string::size_type dash;
2899 if ((slash = path.find_last_of ('/')) == string::npos) {
2903 dir = path.substr (0, slash+1);
2905 /* '-' is not a legal character for the NAME part of the path */
2907 if ((dash = path.find_last_of ('-')) == string::npos) {
2911 prefix = path.substr (slash+1, dash-(slash+1));
2916 path += new_legalized;
2917 path += ".wav"; /* XXX gag me with a spoon */
2921 /* non-destructive file sources have a name of the form:
2923 /path/to/NAME-nnnnn(%[LR])?.wav
2925 the task here is to replace NAME with the new name.
2930 string::size_type slash;
2931 string::size_type dash;
2932 string::size_type postfix;
2934 /* find last slash */
2936 if ((slash = path.find_last_of ('/')) == string::npos) {
2940 dir = path.substr (0, slash+1);
2942 /* '-' is not a legal character for the NAME part of the path */
2944 if ((dash = path.find_last_of ('-')) == string::npos) {
2948 suffix = path.substr (dash+1);
2950 // Suffix is now everything after the dash. Now we need to eliminate
2951 // the nnnnn part, which is done by either finding a '%' or a '.'
2953 postfix = suffix.find_last_of ("%");
2954 if (postfix == string::npos) {
2955 postfix = suffix.find_last_of ('.');
2958 if (postfix != string::npos) {
2959 suffix = suffix.substr (postfix);
2961 error << "Logic error in Session::change_audio_path_by_name(), please report to the developers" << endl;
2965 const uint32_t limit = 10000;
2966 char buf[PATH_MAX+1];
2968 for (uint32_t cnt = 1; cnt <= limit; ++cnt) {
2970 snprintf (buf, sizeof(buf), "%s%s-%u%s", dir.c_str(), newname.c_str(), cnt, suffix.c_str());
2972 if (access (buf, F_OK) != 0) {
2980 error << "FATAL ERROR! Could not find a " << endl;
2989 Session::audio_path_from_name (string name, uint32_t nchan, uint32_t chan, bool destructive)
2993 char buf[PATH_MAX+1];
2994 const uint32_t limit = 10000;
2998 legalized = legalize_for_path (name);
3000 /* find a "version" of the file name that doesn't exist in
3001 any of the possible directories.
3004 for (cnt = (destructive ? ++destructive_index : 1); cnt <= limit; ++cnt) {
3006 vector<space_and_path>::iterator i;
3007 uint32_t existing = 0;
3009 for (i = session_dirs.begin(); i != session_dirs.end(); ++i) {
3011 SessionDirectory sdir((*i).path);
3013 spath = sdir.sound_path().to_string();
3017 snprintf (buf, sizeof(buf), "%s/T%04d-%s.wav", spath.c_str(), cnt, legalized.c_str());
3018 } else if (nchan == 2) {
3020 snprintf (buf, sizeof(buf), "%s/T%04d-%s%%L.wav", spath.c_str(), cnt, legalized.c_str());
3022 snprintf (buf, sizeof(buf), "%s/T%04d-%s%%R.wav", spath.c_str(), cnt, legalized.c_str());
3024 } else if (nchan < 26) {
3025 snprintf (buf, sizeof(buf), "%s/T%04d-%s%%%c.wav", spath.c_str(), cnt, legalized.c_str(), 'a' + chan);
3027 snprintf (buf, sizeof(buf), "%s/T%04d-%s.wav", spath.c_str(), cnt, legalized.c_str());
3036 snprintf (buf, sizeof(buf), "%s-%u.wav", spath.c_str(), cnt);
3037 } else if (nchan == 2) {
3039 snprintf (buf, sizeof(buf), "%s-%u%%L.wav", spath.c_str(), cnt);
3041 snprintf (buf, sizeof(buf), "%s-%u%%R.wav", spath.c_str(), cnt);
3043 } else if (nchan < 26) {
3044 snprintf (buf, sizeof(buf), "%s-%u%%%c.wav", spath.c_str(), cnt, 'a' + chan);
3046 snprintf (buf, sizeof(buf), "%s-%u.wav", spath.c_str(), cnt);
3050 if (sys::exists(buf)) {
3056 if (existing == 0) {
3061 error << string_compose(_("There are already %1 recordings for %2, which I consider too many."), limit, name) << endmsg;
3063 throw failed_constructor();
3067 /* we now have a unique name for the file, but figure out where to
3073 SessionDirectory sdir(get_best_session_directory_for_new_source ());
3075 spath = sdir.sound_path().to_string();
3078 string::size_type pos = foo.find_last_of ('/');
3080 if (pos == string::npos) {
3083 spath += foo.substr (pos + 1);
3089 boost::shared_ptr<AudioFileSource>
3090 Session::create_audio_source_for_session (AudioDiskstream& ds, uint32_t chan, bool destructive)
3092 string spath = audio_path_from_name (ds.name(), ds.n_channels().n_audio(), chan, destructive);
3093 return boost::dynamic_pointer_cast<AudioFileSource> (
3094 SourceFactory::createWritable (DataType::AUDIO, *this, spath, destructive, frame_rate()));
3097 // FIXME: _terrible_ code duplication
3099 Session::change_midi_path_by_name (string path, string oldname, string newname, bool destructive)
3102 string old_basename = PBD::basename_nosuffix (oldname);
3103 string new_legalized = legalize_for_path (newname);
3105 /* note: we know (or assume) the old path is already valid */
3109 /* destructive file sources have a name of the form:
3111 /path/to/Tnnnn-NAME(%[LR])?.wav
3113 the task here is to replace NAME with the new name.
3116 /* find last slash */
3120 string::size_type slash;
3121 string::size_type dash;
3123 if ((slash = path.find_last_of ('/')) == string::npos) {
3127 dir = path.substr (0, slash+1);
3129 /* '-' is not a legal character for the NAME part of the path */
3131 if ((dash = path.find_last_of ('-')) == string::npos) {
3135 prefix = path.substr (slash+1, dash-(slash+1));
3140 path += new_legalized;
3141 path += ".mid"; /* XXX gag me with a spoon */
3145 /* non-destructive file sources have a name of the form:
3147 /path/to/NAME-nnnnn(%[LR])?.wav
3149 the task here is to replace NAME with the new name.
3154 string::size_type slash;
3155 string::size_type dash;
3156 string::size_type postfix;
3158 /* find last slash */
3160 if ((slash = path.find_last_of ('/')) == string::npos) {
3164 dir = path.substr (0, slash+1);
3166 /* '-' is not a legal character for the NAME part of the path */
3168 if ((dash = path.find_last_of ('-')) == string::npos) {
3172 suffix = path.substr (dash+1);
3174 // Suffix is now everything after the dash. Now we need to eliminate
3175 // the nnnnn part, which is done by either finding a '%' or a '.'
3177 postfix = suffix.find_last_of ("%");
3178 if (postfix == string::npos) {
3179 postfix = suffix.find_last_of ('.');
3182 if (postfix != string::npos) {
3183 suffix = suffix.substr (postfix);
3185 error << "Logic error in Session::change_midi_path_by_name(), please report to the developers" << endl;
3189 const uint32_t limit = 10000;
3190 char buf[PATH_MAX+1];
3192 for (uint32_t cnt = 1; cnt <= limit; ++cnt) {
3194 snprintf (buf, sizeof(buf), "%s%s-%u%s", dir.c_str(), newname.c_str(), cnt, suffix.c_str());
3196 if (access (buf, F_OK) != 0) {
3204 error << "FATAL ERROR! Could not find a " << endl;
3213 Session::midi_path_from_name (string name)
3217 char buf[PATH_MAX+1];
3218 const uint32_t limit = 10000;
3222 legalized = legalize_for_path (name);
3224 /* find a "version" of the file name that doesn't exist in
3225 any of the possible directories.
3228 for (cnt = 1; cnt <= limit; ++cnt) {
3230 vector<space_and_path>::iterator i;
3231 uint32_t existing = 0;
3233 for (i = session_dirs.begin(); i != session_dirs.end(); ++i) {
3235 SessionDirectory sdir((*i).path);
3237 sys::path p = sdir.midi_path();
3241 spath = p.to_string();
3243 snprintf (buf, sizeof(buf), "%s-%u.mid", spath.c_str(), cnt);
3245 if (sys::exists (buf)) {
3250 if (existing == 0) {
3255 error << string_compose(_("There are already %1 recordings for %2, which I consider too many."), limit, name) << endmsg;
3256 throw failed_constructor();
3260 /* we now have a unique name for the file, but figure out where to
3266 SessionDirectory sdir(get_best_session_directory_for_new_source ());
3268 spath = sdir.midi_path().to_string();
3271 string::size_type pos = foo.find_last_of ('/');
3273 if (pos == string::npos) {
3276 spath += foo.substr (pos + 1);
3282 boost::shared_ptr<MidiSource>
3283 Session::create_midi_source_for_session (MidiDiskstream& ds)
3285 string mpath = midi_path_from_name (ds.name());
3287 return boost::dynamic_pointer_cast<SMFSource> (SourceFactory::createWritable (DataType::MIDI, *this, mpath, false, frame_rate()));
3291 /* Playlist management */
3293 boost::shared_ptr<Playlist>
3294 Session::playlist_by_name (string name)
3296 Glib::Mutex::Lock lm (playlist_lock);
3297 for (PlaylistList::iterator i = playlists.begin(); i != playlists.end(); ++i) {
3298 if ((*i)->name() == name) {
3302 for (PlaylistList::iterator i = unused_playlists.begin(); i != unused_playlists.end(); ++i) {
3303 if ((*i)->name() == name) {
3308 return boost::shared_ptr<Playlist>();
3312 Session::add_playlist (boost::shared_ptr<Playlist> playlist)
3314 if (playlist->hidden()) {
3319 Glib::Mutex::Lock lm (playlist_lock);
3320 if (find (playlists.begin(), playlists.end(), playlist) == playlists.end()) {
3321 playlists.insert (playlists.begin(), playlist);
3322 playlist->InUse.connect (sigc::bind (mem_fun (*this, &Session::track_playlist), boost::weak_ptr<Playlist>(playlist)));
3323 playlist->GoingAway.connect (sigc::bind (mem_fun (*this, &Session::remove_playlist), boost::weak_ptr<Playlist>(playlist)));
3329 PlaylistAdded (playlist); /* EMIT SIGNAL */
3333 Session::get_playlists (vector<boost::shared_ptr<Playlist> >& s)
3336 Glib::Mutex::Lock lm (playlist_lock);
3337 for (PlaylistList::iterator i = playlists.begin(); i != playlists.end(); ++i) {
3340 for (PlaylistList::iterator i = unused_playlists.begin(); i != unused_playlists.end(); ++i) {
3347 Session::track_playlist (bool inuse, boost::weak_ptr<Playlist> wpl)
3349 boost::shared_ptr<Playlist> pl(wpl.lock());
3355 PlaylistList::iterator x;
3358 /* its not supposed to be visible */
3363 Glib::Mutex::Lock lm (playlist_lock);
3367 unused_playlists.insert (pl);
3369 if ((x = playlists.find (pl)) != playlists.end()) {
3370 playlists.erase (x);
3376 playlists.insert (pl);
3378 if ((x = unused_playlists.find (pl)) != unused_playlists.end()) {
3379 unused_playlists.erase (x);
3386 Session::remove_playlist (boost::weak_ptr<Playlist> weak_playlist)
3388 if (_state_of_the_state & Deletion) {
3392 boost::shared_ptr<Playlist> playlist (weak_playlist.lock());
3399 Glib::Mutex::Lock lm (playlist_lock);
3401 PlaylistList::iterator i;
3403 i = find (playlists.begin(), playlists.end(), playlist);
3404 if (i != playlists.end()) {
3405 playlists.erase (i);
3408 i = find (unused_playlists.begin(), unused_playlists.end(), playlist);
3409 if (i != unused_playlists.end()) {
3410 unused_playlists.erase (i);
3417 PlaylistRemoved (playlist); /* EMIT SIGNAL */
3421 Session::set_audition (boost::shared_ptr<Region> r)
3423 pending_audition_region = r;
3424 post_transport_work = PostTransportWork (post_transport_work | PostTransportAudition);
3425 schedule_butler_transport_work ();
3429 Session::audition_playlist ()
3431 Event* ev = new Event (Event::Audition, Event::Add, Event::Immediate, 0, 0.0);
3432 ev->region.reset ();
3437 Session::non_realtime_set_audition ()
3439 if (!pending_audition_region) {
3440 auditioner->audition_current_playlist ();
3442 auditioner->audition_region (pending_audition_region);
3443 pending_audition_region.reset ();
3445 AuditionActive (true); /* EMIT SIGNAL */
3449 Session::audition_region (boost::shared_ptr<Region> r)
3451 Event* ev = new Event (Event::Audition, Event::Add, Event::Immediate, 0, 0.0);
3457 Session::cancel_audition ()
3459 if (auditioner->active()) {
3460 auditioner->cancel_audition ();
3461 AuditionActive (false); /* EMIT SIGNAL */
3466 Session::RoutePublicOrderSorter::operator() (boost::shared_ptr<Route> a, boost::shared_ptr<Route> b)
3468 return a->order_key(N_("signal")) < b->order_key(N_("signal"));
3472 Session::remove_empty_sounds ()
3474 vector<string> audio_filenames;
3476 get_files_in_directory (_session_dir->sound_path(), audio_filenames);
3478 Glib::Mutex::Lock lm (source_lock);
3480 TapeFileMatcher tape_file_matcher;
3482 remove_if (audio_filenames.begin(), audio_filenames.end(),
3483 sigc::mem_fun (tape_file_matcher, &TapeFileMatcher::matches));
3485 for (vector<string>::iterator i = audio_filenames.begin(); i != audio_filenames.end(); ++i) {
3487 sys::path audio_file_path (_session_dir->sound_path());
3489 audio_file_path /= *i;
3491 if (AudioFileSource::is_empty (*this, audio_file_path.to_string())) {
3495 sys::remove (audio_file_path);
3496 const string peakfile = peak_path (audio_file_path.to_string());
3497 sys::remove (peakfile);
3499 catch (const sys::filesystem_error& err)
3501 error << err.what() << endmsg;
3508 Session::is_auditioning () const
3510 /* can be called before we have an auditioner object */
3512 return auditioner->active();
3519 Session::set_all_solo (bool yn)
3521 shared_ptr<RouteList> r = routes.reader ();
3523 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3524 if (!(*i)->is_hidden()) {
3525 (*i)->set_solo (yn, this);
3533 Session::set_all_mute (bool yn)
3535 shared_ptr<RouteList> r = routes.reader ();
3537 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3538 if (!(*i)->is_hidden()) {
3539 (*i)->set_mute (yn, this);
3547 Session::n_diskstreams () const
3551 boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
3553 for (DiskstreamList::const_iterator i = dsl->begin(); i != dsl->end(); ++i) {
3554 if (!(*i)->hidden()) {
3562 Session::graph_reordered ()
3564 /* don't do this stuff if we are setting up connections
3565 from a set_state() call or creating new tracks.
3568 if (_state_of_the_state & InitialConnecting) {
3572 /* every track/bus asked for this to be handled but it was deferred because
3573 we were connecting. do it now.
3576 request_input_change_handling ();
3580 /* force all diskstreams to update their capture offset values to
3581 reflect any changes in latencies within the graph.
3584 boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
3586 for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
3587 (*i)->set_capture_offset ();
3592 Session::record_disenable_all ()
3594 record_enable_change_all (false);
3598 Session::record_enable_all ()
3600 record_enable_change_all (true);
3604 Session::record_enable_change_all (bool yn)
3606 shared_ptr<RouteList> r = routes.reader ();
3608 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3611 if ((at = dynamic_cast<Track*>((*i).get())) != 0) {
3612 at->set_record_enable (yn, this);
3616 /* since we don't keep rec-enable state, don't mark session dirty */
3620 Session::add_processor (Processor* processor)
3623 PortInsert* port_insert;
3624 PluginInsert* plugin_insert;
3626 if ((port_insert = dynamic_cast<PortInsert *> (processor)) != 0) {
3627 _port_inserts.insert (_port_inserts.begin(), port_insert);
3628 } else if ((plugin_insert = dynamic_cast<PluginInsert *> (processor)) != 0) {
3629 _plugin_inserts.insert (_plugin_inserts.begin(), plugin_insert);
3630 } else if ((send = dynamic_cast<Send *> (processor)) != 0) {
3631 _sends.insert (_sends.begin(), send);
3633 fatal << _("programming error: unknown type of Insert created!") << endmsg;
3637 processor->GoingAway.connect (sigc::bind (mem_fun (*this, &Session::remove_processor), processor));
3643 Session::remove_processor (Processor* processor)
3646 PortInsert* port_insert;
3647 PluginInsert* plugin_insert;
3649 if ((port_insert = dynamic_cast<PortInsert *> (processor)) != 0) {
3650 list<PortInsert*>::iterator x = find (_port_inserts.begin(), _port_inserts.end(), port_insert);
3651 if (x != _port_inserts.end()) {
3652 insert_bitset[port_insert->bit_slot()] = false;
3653 _port_inserts.erase (x);
3655 } else if ((plugin_insert = dynamic_cast<PluginInsert *> (processor)) != 0) {
3656 _plugin_inserts.remove (plugin_insert);
3657 } else if ((send = dynamic_cast<Send *> (processor)) != 0) {
3658 list<Send*>::iterator x = find (_sends.begin(), _sends.end(), send);
3659 if (x != _sends.end()) {
3660 send_bitset[send->bit_slot()] = false;
3664 fatal << _("programming error: unknown type of Insert deleted!") << endmsg;
3672 Session::available_capture_duration ()
3674 float sample_bytes_on_disk = 4.0; // keep gcc happy
3676 switch (Config->get_native_file_data_format()) {
3678 sample_bytes_on_disk = 4.0;
3682 sample_bytes_on_disk = 3.0;
3686 sample_bytes_on_disk = 2.0;
3690 /* impossible, but keep some gcc versions happy */
3691 fatal << string_compose (_("programming error: %1"),
3692 X_("illegal native file data format"))
3697 double scale = 4096.0 / sample_bytes_on_disk;
3699 if (_total_free_4k_blocks * scale > (double) max_frames) {
3703 return (nframes_t) floor (_total_free_4k_blocks * scale);
3707 Session::add_bundle (shared_ptr<Bundle> bundle)
3710 Glib::Mutex::Lock guard (bundle_lock);
3711 _bundles.push_back (bundle);
3714 BundleAdded (bundle); /* EMIT SIGNAL */
3720 Session::remove_bundle (shared_ptr<Bundle> bundle)
3722 bool removed = false;
3725 Glib::Mutex::Lock guard (bundle_lock);
3726 BundleList::iterator i = find (_bundles.begin(), _bundles.end(), bundle);
3728 if (i != _bundles.end()) {
3735 BundleRemoved (bundle); /* EMIT SIGNAL */
3742 Session::bundle_by_name (string name) const
3744 Glib::Mutex::Lock lm (bundle_lock);
3746 for (BundleList::const_iterator i = _bundles.begin(); i != _bundles.end(); ++i) {
3747 if ((*i)->name() == name) {
3752 return boost::shared_ptr<Bundle> ();
3756 Session::tempo_map_changed (Change ignored)
3762 /** Ensures that all buffers (scratch, send, silent, etc) are allocated for
3763 * the given count with the current block size.
3766 Session::ensure_buffers (ChanCount howmany)
3768 if (current_block_size == 0)
3769 return; // too early? (is this ok?)
3771 // We need at least 2 MIDI scratch buffers to mix/merge
3772 if (howmany.n_midi() < 2)
3773 howmany.set_midi(2);
3775 // FIXME: JACK needs to tell us maximum MIDI buffer size
3776 // Using nasty assumption (max # events == nframes) for now
3777 _scratch_buffers->ensure_buffers(howmany, current_block_size);
3778 _mix_buffers->ensure_buffers(howmany, current_block_size);
3779 _silent_buffers->ensure_buffers(howmany, current_block_size);
3781 allocate_pan_automation_buffers (current_block_size, howmany.n_audio(), false);
3785 Session::next_insert_id ()
3787 /* this doesn't really loop forever. just think about it */
3790 for (boost::dynamic_bitset<uint32_t>::size_type n = 0; n < insert_bitset.size(); ++n) {
3791 if (!insert_bitset[n]) {
3792 insert_bitset[n] = true;
3798 /* none available, so resize and try again */
3800 insert_bitset.resize (insert_bitset.size() + 16, false);
3805 Session::next_send_id ()
3807 /* this doesn't really loop forever. just think about it */
3810 for (boost::dynamic_bitset<uint32_t>::size_type n = 0; n < send_bitset.size(); ++n) {
3811 if (!send_bitset[n]) {
3812 send_bitset[n] = true;
3818 /* none available, so resize and try again */
3820 send_bitset.resize (send_bitset.size() + 16, false);
3825 Session::mark_send_id (uint32_t id)
3827 if (id >= send_bitset.size()) {
3828 send_bitset.resize (id+16, false);
3830 if (send_bitset[id]) {
3831 warning << string_compose (_("send ID %1 appears to be in use already"), id) << endmsg;
3833 send_bitset[id] = true;
3837 Session::mark_insert_id (uint32_t id)
3839 if (id >= insert_bitset.size()) {
3840 insert_bitset.resize (id+16, false);
3842 if (insert_bitset[id]) {
3843 warning << string_compose (_("insert ID %1 appears to be in use already"), id) << endmsg;
3845 insert_bitset[id] = true;
3848 /* Named Selection management */
3851 Session::named_selection_by_name (string name)
3853 Glib::Mutex::Lock lm (named_selection_lock);
3854 for (NamedSelectionList::iterator i = named_selections.begin(); i != named_selections.end(); ++i) {
3855 if ((*i)->name == name) {
3863 Session::add_named_selection (NamedSelection* named_selection)
3866 Glib::Mutex::Lock lm (named_selection_lock);
3867 named_selections.insert (named_selections.begin(), named_selection);
3870 for (list<boost::shared_ptr<Playlist> >::iterator i = named_selection->playlists.begin(); i != named_selection->playlists.end(); ++i) {
3876 NamedSelectionAdded (); /* EMIT SIGNAL */
3880 Session::remove_named_selection (NamedSelection* named_selection)
3882 bool removed = false;
3885 Glib::Mutex::Lock lm (named_selection_lock);
3887 NamedSelectionList::iterator i = find (named_selections.begin(), named_selections.end(), named_selection);
3889 if (i != named_selections.end()) {
3891 named_selections.erase (i);
3898 NamedSelectionRemoved (); /* EMIT SIGNAL */
3903 Session::reset_native_file_format ()
3905 boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
3907 for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
3908 (*i)->reset_write_sources (false);
3913 Session::route_name_unique (string n) const
3915 shared_ptr<RouteList> r = routes.reader ();
3917 for (RouteList::const_iterator i = r->begin(); i != r->end(); ++i) {
3918 if ((*i)->name() == n) {
3927 Session::n_playlists () const
3929 Glib::Mutex::Lock lm (playlist_lock);
3930 return playlists.size();
3934 Session::allocate_pan_automation_buffers (nframes_t nframes, uint32_t howmany, bool force)
3936 if (!force && howmany <= _npan_buffers) {
3940 if (_pan_automation_buffer) {
3942 for (uint32_t i = 0; i < _npan_buffers; ++i) {
3943 delete [] _pan_automation_buffer[i];
3946 delete [] _pan_automation_buffer;
3949 _pan_automation_buffer = new pan_t*[howmany];
3951 for (uint32_t i = 0; i < howmany; ++i) {
3952 _pan_automation_buffer[i] = new pan_t[nframes];
3955 _npan_buffers = howmany;
3959 Session::freeze (InterThreadInfo& itt)
3961 shared_ptr<RouteList> r = routes.reader ();
3963 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3967 if ((at = dynamic_cast<Track*>((*i).get())) != 0) {
3968 /* XXX this is wrong because itt.progress will keep returning to zero at the start
3979 Session::write_one_audio_track (AudioTrack& track, nframes_t start, nframes_t len,
3980 bool overwrite, vector<boost::shared_ptr<Source> >& srcs, InterThreadInfo& itt)
3983 boost::shared_ptr<Playlist> playlist;
3984 boost::shared_ptr<AudioFileSource> fsource;
3986 char buf[PATH_MAX+1];
3987 ChanCount nchans(track.audio_diskstream()->n_channels());
3989 nframes_t this_chunk;
3992 SessionDirectory sdir(get_best_session_directory_for_new_source ());
3993 const string sound_dir = sdir.sound_path().to_string();
3995 // any bigger than this seems to cause stack overflows in called functions
3996 const nframes_t chunk_size = (128 * 1024)/4;
3998 g_atomic_int_set (&processing_prohibited, 1);
4000 /* call tree *MUST* hold route_lock */
4002 if ((playlist = track.diskstream()->playlist()) == 0) {
4006 /* external redirects will be a problem */
4008 if (track.has_external_redirects()) {
4012 for (uint32_t chan_n=0; chan_n < nchans.n_audio(); ++chan_n) {
4014 for (x = 0; x < 99999; ++x) {
4015 snprintf (buf, sizeof(buf), "%s/%s-%d-bounce-%" PRIu32 ".wav", sound_dir.c_str(), playlist->name().c_str(), chan_n, x+1);
4016 if (access (buf, F_OK) != 0) {
4022 error << string_compose (_("too many bounced versions of playlist \"%1\""), playlist->name()) << endmsg;
4027 fsource = boost::dynamic_pointer_cast<AudioFileSource> (
4028 SourceFactory::createWritable (DataType::AUDIO, *this, buf, false, frame_rate()));
4031 catch (failed_constructor& err) {
4032 error << string_compose (_("cannot create new audio file \"%1\" for %2"), buf, track.name()) << endmsg;
4036 srcs.push_back (fsource);
4039 /* XXX need to flush all redirects */
4044 /* create a set of reasonably-sized buffers */
4045 buffers.ensure_buffers(nchans, chunk_size);
4046 buffers.set_count(nchans);
4048 for (vector<boost::shared_ptr<Source> >::iterator src=srcs.begin(); src != srcs.end(); ++src) {
4049 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
4051 afs->prepare_for_peakfile_writes ();
4054 while (to_do && !itt.cancel) {
4056 this_chunk = min (to_do, chunk_size);
4058 if (track.export_stuff (buffers, start, this_chunk)) {
4063 for (vector<boost::shared_ptr<Source> >::iterator src=srcs.begin(); src != srcs.end(); ++src, ++n) {
4064 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
4067 if (afs->write (buffers.get_audio(n).data(), this_chunk) != this_chunk) {
4073 start += this_chunk;
4074 to_do -= this_chunk;
4076 itt.progress = (float) (1.0 - ((double) to_do / len));
4085 xnow = localtime (&now);
4087 for (vector<boost::shared_ptr<Source> >::iterator src=srcs.begin(); src != srcs.end(); ++src) {
4088 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
4091 afs->update_header (position, *xnow, now);
4092 afs->flush_header ();
4096 /* construct a region to represent the bounced material */
4098 boost::shared_ptr<Region> aregion = RegionFactory::create (srcs, 0, srcs.front()->length(),
4099 region_name_from_path (srcs.front()->name(), true));
4106 for (vector<boost::shared_ptr<Source> >::iterator src = srcs.begin(); src != srcs.end(); ++src) {
4107 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
4110 afs->mark_for_remove ();
4113 (*src)->drop_references ();
4117 for (vector<boost::shared_ptr<Source> >::iterator src = srcs.begin(); src != srcs.end(); ++src) {
4118 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
4121 afs->done_with_peakfile_writes ();
4125 g_atomic_int_set (&processing_prohibited, 0);
4131 Session::get_silent_buffers (ChanCount count)
4133 assert(_silent_buffers->available() >= count);
4134 _silent_buffers->set_count(count);
4136 for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
4137 for (size_t i=0; i < count.get(*t); ++i) {
4138 _silent_buffers->get(*t, i).clear();
4142 return *_silent_buffers;
4146 Session::get_scratch_buffers (ChanCount count)
4148 assert(_scratch_buffers->available() >= count);
4149 _scratch_buffers->set_count(count);
4150 return *_scratch_buffers;
4154 Session::get_mix_buffers (ChanCount count)
4156 assert(_mix_buffers->available() >= count);
4157 _mix_buffers->set_count(count);
4158 return *_mix_buffers;
4162 Session::ntracks () const
4165 shared_ptr<RouteList> r = routes.reader ();
4167 for (RouteList::const_iterator i = r->begin(); i != r->end(); ++i) {
4168 if (dynamic_cast<Track*> ((*i).get())) {
4177 Session::nbusses () const
4180 shared_ptr<RouteList> r = routes.reader ();
4182 for (RouteList::const_iterator i = r->begin(); i != r->end(); ++i) {
4183 if (dynamic_cast<Track*> ((*i).get()) == 0) {
4192 Session::add_automation_list(AutomationList *al)
4194 automation_lists[al->id()] = al;
4198 Session::compute_initial_length ()
4200 return _engine.frame_rate() * 60 * 5;
4204 Session::sync_order_keys ()
4206 if (!Config->get_sync_all_route_ordering()) {
4207 /* leave order keys as they are */
4211 boost::shared_ptr<RouteList> r = routes.reader ();
4213 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4214 (*i)->sync_order_keys ();
4217 Route::SyncOrderKeys (); // EMIT SIGNAL
4221 Session::foreach_bundle (sigc::slot<void, boost::shared_ptr<Bundle> > sl)
4223 Glib::Mutex::Lock lm (bundle_lock);
4224 for (BundleList::iterator i = _bundles.begin(); i != _bundles.end(); ++i) {