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 // We need to disconnect the routes inputs and outputs
2094 route->disconnect_inputs (0);
2095 route->disconnect_outputs (0);
2097 update_latency_compensation (false, false);
2100 /* get rid of it from the dead wood collection in the route list manager */
2102 /* XXX i think this is unsafe as it currently stands, but i am not sure. (pd, october 2nd, 2006) */
2106 /* try to cause everyone to drop their references */
2108 route->drop_references ();
2110 /* save the new state of the world */
2112 if (save_state (_current_snapshot_name)) {
2113 save_history (_current_snapshot_name);
2118 Session::route_mute_changed (void* src)
2124 Session::route_solo_changed (void* src, boost::weak_ptr<Route> wpr)
2126 if (solo_update_disabled) {
2132 boost::shared_ptr<Route> route = wpr.lock ();
2135 /* should not happen */
2136 error << string_compose (_("programming error: %1"), X_("invalid route weak ptr passed to route_solo_changed")) << endmsg;
2140 is_track = (boost::dynamic_pointer_cast<AudioTrack>(route) != 0);
2142 shared_ptr<RouteList> r = routes.reader ();
2144 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2146 /* soloing a track mutes all other tracks, soloing a bus mutes all other busses */
2150 /* don't mess with busses */
2152 if (dynamic_cast<Track*>((*i).get()) == 0) {
2158 /* don't mess with tracks */
2160 if (dynamic_cast<Track*>((*i).get()) != 0) {
2165 if ((*i) != route &&
2166 ((*i)->mix_group () == 0 ||
2167 (*i)->mix_group () != route->mix_group () ||
2168 !route->mix_group ()->is_active())) {
2170 if ((*i)->soloed()) {
2172 /* if its already soloed, and solo latching is enabled,
2173 then leave it as it is.
2176 if (Config->get_solo_latched()) {
2183 solo_update_disabled = true;
2184 (*i)->set_solo (false, src);
2185 solo_update_disabled = false;
2189 bool something_soloed = false;
2190 bool same_thing_soloed = false;
2191 bool signal = false;
2193 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2194 if ((*i)->soloed()) {
2195 something_soloed = true;
2196 if (dynamic_cast<Track*>((*i).get())) {
2198 same_thing_soloed = true;
2203 same_thing_soloed = true;
2211 if (something_soloed != currently_soloing) {
2213 currently_soloing = something_soloed;
2216 modify_solo_mute (is_track, same_thing_soloed);
2219 SoloActive (currently_soloing); /* EMIT SIGNAL */
2222 SoloChanged (); /* EMIT SIGNAL */
2228 Session::update_route_solo_state ()
2231 bool is_track = false;
2232 bool signal = false;
2234 /* caller must hold RouteLock */
2236 /* this is where we actually implement solo by changing
2237 the solo mute setting of each track.
2240 shared_ptr<RouteList> r = routes.reader ();
2242 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2243 if ((*i)->soloed()) {
2245 if (dynamic_cast<Track*>((*i).get())) {
2252 if (mute != currently_soloing) {
2254 currently_soloing = mute;
2257 if (!is_track && !mute) {
2259 /* nothing is soloed */
2261 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2262 (*i)->set_solo_mute (false);
2272 modify_solo_mute (is_track, mute);
2275 SoloActive (currently_soloing);
2280 Session::modify_solo_mute (bool is_track, bool mute)
2282 shared_ptr<RouteList> r = routes.reader ();
2284 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2288 /* only alter track solo mute */
2290 if (dynamic_cast<Track*>((*i).get())) {
2291 if ((*i)->soloed()) {
2292 (*i)->set_solo_mute (!mute);
2294 (*i)->set_solo_mute (mute);
2300 /* only alter bus solo mute */
2302 if (!dynamic_cast<Track*>((*i).get())) {
2304 if ((*i)->soloed()) {
2306 (*i)->set_solo_mute (false);
2310 /* don't mute master or control outs
2311 in response to another bus solo
2314 if ((*i) != _master_out &&
2315 (*i) != _control_out) {
2316 (*i)->set_solo_mute (mute);
2327 Session::catch_up_on_solo ()
2329 /* this is called after set_state() to catch the full solo
2330 state, which can't be correctly determined on a per-route
2331 basis, but needs the global overview that only the session
2334 update_route_solo_state();
2338 Session::route_by_name (string name)
2340 shared_ptr<RouteList> r = routes.reader ();
2342 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2343 if ((*i)->name() == name) {
2348 return shared_ptr<Route> ((Route*) 0);
2352 Session::route_by_id (PBD::ID id)
2354 shared_ptr<RouteList> r = routes.reader ();
2356 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2357 if ((*i)->id() == id) {
2362 return shared_ptr<Route> ((Route*) 0);
2366 Session::route_by_remote_id (uint32_t id)
2368 shared_ptr<RouteList> r = routes.reader ();
2370 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2371 if ((*i)->remote_control_id() == id) {
2376 return shared_ptr<Route> ((Route*) 0);
2380 Session::find_current_end ()
2382 if (_state_of_the_state & Loading) {
2386 nframes_t max = get_maximum_extent ();
2388 if (max > end_location->end()) {
2389 end_location->set_end (max);
2391 DurationChanged(); /* EMIT SIGNAL */
2396 Session::get_maximum_extent () const
2401 boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
2403 for (DiskstreamList::const_iterator i = dsl->begin(); i != dsl->end(); ++i) {
2404 boost::shared_ptr<Playlist> pl = (*i)->playlist();
2405 if ((me = pl->get_maximum_extent()) > max) {
2413 boost::shared_ptr<Diskstream>
2414 Session::diskstream_by_name (string name)
2416 boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
2418 for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
2419 if ((*i)->name() == name) {
2424 return boost::shared_ptr<Diskstream>((Diskstream*) 0);
2427 boost::shared_ptr<Diskstream>
2428 Session::diskstream_by_id (const PBD::ID& id)
2430 boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
2432 for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
2433 if ((*i)->id() == id) {
2438 return boost::shared_ptr<Diskstream>((Diskstream*) 0);
2441 /* Region management */
2444 Session::new_region_name (string old)
2446 string::size_type last_period;
2448 string::size_type len = old.length() + 64;
2451 if ((last_period = old.find_last_of ('.')) == string::npos) {
2453 /* no period present - add one explicitly */
2456 last_period = old.length() - 1;
2461 number = atoi (old.substr (last_period+1).c_str());
2465 while (number < (UINT_MAX-1)) {
2467 RegionList::const_iterator i;
2472 snprintf (buf, len, "%s%" PRIu32, old.substr (0, last_period + 1).c_str(), number);
2475 for (i = regions.begin(); i != regions.end(); ++i) {
2476 if (i->second->name() == sbuf) {
2481 if (i == regions.end()) {
2486 if (number != (UINT_MAX-1)) {
2490 error << string_compose (_("cannot create new name for region \"%1\""), old) << endmsg;
2495 Session::region_name (string& result, string base, bool newlevel) const
2500 assert(base.find("/") == string::npos);
2504 Glib::Mutex::Lock lm (region_lock);
2506 snprintf (buf, sizeof (buf), "%d", (int)regions.size() + 1);
2514 /* XXX this is going to be slow. optimize me later */
2519 string::size_type pos;
2521 pos = base.find_last_of ('.');
2523 /* pos may be npos, but then we just use entire base */
2525 subbase = base.substr (0, pos);
2529 bool name_taken = true;
2532 Glib::Mutex::Lock lm (region_lock);
2534 for (int n = 1; n < 5000; ++n) {
2537 snprintf (buf, sizeof (buf), ".%d", n);
2542 for (RegionList::const_iterator i = regions.begin(); i != regions.end(); ++i) {
2543 if (i->second->name() == result) {
2556 fatal << string_compose(_("too many regions with names like %1"), base) << endmsg;
2564 Session::add_region (boost::shared_ptr<Region> region)
2566 boost::shared_ptr<Region> other;
2570 Glib::Mutex::Lock lm (region_lock);
2572 RegionList::iterator x;
2574 for (x = regions.begin(); x != regions.end(); ++x) {
2578 if (region->region_list_equivalent (other)) {
2583 if (x == regions.end()) {
2585 pair<RegionList::key_type,RegionList::mapped_type> entry;
2587 entry.first = region->id();
2588 entry.second = region;
2590 pair<RegionList::iterator,bool> x = regions.insert (entry);
2602 /* mark dirty because something has changed even if we didn't
2603 add the region to the region list.
2609 region->GoingAway.connect (sigc::bind (mem_fun (*this, &Session::remove_region), boost::weak_ptr<Region>(region)));
2610 region->StateChanged.connect (sigc::bind (mem_fun (*this, &Session::region_changed), boost::weak_ptr<Region>(region)));
2611 RegionAdded (region); /* EMIT SIGNAL */
2616 Session::region_changed (Change what_changed, boost::weak_ptr<Region> weak_region)
2618 boost::shared_ptr<Region> region (weak_region.lock ());
2624 if (what_changed & Region::HiddenChanged) {
2625 /* relay hidden changes */
2626 RegionHiddenChange (region);
2631 Session::remove_region (boost::weak_ptr<Region> weak_region)
2633 RegionList::iterator i;
2634 boost::shared_ptr<Region> region (weak_region.lock ());
2640 bool removed = false;
2643 Glib::Mutex::Lock lm (region_lock);
2645 if ((i = regions.find (region->id())) != regions.end()) {
2651 /* mark dirty because something has changed even if we didn't
2652 remove the region from the region list.
2658 RegionRemoved(region); /* EMIT SIGNAL */
2662 boost::shared_ptr<Region>
2663 Session::find_whole_file_parent (boost::shared_ptr<Region const> child)
2665 RegionList::iterator i;
2666 boost::shared_ptr<Region> region;
2668 Glib::Mutex::Lock lm (region_lock);
2670 for (i = regions.begin(); i != regions.end(); ++i) {
2674 if (region->whole_file()) {
2676 if (child->source_equivalent (region)) {
2682 return boost::shared_ptr<Region> ();
2686 Session::find_equivalent_playlist_regions (boost::shared_ptr<Region> region, vector<boost::shared_ptr<Region> >& result)
2688 for (PlaylistList::iterator i = playlists.begin(); i != playlists.end(); ++i)
2689 (*i)->get_region_list_equivalent_regions (region, result);
2693 Session::destroy_region (boost::shared_ptr<Region> region)
2695 vector<boost::shared_ptr<Source> > srcs;
2698 boost::shared_ptr<AudioRegion> aregion;
2700 if ((aregion = boost::dynamic_pointer_cast<AudioRegion> (region)) == 0) {
2704 if (aregion->playlist()) {
2705 aregion->playlist()->destroy_region (region);
2708 for (uint32_t n = 0; n < aregion->n_channels(); ++n) {
2709 srcs.push_back (aregion->source (n));
2713 region->drop_references ();
2715 for (vector<boost::shared_ptr<Source> >::iterator i = srcs.begin(); i != srcs.end(); ++i) {
2717 if (!(*i)->used()) {
2718 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*i);
2721 (afs)->mark_for_remove ();
2724 (*i)->drop_references ();
2726 cerr << "source was not used by any playlist\n";
2734 Session::destroy_regions (list<boost::shared_ptr<Region> > regions)
2736 for (list<boost::shared_ptr<Region> >::iterator i = regions.begin(); i != regions.end(); ++i) {
2737 destroy_region (*i);
2743 Session::remove_last_capture ()
2745 list<boost::shared_ptr<Region> > r;
2747 boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
2749 for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
2750 list<boost::shared_ptr<Region> >& l = (*i)->last_capture_regions();
2753 r.insert (r.end(), l.begin(), l.end());
2758 destroy_regions (r);
2760 save_state (_current_snapshot_name);
2766 Session::remove_region_from_region_list (boost::shared_ptr<Region> r)
2772 /* Source Management */
2774 Session::add_source (boost::shared_ptr<Source> source)
2776 pair<SourceMap::key_type, SourceMap::mapped_type> entry;
2777 pair<SourceMap::iterator,bool> result;
2779 entry.first = source->id();
2780 entry.second = source;
2783 Glib::Mutex::Lock lm (source_lock);
2784 result = sources.insert (entry);
2787 if (result.second) {
2788 source->GoingAway.connect (sigc::bind (mem_fun (this, &Session::remove_source), boost::weak_ptr<Source> (source)));
2794 Session::remove_source (boost::weak_ptr<Source> src)
2796 SourceMap::iterator i;
2797 boost::shared_ptr<Source> source = src.lock();
2804 Glib::Mutex::Lock lm (source_lock);
2806 if ((i = sources.find (source->id())) != sources.end()) {
2811 if (!_state_of_the_state & InCleanup) {
2813 /* save state so we don't end up with a session file
2814 referring to non-existent sources.
2817 save_state (_current_snapshot_name);
2821 boost::shared_ptr<Source>
2822 Session::source_by_id (const PBD::ID& id)
2824 Glib::Mutex::Lock lm (source_lock);
2825 SourceMap::iterator i;
2826 boost::shared_ptr<Source> source;
2828 if ((i = sources.find (id)) != sources.end()) {
2836 boost::shared_ptr<Source>
2837 Session::source_by_path_and_channel (const Glib::ustring& path, uint16_t chn)
2839 Glib::Mutex::Lock lm (source_lock);
2841 for (SourceMap::iterator i = sources.begin(); i != sources.end(); ++i) {
2842 cerr << "comparing " << path << " with " << i->second->name() << endl;
2843 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(i->second);
2845 if (afs && afs->path() == path && chn == afs->channel()) {
2850 return boost::shared_ptr<Source>();
2854 Session::peak_path (Glib::ustring base) const
2856 sys::path peakfile_path(_session_dir->peak_path());
2857 peakfile_path /= basename_nosuffix (base) + peakfile_suffix;
2858 return peakfile_path.to_string();
2862 Session::change_audio_path_by_name (string path, string oldname, string newname, bool destructive)
2865 string old_basename = PBD::basename_nosuffix (oldname);
2866 string new_legalized = legalize_for_path (newname);
2868 /* note: we know (or assume) the old path is already valid */
2872 /* destructive file sources have a name of the form:
2874 /path/to/Tnnnn-NAME(%[LR])?.wav
2876 the task here is to replace NAME with the new name.
2879 /* find last slash */
2883 string::size_type slash;
2884 string::size_type dash;
2886 if ((slash = path.find_last_of ('/')) == string::npos) {
2890 dir = path.substr (0, slash+1);
2892 /* '-' is not a legal character for the NAME part of the path */
2894 if ((dash = path.find_last_of ('-')) == string::npos) {
2898 prefix = path.substr (slash+1, dash-(slash+1));
2903 path += new_legalized;
2904 path += ".wav"; /* XXX gag me with a spoon */
2908 /* non-destructive file sources have a name of the form:
2910 /path/to/NAME-nnnnn(%[LR])?.wav
2912 the task here is to replace NAME with the new name.
2917 string::size_type slash;
2918 string::size_type dash;
2919 string::size_type postfix;
2921 /* find last slash */
2923 if ((slash = path.find_last_of ('/')) == string::npos) {
2927 dir = path.substr (0, slash+1);
2929 /* '-' is not a legal character for the NAME part of the path */
2931 if ((dash = path.find_last_of ('-')) == string::npos) {
2935 suffix = path.substr (dash+1);
2937 // Suffix is now everything after the dash. Now we need to eliminate
2938 // the nnnnn part, which is done by either finding a '%' or a '.'
2940 postfix = suffix.find_last_of ("%");
2941 if (postfix == string::npos) {
2942 postfix = suffix.find_last_of ('.');
2945 if (postfix != string::npos) {
2946 suffix = suffix.substr (postfix);
2948 error << "Logic error in Session::change_audio_path_by_name(), please report to the developers" << endl;
2952 const uint32_t limit = 10000;
2953 char buf[PATH_MAX+1];
2955 for (uint32_t cnt = 1; cnt <= limit; ++cnt) {
2957 snprintf (buf, sizeof(buf), "%s%s-%u%s", dir.c_str(), newname.c_str(), cnt, suffix.c_str());
2959 if (access (buf, F_OK) != 0) {
2967 error << "FATAL ERROR! Could not find a " << endl;
2976 Session::audio_path_from_name (string name, uint32_t nchan, uint32_t chan, bool destructive)
2980 char buf[PATH_MAX+1];
2981 const uint32_t limit = 10000;
2985 legalized = legalize_for_path (name);
2987 /* find a "version" of the file name that doesn't exist in
2988 any of the possible directories.
2991 for (cnt = (destructive ? ++destructive_index : 1); cnt <= limit; ++cnt) {
2993 vector<space_and_path>::iterator i;
2994 uint32_t existing = 0;
2996 for (i = session_dirs.begin(); i != session_dirs.end(); ++i) {
2998 SessionDirectory sdir((*i).path);
3000 spath = sdir.sound_path().to_string();
3004 snprintf (buf, sizeof(buf), "%s/T%04d-%s.wav", spath.c_str(), cnt, legalized.c_str());
3005 } else if (nchan == 2) {
3007 snprintf (buf, sizeof(buf), "%s/T%04d-%s%%L.wav", spath.c_str(), cnt, legalized.c_str());
3009 snprintf (buf, sizeof(buf), "%s/T%04d-%s%%R.wav", spath.c_str(), cnt, legalized.c_str());
3011 } else if (nchan < 26) {
3012 snprintf (buf, sizeof(buf), "%s/T%04d-%s%%%c.wav", spath.c_str(), cnt, legalized.c_str(), 'a' + chan);
3014 snprintf (buf, sizeof(buf), "%s/T%04d-%s.wav", spath.c_str(), cnt, legalized.c_str());
3023 snprintf (buf, sizeof(buf), "%s-%u.wav", spath.c_str(), cnt);
3024 } else if (nchan == 2) {
3026 snprintf (buf, sizeof(buf), "%s-%u%%L.wav", spath.c_str(), cnt);
3028 snprintf (buf, sizeof(buf), "%s-%u%%R.wav", spath.c_str(), cnt);
3030 } else if (nchan < 26) {
3031 snprintf (buf, sizeof(buf), "%s-%u%%%c.wav", spath.c_str(), cnt, 'a' + chan);
3033 snprintf (buf, sizeof(buf), "%s-%u.wav", spath.c_str(), cnt);
3037 if (sys::exists(buf)) {
3043 if (existing == 0) {
3048 error << string_compose(_("There are already %1 recordings for %2, which I consider too many."), limit, name) << endmsg;
3050 throw failed_constructor();
3054 /* we now have a unique name for the file, but figure out where to
3060 SessionDirectory sdir(get_best_session_directory_for_new_source ());
3062 spath = sdir.sound_path().to_string();
3065 string::size_type pos = foo.find_last_of ('/');
3067 if (pos == string::npos) {
3070 spath += foo.substr (pos + 1);
3076 boost::shared_ptr<AudioFileSource>
3077 Session::create_audio_source_for_session (AudioDiskstream& ds, uint32_t chan, bool destructive)
3079 string spath = audio_path_from_name (ds.name(), ds.n_channels().n_audio(), chan, destructive);
3080 return boost::dynamic_pointer_cast<AudioFileSource> (
3081 SourceFactory::createWritable (DataType::AUDIO, *this, spath, destructive, frame_rate()));
3084 // FIXME: _terrible_ code duplication
3086 Session::change_midi_path_by_name (string path, string oldname, string newname, bool destructive)
3089 string old_basename = PBD::basename_nosuffix (oldname);
3090 string new_legalized = legalize_for_path (newname);
3092 /* note: we know (or assume) the old path is already valid */
3096 /* destructive file sources have a name of the form:
3098 /path/to/Tnnnn-NAME(%[LR])?.wav
3100 the task here is to replace NAME with the new name.
3103 /* find last slash */
3107 string::size_type slash;
3108 string::size_type dash;
3110 if ((slash = path.find_last_of ('/')) == string::npos) {
3114 dir = path.substr (0, slash+1);
3116 /* '-' is not a legal character for the NAME part of the path */
3118 if ((dash = path.find_last_of ('-')) == string::npos) {
3122 prefix = path.substr (slash+1, dash-(slash+1));
3127 path += new_legalized;
3128 path += ".mid"; /* XXX gag me with a spoon */
3132 /* non-destructive file sources have a name of the form:
3134 /path/to/NAME-nnnnn(%[LR])?.wav
3136 the task here is to replace NAME with the new name.
3141 string::size_type slash;
3142 string::size_type dash;
3143 string::size_type postfix;
3145 /* find last slash */
3147 if ((slash = path.find_last_of ('/')) == string::npos) {
3151 dir = path.substr (0, slash+1);
3153 /* '-' is not a legal character for the NAME part of the path */
3155 if ((dash = path.find_last_of ('-')) == string::npos) {
3159 suffix = path.substr (dash+1);
3161 // Suffix is now everything after the dash. Now we need to eliminate
3162 // the nnnnn part, which is done by either finding a '%' or a '.'
3164 postfix = suffix.find_last_of ("%");
3165 if (postfix == string::npos) {
3166 postfix = suffix.find_last_of ('.');
3169 if (postfix != string::npos) {
3170 suffix = suffix.substr (postfix);
3172 error << "Logic error in Session::change_midi_path_by_name(), please report to the developers" << endl;
3176 const uint32_t limit = 10000;
3177 char buf[PATH_MAX+1];
3179 for (uint32_t cnt = 1; cnt <= limit; ++cnt) {
3181 snprintf (buf, sizeof(buf), "%s%s-%u%s", dir.c_str(), newname.c_str(), cnt, suffix.c_str());
3183 if (access (buf, F_OK) != 0) {
3191 error << "FATAL ERROR! Could not find a " << endl;
3200 Session::midi_path_from_name (string name)
3204 char buf[PATH_MAX+1];
3205 const uint32_t limit = 10000;
3209 legalized = legalize_for_path (name);
3211 /* find a "version" of the file name that doesn't exist in
3212 any of the possible directories.
3215 for (cnt = 1; cnt <= limit; ++cnt) {
3217 vector<space_and_path>::iterator i;
3218 uint32_t existing = 0;
3220 for (i = session_dirs.begin(); i != session_dirs.end(); ++i) {
3222 SessionDirectory sdir((*i).path);
3224 sys::path p = sdir.midi_path();
3228 spath = p.to_string();
3230 snprintf (buf, sizeof(buf), "%s-%u.mid", spath.c_str(), cnt);
3232 if (sys::exists (buf)) {
3237 if (existing == 0) {
3242 error << string_compose(_("There are already %1 recordings for %2, which I consider too many."), limit, name) << endmsg;
3243 throw failed_constructor();
3247 /* we now have a unique name for the file, but figure out where to
3253 SessionDirectory sdir(get_best_session_directory_for_new_source ());
3255 spath = sdir.midi_path().to_string();
3258 string::size_type pos = foo.find_last_of ('/');
3260 if (pos == string::npos) {
3263 spath += foo.substr (pos + 1);
3269 boost::shared_ptr<MidiSource>
3270 Session::create_midi_source_for_session (MidiDiskstream& ds)
3272 string mpath = midi_path_from_name (ds.name());
3274 return boost::dynamic_pointer_cast<SMFSource> (SourceFactory::createWritable (DataType::MIDI, *this, mpath, false, frame_rate()));
3278 /* Playlist management */
3280 boost::shared_ptr<Playlist>
3281 Session::playlist_by_name (string name)
3283 Glib::Mutex::Lock lm (playlist_lock);
3284 for (PlaylistList::iterator i = playlists.begin(); i != playlists.end(); ++i) {
3285 if ((*i)->name() == name) {
3289 for (PlaylistList::iterator i = unused_playlists.begin(); i != unused_playlists.end(); ++i) {
3290 if ((*i)->name() == name) {
3295 return boost::shared_ptr<Playlist>();
3299 Session::add_playlist (boost::shared_ptr<Playlist> playlist)
3301 if (playlist->hidden()) {
3306 Glib::Mutex::Lock lm (playlist_lock);
3307 if (find (playlists.begin(), playlists.end(), playlist) == playlists.end()) {
3308 playlists.insert (playlists.begin(), playlist);
3309 playlist->InUse.connect (sigc::bind (mem_fun (*this, &Session::track_playlist), boost::weak_ptr<Playlist>(playlist)));
3310 playlist->GoingAway.connect (sigc::bind (mem_fun (*this, &Session::remove_playlist), boost::weak_ptr<Playlist>(playlist)));
3316 PlaylistAdded (playlist); /* EMIT SIGNAL */
3320 Session::get_playlists (vector<boost::shared_ptr<Playlist> >& s)
3323 Glib::Mutex::Lock lm (playlist_lock);
3324 for (PlaylistList::iterator i = playlists.begin(); i != playlists.end(); ++i) {
3327 for (PlaylistList::iterator i = unused_playlists.begin(); i != unused_playlists.end(); ++i) {
3334 Session::track_playlist (bool inuse, boost::weak_ptr<Playlist> wpl)
3336 boost::shared_ptr<Playlist> pl(wpl.lock());
3342 PlaylistList::iterator x;
3345 /* its not supposed to be visible */
3350 Glib::Mutex::Lock lm (playlist_lock);
3354 unused_playlists.insert (pl);
3356 if ((x = playlists.find (pl)) != playlists.end()) {
3357 playlists.erase (x);
3363 playlists.insert (pl);
3365 if ((x = unused_playlists.find (pl)) != unused_playlists.end()) {
3366 unused_playlists.erase (x);
3373 Session::remove_playlist (boost::weak_ptr<Playlist> weak_playlist)
3375 if (_state_of_the_state & Deletion) {
3379 boost::shared_ptr<Playlist> playlist (weak_playlist.lock());
3386 Glib::Mutex::Lock lm (playlist_lock);
3388 PlaylistList::iterator i;
3390 i = find (playlists.begin(), playlists.end(), playlist);
3391 if (i != playlists.end()) {
3392 playlists.erase (i);
3395 i = find (unused_playlists.begin(), unused_playlists.end(), playlist);
3396 if (i != unused_playlists.end()) {
3397 unused_playlists.erase (i);
3404 PlaylistRemoved (playlist); /* EMIT SIGNAL */
3408 Session::set_audition (boost::shared_ptr<Region> r)
3410 pending_audition_region = r;
3411 post_transport_work = PostTransportWork (post_transport_work | PostTransportAudition);
3412 schedule_butler_transport_work ();
3416 Session::audition_playlist ()
3418 Event* ev = new Event (Event::Audition, Event::Add, Event::Immediate, 0, 0.0);
3419 ev->region.reset ();
3424 Session::non_realtime_set_audition ()
3426 if (!pending_audition_region) {
3427 auditioner->audition_current_playlist ();
3429 auditioner->audition_region (pending_audition_region);
3430 pending_audition_region.reset ();
3432 AuditionActive (true); /* EMIT SIGNAL */
3436 Session::audition_region (boost::shared_ptr<Region> r)
3438 Event* ev = new Event (Event::Audition, Event::Add, Event::Immediate, 0, 0.0);
3444 Session::cancel_audition ()
3446 if (auditioner->active()) {
3447 auditioner->cancel_audition ();
3448 AuditionActive (false); /* EMIT SIGNAL */
3453 Session::RoutePublicOrderSorter::operator() (boost::shared_ptr<Route> a, boost::shared_ptr<Route> b)
3455 return a->order_key(N_("signal")) < b->order_key(N_("signal"));
3459 Session::remove_empty_sounds ()
3461 vector<string> audio_filenames;
3463 get_files_in_directory (_session_dir->sound_path(), audio_filenames);
3465 Glib::Mutex::Lock lm (source_lock);
3467 TapeFileMatcher tape_file_matcher;
3469 remove_if (audio_filenames.begin(), audio_filenames.end(),
3470 sigc::mem_fun (tape_file_matcher, &TapeFileMatcher::matches));
3472 for (vector<string>::iterator i = audio_filenames.begin(); i != audio_filenames.end(); ++i) {
3474 sys::path audio_file_path (_session_dir->sound_path());
3476 audio_file_path /= *i;
3478 if (AudioFileSource::is_empty (*this, audio_file_path.to_string())) {
3482 sys::remove (audio_file_path);
3483 const string peakfile = peak_path (audio_file_path.to_string());
3484 sys::remove (peakfile);
3486 catch (const sys::filesystem_error& err)
3488 error << err.what() << endmsg;
3495 Session::is_auditioning () const
3497 /* can be called before we have an auditioner object */
3499 return auditioner->active();
3506 Session::set_all_solo (bool yn)
3508 shared_ptr<RouteList> r = routes.reader ();
3510 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3511 if (!(*i)->is_hidden()) {
3512 (*i)->set_solo (yn, this);
3520 Session::set_all_mute (bool yn)
3522 shared_ptr<RouteList> r = routes.reader ();
3524 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3525 if (!(*i)->is_hidden()) {
3526 (*i)->set_mute (yn, this);
3534 Session::n_diskstreams () const
3538 boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
3540 for (DiskstreamList::const_iterator i = dsl->begin(); i != dsl->end(); ++i) {
3541 if (!(*i)->hidden()) {
3549 Session::graph_reordered ()
3551 /* don't do this stuff if we are setting up connections
3552 from a set_state() call or creating new tracks.
3555 if (_state_of_the_state & InitialConnecting) {
3559 /* every track/bus asked for this to be handled but it was deferred because
3560 we were connecting. do it now.
3563 request_input_change_handling ();
3567 /* force all diskstreams to update their capture offset values to
3568 reflect any changes in latencies within the graph.
3571 boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
3573 for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
3574 (*i)->set_capture_offset ();
3579 Session::record_disenable_all ()
3581 record_enable_change_all (false);
3585 Session::record_enable_all ()
3587 record_enable_change_all (true);
3591 Session::record_enable_change_all (bool yn)
3593 shared_ptr<RouteList> r = routes.reader ();
3595 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3598 if ((at = dynamic_cast<Track*>((*i).get())) != 0) {
3599 at->set_record_enable (yn, this);
3603 /* since we don't keep rec-enable state, don't mark session dirty */
3607 Session::add_processor (Processor* processor)
3610 PortInsert* port_insert;
3611 PluginInsert* plugin_insert;
3613 if ((port_insert = dynamic_cast<PortInsert *> (processor)) != 0) {
3614 _port_inserts.insert (_port_inserts.begin(), port_insert);
3615 } else if ((plugin_insert = dynamic_cast<PluginInsert *> (processor)) != 0) {
3616 _plugin_inserts.insert (_plugin_inserts.begin(), plugin_insert);
3617 } else if ((send = dynamic_cast<Send *> (processor)) != 0) {
3618 _sends.insert (_sends.begin(), send);
3620 fatal << _("programming error: unknown type of Insert created!") << endmsg;
3624 processor->GoingAway.connect (sigc::bind (mem_fun (*this, &Session::remove_processor), processor));
3630 Session::remove_processor (Processor* processor)
3633 PortInsert* port_insert;
3634 PluginInsert* plugin_insert;
3636 if ((port_insert = dynamic_cast<PortInsert *> (processor)) != 0) {
3637 list<PortInsert*>::iterator x = find (_port_inserts.begin(), _port_inserts.end(), port_insert);
3638 if (x != _port_inserts.end()) {
3639 insert_bitset[port_insert->bit_slot()] = false;
3640 _port_inserts.erase (x);
3642 } else if ((plugin_insert = dynamic_cast<PluginInsert *> (processor)) != 0) {
3643 _plugin_inserts.remove (plugin_insert);
3644 } else if ((send = dynamic_cast<Send *> (processor)) != 0) {
3645 list<Send*>::iterator x = find (_sends.begin(), _sends.end(), send);
3646 if (x != _sends.end()) {
3647 send_bitset[send->bit_slot()] = false;
3651 fatal << _("programming error: unknown type of Insert deleted!") << endmsg;
3659 Session::available_capture_duration ()
3661 float sample_bytes_on_disk = 4.0; // keep gcc happy
3663 switch (Config->get_native_file_data_format()) {
3665 sample_bytes_on_disk = 4.0;
3669 sample_bytes_on_disk = 3.0;
3673 sample_bytes_on_disk = 2.0;
3677 /* impossible, but keep some gcc versions happy */
3678 fatal << string_compose (_("programming error: %1"),
3679 X_("illegal native file data format"))
3684 double scale = 4096.0 / sample_bytes_on_disk;
3686 if (_total_free_4k_blocks * scale > (double) max_frames) {
3690 return (nframes_t) floor (_total_free_4k_blocks * scale);
3694 Session::add_bundle (shared_ptr<Bundle> bundle)
3697 Glib::Mutex::Lock guard (bundle_lock);
3698 _bundles.push_back (bundle);
3701 BundleAdded (bundle); /* EMIT SIGNAL */
3707 Session::remove_bundle (shared_ptr<Bundle> bundle)
3709 bool removed = false;
3712 Glib::Mutex::Lock guard (bundle_lock);
3713 BundleList::iterator i = find (_bundles.begin(), _bundles.end(), bundle);
3715 if (i != _bundles.end()) {
3722 BundleRemoved (bundle); /* EMIT SIGNAL */
3729 Session::bundle_by_name (string name) const
3731 Glib::Mutex::Lock lm (bundle_lock);
3733 for (BundleList::const_iterator i = _bundles.begin(); i != _bundles.end(); ++i) {
3734 if ((*i)->name() == name) {
3739 return boost::shared_ptr<Bundle> ();
3742 boost::shared_ptr<Bundle>
3743 Session::bundle_by_ports (std::vector<std::string> const & wanted_ports) const
3745 Glib::Mutex::Lock lm (bundle_lock);
3747 for (BundleList::const_iterator i = _bundles.begin(); i != _bundles.end(); ++i) {
3748 if ((*i)->nchannels() != wanted_ports.size()) {
3753 for (uint32_t j = 0; j < (*i)->nchannels(); ++j) {
3754 Bundle::PortList const p = (*i)->channel_ports (j);
3755 if (p.empty() || p[0] != wanted_ports[j]) {
3756 /* not this bundle */
3763 /* matched bundle */
3768 return boost::shared_ptr<Bundle> ();
3772 Session::tempo_map_changed (Change ignored)
3778 /** Ensures that all buffers (scratch, send, silent, etc) are allocated for
3779 * the given count with the current block size.
3782 Session::ensure_buffers (ChanCount howmany)
3784 if (current_block_size == 0)
3785 return; // too early? (is this ok?)
3787 // We need at least 2 MIDI scratch buffers to mix/merge
3788 if (howmany.n_midi() < 2)
3789 howmany.set_midi(2);
3791 // FIXME: JACK needs to tell us maximum MIDI buffer size
3792 // Using nasty assumption (max # events == nframes) for now
3793 _scratch_buffers->ensure_buffers(howmany, current_block_size);
3794 _mix_buffers->ensure_buffers(howmany, current_block_size);
3795 _silent_buffers->ensure_buffers(howmany, current_block_size);
3797 allocate_pan_automation_buffers (current_block_size, howmany.n_audio(), false);
3801 Session::next_insert_id ()
3803 /* this doesn't really loop forever. just think about it */
3806 for (boost::dynamic_bitset<uint32_t>::size_type n = 0; n < insert_bitset.size(); ++n) {
3807 if (!insert_bitset[n]) {
3808 insert_bitset[n] = true;
3814 /* none available, so resize and try again */
3816 insert_bitset.resize (insert_bitset.size() + 16, false);
3821 Session::next_send_id ()
3823 /* this doesn't really loop forever. just think about it */
3826 for (boost::dynamic_bitset<uint32_t>::size_type n = 0; n < send_bitset.size(); ++n) {
3827 if (!send_bitset[n]) {
3828 send_bitset[n] = true;
3834 /* none available, so resize and try again */
3836 send_bitset.resize (send_bitset.size() + 16, false);
3841 Session::mark_send_id (uint32_t id)
3843 if (id >= send_bitset.size()) {
3844 send_bitset.resize (id+16, false);
3846 if (send_bitset[id]) {
3847 warning << string_compose (_("send ID %1 appears to be in use already"), id) << endmsg;
3849 send_bitset[id] = true;
3853 Session::mark_insert_id (uint32_t id)
3855 if (id >= insert_bitset.size()) {
3856 insert_bitset.resize (id+16, false);
3858 if (insert_bitset[id]) {
3859 warning << string_compose (_("insert ID %1 appears to be in use already"), id) << endmsg;
3861 insert_bitset[id] = true;
3864 /* Named Selection management */
3867 Session::named_selection_by_name (string name)
3869 Glib::Mutex::Lock lm (named_selection_lock);
3870 for (NamedSelectionList::iterator i = named_selections.begin(); i != named_selections.end(); ++i) {
3871 if ((*i)->name == name) {
3879 Session::add_named_selection (NamedSelection* named_selection)
3882 Glib::Mutex::Lock lm (named_selection_lock);
3883 named_selections.insert (named_selections.begin(), named_selection);
3886 for (list<boost::shared_ptr<Playlist> >::iterator i = named_selection->playlists.begin(); i != named_selection->playlists.end(); ++i) {
3892 NamedSelectionAdded (); /* EMIT SIGNAL */
3896 Session::remove_named_selection (NamedSelection* named_selection)
3898 bool removed = false;
3901 Glib::Mutex::Lock lm (named_selection_lock);
3903 NamedSelectionList::iterator i = find (named_selections.begin(), named_selections.end(), named_selection);
3905 if (i != named_selections.end()) {
3907 named_selections.erase (i);
3914 NamedSelectionRemoved (); /* EMIT SIGNAL */
3919 Session::reset_native_file_format ()
3921 boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
3923 for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
3924 (*i)->reset_write_sources (false);
3929 Session::route_name_unique (string n) const
3931 shared_ptr<RouteList> r = routes.reader ();
3933 for (RouteList::const_iterator i = r->begin(); i != r->end(); ++i) {
3934 if ((*i)->name() == n) {
3943 Session::n_playlists () const
3945 Glib::Mutex::Lock lm (playlist_lock);
3946 return playlists.size();
3950 Session::allocate_pan_automation_buffers (nframes_t nframes, uint32_t howmany, bool force)
3952 if (!force && howmany <= _npan_buffers) {
3956 if (_pan_automation_buffer) {
3958 for (uint32_t i = 0; i < _npan_buffers; ++i) {
3959 delete [] _pan_automation_buffer[i];
3962 delete [] _pan_automation_buffer;
3965 _pan_automation_buffer = new pan_t*[howmany];
3967 for (uint32_t i = 0; i < howmany; ++i) {
3968 _pan_automation_buffer[i] = new pan_t[nframes];
3971 _npan_buffers = howmany;
3975 Session::freeze (InterThreadInfo& itt)
3977 shared_ptr<RouteList> r = routes.reader ();
3979 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3983 if ((at = dynamic_cast<Track*>((*i).get())) != 0) {
3984 /* XXX this is wrong because itt.progress will keep returning to zero at the start
3995 Session::write_one_audio_track (AudioTrack& track, nframes_t start, nframes_t len,
3996 bool overwrite, vector<boost::shared_ptr<Source> >& srcs, InterThreadInfo& itt)
3999 boost::shared_ptr<Playlist> playlist;
4000 boost::shared_ptr<AudioFileSource> fsource;
4002 char buf[PATH_MAX+1];
4003 ChanCount nchans(track.audio_diskstream()->n_channels());
4005 nframes_t this_chunk;
4008 SessionDirectory sdir(get_best_session_directory_for_new_source ());
4009 const string sound_dir = sdir.sound_path().to_string();
4011 // any bigger than this seems to cause stack overflows in called functions
4012 const nframes_t chunk_size = (128 * 1024)/4;
4014 g_atomic_int_set (&processing_prohibited, 1);
4016 /* call tree *MUST* hold route_lock */
4018 if ((playlist = track.diskstream()->playlist()) == 0) {
4022 /* external redirects will be a problem */
4024 if (track.has_external_redirects()) {
4028 for (uint32_t chan_n=0; chan_n < nchans.n_audio(); ++chan_n) {
4030 for (x = 0; x < 99999; ++x) {
4031 snprintf (buf, sizeof(buf), "%s/%s-%d-bounce-%" PRIu32 ".wav", sound_dir.c_str(), playlist->name().c_str(), chan_n, x+1);
4032 if (access (buf, F_OK) != 0) {
4038 error << string_compose (_("too many bounced versions of playlist \"%1\""), playlist->name()) << endmsg;
4043 fsource = boost::dynamic_pointer_cast<AudioFileSource> (
4044 SourceFactory::createWritable (DataType::AUDIO, *this, buf, false, frame_rate()));
4047 catch (failed_constructor& err) {
4048 error << string_compose (_("cannot create new audio file \"%1\" for %2"), buf, track.name()) << endmsg;
4052 srcs.push_back (fsource);
4055 /* XXX need to flush all redirects */
4060 /* create a set of reasonably-sized buffers */
4061 buffers.ensure_buffers(nchans, chunk_size);
4062 buffers.set_count(nchans);
4064 for (vector<boost::shared_ptr<Source> >::iterator src=srcs.begin(); src != srcs.end(); ++src) {
4065 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
4067 afs->prepare_for_peakfile_writes ();
4070 while (to_do && !itt.cancel) {
4072 this_chunk = min (to_do, chunk_size);
4074 if (track.export_stuff (buffers, start, this_chunk)) {
4079 for (vector<boost::shared_ptr<Source> >::iterator src=srcs.begin(); src != srcs.end(); ++src, ++n) {
4080 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
4083 if (afs->write (buffers.get_audio(n).data(), this_chunk) != this_chunk) {
4089 start += this_chunk;
4090 to_do -= this_chunk;
4092 itt.progress = (float) (1.0 - ((double) to_do / len));
4101 xnow = localtime (&now);
4103 for (vector<boost::shared_ptr<Source> >::iterator src=srcs.begin(); src != srcs.end(); ++src) {
4104 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
4107 afs->update_header (position, *xnow, now);
4108 afs->flush_header ();
4112 /* construct a region to represent the bounced material */
4114 boost::shared_ptr<Region> aregion = RegionFactory::create (srcs, 0, srcs.front()->length(),
4115 region_name_from_path (srcs.front()->name(), true));
4122 for (vector<boost::shared_ptr<Source> >::iterator src = srcs.begin(); src != srcs.end(); ++src) {
4123 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
4126 afs->mark_for_remove ();
4129 (*src)->drop_references ();
4133 for (vector<boost::shared_ptr<Source> >::iterator src = srcs.begin(); src != srcs.end(); ++src) {
4134 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
4137 afs->done_with_peakfile_writes ();
4141 g_atomic_int_set (&processing_prohibited, 0);
4147 Session::get_silent_buffers (ChanCount count)
4149 assert(_silent_buffers->available() >= count);
4150 _silent_buffers->set_count(count);
4152 for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
4153 for (size_t i=0; i < count.get(*t); ++i) {
4154 _silent_buffers->get(*t, i).clear();
4158 return *_silent_buffers;
4162 Session::get_scratch_buffers (ChanCount count)
4164 assert(_scratch_buffers->available() >= count);
4165 _scratch_buffers->set_count(count);
4166 return *_scratch_buffers;
4170 Session::get_mix_buffers (ChanCount count)
4172 assert(_mix_buffers->available() >= count);
4173 _mix_buffers->set_count(count);
4174 return *_mix_buffers;
4178 Session::ntracks () const
4181 shared_ptr<RouteList> r = routes.reader ();
4183 for (RouteList::const_iterator i = r->begin(); i != r->end(); ++i) {
4184 if (dynamic_cast<Track*> ((*i).get())) {
4193 Session::nbusses () const
4196 shared_ptr<RouteList> r = routes.reader ();
4198 for (RouteList::const_iterator i = r->begin(); i != r->end(); ++i) {
4199 if (dynamic_cast<Track*> ((*i).get()) == 0) {
4208 Session::add_automation_list(AutomationList *al)
4210 automation_lists[al->id()] = al;
4214 Session::compute_initial_length ()
4216 return _engine.frame_rate() * 60 * 5;
4220 Session::sync_order_keys ()
4222 if (!Config->get_sync_all_route_ordering()) {
4223 /* leave order keys as they are */
4227 boost::shared_ptr<RouteList> r = routes.reader ();
4229 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4230 (*i)->sync_order_keys ();
4233 Route::SyncOrderKeys (); // EMIT SIGNAL
4237 Session::foreach_bundle (sigc::slot<void, boost::shared_ptr<Bundle> > sl)
4239 Glib::Mutex::Lock lm (bundle_lock);
4240 for (BundleList::iterator i = _bundles.begin(); i != _bundles.end(); ++i) {