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/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),
129 if (!eng.connected()) {
130 throw failed_constructor();
133 n_physical_outputs = _engine.n_physical_outputs();
134 n_physical_inputs = _engine.n_physical_inputs();
136 first_stage_init (fullpath, snapshot_name);
138 initialize_start_and_end_locations(0, compute_initial_length ());
141 // try and create a new session directory
144 if(!_session_dir->create()) {
145 // an existing session.
146 // throw a_more_meaningful_exception()
148 throw failed_constructor ();
151 catch(sys::filesystem_error& ex)
154 throw failed_constructor ();
157 if(!create_session_file_from_template (*mix_template)) {
159 throw failed_constructor ();
162 cerr << "Creating session " << fullpath
163 <<" using template" << *mix_template
166 // must be an existing session
169 // ensure the necessary session subdirectories exist
170 // in case the directory structure has changed etc.
171 _session_dir->create();
173 catch(sys::filesystem_error& ex)
176 throw failed_constructor ();
179 cerr << "Loading session " << fullpath
180 << " using snapshot " << snapshot_name << " (1)"
184 if (second_stage_init (false)) {
186 throw failed_constructor ();
189 store_recent_sessions(_name, _path);
191 bool was_dirty = dirty();
193 _state_of_the_state = StateOfTheState (_state_of_the_state & ~Dirty);
195 Config->ParameterChanged.connect (mem_fun (*this, &Session::config_changed));
198 DirtyChanged (); /* EMIT SIGNAL */
202 Session::Session (AudioEngine &eng,
204 string snapshot_name,
205 AutoConnectOption input_ac,
206 AutoConnectOption output_ac,
207 uint32_t control_out_channels,
208 uint32_t master_out_channels,
209 uint32_t requested_physical_in,
210 uint32_t requested_physical_out,
211 nframes_t initial_length)
214 _scratch_buffers(new BufferSet()),
215 _silent_buffers(new BufferSet()),
216 _mix_buffers(new BufferSet()),
217 _mmc_port (default_mmc_port),
218 _mtc_port (default_mtc_port),
219 _midi_port (default_midi_port),
220 _session_dir ( new SessionDirectory(fullpath)),
221 pending_events (2048),
222 //midi_requests (16),
223 _send_smpte_update (false),
224 diskstreams (new DiskstreamList),
225 routes (new RouteList),
229 if (!eng.connected()) {
230 throw failed_constructor();
233 cerr << "Loading session " << fullpath << " using snapshot " << snapshot_name << " (2)" << endl;
235 n_physical_outputs = _engine.n_physical_outputs();
236 n_physical_inputs = _engine.n_physical_inputs();
238 if (n_physical_inputs) {
239 n_physical_inputs = max (requested_physical_in, n_physical_inputs);
242 if (n_physical_outputs) {
243 n_physical_outputs = max (requested_physical_out, n_physical_outputs);
246 first_stage_init (fullpath, snapshot_name);
248 initialize_start_and_end_locations(0, initial_length);
250 if (!_session_dir->create () || !create_session_file ()) {
252 throw failed_constructor ();
256 /* set up Master Out and Control Out if necessary */
261 if (control_out_channels) {
262 shared_ptr<Route> r (new Route (*this, _("monitor"), -1, control_out_channels, -1, control_out_channels, Route::ControlOut));
263 r->set_remote_control_id (control_id++);
268 if (master_out_channels) {
269 shared_ptr<Route> r (new Route (*this, _("master"), -1, master_out_channels, -1, master_out_channels, Route::MasterOut));
270 r->set_remote_control_id (control_id);
274 /* prohibit auto-connect to master, because there isn't one */
275 output_ac = AutoConnectOption (output_ac & ~AutoConnectMaster);
284 Config->set_input_auto_connect (input_ac);
285 Config->set_output_auto_connect (output_ac);
287 if (second_stage_init (true)) {
289 throw failed_constructor ();
292 store_recent_sessions(_name, _path);
294 bool was_dirty = dirty ();
296 _state_of_the_state = StateOfTheState (_state_of_the_state & ~Dirty);
298 Config->ParameterChanged.connect (mem_fun (*this, &Session::config_changed));
301 DirtyChanged (); /* EMIT SIGNAL */
313 /* if we got to here, leaving pending capture state around
317 remove_pending_capture_state ();
319 _state_of_the_state = StateOfTheState (CannotSave|Deletion);
320 _engine.remove_session ();
322 GoingAway (); /* EMIT SIGNAL */
328 /* clear history so that no references to objects are held any more */
332 /* clear state tree so that no references to objects are held any more */
338 terminate_butler_thread ();
339 //terminate_midi_thread ();
341 if (click_data && click_data != default_click) {
342 delete [] click_data;
345 if (click_emphasis_data && click_emphasis_data != default_click_emphasis) {
346 delete [] click_emphasis_data;
351 delete _scratch_buffers;
352 delete _silent_buffers;
355 AudioDiskstream::free_working_buffers();
357 #undef TRACK_DESTRUCTION
358 #ifdef TRACK_DESTRUCTION
359 cerr << "delete named selections\n";
360 #endif /* TRACK_DESTRUCTION */
361 for (NamedSelectionList::iterator i = named_selections.begin(); i != named_selections.end(); ) {
362 NamedSelectionList::iterator tmp;
371 #ifdef TRACK_DESTRUCTION
372 cerr << "delete playlists\n";
373 #endif /* TRACK_DESTRUCTION */
374 for (PlaylistList::iterator i = playlists.begin(); i != playlists.end(); ) {
375 PlaylistList::iterator tmp;
380 (*i)->drop_references ();
385 for (PlaylistList::iterator i = unused_playlists.begin(); i != unused_playlists.end(); ) {
386 PlaylistList::iterator tmp;
391 (*i)->drop_references ();
397 unused_playlists.clear ();
399 #ifdef TRACK_DESTRUCTION
400 cerr << "delete regions\n";
401 #endif /* TRACK_DESTRUCTION */
403 for (RegionList::iterator i = regions.begin(); i != regions.end(); ) {
404 RegionList::iterator tmp;
409 i->second->drop_references ();
416 #ifdef TRACK_DESTRUCTION
417 cerr << "delete routes\n";
418 #endif /* TRACK_DESTRUCTION */
420 RCUWriter<RouteList> writer (routes);
421 boost::shared_ptr<RouteList> r = writer.get_copy ();
422 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
423 (*i)->drop_references ();
426 /* writer goes out of scope and updates master */
431 #ifdef TRACK_DESTRUCTION
432 cerr << "delete diskstreams\n";
433 #endif /* TRACK_DESTRUCTION */
435 RCUWriter<DiskstreamList> dwriter (diskstreams);
436 boost::shared_ptr<DiskstreamList> dsl = dwriter.get_copy();
437 for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
438 (*i)->drop_references ();
442 diskstreams.flush ();
444 #ifdef TRACK_DESTRUCTION
445 cerr << "delete audio sources\n";
446 #endif /* TRACK_DESTRUCTION */
447 for (SourceMap::iterator i = sources.begin(); i != sources.end(); ) {
448 SourceMap::iterator tmp;
453 i->second->drop_references ();
460 #ifdef TRACK_DESTRUCTION
461 cerr << "delete mix groups\n";
462 #endif /* TRACK_DESTRUCTION */
463 for (list<RouteGroup *>::iterator i = mix_groups.begin(); i != mix_groups.end(); ) {
464 list<RouteGroup*>::iterator tmp;
474 #ifdef TRACK_DESTRUCTION
475 cerr << "delete edit groups\n";
476 #endif /* TRACK_DESTRUCTION */
477 for (list<RouteGroup *>::iterator i = edit_groups.begin(); i != edit_groups.end(); ) {
478 list<RouteGroup*>::iterator tmp;
488 if (butler_mixdown_buffer) {
489 delete [] butler_mixdown_buffer;
492 if (butler_gain_buffer) {
493 delete [] butler_gain_buffer;
496 Crossfade::set_buffer_size (0);
504 Session::set_worst_io_latencies ()
506 _worst_output_latency = 0;
507 _worst_input_latency = 0;
509 if (!_engine.connected()) {
513 boost::shared_ptr<RouteList> r = routes.reader ();
515 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
516 _worst_output_latency = max (_worst_output_latency, (*i)->output_latency());
517 _worst_input_latency = max (_worst_input_latency, (*i)->input_latency());
522 Session::when_engine_running ()
524 string first_physical_output;
526 /* we don't want to run execute this again */
528 set_block_size (_engine.frames_per_cycle());
529 set_frame_rate (_engine.frame_rate());
531 Config->map_parameters (mem_fun (*this, &Session::config_changed));
533 /* every time we reconnect, recompute worst case output latencies */
535 _engine.Running.connect (mem_fun (*this, &Session::set_worst_io_latencies));
537 if (synced_to_jack()) {
538 _engine.transport_stop ();
541 if (Config->get_jack_time_master()) {
542 _engine.transport_locate (_transport_frame);
550 _click_io.reset (new ClickIO (*this, "click", 0, 0, -1, -1));
552 if (state_tree && (child = find_named_node (*state_tree->root(), "Click")) != 0) {
554 /* existing state for Click */
556 if (_click_io->set_state (*child->children().front()) == 0) {
558 _clicking = Config->get_clicking ();
562 error << _("could not setup Click I/O") << endmsg;
568 /* default state for Click */
570 first_physical_output = _engine.get_nth_physical_output (DataType::AUDIO, 0);
572 if (first_physical_output.length()) {
573 if (_click_io->add_output_port (first_physical_output, this)) {
574 // relax, even though its an error
576 _clicking = Config->get_clicking ();
582 catch (failed_constructor& err) {
583 error << _("cannot setup Click I/O") << endmsg;
586 set_worst_io_latencies ();
589 // XXX HOW TO ALERT UI TO THIS ? DO WE NEED TO?
592 /* Create a set of Bundle objects that map
593 to the physical outputs currently available
598 for (uint32_t np = 0; np < n_physical_outputs; ++np) {
600 snprintf (buf, sizeof (buf), _("out %" PRIu32), np+1);
602 shared_ptr<Bundle> c (new InputBundle (buf, true));
603 c->set_nchannels (1);
604 c->add_port_to_channel (0, _engine.get_nth_physical_output (DataType::AUDIO, np));
609 for (uint32_t np = 0; np < n_physical_inputs; ++np) {
611 snprintf (buf, sizeof (buf), _("in %" PRIu32), np+1);
613 shared_ptr<Bundle> c (new OutputBundle (buf, true));
614 c->set_nchannels (1);
615 c->add_port_to_channel (0, _engine.get_nth_physical_input (DataType::AUDIO, np));
622 for (uint32_t np = 0; np < n_physical_outputs; np +=2) {
624 snprintf (buf, sizeof (buf), _("out %" PRIu32 "+%" PRIu32), np+1, np+2);
626 shared_ptr<Bundle> c (new InputBundle (buf, true));
627 c->set_nchannels (2);
628 c->add_port_to_channel (0, _engine.get_nth_physical_output (DataType::AUDIO, np));
629 c->add_port_to_channel (1, _engine.get_nth_physical_output (DataType::AUDIO, np+1));
634 for (uint32_t np = 0; np < n_physical_inputs; np +=2) {
636 snprintf (buf, sizeof (buf), _("in %" PRIu32 "+%" PRIu32), np+1, np+2);
638 shared_ptr<Bundle> c (new OutputBundle (buf, true));
639 c->set_nchannels (2);
640 c->add_port_to_channel (0, _engine.get_nth_physical_input (DataType::AUDIO, np));
641 c->add_port_to_channel (1, _engine.get_nth_physical_input (DataType::AUDIO, np+1));
650 /* create master/control ports */
655 /* force the master to ignore any later call to this */
657 if (_master_out->pending_state_node) {
658 _master_out->ports_became_legal();
661 /* no panner resets till we are through */
663 _master_out->defer_pan_reset ();
665 while (_master_out->n_inputs().n_audio()
666 < _master_out->input_maximum().n_audio()) {
667 if (_master_out->add_input_port ("", this, DataType::AUDIO)) {
668 error << _("cannot setup master inputs")
674 while (_master_out->n_outputs().n_audio()
675 < _master_out->output_maximum().n_audio()) {
676 if (_master_out->add_output_port (_engine.get_nth_physical_output (DataType::AUDIO, n), this, DataType::AUDIO)) {
677 error << _("cannot setup master outputs")
684 _master_out->allow_pan_reset ();
688 shared_ptr<Bundle> c (new OutputBundle (_("Master Out"), true));
690 c->set_nchannels (_master_out->n_inputs().n_total());
691 for (uint32_t n = 0; n < _master_out->n_inputs ().n_total(); ++n) {
692 c->add_port_to_channel ((int) n, _master_out->input(n)->name());
699 /* catch up on send+insert cnts */
703 for (list<PortInsert*>::iterator i = _port_inserts.begin(); i != _port_inserts.end(); ++i) {
706 if (sscanf ((*i)->name().c_str(), "%*s %u", &id) == 1) {
707 if (id > insert_cnt) {
715 for (list<Send*>::iterator i = _sends.begin(); i != _sends.end(); ++i) {
718 if (sscanf ((*i)->name().c_str(), "%*s %u", &id) == 1) {
726 _state_of_the_state = StateOfTheState (_state_of_the_state & ~(CannotSave|Dirty));
728 /* hook us up to the engine */
730 _engine.set_session (this);
735 osc->set_session (*this);
738 _state_of_the_state = Clean;
740 DirtyChanged (); /* EMIT SIGNAL */
744 Session::hookup_io ()
746 /* stop graph reordering notifications from
747 causing resorts, etc.
750 _state_of_the_state = StateOfTheState (_state_of_the_state | InitialConnecting);
752 if (auditioner == 0) {
754 /* we delay creating the auditioner till now because
755 it makes its own connections to ports.
756 the engine has to be running for this to work.
760 auditioner.reset (new Auditioner (*this));
763 catch (failed_constructor& err) {
764 warning << _("cannot create Auditioner: no auditioning of regions possible") << endmsg;
768 /* Tell all IO objects to create their ports */
774 vector<string> cports;
776 while (_control_out->n_inputs().n_audio() < _control_out->input_maximum().n_audio()) {
777 if (_control_out->add_input_port ("", this)) {
778 error << _("cannot setup control inputs")
784 while (_control_out->n_outputs().n_audio() < _control_out->output_maximum().n_audio()) {
785 if (_control_out->add_output_port (_engine.get_nth_physical_output (DataType::AUDIO, n), this)) {
786 error << _("cannot set up master outputs")
794 uint32_t ni = _control_out->n_inputs().get (DataType::AUDIO);
796 for (n = 0; n < ni; ++n) {
797 cports.push_back (_control_out->input(n)->name());
800 boost::shared_ptr<RouteList> r = routes.reader ();
802 for (RouteList::iterator x = r->begin(); x != r->end(); ++x) {
803 (*x)->set_control_outs (cports);
807 /* Tell all IO objects to connect themselves together */
809 IO::enable_connecting ();
811 /* Now reset all panners */
813 IO::reset_panners ();
815 /* Anyone who cares about input state, wake up and do something */
817 IOConnectionsComplete (); /* EMIT SIGNAL */
819 _state_of_the_state = StateOfTheState (_state_of_the_state & ~InitialConnecting);
821 /* now handle the whole enchilada as if it was one
827 /* update mixer solo state */
833 Session::playlist_length_changed ()
835 /* we can't just increase end_location->end() if pl->get_maximum_extent()
836 if larger. if the playlist used to be the longest playlist,
837 and its now shorter, we have to decrease end_location->end(). hence,
838 we have to iterate over all diskstreams and check the
839 playlists currently in use.
845 Session::diskstream_playlist_changed (boost::shared_ptr<Diskstream> dstream)
847 boost::shared_ptr<Playlist> playlist;
849 if ((playlist = dstream->playlist()) != 0) {
850 playlist->LengthChanged.connect (mem_fun (this, &Session::playlist_length_changed));
853 /* see comment in playlist_length_changed () */
858 Session::record_enabling_legal () const
860 /* this used to be in here, but survey says.... we don't need to restrict it */
861 // if (record_status() == Recording) {
865 if (Config->get_all_safe()) {
872 Session::reset_input_monitor_state ()
874 if (transport_rolling()) {
876 boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
878 for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
879 if ((*i)->record_enabled ()) {
880 //cerr << "switching to input = " << !auto_input << __FILE__ << __LINE__ << endl << endl;
881 (*i)->monitor_input (Config->get_monitoring_model() == HardwareMonitoring && !Config->get_auto_input());
885 boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
887 for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
888 if ((*i)->record_enabled ()) {
889 //cerr << "switching to input = " << !Config->get_auto_input() << __FILE__ << __LINE__ << endl << endl;
890 (*i)->monitor_input (Config->get_monitoring_model() == HardwareMonitoring);
897 Session::auto_punch_start_changed (Location* location)
899 replace_event (Event::PunchIn, location->start());
901 if (get_record_enabled() && Config->get_punch_in()) {
902 /* capture start has been changed, so save new pending state */
903 save_state ("", true);
908 Session::auto_punch_end_changed (Location* location)
910 nframes_t when_to_stop = location->end();
911 // when_to_stop += _worst_output_latency + _worst_input_latency;
912 replace_event (Event::PunchOut, when_to_stop);
916 Session::auto_punch_changed (Location* location)
918 nframes_t when_to_stop = location->end();
920 replace_event (Event::PunchIn, location->start());
921 //when_to_stop += _worst_output_latency + _worst_input_latency;
922 replace_event (Event::PunchOut, when_to_stop);
926 Session::auto_loop_changed (Location* location)
928 replace_event (Event::AutoLoop, location->end(), location->start());
930 if (transport_rolling() && play_loop) {
932 //if (_transport_frame < location->start() || _transport_frame > location->end()) {
934 if (_transport_frame > location->end()) {
935 // relocate to beginning of loop
936 clear_events (Event::LocateRoll);
938 request_locate (location->start(), true);
941 else if (Config->get_seamless_loop() && !loop_changing) {
943 // schedule a locate-roll to refill the diskstreams at the
945 loop_changing = true;
947 if (location->end() > last_loopend) {
948 clear_events (Event::LocateRoll);
949 Event *ev = new Event (Event::LocateRoll, Event::Add, last_loopend, last_loopend, 0, true);
956 last_loopend = location->end();
961 Session::set_auto_punch_location (Location* location)
965 if ((existing = _locations.auto_punch_location()) != 0 && existing != location) {
966 auto_punch_start_changed_connection.disconnect();
967 auto_punch_end_changed_connection.disconnect();
968 auto_punch_changed_connection.disconnect();
969 existing->set_auto_punch (false, this);
970 remove_event (existing->start(), Event::PunchIn);
971 clear_events (Event::PunchOut);
972 auto_punch_location_changed (0);
981 if (location->end() <= location->start()) {
982 error << _("Session: you can't use that location for auto punch (start <= end)") << endmsg;
986 auto_punch_start_changed_connection.disconnect();
987 auto_punch_end_changed_connection.disconnect();
988 auto_punch_changed_connection.disconnect();
990 auto_punch_start_changed_connection = location->start_changed.connect (mem_fun (this, &Session::auto_punch_start_changed));
991 auto_punch_end_changed_connection = location->end_changed.connect (mem_fun (this, &Session::auto_punch_end_changed));
992 auto_punch_changed_connection = location->changed.connect (mem_fun (this, &Session::auto_punch_changed));
994 location->set_auto_punch (true, this);
995 auto_punch_location_changed (location);
999 Session::set_auto_loop_location (Location* location)
1003 if ((existing = _locations.auto_loop_location()) != 0 && existing != location) {
1004 auto_loop_start_changed_connection.disconnect();
1005 auto_loop_end_changed_connection.disconnect();
1006 auto_loop_changed_connection.disconnect();
1007 existing->set_auto_loop (false, this);
1008 remove_event (existing->end(), Event::AutoLoop);
1009 auto_loop_location_changed (0);
1014 if (location == 0) {
1018 if (location->end() <= location->start()) {
1019 error << _("Session: you can't use a mark for auto loop") << endmsg;
1023 last_loopend = location->end();
1025 auto_loop_start_changed_connection.disconnect();
1026 auto_loop_end_changed_connection.disconnect();
1027 auto_loop_changed_connection.disconnect();
1029 auto_loop_start_changed_connection = location->start_changed.connect (mem_fun (this, &Session::auto_loop_changed));
1030 auto_loop_end_changed_connection = location->end_changed.connect (mem_fun (this, &Session::auto_loop_changed));
1031 auto_loop_changed_connection = location->changed.connect (mem_fun (this, &Session::auto_loop_changed));
1033 location->set_auto_loop (true, this);
1034 auto_loop_location_changed (location);
1038 Session::locations_added (Location* ignored)
1044 Session::locations_changed ()
1046 _locations.apply (*this, &Session::handle_locations_changed);
1050 Session::handle_locations_changed (Locations::LocationList& locations)
1052 Locations::LocationList::iterator i;
1054 bool set_loop = false;
1055 bool set_punch = false;
1057 for (i = locations.begin(); i != locations.end(); ++i) {
1061 if (location->is_auto_punch()) {
1062 set_auto_punch_location (location);
1065 if (location->is_auto_loop()) {
1066 set_auto_loop_location (location);
1073 set_auto_loop_location (0);
1076 set_auto_punch_location (0);
1083 Session::enable_record ()
1085 /* XXX really atomic compare+swap here */
1086 if (g_atomic_int_get (&_record_status) != Recording) {
1087 g_atomic_int_set (&_record_status, Recording);
1088 _last_record_location = _transport_frame;
1089 deliver_mmc(MIDI::MachineControl::cmdRecordStrobe, _last_record_location);
1091 if (Config->get_monitoring_model() == HardwareMonitoring && Config->get_auto_input()) {
1092 boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
1093 for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
1094 if ((*i)->record_enabled ()) {
1095 (*i)->monitor_input (true);
1100 RecordStateChanged ();
1105 Session::disable_record (bool rt_context, bool force)
1109 if ((rs = (RecordState) g_atomic_int_get (&_record_status)) != Disabled) {
1111 if ((!Config->get_latched_record_enable () && !play_loop) || force) {
1112 g_atomic_int_set (&_record_status, Disabled);
1114 if (rs == Recording) {
1115 g_atomic_int_set (&_record_status, Enabled);
1119 // FIXME: timestamp correct? [DR]
1120 // FIXME FIXME FIXME: rt_context? this must be called in the process thread.
1121 // does this /need/ to be sent in all cases?
1123 deliver_mmc (MIDI::MachineControl::cmdRecordExit, _transport_frame);
1125 if (Config->get_monitoring_model() == HardwareMonitoring && Config->get_auto_input()) {
1126 boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
1128 for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
1129 if ((*i)->record_enabled ()) {
1130 (*i)->monitor_input (false);
1135 RecordStateChanged (); /* emit signal */
1138 remove_pending_capture_state ();
1144 Session::step_back_from_record ()
1146 /* XXX really atomic compare+swap here */
1147 if (g_atomic_int_get (&_record_status) == Recording) {
1148 g_atomic_int_set (&_record_status, Enabled);
1150 if (Config->get_monitoring_model() == HardwareMonitoring) {
1151 boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
1153 for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
1154 if (Config->get_auto_input() && (*i)->record_enabled ()) {
1155 //cerr << "switching from input" << __FILE__ << __LINE__ << endl << endl;
1156 (*i)->monitor_input (false);
1164 Session::maybe_enable_record ()
1166 g_atomic_int_set (&_record_status, Enabled);
1168 /* this function is currently called from somewhere other than an RT thread.
1169 this save_state() call therefore doesn't impact anything.
1172 save_state ("", true);
1174 if (_transport_speed) {
1175 if (!Config->get_punch_in()) {
1179 deliver_mmc (MIDI::MachineControl::cmdRecordPause, _transport_frame);
1180 RecordStateChanged (); /* EMIT SIGNAL */
1187 Session::audible_frame () const
1193 /* the first of these two possible settings for "offset"
1194 mean that the audible frame is stationary until
1195 audio emerges from the latency compensation
1198 the second means that the audible frame is stationary
1199 until audio would emerge from a physical port
1200 in the absence of any plugin latency compensation
1203 offset = _worst_output_latency;
1205 if (offset > current_block_size) {
1206 offset -= current_block_size;
1208 /* XXX is this correct? if we have no external
1209 physical connections and everything is internal
1210 then surely this is zero? still, how
1211 likely is that anyway?
1213 offset = current_block_size;
1216 if (synced_to_jack()) {
1217 tf = _engine.transport_frame();
1219 tf = _transport_frame;
1222 if (_transport_speed == 0) {
1232 if (!non_realtime_work_pending()) {
1236 /* take latency into account */
1245 Session::set_frame_rate (nframes_t frames_per_second)
1247 /** \fn void Session::set_frame_size(nframes_t)
1248 the AudioEngine object that calls this guarantees
1249 that it will not be called while we are also in
1250 ::process(). Its fine to do things that block
1254 _base_frame_rate = frames_per_second;
1258 Automatable::set_automation_interval ((jack_nframes_t) ceil ((double) frames_per_second * (0.001 * Config->get_automation_interval())));
1262 // XXX we need some equivalent to this, somehow
1263 // SndFileSource::setup_standard_crossfades (frames_per_second);
1267 /* XXX need to reset/reinstantiate all LADSPA plugins */
1271 Session::set_block_size (nframes_t nframes)
1273 /* the AudioEngine guarantees
1274 that it will not be called while we are also in
1275 ::process(). It is therefore fine to do things that block
1281 current_block_size = nframes;
1283 ensure_buffers(_scratch_buffers->available());
1285 if (_gain_automation_buffer) {
1286 delete [] _gain_automation_buffer;
1288 _gain_automation_buffer = new gain_t[nframes];
1290 allocate_pan_automation_buffers (nframes, _npan_buffers, true);
1292 boost::shared_ptr<RouteList> r = routes.reader ();
1294 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
1295 (*i)->set_block_size (nframes);
1298 boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
1299 for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
1300 (*i)->set_block_size (nframes);
1303 set_worst_io_latencies ();
1308 Session::set_default_fade (float steepness, float fade_msecs)
1311 nframes_t fade_frames;
1313 /* Don't allow fade of less 1 frame */
1315 if (fade_msecs < (1000.0 * (1.0/_current_frame_rate))) {
1322 fade_frames = (nframes_t) floor (fade_msecs * _current_frame_rate * 0.001);
1326 default_fade_msecs = fade_msecs;
1327 default_fade_steepness = steepness;
1330 // jlc, WTF is this!
1331 Glib::RWLock::ReaderLock lm (route_lock);
1332 AudioRegion::set_default_fade (steepness, fade_frames);
1337 /* XXX have to do this at some point */
1338 /* foreach region using default fade, reset, then
1339 refill_all_diskstream_buffers ();
1344 struct RouteSorter {
1345 bool operator() (boost::shared_ptr<Route> r1, boost::shared_ptr<Route> r2) {
1346 if (r1->fed_by.find (r2) != r1->fed_by.end()) {
1348 } else if (r2->fed_by.find (r1) != r2->fed_by.end()) {
1351 if (r1->fed_by.empty()) {
1352 if (r2->fed_by.empty()) {
1353 /* no ardour-based connections inbound to either route. just use signal order */
1354 return r1->order_key(N_("signal")) < r2->order_key(N_("signal"));
1356 /* r2 has connections, r1 does not; run r1 early */
1360 return r1->order_key(N_("signal")) < r2->order_key(N_("signal"));
1367 trace_terminal (shared_ptr<Route> r1, shared_ptr<Route> rbase)
1369 shared_ptr<Route> r2;
1371 if ((r1->fed_by.find (rbase) != r1->fed_by.end()) && (rbase->fed_by.find (r1) != rbase->fed_by.end())) {
1372 info << string_compose(_("feedback loop setup between %1 and %2"), r1->name(), rbase->name()) << endmsg;
1376 /* make a copy of the existing list of routes that feed r1 */
1378 set<shared_ptr<Route> > existing = r1->fed_by;
1380 /* for each route that feeds r1, recurse, marking it as feeding
1384 for (set<shared_ptr<Route> >::iterator i = existing.begin(); i != existing.end(); ++i) {
1387 /* r2 is a route that feeds r1 which somehow feeds base. mark
1388 base as being fed by r2
1391 rbase->fed_by.insert (r2);
1395 /* 2nd level feedback loop detection. if r1 feeds or is fed by r2,
1399 if ((r1->fed_by.find (r2) != r1->fed_by.end()) && (r2->fed_by.find (r1) != r2->fed_by.end())) {
1403 /* now recurse, so that we can mark base as being fed by
1404 all routes that feed r2
1407 trace_terminal (r2, rbase);
1414 Session::resort_routes ()
1416 /* don't do anything here with signals emitted
1417 by Routes while we are being destroyed.
1420 if (_state_of_the_state & Deletion) {
1427 RCUWriter<RouteList> writer (routes);
1428 shared_ptr<RouteList> r = writer.get_copy ();
1429 resort_routes_using (r);
1430 /* writer goes out of scope and forces update */
1435 Session::resort_routes_using (shared_ptr<RouteList> r)
1437 RouteList::iterator i, j;
1439 for (i = r->begin(); i != r->end(); ++i) {
1441 (*i)->fed_by.clear ();
1443 for (j = r->begin(); j != r->end(); ++j) {
1445 /* although routes can feed themselves, it will
1446 cause an endless recursive descent if we
1447 detect it. so don't bother checking for
1455 if ((*j)->feeds (*i)) {
1456 (*i)->fed_by.insert (*j);
1461 for (i = r->begin(); i != r->end(); ++i) {
1462 trace_terminal (*i, *i);
1469 cerr << "finished route resort\n";
1471 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
1472 cerr << " " << (*i)->name() << " signal order = " << (*i)->order_key ("signal") << endl;
1479 list<boost::shared_ptr<MidiTrack> >
1480 Session::new_midi_track (TrackMode mode, uint32_t how_many)
1482 char track_name[32];
1483 uint32_t track_id = 0;
1486 RouteList new_routes;
1487 list<boost::shared_ptr<MidiTrack> > ret;
1488 //uint32_t control_id;
1490 // FIXME: need physical I/O and autoconnect stuff for MIDI
1492 /* count existing midi tracks */
1495 shared_ptr<RouteList> r = routes.reader ();
1497 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
1498 if (dynamic_cast<MidiTrack*>((*i).get()) != 0) {
1499 if (!(*i)->is_hidden()) {
1501 //channels_used += (*i)->n_inputs().n_midi();
1508 vector<string> physinputs;
1509 vector<string> physoutputs;
1510 uint32_t nphysical_in;
1511 uint32_t nphysical_out;
1513 _engine.get_physical_outputs (physoutputs);
1514 _engine.get_physical_inputs (physinputs);
1515 control_id = ntracks() + nbusses() + 1;
1520 /* check for duplicate route names, since we might have pre-existing
1521 routes with this name (e.g. create Audio1, Audio2, delete Audio1,
1522 save, close,restart,add new route - first named route is now
1530 snprintf (track_name, sizeof(track_name), "Midi %" PRIu32, track_id);
1532 if (route_by_name (track_name) == 0) {
1536 } while (track_id < (UINT_MAX-1));
1539 if (Config->get_input_auto_connect() & AutoConnectPhysical) {
1540 nphysical_in = min (n_physical_inputs, (uint32_t) physinputs.size());
1545 if (Config->get_output_auto_connect() & AutoConnectPhysical) {
1546 nphysical_out = min (n_physical_outputs, (uint32_t) physinputs.size());
1552 shared_ptr<MidiTrack> track;
1555 track = boost::shared_ptr<MidiTrack>((new MidiTrack (*this, track_name, Route::Flag (0), mode)));
1557 if (track->ensure_io (ChanCount(DataType::MIDI, 1), ChanCount(DataType::AUDIO, 1), false, this)) {
1558 error << "cannot configure 1 in/1 out configuration for new midi track" << endmsg;
1564 for (uint32_t x = 0; x < track->n_inputs().n_midi() && x < nphysical_in; ++x) {
1568 if (Config->get_input_auto_connect() & AutoConnectPhysical) {
1569 port = physinputs[(channels_used+x)%nphysical_in];
1572 if (port.length() && track->connect_input (track->input (x), port, this)) {
1578 for (uint32_t x = 0; x < track->n_outputs().n_midi(); ++x) {
1582 if (nphysical_out && (Config->get_output_auto_connect() & AutoConnectPhysical)) {
1583 port = physoutputs[(channels_used+x)%nphysical_out];
1584 } else if (Config->get_output_auto_connect() & AutoConnectMaster) {
1586 port = _master_out->input (x%_master_out->n_inputs().n_midi())->name();
1590 if (port.length() && track->connect_output (track->output (x), port, this)) {
1595 channels_used += track->n_inputs ().n_midi();
1599 track->midi_diskstream()->non_realtime_input_change();
1601 track->DiskstreamChanged.connect (mem_fun (this, &Session::resort_routes));
1602 //track->set_remote_control_id (control_id);
1604 new_routes.push_back (track);
1605 ret.push_back (track);
1608 catch (failed_constructor &err) {
1609 error << _("Session: could not create new midi track.") << endmsg;
1612 /* we need to get rid of this, since the track failed to be created */
1613 /* XXX arguably, AudioTrack::AudioTrack should not do the Session::add_diskstream() */
1616 RCUWriter<DiskstreamList> writer (diskstreams);
1617 boost::shared_ptr<DiskstreamList> ds = writer.get_copy();
1618 ds->remove (track->midi_diskstream());
1625 catch (AudioEngine::PortRegistrationFailure& pfe) {
1627 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;
1630 /* we need to get rid of this, since the track failed to be created */
1631 /* XXX arguably, MidiTrack::MidiTrack should not do the Session::add_diskstream() */
1634 RCUWriter<DiskstreamList> writer (diskstreams);
1635 boost::shared_ptr<DiskstreamList> ds = writer.get_copy();
1636 ds->remove (track->midi_diskstream());
1647 if (!new_routes.empty()) {
1648 add_routes (new_routes, false);
1649 save_state (_current_snapshot_name);
1655 list<boost::shared_ptr<AudioTrack> >
1656 Session::new_audio_track (int input_channels, int output_channels, TrackMode mode, uint32_t how_many)
1658 char track_name[32];
1659 uint32_t track_id = 0;
1661 uint32_t channels_used = 0;
1663 RouteList new_routes;
1664 list<boost::shared_ptr<AudioTrack> > ret;
1665 uint32_t control_id;
1667 /* count existing audio tracks */
1670 shared_ptr<RouteList> r = routes.reader ();
1672 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
1673 if (dynamic_cast<AudioTrack*>((*i).get()) != 0) {
1674 if (!(*i)->is_hidden()) {
1676 channels_used += (*i)->n_inputs().n_audio();
1682 vector<string> physinputs;
1683 vector<string> physoutputs;
1684 uint32_t nphysical_in;
1685 uint32_t nphysical_out;
1687 _engine.get_physical_outputs (physoutputs);
1688 _engine.get_physical_inputs (physinputs);
1689 control_id = ntracks() + nbusses() + 1;
1693 /* check for duplicate route names, since we might have pre-existing
1694 routes with this name (e.g. create Audio1, Audio2, delete Audio1,
1695 save, close,restart,add new route - first named route is now
1703 snprintf (track_name, sizeof(track_name), "Audio %" PRIu32, track_id);
1705 if (route_by_name (track_name) == 0) {
1709 } while (track_id < (UINT_MAX-1));
1711 if (Config->get_input_auto_connect() & AutoConnectPhysical) {
1712 nphysical_in = min (n_physical_inputs, (uint32_t) physinputs.size());
1717 if (Config->get_output_auto_connect() & AutoConnectPhysical) {
1718 nphysical_out = min (n_physical_outputs, (uint32_t) physinputs.size());
1723 shared_ptr<AudioTrack> track;
1726 track = boost::shared_ptr<AudioTrack>((new AudioTrack (*this, track_name, Route::Flag (0), mode)));
1728 if (track->ensure_io (ChanCount(DataType::AUDIO, input_channels), ChanCount(DataType::AUDIO, output_channels), false, this)) {
1729 error << string_compose (_("cannot configure %1 in/%2 out configuration for new audio track"),
1730 input_channels, output_channels)
1736 for (uint32_t x = 0; x < track->n_inputs().n_audio() && x < nphysical_in; ++x) {
1740 if (Config->get_input_auto_connect() & AutoConnectPhysical) {
1741 port = physinputs[(channels_used+x)%nphysical_in];
1744 if (port.length() && track->connect_input (track->input (x), port, this)) {
1750 for (uint32_t x = 0; x < track->n_outputs().n_midi(); ++x) {
1754 if (nphysical_out && (Config->get_output_auto_connect() & AutoConnectPhysical)) {
1755 port = physoutputs[(channels_used+x)%nphysical_out];
1756 } else if (Config->get_output_auto_connect() & AutoConnectMaster) {
1758 port = _master_out->input (x%_master_out->n_inputs().n_audio())->name();
1762 if (port.length() && track->connect_output (track->output (x), port, this)) {
1767 channels_used += track->n_inputs ().n_audio();
1769 track->audio_diskstream()->non_realtime_input_change();
1771 track->DiskstreamChanged.connect (mem_fun (this, &Session::resort_routes));
1772 track->set_remote_control_id (control_id);
1775 new_routes.push_back (track);
1776 ret.push_back (track);
1779 catch (failed_constructor &err) {
1780 error << _("Session: could not create new audio track.") << endmsg;
1783 /* we need to get rid of this, since the track failed to be created */
1784 /* XXX arguably, AudioTrack::AudioTrack should not do the Session::add_diskstream() */
1787 RCUWriter<DiskstreamList> writer (diskstreams);
1788 boost::shared_ptr<DiskstreamList> ds = writer.get_copy();
1789 ds->remove (track->audio_diskstream());
1796 catch (AudioEngine::PortRegistrationFailure& pfe) {
1798 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;
1801 /* we need to get rid of this, since the track failed to be created */
1802 /* XXX arguably, AudioTrack::AudioTrack should not do the Session::add_diskstream() */
1805 RCUWriter<DiskstreamList> writer (diskstreams);
1806 boost::shared_ptr<DiskstreamList> ds = writer.get_copy();
1807 ds->remove (track->audio_diskstream());
1818 if (!new_routes.empty()) {
1819 add_routes (new_routes, false);
1820 save_state (_current_snapshot_name);
1827 Session::set_remote_control_ids ()
1829 RemoteModel m = Config->get_remote_model();
1831 shared_ptr<RouteList> r = routes.reader ();
1833 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
1834 if ( MixerOrdered == m) {
1835 long order = (*i)->order_key(N_("signal"));
1836 (*i)->set_remote_control_id( order+1 );
1837 } else if ( EditorOrdered == m) {
1838 long order = (*i)->order_key(N_("editor"));
1839 (*i)->set_remote_control_id( order+1 );
1840 } else if ( UserOrdered == m) {
1841 //do nothing ... only changes to remote id's are initiated by user
1848 Session::new_audio_route (int input_channels, int output_channels, uint32_t how_many)
1851 uint32_t bus_id = 1;
1855 uint32_t control_id;
1857 /* count existing audio busses */
1860 shared_ptr<RouteList> r = routes.reader ();
1862 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
1863 if (dynamic_cast<AudioTrack*>((*i).get()) == 0) {
1864 if (!(*i)->is_hidden() && (*i)->name() != _("master")) {
1871 vector<string> physinputs;
1872 vector<string> physoutputs;
1874 _engine.get_physical_outputs (physoutputs);
1875 _engine.get_physical_inputs (physinputs);
1876 control_id = ntracks() + nbusses() + 1;
1881 snprintf (bus_name, sizeof(bus_name), "Bus %" PRIu32, bus_id);
1885 if (route_by_name (bus_name) == 0) {
1889 } while (bus_id < (UINT_MAX-1));
1892 shared_ptr<Route> bus (new Route (*this, bus_name, -1, -1, -1, -1, Route::Flag(0), DataType::AUDIO));
1894 if (bus->ensure_io (ChanCount(DataType::AUDIO, input_channels), ChanCount(DataType::AUDIO, output_channels), false, this)) {
1895 error << string_compose (_("cannot configure %1 in/%2 out configuration for new audio track"),
1896 input_channels, output_channels)
1901 for (uint32_t x = 0; n_physical_inputs && x < bus->n_inputs().n_audio(); ++x) {
1905 if (Config->get_input_auto_connect() & AutoConnectPhysical) {
1906 port = physinputs[((n+x)%n_physical_inputs)];
1909 if (port.length() && bus->connect_input (bus->input (x), port, this)) {
1914 for (uint32_t x = 0; n_physical_outputs && x < bus->n_outputs().n_audio(); ++x) {
1918 if (Config->get_output_auto_connect() & AutoConnectPhysical) {
1919 port = physoutputs[((n+x)%n_physical_outputs)];
1920 } else if (Config->get_output_auto_connect() & AutoConnectMaster) {
1922 port = _master_out->input (x%_master_out->n_inputs().n_audio())->name();
1926 if (port.length() && bus->connect_output (bus->output (x), port, this)) {
1931 bus->set_remote_control_id (control_id);
1934 ret.push_back (bus);
1938 catch (failed_constructor &err) {
1939 error << _("Session: could not create new audio route.") << endmsg;
1943 catch (AudioEngine::PortRegistrationFailure& pfe) {
1944 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;
1954 add_routes (ret, false);
1955 save_state (_current_snapshot_name);
1963 Session::add_routes (RouteList& new_routes, bool save)
1966 RCUWriter<RouteList> writer (routes);
1967 shared_ptr<RouteList> r = writer.get_copy ();
1968 r->insert (r->end(), new_routes.begin(), new_routes.end());
1969 resort_routes_using (r);
1972 for (RouteList::iterator x = new_routes.begin(); x != new_routes.end(); ++x) {
1974 boost::weak_ptr<Route> wpr (*x);
1976 (*x)->solo_changed.connect (sigc::bind (mem_fun (*this, &Session::route_solo_changed), wpr));
1977 (*x)->mute_changed.connect (mem_fun (*this, &Session::route_mute_changed));
1978 (*x)->output_changed.connect (mem_fun (*this, &Session::set_worst_io_latencies_x));
1979 (*x)->processors_changed.connect (bind (mem_fun (*this, &Session::update_latency_compensation), false, false));
1981 if ((*x)->is_master()) {
1985 if ((*x)->is_control()) {
1986 _control_out = (*x);
1989 add_bundle ((*x)->bundle_for_inputs());
1990 add_bundle ((*x)->bundle_for_outputs());
1993 if (_control_out && IO::connecting_legal) {
1995 vector<string> cports;
1996 uint32_t ni = _control_out->n_inputs().n_audio();
1998 for (uint32_t n = 0; n < ni; ++n) {
1999 cports.push_back (_control_out->input(n)->name());
2002 for (RouteList::iterator x = new_routes.begin(); x != new_routes.end(); ++x) {
2003 (*x)->set_control_outs (cports);
2010 save_state (_current_snapshot_name);
2013 RouteAdded (new_routes); /* EMIT SIGNAL */
2017 Session::add_diskstream (boost::shared_ptr<Diskstream> dstream)
2019 /* need to do this in case we're rolling at the time, to prevent false underruns */
2020 dstream->do_refill_with_alloc ();
2022 dstream->set_block_size (current_block_size);
2025 RCUWriter<DiskstreamList> writer (diskstreams);
2026 boost::shared_ptr<DiskstreamList> ds = writer.get_copy();
2027 ds->push_back (dstream);
2028 /* writer goes out of scope, copies ds back to main */
2031 dstream->PlaylistChanged.connect (sigc::bind (mem_fun (*this, &Session::diskstream_playlist_changed), dstream));
2032 /* this will connect to future changes, and check the current length */
2033 diskstream_playlist_changed (dstream);
2035 dstream->prepare ();
2040 Session::remove_route (shared_ptr<Route> route)
2043 RCUWriter<RouteList> writer (routes);
2044 shared_ptr<RouteList> rs = writer.get_copy ();
2048 /* deleting the master out seems like a dumb
2049 idea, but its more of a UI policy issue
2053 if (route == _master_out) {
2054 _master_out = shared_ptr<Route> ();
2057 if (route == _control_out) {
2058 _control_out = shared_ptr<Route> ();
2060 /* cancel control outs for all routes */
2062 vector<string> empty;
2064 for (RouteList::iterator r = rs->begin(); r != rs->end(); ++r) {
2065 (*r)->set_control_outs (empty);
2069 update_route_solo_state ();
2071 /* writer goes out of scope, forces route list update */
2075 boost::shared_ptr<Diskstream> ds;
2077 if ((t = dynamic_cast<Track*>(route.get())) != 0) {
2078 ds = t->diskstream();
2084 RCUWriter<DiskstreamList> dsl (diskstreams);
2085 boost::shared_ptr<DiskstreamList> d = dsl.get_copy();
2090 find_current_end ();
2092 update_latency_compensation (false, false);
2095 // We need to disconnect the routes inputs and outputs
2096 route->disconnect_inputs(NULL);
2097 route->disconnect_outputs(NULL);
2099 /* get rid of it from the dead wood collection in the route list manager */
2101 /* XXX i think this is unsafe as it currently stands, but i am not sure. (pd, october 2nd, 2006) */
2105 /* try to cause everyone to drop their references */
2107 route->drop_references ();
2109 /* save the new state of the world */
2111 if (save_state (_current_snapshot_name)) {
2112 save_history (_current_snapshot_name);
2117 Session::route_mute_changed (void* src)
2123 Session::route_solo_changed (void* src, boost::weak_ptr<Route> wpr)
2125 if (solo_update_disabled) {
2131 boost::shared_ptr<Route> route = wpr.lock ();
2134 /* should not happen */
2135 error << string_compose (_("programming error: %1"), X_("invalid route weak ptr passed to route_solo_changed")) << endmsg;
2139 is_track = (boost::dynamic_pointer_cast<AudioTrack>(route) != 0);
2141 shared_ptr<RouteList> r = routes.reader ();
2143 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2145 /* soloing a track mutes all other tracks, soloing a bus mutes all other busses */
2149 /* don't mess with busses */
2151 if (dynamic_cast<Track*>((*i).get()) == 0) {
2157 /* don't mess with tracks */
2159 if (dynamic_cast<Track*>((*i).get()) != 0) {
2164 if ((*i) != route &&
2165 ((*i)->mix_group () == 0 ||
2166 (*i)->mix_group () != route->mix_group () ||
2167 !route->mix_group ()->is_active())) {
2169 if ((*i)->soloed()) {
2171 /* if its already soloed, and solo latching is enabled,
2172 then leave it as it is.
2175 if (Config->get_solo_latched()) {
2182 solo_update_disabled = true;
2183 (*i)->set_solo (false, src);
2184 solo_update_disabled = false;
2188 bool something_soloed = false;
2189 bool same_thing_soloed = false;
2190 bool signal = false;
2192 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2193 if ((*i)->soloed()) {
2194 something_soloed = true;
2195 if (dynamic_cast<Track*>((*i).get())) {
2197 same_thing_soloed = true;
2202 same_thing_soloed = true;
2210 if (something_soloed != currently_soloing) {
2212 currently_soloing = something_soloed;
2215 modify_solo_mute (is_track, same_thing_soloed);
2218 SoloActive (currently_soloing); /* EMIT SIGNAL */
2221 SoloChanged (); /* EMIT SIGNAL */
2227 Session::update_route_solo_state ()
2230 bool is_track = false;
2231 bool signal = false;
2233 /* caller must hold RouteLock */
2235 /* this is where we actually implement solo by changing
2236 the solo mute setting of each track.
2239 shared_ptr<RouteList> r = routes.reader ();
2241 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2242 if ((*i)->soloed()) {
2244 if (dynamic_cast<Track*>((*i).get())) {
2251 if (mute != currently_soloing) {
2253 currently_soloing = mute;
2256 if (!is_track && !mute) {
2258 /* nothing is soloed */
2260 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2261 (*i)->set_solo_mute (false);
2271 modify_solo_mute (is_track, mute);
2274 SoloActive (currently_soloing);
2279 Session::modify_solo_mute (bool is_track, bool mute)
2281 shared_ptr<RouteList> r = routes.reader ();
2283 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2287 /* only alter track solo mute */
2289 if (dynamic_cast<Track*>((*i).get())) {
2290 if ((*i)->soloed()) {
2291 (*i)->set_solo_mute (!mute);
2293 (*i)->set_solo_mute (mute);
2299 /* only alter bus solo mute */
2301 if (!dynamic_cast<Track*>((*i).get())) {
2303 if ((*i)->soloed()) {
2305 (*i)->set_solo_mute (false);
2309 /* don't mute master or control outs
2310 in response to another bus solo
2313 if ((*i) != _master_out &&
2314 (*i) != _control_out) {
2315 (*i)->set_solo_mute (mute);
2326 Session::catch_up_on_solo ()
2328 /* this is called after set_state() to catch the full solo
2329 state, which can't be correctly determined on a per-route
2330 basis, but needs the global overview that only the session
2333 update_route_solo_state();
2337 Session::route_by_name (string name)
2339 shared_ptr<RouteList> r = routes.reader ();
2341 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2342 if ((*i)->name() == name) {
2347 return shared_ptr<Route> ((Route*) 0);
2351 Session::route_by_id (PBD::ID id)
2353 shared_ptr<RouteList> r = routes.reader ();
2355 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2356 if ((*i)->id() == id) {
2361 return shared_ptr<Route> ((Route*) 0);
2365 Session::route_by_remote_id (uint32_t id)
2367 shared_ptr<RouteList> r = routes.reader ();
2369 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2370 if ((*i)->remote_control_id() == id) {
2375 return shared_ptr<Route> ((Route*) 0);
2379 Session::find_current_end ()
2381 if (_state_of_the_state & Loading) {
2385 nframes_t max = get_maximum_extent ();
2387 if (max > end_location->end()) {
2388 end_location->set_end (max);
2390 DurationChanged(); /* EMIT SIGNAL */
2395 Session::get_maximum_extent () const
2400 boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
2402 for (DiskstreamList::const_iterator i = dsl->begin(); i != dsl->end(); ++i) {
2403 boost::shared_ptr<Playlist> pl = (*i)->playlist();
2404 if ((me = pl->get_maximum_extent()) > max) {
2412 boost::shared_ptr<Diskstream>
2413 Session::diskstream_by_name (string name)
2415 boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
2417 for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
2418 if ((*i)->name() == name) {
2423 return boost::shared_ptr<Diskstream>((Diskstream*) 0);
2426 boost::shared_ptr<Diskstream>
2427 Session::diskstream_by_id (const PBD::ID& id)
2429 boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
2431 for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
2432 if ((*i)->id() == id) {
2437 return boost::shared_ptr<Diskstream>((Diskstream*) 0);
2440 /* Region management */
2443 Session::new_region_name (string old)
2445 string::size_type last_period;
2447 string::size_type len = old.length() + 64;
2450 if ((last_period = old.find_last_of ('.')) == string::npos) {
2452 /* no period present - add one explicitly */
2455 last_period = old.length() - 1;
2460 number = atoi (old.substr (last_period+1).c_str());
2464 while (number < (UINT_MAX-1)) {
2466 RegionList::const_iterator i;
2471 snprintf (buf, len, "%s%" PRIu32, old.substr (0, last_period + 1).c_str(), number);
2474 for (i = regions.begin(); i != regions.end(); ++i) {
2475 if (i->second->name() == sbuf) {
2480 if (i == regions.end()) {
2485 if (number != (UINT_MAX-1)) {
2489 error << string_compose (_("cannot create new name for region \"%1\""), old) << endmsg;
2494 Session::region_name (string& result, string base, bool newlevel) const
2499 assert(base.find("/") == string::npos);
2503 Glib::Mutex::Lock lm (region_lock);
2505 snprintf (buf, sizeof (buf), "%d", (int)regions.size() + 1);
2513 /* XXX this is going to be slow. optimize me later */
2518 string::size_type pos;
2520 pos = base.find_last_of ('.');
2522 /* pos may be npos, but then we just use entire base */
2524 subbase = base.substr (0, pos);
2528 bool name_taken = true;
2531 Glib::Mutex::Lock lm (region_lock);
2533 for (int n = 1; n < 5000; ++n) {
2536 snprintf (buf, sizeof (buf), ".%d", n);
2541 for (RegionList::const_iterator i = regions.begin(); i != regions.end(); ++i) {
2542 if (i->second->name() == result) {
2555 fatal << string_compose(_("too many regions with names like %1"), base) << endmsg;
2563 Session::add_region (boost::shared_ptr<Region> region)
2565 boost::shared_ptr<Region> other;
2569 Glib::Mutex::Lock lm (region_lock);
2571 RegionList::iterator x;
2573 for (x = regions.begin(); x != regions.end(); ++x) {
2577 if (region->region_list_equivalent (other)) {
2582 if (x == regions.end()) {
2584 pair<RegionList::key_type,RegionList::mapped_type> entry;
2586 entry.first = region->id();
2587 entry.second = region;
2589 pair<RegionList::iterator,bool> x = regions.insert (entry);
2601 /* mark dirty because something has changed even if we didn't
2602 add the region to the region list.
2608 region->GoingAway.connect (sigc::bind (mem_fun (*this, &Session::remove_region), boost::weak_ptr<Region>(region)));
2609 region->StateChanged.connect (sigc::bind (mem_fun (*this, &Session::region_changed), boost::weak_ptr<Region>(region)));
2610 RegionAdded (region); /* EMIT SIGNAL */
2615 Session::region_changed (Change what_changed, boost::weak_ptr<Region> weak_region)
2617 boost::shared_ptr<Region> region (weak_region.lock ());
2623 if (what_changed & Region::HiddenChanged) {
2624 /* relay hidden changes */
2625 RegionHiddenChange (region);
2630 Session::remove_region (boost::weak_ptr<Region> weak_region)
2632 RegionList::iterator i;
2633 boost::shared_ptr<Region> region (weak_region.lock ());
2639 bool removed = false;
2642 Glib::Mutex::Lock lm (region_lock);
2644 if ((i = regions.find (region->id())) != regions.end()) {
2650 /* mark dirty because something has changed even if we didn't
2651 remove the region from the region list.
2657 RegionRemoved(region); /* EMIT SIGNAL */
2661 boost::shared_ptr<Region>
2662 Session::find_whole_file_parent (boost::shared_ptr<Region const> child)
2664 RegionList::iterator i;
2665 boost::shared_ptr<Region> region;
2667 Glib::Mutex::Lock lm (region_lock);
2669 for (i = regions.begin(); i != regions.end(); ++i) {
2673 if (region->whole_file()) {
2675 if (child->source_equivalent (region)) {
2681 return boost::shared_ptr<Region> ();
2685 Session::find_equivalent_playlist_regions (boost::shared_ptr<Region> region, vector<boost::shared_ptr<Region> >& result)
2687 for (PlaylistList::iterator i = playlists.begin(); i != playlists.end(); ++i)
2688 (*i)->get_region_list_equivalent_regions (region, result);
2692 Session::destroy_region (boost::shared_ptr<Region> region)
2694 vector<boost::shared_ptr<Source> > srcs;
2697 boost::shared_ptr<AudioRegion> aregion;
2699 if ((aregion = boost::dynamic_pointer_cast<AudioRegion> (region)) == 0) {
2703 if (aregion->playlist()) {
2704 aregion->playlist()->destroy_region (region);
2707 for (uint32_t n = 0; n < aregion->n_channels(); ++n) {
2708 srcs.push_back (aregion->source (n));
2712 region->drop_references ();
2714 for (vector<boost::shared_ptr<Source> >::iterator i = srcs.begin(); i != srcs.end(); ++i) {
2716 if (!(*i)->used()) {
2717 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*i);
2720 (afs)->mark_for_remove ();
2723 (*i)->drop_references ();
2725 cerr << "source was not used by any playlist\n";
2733 Session::destroy_regions (list<boost::shared_ptr<Region> > regions)
2735 for (list<boost::shared_ptr<Region> >::iterator i = regions.begin(); i != regions.end(); ++i) {
2736 destroy_region (*i);
2742 Session::remove_last_capture ()
2744 list<boost::shared_ptr<Region> > r;
2746 boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
2748 for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
2749 list<boost::shared_ptr<Region> >& l = (*i)->last_capture_regions();
2752 r.insert (r.end(), l.begin(), l.end());
2757 destroy_regions (r);
2759 save_state (_current_snapshot_name);
2765 Session::remove_region_from_region_list (boost::shared_ptr<Region> r)
2771 /* Source Management */
2773 Session::add_source (boost::shared_ptr<Source> source)
2775 pair<SourceMap::key_type, SourceMap::mapped_type> entry;
2776 pair<SourceMap::iterator,bool> result;
2778 entry.first = source->id();
2779 entry.second = source;
2782 Glib::Mutex::Lock lm (source_lock);
2783 result = sources.insert (entry);
2786 if (result.second) {
2787 source->GoingAway.connect (sigc::bind (mem_fun (this, &Session::remove_source), boost::weak_ptr<Source> (source)));
2793 Session::remove_source (boost::weak_ptr<Source> src)
2795 SourceMap::iterator i;
2796 boost::shared_ptr<Source> source = src.lock();
2803 Glib::Mutex::Lock lm (source_lock);
2805 if ((i = sources.find (source->id())) != sources.end()) {
2810 if (!_state_of_the_state & InCleanup) {
2812 /* save state so we don't end up with a session file
2813 referring to non-existent sources.
2816 save_state (_current_snapshot_name);
2820 boost::shared_ptr<Source>
2821 Session::source_by_id (const PBD::ID& id)
2823 Glib::Mutex::Lock lm (source_lock);
2824 SourceMap::iterator i;
2825 boost::shared_ptr<Source> source;
2827 if ((i = sources.find (id)) != sources.end()) {
2835 boost::shared_ptr<Source>
2836 Session::source_by_path_and_channel (const Glib::ustring& path, uint16_t chn)
2838 Glib::Mutex::Lock lm (source_lock);
2840 for (SourceMap::iterator i = sources.begin(); i != sources.end(); ++i) {
2841 cerr << "comparing " << path << " with " << i->second->name() << endl;
2842 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(i->second);
2844 if (afs && afs->path() == path && chn == afs->channel()) {
2849 return boost::shared_ptr<Source>();
2853 Session::peak_path (Glib::ustring base) const
2855 sys::path peakfile_path(_session_dir->peak_path());
2856 peakfile_path /= basename_nosuffix (base) + peakfile_suffix;
2857 return peakfile_path.to_string();
2861 Session::change_audio_path_by_name (string path, string oldname, string newname, bool destructive)
2864 string old_basename = PBD::basename_nosuffix (oldname);
2865 string new_legalized = legalize_for_path (newname);
2867 /* note: we know (or assume) the old path is already valid */
2871 /* destructive file sources have a name of the form:
2873 /path/to/Tnnnn-NAME(%[LR])?.wav
2875 the task here is to replace NAME with the new name.
2878 /* find last slash */
2882 string::size_type slash;
2883 string::size_type dash;
2885 if ((slash = path.find_last_of ('/')) == string::npos) {
2889 dir = path.substr (0, slash+1);
2891 /* '-' is not a legal character for the NAME part of the path */
2893 if ((dash = path.find_last_of ('-')) == string::npos) {
2897 prefix = path.substr (slash+1, dash-(slash+1));
2902 path += new_legalized;
2903 path += ".wav"; /* XXX gag me with a spoon */
2907 /* non-destructive file sources have a name of the form:
2909 /path/to/NAME-nnnnn(%[LR])?.wav
2911 the task here is to replace NAME with the new name.
2916 string::size_type slash;
2917 string::size_type dash;
2918 string::size_type postfix;
2920 /* find last slash */
2922 if ((slash = path.find_last_of ('/')) == string::npos) {
2926 dir = path.substr (0, slash+1);
2928 /* '-' is not a legal character for the NAME part of the path */
2930 if ((dash = path.find_last_of ('-')) == string::npos) {
2934 suffix = path.substr (dash+1);
2936 // Suffix is now everything after the dash. Now we need to eliminate
2937 // the nnnnn part, which is done by either finding a '%' or a '.'
2939 postfix = suffix.find_last_of ("%");
2940 if (postfix == string::npos) {
2941 postfix = suffix.find_last_of ('.');
2944 if (postfix != string::npos) {
2945 suffix = suffix.substr (postfix);
2947 error << "Logic error in Session::change_audio_path_by_name(), please report to the developers" << endl;
2951 const uint32_t limit = 10000;
2952 char buf[PATH_MAX+1];
2954 for (uint32_t cnt = 1; cnt <= limit; ++cnt) {
2956 snprintf (buf, sizeof(buf), "%s%s-%u%s", dir.c_str(), newname.c_str(), cnt, suffix.c_str());
2958 if (access (buf, F_OK) != 0) {
2966 error << "FATAL ERROR! Could not find a " << endl;
2975 Session::audio_path_from_name (string name, uint32_t nchan, uint32_t chan, bool destructive)
2979 char buf[PATH_MAX+1];
2980 const uint32_t limit = 10000;
2984 legalized = legalize_for_path (name);
2986 /* find a "version" of the file name that doesn't exist in
2987 any of the possible directories.
2990 for (cnt = (destructive ? ++destructive_index : 1); cnt <= limit; ++cnt) {
2992 vector<space_and_path>::iterator i;
2993 uint32_t existing = 0;
2995 for (i = session_dirs.begin(); i != session_dirs.end(); ++i) {
2997 SessionDirectory sdir((*i).path);
2999 spath = sdir.sound_path().to_string();
3003 snprintf (buf, sizeof(buf), "%s/T%04d-%s.wav", spath.c_str(), cnt, legalized.c_str());
3004 } else if (nchan == 2) {
3006 snprintf (buf, sizeof(buf), "%s/T%04d-%s%%L.wav", spath.c_str(), cnt, legalized.c_str());
3008 snprintf (buf, sizeof(buf), "%s/T%04d-%s%%R.wav", spath.c_str(), cnt, legalized.c_str());
3010 } else if (nchan < 26) {
3011 snprintf (buf, sizeof(buf), "%s/T%04d-%s%%%c.wav", spath.c_str(), cnt, legalized.c_str(), 'a' + chan);
3013 snprintf (buf, sizeof(buf), "%s/T%04d-%s.wav", spath.c_str(), cnt, legalized.c_str());
3022 snprintf (buf, sizeof(buf), "%s-%u.wav", spath.c_str(), cnt);
3023 } else if (nchan == 2) {
3025 snprintf (buf, sizeof(buf), "%s-%u%%L.wav", spath.c_str(), cnt);
3027 snprintf (buf, sizeof(buf), "%s-%u%%R.wav", spath.c_str(), cnt);
3029 } else if (nchan < 26) {
3030 snprintf (buf, sizeof(buf), "%s-%u%%%c.wav", spath.c_str(), cnt, 'a' + chan);
3032 snprintf (buf, sizeof(buf), "%s-%u.wav", spath.c_str(), cnt);
3036 if (sys::exists(buf)) {
3042 if (existing == 0) {
3047 error << string_compose(_("There are already %1 recordings for %2, which I consider too many."), limit, name) << endmsg;
3049 throw failed_constructor();
3053 /* we now have a unique name for the file, but figure out where to
3059 SessionDirectory sdir(get_best_session_directory_for_new_source ());
3061 spath = sdir.sound_path().to_string();
3064 string::size_type pos = foo.find_last_of ('/');
3066 if (pos == string::npos) {
3069 spath += foo.substr (pos + 1);
3075 boost::shared_ptr<AudioFileSource>
3076 Session::create_audio_source_for_session (AudioDiskstream& ds, uint32_t chan, bool destructive)
3078 string spath = audio_path_from_name (ds.name(), ds.n_channels().n_audio(), chan, destructive);
3079 return boost::dynamic_pointer_cast<AudioFileSource> (
3080 SourceFactory::createWritable (DataType::AUDIO, *this, spath, destructive, frame_rate()));
3083 // FIXME: _terrible_ code duplication
3085 Session::change_midi_path_by_name (string path, string oldname, string newname, bool destructive)
3088 string old_basename = PBD::basename_nosuffix (oldname);
3089 string new_legalized = legalize_for_path (newname);
3091 /* note: we know (or assume) the old path is already valid */
3095 /* destructive file sources have a name of the form:
3097 /path/to/Tnnnn-NAME(%[LR])?.wav
3099 the task here is to replace NAME with the new name.
3102 /* find last slash */
3106 string::size_type slash;
3107 string::size_type dash;
3109 if ((slash = path.find_last_of ('/')) == string::npos) {
3113 dir = path.substr (0, slash+1);
3115 /* '-' is not a legal character for the NAME part of the path */
3117 if ((dash = path.find_last_of ('-')) == string::npos) {
3121 prefix = path.substr (slash+1, dash-(slash+1));
3126 path += new_legalized;
3127 path += ".mid"; /* XXX gag me with a spoon */
3131 /* non-destructive file sources have a name of the form:
3133 /path/to/NAME-nnnnn(%[LR])?.wav
3135 the task here is to replace NAME with the new name.
3140 string::size_type slash;
3141 string::size_type dash;
3142 string::size_type postfix;
3144 /* find last slash */
3146 if ((slash = path.find_last_of ('/')) == string::npos) {
3150 dir = path.substr (0, slash+1);
3152 /* '-' is not a legal character for the NAME part of the path */
3154 if ((dash = path.find_last_of ('-')) == string::npos) {
3158 suffix = path.substr (dash+1);
3160 // Suffix is now everything after the dash. Now we need to eliminate
3161 // the nnnnn part, which is done by either finding a '%' or a '.'
3163 postfix = suffix.find_last_of ("%");
3164 if (postfix == string::npos) {
3165 postfix = suffix.find_last_of ('.');
3168 if (postfix != string::npos) {
3169 suffix = suffix.substr (postfix);
3171 error << "Logic error in Session::change_midi_path_by_name(), please report to the developers" << endl;
3175 const uint32_t limit = 10000;
3176 char buf[PATH_MAX+1];
3178 for (uint32_t cnt = 1; cnt <= limit; ++cnt) {
3180 snprintf (buf, sizeof(buf), "%s%s-%u%s", dir.c_str(), newname.c_str(), cnt, suffix.c_str());
3182 if (access (buf, F_OK) != 0) {
3190 error << "FATAL ERROR! Could not find a " << endl;
3199 Session::midi_path_from_name (string name)
3203 char buf[PATH_MAX+1];
3204 const uint32_t limit = 10000;
3208 legalized = legalize_for_path (name);
3210 /* find a "version" of the file name that doesn't exist in
3211 any of the possible directories.
3214 for (cnt = 1; cnt <= limit; ++cnt) {
3216 vector<space_and_path>::iterator i;
3217 uint32_t existing = 0;
3219 for (i = session_dirs.begin(); i != session_dirs.end(); ++i) {
3221 SessionDirectory sdir((*i).path);
3223 sys::path p = sdir.midi_path();
3227 spath = p.to_string();
3229 snprintf (buf, sizeof(buf), "%s-%u.mid", spath.c_str(), cnt);
3231 if (sys::exists (buf)) {
3236 if (existing == 0) {
3241 error << string_compose(_("There are already %1 recordings for %2, which I consider too many."), limit, name) << endmsg;
3242 throw failed_constructor();
3246 /* we now have a unique name for the file, but figure out where to
3252 SessionDirectory sdir(get_best_session_directory_for_new_source ());
3254 spath = sdir.midi_path().to_string();
3257 string::size_type pos = foo.find_last_of ('/');
3259 if (pos == string::npos) {
3262 spath += foo.substr (pos + 1);
3268 boost::shared_ptr<MidiSource>
3269 Session::create_midi_source_for_session (MidiDiskstream& ds)
3271 string mpath = midi_path_from_name (ds.name());
3273 return boost::dynamic_pointer_cast<SMFSource> (SourceFactory::createWritable (DataType::MIDI, *this, mpath, false, frame_rate()));
3277 /* Playlist management */
3279 boost::shared_ptr<Playlist>
3280 Session::playlist_by_name (string name)
3282 Glib::Mutex::Lock lm (playlist_lock);
3283 for (PlaylistList::iterator i = playlists.begin(); i != playlists.end(); ++i) {
3284 if ((*i)->name() == name) {
3288 for (PlaylistList::iterator i = unused_playlists.begin(); i != unused_playlists.end(); ++i) {
3289 if ((*i)->name() == name) {
3294 return boost::shared_ptr<Playlist>();
3298 Session::add_playlist (boost::shared_ptr<Playlist> playlist)
3300 if (playlist->hidden()) {
3305 Glib::Mutex::Lock lm (playlist_lock);
3306 if (find (playlists.begin(), playlists.end(), playlist) == playlists.end()) {
3307 playlists.insert (playlists.begin(), playlist);
3308 playlist->InUse.connect (sigc::bind (mem_fun (*this, &Session::track_playlist), boost::weak_ptr<Playlist>(playlist)));
3309 playlist->GoingAway.connect (sigc::bind (mem_fun (*this, &Session::remove_playlist), boost::weak_ptr<Playlist>(playlist)));
3315 PlaylistAdded (playlist); /* EMIT SIGNAL */
3319 Session::get_playlists (vector<boost::shared_ptr<Playlist> >& s)
3322 Glib::Mutex::Lock lm (playlist_lock);
3323 for (PlaylistList::iterator i = playlists.begin(); i != playlists.end(); ++i) {
3326 for (PlaylistList::iterator i = unused_playlists.begin(); i != unused_playlists.end(); ++i) {
3333 Session::track_playlist (bool inuse, boost::weak_ptr<Playlist> wpl)
3335 boost::shared_ptr<Playlist> pl(wpl.lock());
3341 PlaylistList::iterator x;
3344 /* its not supposed to be visible */
3349 Glib::Mutex::Lock lm (playlist_lock);
3353 unused_playlists.insert (pl);
3355 if ((x = playlists.find (pl)) != playlists.end()) {
3356 playlists.erase (x);
3362 playlists.insert (pl);
3364 if ((x = unused_playlists.find (pl)) != unused_playlists.end()) {
3365 unused_playlists.erase (x);
3372 Session::remove_playlist (boost::weak_ptr<Playlist> weak_playlist)
3374 if (_state_of_the_state & Deletion) {
3378 boost::shared_ptr<Playlist> playlist (weak_playlist.lock());
3385 Glib::Mutex::Lock lm (playlist_lock);
3387 PlaylistList::iterator i;
3389 i = find (playlists.begin(), playlists.end(), playlist);
3390 if (i != playlists.end()) {
3391 playlists.erase (i);
3394 i = find (unused_playlists.begin(), unused_playlists.end(), playlist);
3395 if (i != unused_playlists.end()) {
3396 unused_playlists.erase (i);
3403 PlaylistRemoved (playlist); /* EMIT SIGNAL */
3407 Session::set_audition (boost::shared_ptr<Region> r)
3409 pending_audition_region = r;
3410 post_transport_work = PostTransportWork (post_transport_work | PostTransportAudition);
3411 schedule_butler_transport_work ();
3415 Session::audition_playlist ()
3417 Event* ev = new Event (Event::Audition, Event::Add, Event::Immediate, 0, 0.0);
3418 ev->region.reset ();
3423 Session::non_realtime_set_audition ()
3425 if (!pending_audition_region) {
3426 auditioner->audition_current_playlist ();
3428 auditioner->audition_region (pending_audition_region);
3429 pending_audition_region.reset ();
3431 AuditionActive (true); /* EMIT SIGNAL */
3435 Session::audition_region (boost::shared_ptr<Region> r)
3437 Event* ev = new Event (Event::Audition, Event::Add, Event::Immediate, 0, 0.0);
3443 Session::cancel_audition ()
3445 if (auditioner->active()) {
3446 auditioner->cancel_audition ();
3447 AuditionActive (false); /* EMIT SIGNAL */
3452 Session::RoutePublicOrderSorter::operator() (boost::shared_ptr<Route> a, boost::shared_ptr<Route> b)
3454 return a->order_key(N_("signal")) < b->order_key(N_("signal"));
3458 Session::remove_empty_sounds ()
3460 vector<string> audio_filenames;
3462 get_files_in_directory (_session_dir->sound_path(), audio_filenames);
3464 Glib::Mutex::Lock lm (source_lock);
3466 TapeFileMatcher tape_file_matcher;
3468 remove_if (audio_filenames.begin(), audio_filenames.end(),
3469 sigc::mem_fun (tape_file_matcher, &TapeFileMatcher::matches));
3471 for (vector<string>::iterator i = audio_filenames.begin(); i != audio_filenames.end(); ++i) {
3473 sys::path audio_file_path (_session_dir->sound_path());
3475 audio_file_path /= *i;
3477 if (AudioFileSource::is_empty (*this, audio_file_path.to_string())) {
3481 sys::remove (audio_file_path);
3482 const string peakfile = peak_path (audio_file_path.to_string());
3483 sys::remove (peakfile);
3485 catch (const sys::filesystem_error& err)
3487 error << err.what() << endmsg;
3494 Session::is_auditioning () const
3496 /* can be called before we have an auditioner object */
3498 return auditioner->active();
3505 Session::set_all_solo (bool yn)
3507 shared_ptr<RouteList> r = routes.reader ();
3509 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3510 if (!(*i)->is_hidden()) {
3511 (*i)->set_solo (yn, this);
3519 Session::set_all_mute (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_mute (yn, this);
3533 Session::n_diskstreams () const
3537 boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
3539 for (DiskstreamList::const_iterator i = dsl->begin(); i != dsl->end(); ++i) {
3540 if (!(*i)->hidden()) {
3548 Session::graph_reordered ()
3550 /* don't do this stuff if we are setting up connections
3551 from a set_state() call or creating new tracks.
3554 if (_state_of_the_state & InitialConnecting) {
3558 /* every track/bus asked for this to be handled but it was deferred because
3559 we were connecting. do it now.
3562 request_input_change_handling ();
3566 /* force all diskstreams to update their capture offset values to
3567 reflect any changes in latencies within the graph.
3570 boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
3572 for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
3573 (*i)->set_capture_offset ();
3578 Session::record_disenable_all ()
3580 record_enable_change_all (false);
3584 Session::record_enable_all ()
3586 record_enable_change_all (true);
3590 Session::record_enable_change_all (bool yn)
3592 shared_ptr<RouteList> r = routes.reader ();
3594 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3597 if ((at = dynamic_cast<Track*>((*i).get())) != 0) {
3598 at->set_record_enable (yn, this);
3602 /* since we don't keep rec-enable state, don't mark session dirty */
3606 Session::add_processor (Processor* processor)
3609 PortInsert* port_insert;
3610 PluginInsert* plugin_insert;
3612 if ((port_insert = dynamic_cast<PortInsert *> (processor)) != 0) {
3613 _port_inserts.insert (_port_inserts.begin(), port_insert);
3614 } else if ((plugin_insert = dynamic_cast<PluginInsert *> (processor)) != 0) {
3615 _plugin_inserts.insert (_plugin_inserts.begin(), plugin_insert);
3616 } else if ((send = dynamic_cast<Send *> (processor)) != 0) {
3617 _sends.insert (_sends.begin(), send);
3619 fatal << _("programming error: unknown type of Insert created!") << endmsg;
3623 processor->GoingAway.connect (sigc::bind (mem_fun (*this, &Session::remove_processor), processor));
3629 Session::remove_processor (Processor* processor)
3632 PortInsert* port_insert;
3633 PluginInsert* plugin_insert;
3635 if ((port_insert = dynamic_cast<PortInsert *> (processor)) != 0) {
3636 list<PortInsert*>::iterator x = find (_port_inserts.begin(), _port_inserts.end(), port_insert);
3637 if (x != _port_inserts.end()) {
3638 insert_bitset[port_insert->bit_slot()] = false;
3639 _port_inserts.erase (x);
3641 } else if ((plugin_insert = dynamic_cast<PluginInsert *> (processor)) != 0) {
3642 _plugin_inserts.remove (plugin_insert);
3643 } else if ((send = dynamic_cast<Send *> (processor)) != 0) {
3644 list<Send*>::iterator x = find (_sends.begin(), _sends.end(), send);
3645 if (x != _sends.end()) {
3646 send_bitset[send->bit_slot()] = false;
3650 fatal << _("programming error: unknown type of Insert deleted!") << endmsg;
3658 Session::available_capture_duration ()
3660 float sample_bytes_on_disk = 4.0; // keep gcc happy
3662 switch (Config->get_native_file_data_format()) {
3664 sample_bytes_on_disk = 4.0;
3668 sample_bytes_on_disk = 3.0;
3672 sample_bytes_on_disk = 2.0;
3676 /* impossible, but keep some gcc versions happy */
3677 fatal << string_compose (_("programming error: %1"),
3678 X_("illegal native file data format"))
3683 double scale = 4096.0 / sample_bytes_on_disk;
3685 if (_total_free_4k_blocks * scale > (double) max_frames) {
3689 return (nframes_t) floor (_total_free_4k_blocks * scale);
3693 Session::add_bundle (shared_ptr<Bundle> bundle)
3696 Glib::Mutex::Lock guard (bundle_lock);
3697 _bundles.push_back (bundle);
3700 BundleAdded (bundle); /* EMIT SIGNAL */
3706 Session::remove_bundle (shared_ptr<Bundle> bundle)
3708 bool removed = false;
3711 Glib::Mutex::Lock guard (bundle_lock);
3712 BundleList::iterator i = find (_bundles.begin(), _bundles.end(), bundle);
3714 if (i != _bundles.end()) {
3721 BundleRemoved (bundle); /* EMIT SIGNAL */
3728 Session::bundle_by_name (string name) const
3730 Glib::Mutex::Lock lm (bundle_lock);
3732 for (BundleList::const_iterator i = _bundles.begin(); i != _bundles.end(); ++i) {
3733 if ((*i)->name() == name) {
3738 return boost::shared_ptr<Bundle> ();
3741 boost::shared_ptr<Bundle>
3742 Session::bundle_by_ports (std::vector<std::string> const & wanted_ports) const
3744 Glib::Mutex::Lock lm (bundle_lock);
3746 for (BundleList::const_iterator i = _bundles.begin(); i != _bundles.end(); ++i) {
3747 if ((*i)->nchannels() != wanted_ports.size()) {
3752 for (uint32_t j = 0; j < (*i)->nchannels(); ++j) {
3753 Bundle::PortList const p = (*i)->channel_ports (j);
3754 if (p.empty() || p[0] != wanted_ports[j]) {
3755 /* not this bundle */
3762 /* matched bundle */
3767 return boost::shared_ptr<Bundle> ();
3771 Session::tempo_map_changed (Change ignored)
3777 /** Ensures that all buffers (scratch, send, silent, etc) are allocated for
3778 * the given count with the current block size.
3781 Session::ensure_buffers (ChanCount howmany)
3783 if (current_block_size == 0)
3784 return; // too early? (is this ok?)
3786 // We need at least 2 MIDI scratch buffers to mix/merge
3787 if (howmany.n_midi() < 2)
3788 howmany.set_midi(2);
3790 // FIXME: JACK needs to tell us maximum MIDI buffer size
3791 // Using nasty assumption (max # events == nframes) for now
3792 _scratch_buffers->ensure_buffers(howmany, current_block_size);
3793 _mix_buffers->ensure_buffers(howmany, current_block_size);
3794 _silent_buffers->ensure_buffers(howmany, current_block_size);
3796 allocate_pan_automation_buffers (current_block_size, howmany.n_audio(), false);
3800 Session::next_insert_id ()
3802 /* this doesn't really loop forever. just think about it */
3805 for (boost::dynamic_bitset<uint32_t>::size_type n = 0; n < insert_bitset.size(); ++n) {
3806 if (!insert_bitset[n]) {
3807 insert_bitset[n] = true;
3813 /* none available, so resize and try again */
3815 insert_bitset.resize (insert_bitset.size() + 16, false);
3820 Session::next_send_id ()
3822 /* this doesn't really loop forever. just think about it */
3825 for (boost::dynamic_bitset<uint32_t>::size_type n = 0; n < send_bitset.size(); ++n) {
3826 if (!send_bitset[n]) {
3827 send_bitset[n] = true;
3833 /* none available, so resize and try again */
3835 send_bitset.resize (send_bitset.size() + 16, false);
3840 Session::mark_send_id (uint32_t id)
3842 if (id >= send_bitset.size()) {
3843 send_bitset.resize (id+16, false);
3845 if (send_bitset[id]) {
3846 warning << string_compose (_("send ID %1 appears to be in use already"), id) << endmsg;
3848 send_bitset[id] = true;
3852 Session::mark_insert_id (uint32_t id)
3854 if (id >= insert_bitset.size()) {
3855 insert_bitset.resize (id+16, false);
3857 if (insert_bitset[id]) {
3858 warning << string_compose (_("insert ID %1 appears to be in use already"), id) << endmsg;
3860 insert_bitset[id] = true;
3863 /* Named Selection management */
3866 Session::named_selection_by_name (string name)
3868 Glib::Mutex::Lock lm (named_selection_lock);
3869 for (NamedSelectionList::iterator i = named_selections.begin(); i != named_selections.end(); ++i) {
3870 if ((*i)->name == name) {
3878 Session::add_named_selection (NamedSelection* named_selection)
3881 Glib::Mutex::Lock lm (named_selection_lock);
3882 named_selections.insert (named_selections.begin(), named_selection);
3885 for (list<boost::shared_ptr<Playlist> >::iterator i = named_selection->playlists.begin(); i != named_selection->playlists.end(); ++i) {
3891 NamedSelectionAdded (); /* EMIT SIGNAL */
3895 Session::remove_named_selection (NamedSelection* named_selection)
3897 bool removed = false;
3900 Glib::Mutex::Lock lm (named_selection_lock);
3902 NamedSelectionList::iterator i = find (named_selections.begin(), named_selections.end(), named_selection);
3904 if (i != named_selections.end()) {
3906 named_selections.erase (i);
3913 NamedSelectionRemoved (); /* EMIT SIGNAL */
3918 Session::reset_native_file_format ()
3920 boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
3922 for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
3923 (*i)->reset_write_sources (false);
3928 Session::route_name_unique (string n) const
3930 shared_ptr<RouteList> r = routes.reader ();
3932 for (RouteList::const_iterator i = r->begin(); i != r->end(); ++i) {
3933 if ((*i)->name() == n) {
3942 Session::n_playlists () const
3944 Glib::Mutex::Lock lm (playlist_lock);
3945 return playlists.size();
3949 Session::allocate_pan_automation_buffers (nframes_t nframes, uint32_t howmany, bool force)
3951 if (!force && howmany <= _npan_buffers) {
3955 if (_pan_automation_buffer) {
3957 for (uint32_t i = 0; i < _npan_buffers; ++i) {
3958 delete [] _pan_automation_buffer[i];
3961 delete [] _pan_automation_buffer;
3964 _pan_automation_buffer = new pan_t*[howmany];
3966 for (uint32_t i = 0; i < howmany; ++i) {
3967 _pan_automation_buffer[i] = new pan_t[nframes];
3970 _npan_buffers = howmany;
3974 Session::freeze (InterThreadInfo& itt)
3976 shared_ptr<RouteList> r = routes.reader ();
3978 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3982 if ((at = dynamic_cast<Track*>((*i).get())) != 0) {
3983 /* XXX this is wrong because itt.progress will keep returning to zero at the start
3994 Session::write_one_audio_track (AudioTrack& track, nframes_t start, nframes_t len,
3995 bool overwrite, vector<boost::shared_ptr<Source> >& srcs, InterThreadInfo& itt)
3998 boost::shared_ptr<Playlist> playlist;
3999 boost::shared_ptr<AudioFileSource> fsource;
4001 char buf[PATH_MAX+1];
4002 ChanCount nchans(track.audio_diskstream()->n_channels());
4004 nframes_t this_chunk;
4007 SessionDirectory sdir(get_best_session_directory_for_new_source ());
4008 const string sound_dir = sdir.sound_path().to_string();
4010 // any bigger than this seems to cause stack overflows in called functions
4011 const nframes_t chunk_size = (128 * 1024)/4;
4013 g_atomic_int_set (&processing_prohibited, 1);
4015 /* call tree *MUST* hold route_lock */
4017 if ((playlist = track.diskstream()->playlist()) == 0) {
4021 /* external redirects will be a problem */
4023 if (track.has_external_redirects()) {
4027 for (uint32_t chan_n=0; chan_n < nchans.n_audio(); ++chan_n) {
4029 for (x = 0; x < 99999; ++x) {
4030 snprintf (buf, sizeof(buf), "%s/%s-%d-bounce-%" PRIu32 ".wav", sound_dir.c_str(), playlist->name().c_str(), chan_n, x+1);
4031 if (access (buf, F_OK) != 0) {
4037 error << string_compose (_("too many bounced versions of playlist \"%1\""), playlist->name()) << endmsg;
4042 fsource = boost::dynamic_pointer_cast<AudioFileSource> (
4043 SourceFactory::createWritable (DataType::AUDIO, *this, buf, false, frame_rate()));
4046 catch (failed_constructor& err) {
4047 error << string_compose (_("cannot create new audio file \"%1\" for %2"), buf, track.name()) << endmsg;
4051 srcs.push_back (fsource);
4054 /* XXX need to flush all redirects */
4059 /* create a set of reasonably-sized buffers */
4060 buffers.ensure_buffers(nchans, chunk_size);
4061 buffers.set_count(nchans);
4063 for (vector<boost::shared_ptr<Source> >::iterator src=srcs.begin(); src != srcs.end(); ++src) {
4064 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
4066 afs->prepare_for_peakfile_writes ();
4069 while (to_do && !itt.cancel) {
4071 this_chunk = min (to_do, chunk_size);
4073 if (track.export_stuff (buffers, start, this_chunk)) {
4078 for (vector<boost::shared_ptr<Source> >::iterator src=srcs.begin(); src != srcs.end(); ++src, ++n) {
4079 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
4082 if (afs->write (buffers.get_audio(n).data(), this_chunk) != this_chunk) {
4088 start += this_chunk;
4089 to_do -= this_chunk;
4091 itt.progress = (float) (1.0 - ((double) to_do / len));
4100 xnow = localtime (&now);
4102 for (vector<boost::shared_ptr<Source> >::iterator src=srcs.begin(); src != srcs.end(); ++src) {
4103 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
4106 afs->update_header (position, *xnow, now);
4107 afs->flush_header ();
4111 /* construct a region to represent the bounced material */
4113 boost::shared_ptr<Region> aregion = RegionFactory::create (srcs, 0, srcs.front()->length(),
4114 region_name_from_path (srcs.front()->name(), true));
4121 for (vector<boost::shared_ptr<Source> >::iterator src = srcs.begin(); src != srcs.end(); ++src) {
4122 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
4125 afs->mark_for_remove ();
4128 (*src)->drop_references ();
4132 for (vector<boost::shared_ptr<Source> >::iterator src = srcs.begin(); src != srcs.end(); ++src) {
4133 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
4136 afs->done_with_peakfile_writes ();
4140 g_atomic_int_set (&processing_prohibited, 0);
4146 Session::get_silent_buffers (ChanCount count)
4148 assert(_silent_buffers->available() >= count);
4149 _silent_buffers->set_count(count);
4151 for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
4152 for (size_t i=0; i < count.get(*t); ++i) {
4153 _silent_buffers->get(*t, i).clear();
4157 return *_silent_buffers;
4161 Session::get_scratch_buffers (ChanCount count)
4163 assert(_scratch_buffers->available() >= count);
4164 _scratch_buffers->set_count(count);
4165 return *_scratch_buffers;
4169 Session::get_mix_buffers (ChanCount count)
4171 assert(_mix_buffers->available() >= count);
4172 _mix_buffers->set_count(count);
4173 return *_mix_buffers;
4177 Session::ntracks () 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())) {
4192 Session::nbusses () const
4195 shared_ptr<RouteList> r = routes.reader ();
4197 for (RouteList::const_iterator i = r->begin(); i != r->end(); ++i) {
4198 if (dynamic_cast<Track*> ((*i).get()) == 0) {
4207 Session::add_automation_list(AutomationList *al)
4209 automation_lists[al->id()] = al;
4213 Session::compute_initial_length ()
4215 return _engine.frame_rate() * 60 * 5;
4219 Session::sync_order_keys ()
4221 if (!Config->get_sync_all_route_ordering()) {
4222 /* leave order keys as they are */
4226 boost::shared_ptr<RouteList> r = routes.reader ();
4228 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4229 (*i)->sync_order_keys ();
4232 Route::SyncOrderKeys (); // EMIT SIGNAL
4236 Session::foreach_bundle (sigc::slot<void, boost::shared_ptr<Bundle> > sl)
4238 Glib::Mutex::Lock lm (bundle_lock);
4239 for (BundleList::iterator i = _bundles.begin(); i != _bundles.end(); ++i) {