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 */
32 #include <sigc++/bind.h>
33 #include <sigc++/retype.h>
35 #include <glibmm/thread.h>
36 #include <glibmm/miscutils.h>
37 #include <glibmm/fileutils.h>
39 #include <pbd/error.h>
40 #include <glibmm/thread.h>
41 #include <pbd/pathscanner.h>
42 #include <pbd/stl_delete.h>
43 #include <pbd/basename.h>
44 #include <pbd/stacktrace.h>
46 #include <ardour/audioengine.h>
47 #include <ardour/configuration.h>
48 #include <ardour/session.h>
49 #include <ardour/analyser.h>
50 #include <ardour/audio_diskstream.h>
51 #include <ardour/utils.h>
52 #include <ardour/audioplaylist.h>
53 #include <ardour/audioregion.h>
54 #include <ardour/audiofilesource.h>
55 #include <ardour/auditioner.h>
56 #include <ardour/recent_sessions.h>
57 #include <ardour/redirect.h>
58 #include <ardour/send.h>
59 #include <ardour/insert.h>
60 #include <ardour/connection.h>
61 #include <ardour/slave.h>
62 #include <ardour/tempo.h>
63 #include <ardour/audio_track.h>
64 #include <ardour/cycle_timer.h>
65 #include <ardour/named_selection.h>
66 #include <ardour/crossfade.h>
67 #include <ardour/playlist.h>
68 #include <ardour/click.h>
69 #include <ardour/data_type.h>
70 #include <ardour/source_factory.h>
71 #include <ardour/region_factory.h>
74 #include <ardour/osc.h>
80 using namespace ARDOUR;
82 using boost::shared_ptr;
85 static const int CPU_CACHE_ALIGN = 64;
87 static const int CPU_CACHE_ALIGN = 16; /* arguably 32 on most arches, but it matters less */
90 const char* Session::_template_suffix = X_(".template");
91 const char* Session::_statefile_suffix = X_(".ardour");
92 const char* Session::_pending_suffix = X_(".pending");
93 const char* Session::old_sound_dir_name = X_("sounds");
94 const char* Session::sound_dir_name = X_("audiofiles");
95 const char* Session::peak_dir_name = X_("peaks");
96 const char* Session::dead_sound_dir_name = X_("dead_sounds");
97 const char* Session::interchange_dir_name = X_("interchange");
98 const char* Session::export_dir_name = X_("export");
100 bool Session::_disable_all_loaded_plugins = false;
102 Session::compute_peak_t Session::compute_peak = 0;
103 Session::find_peaks_t Session::find_peaks = 0;
104 Session::apply_gain_to_buffer_t Session::apply_gain_to_buffer = 0;
105 Session::mix_buffers_with_gain_t Session::mix_buffers_with_gain = 0;
106 Session::mix_buffers_no_gain_t Session::mix_buffers_no_gain = 0;
108 sigc::signal<void,std::string> Session::Dialog;
109 sigc::signal<int> Session::AskAboutPendingState;
110 sigc::signal<int,nframes_t,nframes_t> Session::AskAboutSampleRateMismatch;
111 sigc::signal<void> Session::SendFeedback;
113 sigc::signal<void> Session::SMPTEOffsetChanged;
114 sigc::signal<void> Session::StartTimeChanged;
115 sigc::signal<void> Session::EndTimeChanged;
117 sigc::signal<void> Session::AutoBindingOn;
118 sigc::signal<void> Session::AutoBindingOff;
121 sigc::signal<void, std::string, std::string> Session::Exported;
124 Session::find_session (string str, string& path, string& snapshot, bool& isnew)
127 char buf[PATH_MAX+1];
131 if (!realpath (str.c_str(), buf) && (errno != ENOENT && errno != ENOTDIR)) {
132 error << string_compose (_("Could not resolve path: %1 (%2)"), buf, strerror(errno)) << endmsg;
138 /* check to see if it exists, and what it is */
140 if (stat (str.c_str(), &statbuf)) {
141 if (errno == ENOENT) {
144 error << string_compose (_("cannot check session path %1 (%2)"), str, strerror (errno))
152 /* it exists, so it must either be the name
153 of the directory, or the name of the statefile
157 if (S_ISDIR (statbuf.st_mode)) {
159 string::size_type slash = str.find_last_of ('/');
161 if (slash == string::npos) {
163 /* a subdirectory of cwd, so statefile should be ... */
169 tmp += _statefile_suffix;
173 if (stat (tmp.c_str(), &statbuf)) {
174 error << string_compose (_("cannot check statefile %1 (%2)"), tmp, strerror (errno))
184 /* some directory someplace in the filesystem.
185 the snapshot name is the directory name
190 snapshot = str.substr (slash+1);
194 } else if (S_ISREG (statbuf.st_mode)) {
196 string::size_type slash = str.find_last_of ('/');
197 string::size_type suffix;
199 /* remove the suffix */
201 if (slash != string::npos) {
202 snapshot = str.substr (slash+1);
207 suffix = snapshot.find (_statefile_suffix);
209 if (suffix == string::npos) {
210 error << string_compose (_("%1 is not an Ardour snapshot file"), str) << endmsg;
216 snapshot = snapshot.substr (0, suffix);
218 if (slash == string::npos) {
220 /* we must be in the directory where the
221 statefile lives. get it using cwd().
224 char cwd[PATH_MAX+1];
226 if (getcwd (cwd, sizeof (cwd)) == 0) {
227 error << string_compose (_("cannot determine current working directory (%1)"), strerror (errno))
236 /* full path to the statefile */
238 path = str.substr (0, slash);
243 /* what type of file is it? */
244 error << string_compose (_("unknown file type for session %1"), str) << endmsg;
250 /* its the name of a new directory. get the name
254 string::size_type slash = str.find_last_of ('/');
256 if (slash == string::npos) {
258 /* no slash, just use the name, but clean it up */
260 path = legalize_for_path (str);
266 snapshot = str.substr (slash+1);
273 Session::Session (AudioEngine &eng,
274 const string& fullpath,
275 const string& snapshot_name,
279 _mmc_port (default_mmc_port),
280 _mtc_port (default_mtc_port),
281 _midi_port (default_midi_port),
282 pending_events (2048),
283 midi_requests (128), // the size of this should match the midi request pool size
284 diskstreams (new DiskstreamList),
285 routes (new RouteList),
286 auditioner ((Auditioner*) 0),
287 _total_free_4k_blocks (0),
293 if (!eng.connected()) {
294 throw failed_constructor();
297 cerr << "Loading session " << fullpath << " using snapshot " << snapshot_name << " (1)" << endl;
299 n_physical_audio_outputs = _engine.n_physical_audio_outputs();
300 n_physical_audio_inputs = _engine.n_physical_audio_inputs();
302 first_stage_init (fullpath, snapshot_name);
304 new_session = !Glib::file_test (_path, Glib::FileTest (G_FILE_TEST_EXISTS | G_FILE_TEST_IS_DIR));
307 if (create (new_session, mix_template, compute_initial_length())) {
309 throw failed_constructor ();
313 if (second_stage_init (new_session)) {
315 throw failed_constructor ();
318 store_recent_sessions(_name, _path);
320 bool was_dirty = dirty();
322 _state_of_the_state = StateOfTheState (_state_of_the_state & ~Dirty);
324 Config->ParameterChanged.connect (mem_fun (*this, &Session::config_changed));
327 DirtyChanged (); /* EMIT SIGNAL */
331 Session::Session (AudioEngine &eng,
333 string snapshot_name,
334 AutoConnectOption input_ac,
335 AutoConnectOption output_ac,
336 uint32_t control_out_channels,
337 uint32_t master_out_channels,
338 uint32_t requested_physical_in,
339 uint32_t requested_physical_out,
340 nframes_t initial_length)
343 _mmc_port (default_mmc_port),
344 _mtc_port (default_mtc_port),
345 _midi_port (default_midi_port),
346 pending_events (2048),
348 diskstreams (new DiskstreamList),
349 routes (new RouteList),
350 _total_free_4k_blocks (0),
356 if (!eng.connected()) {
357 throw failed_constructor();
360 cerr << "Loading session " << fullpath << " using snapshot " << snapshot_name << " (2)" << endl;
362 n_physical_audio_outputs = _engine.n_physical_audio_outputs();
363 n_physical_audio_inputs = _engine.n_physical_audio_inputs();
365 if (n_physical_audio_inputs) {
366 n_physical_audio_inputs = max (requested_physical_in, n_physical_audio_inputs);
369 if (n_physical_audio_outputs) {
370 n_physical_audio_outputs = max (requested_physical_out, n_physical_audio_outputs);
373 first_stage_init (fullpath, snapshot_name);
375 new_session = !g_file_test (_path.c_str(), GFileTest (G_FILE_TEST_EXISTS | G_FILE_TEST_IS_DIR));
378 if (create (new_session, string(), initial_length)) {
380 throw failed_constructor ();
385 /* set up Master Out and Control Out if necessary */
390 if (control_out_channels) {
391 shared_ptr<Route> r (new Route (*this, _("monitor"), -1, control_out_channels, -1, control_out_channels, Route::ControlOut));
392 r->set_remote_control_id (control_id++);
397 if (master_out_channels) {
398 shared_ptr<Route> r (new Route (*this, _("master"), -1, master_out_channels, -1, master_out_channels, Route::MasterOut));
399 r->set_remote_control_id (control_id);
403 /* prohibit auto-connect to master, because there isn't one */
404 output_ac = AutoConnectOption (output_ac & ~AutoConnectMaster);
408 add_routes (rl, false);
413 Config->set_input_auto_connect (input_ac);
414 Config->set_output_auto_connect (output_ac);
416 if (second_stage_init (new_session)) {
418 throw failed_constructor ();
421 store_recent_sessions (_name, _path);
423 _state_of_the_state = StateOfTheState (_state_of_the_state & ~Dirty);
426 Config->ParameterChanged.connect (mem_fun (*this, &Session::config_changed));
437 /* if we got to here, leaving pending capture state around
441 remove_pending_capture_state ();
443 _state_of_the_state = StateOfTheState (CannotSave|Deletion);
445 _engine.remove_session ();
447 GoingAway (); /* EMIT SIGNAL */
453 /* clear history so that no references to objects are held any more */
457 /* clear state tree so that no references to objects are held any more */
463 terminate_butler_thread ();
464 terminate_midi_thread ();
466 if (click_data && click_data != default_click) {
467 delete [] click_data;
470 if (click_emphasis_data && click_emphasis_data != default_click_emphasis) {
471 delete [] click_emphasis_data;
476 for (vector<Sample*>::iterator i = _passthru_buffers.begin(); i != _passthru_buffers.end(); ++i) {
480 for (vector<Sample*>::iterator i = _silent_buffers.begin(); i != _silent_buffers.end(); ++i) {
484 for (vector<Sample*>::iterator i = _send_buffers.begin(); i != _send_buffers.end(); ++i) {
488 AudioDiskstream::free_working_buffers();
490 /* this should cause deletion of the auditioner */
492 // auditioner.reset ();
494 #undef TRACK_DESTRUCTION
495 #ifdef TRACK_DESTRUCTION
496 cerr << "delete named selections\n";
497 #endif /* TRACK_DESTRUCTION */
498 for (NamedSelectionList::iterator i = named_selections.begin(); i != named_selections.end(); ) {
499 NamedSelectionList::iterator tmp;
508 #ifdef TRACK_DESTRUCTION
509 cerr << "delete playlists\n";
510 #endif /* TRACK_DESTRUCTION */
511 for (PlaylistList::iterator i = playlists.begin(); i != playlists.end(); ) {
512 PlaylistList::iterator tmp;
517 (*i)->drop_references ();
522 for (PlaylistList::iterator i = unused_playlists.begin(); i != unused_playlists.end(); ) {
523 PlaylistList::iterator tmp;
528 (*i)->drop_references ();
534 unused_playlists.clear ();
536 #ifdef TRACK_DESTRUCTION
537 cerr << "delete audio regions\n";
538 #endif /* TRACK_DESTRUCTION */
540 for (AudioRegionList::iterator i = audio_regions.begin(); i != audio_regions.end(); ) {
541 AudioRegionList::iterator tmp;
546 i->second->drop_references ();
551 audio_regions.clear ();
553 #ifdef TRACK_DESTRUCTION
554 cerr << "delete routes\n";
555 #endif /* TRACK_DESTRUCTION */
557 RCUWriter<RouteList> writer (routes);
558 boost::shared_ptr<RouteList> r = writer.get_copy ();
559 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
560 (*i)->drop_references ();
563 /* writer goes out of scope and updates master */
568 #ifdef TRACK_DESTRUCTION
569 cerr << "delete diskstreams\n";
570 #endif /* TRACK_DESTRUCTION */
572 RCUWriter<DiskstreamList> dwriter (diskstreams);
573 boost::shared_ptr<DiskstreamList> dsl = dwriter.get_copy();
574 for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
575 (*i)->drop_references ();
579 diskstreams.flush ();
581 #ifdef TRACK_DESTRUCTION
582 cerr << "delete audio sources\n";
583 #endif /* TRACK_DESTRUCTION */
584 for (AudioSourceList::iterator i = audio_sources.begin(); i != audio_sources.end(); ) {
585 AudioSourceList::iterator tmp;
590 i->second->drop_references ();
594 audio_sources.clear ();
596 #ifdef TRACK_DESTRUCTION
597 cerr << "delete mix groups\n";
598 #endif /* TRACK_DESTRUCTION */
599 for (list<RouteGroup *>::iterator i = mix_groups.begin(); i != mix_groups.end(); ) {
600 list<RouteGroup*>::iterator tmp;
610 #ifdef TRACK_DESTRUCTION
611 cerr << "delete edit groups\n";
612 #endif /* TRACK_DESTRUCTION */
613 for (list<RouteGroup *>::iterator i = edit_groups.begin(); i != edit_groups.end(); ) {
614 list<RouteGroup*>::iterator tmp;
624 #ifdef TRACK_DESTRUCTION
625 cerr << "delete connections\n";
626 #endif /* TRACK_DESTRUCTION */
627 for (ConnectionList::iterator i = _connections.begin(); i != _connections.end(); ) {
628 ConnectionList::iterator tmp;
638 if (butler_mixdown_buffer) {
639 delete [] butler_mixdown_buffer;
642 if (butler_gain_buffer) {
643 delete [] butler_gain_buffer;
646 Crossfade::set_buffer_size (0);
654 Session::set_worst_io_latencies ()
656 _worst_output_latency = 0;
657 _worst_input_latency = 0;
659 if (!_engine.connected()) {
663 boost::shared_ptr<RouteList> r = routes.reader ();
665 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
666 _worst_output_latency = max (_worst_output_latency, (*i)->output_latency());
667 _worst_input_latency = max (_worst_input_latency, (*i)->input_latency());
672 Session::when_engine_running ()
674 string first_physical_output;
676 /* we don't want to run execute this again */
678 BootMessage (_("Set block size and sample rate"));
680 set_block_size (_engine.frames_per_cycle());
681 set_frame_rate (_engine.frame_rate());
683 BootMessage (_("Using configuration"));
685 Config->map_parameters (mem_fun (*this, &Session::config_changed));
687 /* every time we reconnect, recompute worst case output latencies */
689 _engine.Running.connect (mem_fun (*this, &Session::set_worst_io_latencies));
691 if (synced_to_jack()) {
692 _engine.transport_stop ();
695 if (Config->get_jack_time_master()) {
696 _engine.transport_locate (_transport_frame);
704 _click_io.reset (new ClickIO (*this, "click", 0, 0, -1, -1));
706 if (state_tree && (child = find_named_node (*state_tree->root(), "Click")) != 0) {
708 /* existing state for Click */
710 if (_click_io->set_state (*child->children().front()) == 0) {
712 _clicking = Config->get_clicking ();
716 error << _("could not setup Click I/O") << endmsg;
722 /* default state for Click */
724 first_physical_output = _engine.get_nth_physical_audio_output (0);
726 if (first_physical_output.length()) {
727 if (_click_io->add_output_port (first_physical_output, this)) {
728 // relax, even though its an error
730 _clicking = Config->get_clicking ();
736 catch (failed_constructor& err) {
737 error << _("cannot setup Click I/O") << endmsg;
740 BootMessage (_("Compute I/O Latencies"));
742 set_worst_io_latencies ();
745 // XXX HOW TO ALERT UI TO THIS ? DO WE NEED TO?
748 /* Create a set of Connection objects that map
749 to the physical outputs currently available
752 BootMessage (_("Set up standard connections"));
756 for (uint32_t np = 0; np < n_physical_audio_outputs; ++np) {
758 snprintf (buf, sizeof (buf), _("out %" PRIu32), np+1);
760 Connection* c = new OutputConnection (buf, true);
763 c->add_connection (0, _engine.get_nth_physical_audio_output (np));
768 for (uint32_t np = 0; np < n_physical_audio_inputs; ++np) {
770 snprintf (buf, sizeof (buf), _("in %" PRIu32), np+1);
772 Connection* c = new InputConnection (buf, true);
775 c->add_connection (0, _engine.get_nth_physical_audio_input (np));
782 for (uint32_t np = 0; np < n_physical_audio_outputs; np +=2) {
784 snprintf (buf, sizeof (buf), _("out %" PRIu32 "+%" PRIu32), np+1, np+2);
786 Connection* c = new OutputConnection (buf, true);
790 c->add_connection (0, _engine.get_nth_physical_audio_output (np));
791 c->add_connection (1, _engine.get_nth_physical_audio_output (np+1));
796 for (uint32_t np = 0; np < n_physical_audio_inputs; np +=2) {
798 snprintf (buf, sizeof (buf), _("in %" PRIu32 "+%" PRIu32), np+1, np+2);
800 Connection* c = new InputConnection (buf, true);
804 c->add_connection (0, _engine.get_nth_physical_audio_input (np));
805 c->add_connection (1, _engine.get_nth_physical_audio_input (np+1));
814 /* create master/control ports */
819 /* force the master to ignore any later call to this */
821 if (_master_out->pending_state_node) {
822 _master_out->ports_became_legal();
825 /* no panner resets till we are through */
827 _master_out->defer_pan_reset ();
829 while ((int) _master_out->n_inputs() < _master_out->input_maximum()) {
830 if (_master_out->add_input_port ("", this)) {
831 error << _("cannot setup master inputs")
837 while ((int) _master_out->n_outputs() < _master_out->output_maximum()) {
838 if (_master_out->add_output_port (_engine.get_nth_physical_audio_output (n), this)) {
839 error << _("cannot setup master outputs")
846 _master_out->allow_pan_reset ();
850 Connection* c = new OutputConnection (_("Master Out"), true);
852 for (uint32_t n = 0; n < _master_out->n_inputs (); ++n) {
854 c->add_connection ((int) n, _master_out->input(n)->name());
859 BootMessage (_("Setup signal flow and plugins"));
863 /* catch up on send+insert cnts */
865 BootMessage (_("Catch up with send/insert state"));
869 for (list<PortInsert*>::iterator i = _port_inserts.begin(); i != _port_inserts.end(); ++i) {
872 if (sscanf ((*i)->name().c_str(), "%*s %u", &id) == 1) {
873 if (id > insert_cnt) {
881 for (list<Send*>::iterator i = _sends.begin(); i != _sends.end(); ++i) {
884 if (sscanf ((*i)->name().c_str(), "%*s %u", &id) == 1) {
892 _state_of_the_state = StateOfTheState (_state_of_the_state & ~(CannotSave|Dirty));
894 /* hook us up to the engine */
896 BootMessage (_("Connect to engine"));
898 _engine.set_session (this);
903 BootMessage (_("OSC startup"));
905 osc->set_session (*this);
911 Session::hookup_io ()
913 /* stop graph reordering notifications from
914 causing resorts, etc.
917 _state_of_the_state = StateOfTheState (_state_of_the_state | InitialConnecting);
920 if (auditioner == 0) {
922 /* we delay creating the auditioner till now because
923 it makes its own connections to ports.
924 the engine has to be running for this to work.
928 auditioner.reset (new Auditioner (*this));
931 catch (failed_constructor& err) {
932 warning << _("cannot create Auditioner: no auditioning of regions possible") << endmsg;
936 /* Tell all IO objects to create their ports */
942 vector<string> cports;
944 while ((int) _control_out->n_inputs() < _control_out->input_maximum()) {
945 if (_control_out->add_input_port ("", this)) {
946 error << _("cannot setup control inputs")
952 while ((int) _control_out->n_outputs() < _control_out->output_maximum()) {
953 if (_control_out->add_output_port (_engine.get_nth_physical_audio_output (n), this)) {
954 error << _("cannot set up master outputs")
962 uint32_t ni = _control_out->n_inputs();
964 for (n = 0; n < ni; ++n) {
965 cports.push_back (_control_out->input(n)->name());
968 boost::shared_ptr<RouteList> r = routes.reader ();
970 for (RouteList::iterator x = r->begin(); x != r->end(); ++x) {
971 (*x)->set_control_outs (cports);
975 /* Tell all IO objects to connect themselves together */
977 IO::enable_connecting ();
979 /* Now reset all panners */
981 IO::reset_panners ();
983 /* Anyone who cares about input state, wake up and do something */
985 IOConnectionsComplete (); /* EMIT SIGNAL */
987 _state_of_the_state = StateOfTheState (_state_of_the_state & ~InitialConnecting);
990 /* now handle the whole enchilada as if it was one
996 /* update mixer solo state */
1002 Session::playlist_length_changed ()
1004 /* we can't just increase end_location->end() if pl->get_maximum_extent()
1005 if larger. if the playlist used to be the longest playlist,
1006 and its now shorter, we have to decrease end_location->end(). hence,
1007 we have to iterate over all diskstreams and check the
1008 playlists currently in use.
1010 find_current_end ();
1014 Session::diskstream_playlist_changed (boost::weak_ptr<Diskstream> wptr)
1016 boost::shared_ptr<Diskstream> dstream = wptr.lock();
1023 boost::shared_ptr<Playlist> playlist;
1025 if ((playlist = dstream->playlist()) != 0) {
1026 playlist->LengthChanged.connect (mem_fun (this, &Session::playlist_length_changed));
1029 /* see comment in playlist_length_changed () */
1030 find_current_end ();
1034 Session::record_enabling_legal () const
1036 /* this used to be in here, but survey says.... we don't need to restrict it */
1037 // if (record_status() == Recording) {
1041 if (Config->get_all_safe()) {
1048 Session::reset_input_monitor_state ()
1050 if (transport_rolling()) {
1052 boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
1054 for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
1055 if ((*i)->record_enabled ()) {
1056 //cerr << "switching to input = " << !auto_input << __FILE__ << __LINE__ << endl << endl;
1057 (*i)->monitor_input (Config->get_monitoring_model() == HardwareMonitoring && !Config->get_auto_input());
1061 boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
1063 for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
1064 if ((*i)->record_enabled ()) {
1065 //cerr << "switching to input = " << !Config->get_auto_input() << __FILE__ << __LINE__ << endl << endl;
1066 (*i)->monitor_input (Config->get_monitoring_model() == HardwareMonitoring);
1073 Session::auto_punch_start_changed (Location* location)
1075 replace_event (Event::PunchIn, location->start());
1077 if (get_record_enabled() && Config->get_punch_in()) {
1078 /* capture start has been changed, so save new pending state */
1079 save_state ("", true);
1084 Session::auto_punch_end_changed (Location* location)
1086 nframes_t when_to_stop = location->end();
1087 // when_to_stop += _worst_output_latency + _worst_input_latency;
1088 replace_event (Event::PunchOut, when_to_stop);
1092 Session::auto_punch_changed (Location* location)
1094 nframes_t when_to_stop = location->end();
1096 replace_event (Event::PunchIn, location->start());
1097 //when_to_stop += _worst_output_latency + _worst_input_latency;
1098 replace_event (Event::PunchOut, when_to_stop);
1102 Session::auto_loop_changed (Location* location)
1104 replace_event (Event::AutoLoop, location->end(), location->start());
1106 if (transport_rolling() && play_loop) {
1108 //if (_transport_frame < location->start() || _transport_frame > location->end()) {
1110 if (_transport_frame > location->end()) {
1111 // relocate to beginning of loop
1112 clear_events (Event::LocateRoll);
1114 request_locate (location->start(), true);
1117 else if (Config->get_seamless_loop() && !loop_changing) {
1119 // schedule a locate-roll to refill the diskstreams at the
1120 // previous loop end
1121 loop_changing = true;
1123 if (location->end() > last_loopend) {
1124 clear_events (Event::LocateRoll);
1125 Event *ev = new Event (Event::LocateRoll, Event::Add, last_loopend, last_loopend, 0, true);
1132 last_loopend = location->end();
1136 Session::set_auto_punch_location (Location* location)
1140 if ((existing = _locations.auto_punch_location()) != 0 && existing != location) {
1141 auto_punch_start_changed_connection.disconnect();
1142 auto_punch_end_changed_connection.disconnect();
1143 auto_punch_changed_connection.disconnect();
1144 existing->set_auto_punch (false, this);
1145 remove_event (existing->start(), Event::PunchIn);
1146 clear_events (Event::PunchOut);
1147 auto_punch_location_changed (0);
1152 if (location == 0) {
1156 if (location->end() <= location->start()) {
1157 error << _("Session: you can't use that location for auto punch (start <= end)") << endmsg;
1161 auto_punch_start_changed_connection.disconnect();
1162 auto_punch_end_changed_connection.disconnect();
1163 auto_punch_changed_connection.disconnect();
1165 auto_punch_start_changed_connection = location->start_changed.connect (mem_fun (this, &Session::auto_punch_start_changed));
1166 auto_punch_end_changed_connection = location->end_changed.connect (mem_fun (this, &Session::auto_punch_end_changed));
1167 auto_punch_changed_connection = location->changed.connect (mem_fun (this, &Session::auto_punch_changed));
1169 location->set_auto_punch (true, this);
1172 auto_punch_changed (location);
1174 auto_punch_location_changed (location);
1178 Session::set_auto_loop_location (Location* location)
1182 if ((existing = _locations.auto_loop_location()) != 0 && existing != location) {
1183 auto_loop_start_changed_connection.disconnect();
1184 auto_loop_end_changed_connection.disconnect();
1185 auto_loop_changed_connection.disconnect();
1186 existing->set_auto_loop (false, this);
1187 remove_event (existing->end(), Event::AutoLoop);
1188 auto_loop_location_changed (0);
1193 if (location == 0) {
1197 if (location->end() <= location->start()) {
1198 error << _("Session: you can't use a mark for auto loop") << endmsg;
1202 last_loopend = location->end();
1204 auto_loop_start_changed_connection.disconnect();
1205 auto_loop_end_changed_connection.disconnect();
1206 auto_loop_changed_connection.disconnect();
1208 auto_loop_start_changed_connection = location->start_changed.connect (mem_fun (this, &Session::auto_loop_changed));
1209 auto_loop_end_changed_connection = location->end_changed.connect (mem_fun (this, &Session::auto_loop_changed));
1210 auto_loop_changed_connection = location->changed.connect (mem_fun (this, &Session::auto_loop_changed));
1212 location->set_auto_loop (true, this);
1214 /* take care of our stuff first */
1216 auto_loop_changed (location);
1218 /* now tell everyone else */
1220 auto_loop_location_changed (location);
1224 Session::locations_added (Location* ignored)
1230 Session::locations_changed ()
1232 _locations.apply (*this, &Session::handle_locations_changed);
1236 Session::handle_locations_changed (Locations::LocationList& locations)
1238 Locations::LocationList::iterator i;
1240 bool set_loop = false;
1241 bool set_punch = false;
1243 for (i = locations.begin(); i != locations.end(); ++i) {
1247 if (location->is_auto_punch()) {
1248 set_auto_punch_location (location);
1251 if (location->is_auto_loop()) {
1252 set_auto_loop_location (location);
1256 if (location->is_start()) {
1257 start_location = location;
1259 if (location->is_end()) {
1260 end_location = location;
1265 set_auto_loop_location (0);
1268 set_auto_punch_location (0);
1275 Session::enable_record ()
1277 /* XXX really atomic compare+swap here */
1278 if (g_atomic_int_get (&_record_status) != Recording) {
1279 g_atomic_int_set (&_record_status, Recording);
1280 _last_record_location = _transport_frame;
1281 send_mmc_in_another_thread (MIDI::MachineControl::cmdRecordStrobe);
1283 if (Config->get_monitoring_model() == HardwareMonitoring && Config->get_auto_input()) {
1284 boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
1285 for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
1286 if ((*i)->record_enabled ()) {
1287 (*i)->monitor_input (true);
1292 RecordStateChanged ();
1297 Session::disable_record (bool rt_context, bool force)
1301 if ((rs = (RecordState) g_atomic_int_get (&_record_status)) != Disabled) {
1303 if ((!Config->get_latched_record_enable () && !play_loop) || force) {
1304 g_atomic_int_set (&_record_status, Disabled);
1306 if (rs == Recording) {
1307 g_atomic_int_set (&_record_status, Enabled);
1311 send_mmc_in_another_thread (MIDI::MachineControl::cmdRecordExit);
1313 if (Config->get_monitoring_model() == HardwareMonitoring && Config->get_auto_input()) {
1314 boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
1316 for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
1317 if ((*i)->record_enabled ()) {
1318 (*i)->monitor_input (false);
1323 RecordStateChanged (); /* emit signal */
1326 remove_pending_capture_state ();
1332 Session::step_back_from_record ()
1334 /* XXX really atomic compare+swap here */
1335 if (g_atomic_int_get (&_record_status) == Recording) {
1336 g_atomic_int_set (&_record_status, Enabled);
1338 if (Config->get_monitoring_model() == HardwareMonitoring && Config->get_auto_input()) {
1339 boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
1341 for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
1342 if ((*i)->record_enabled ()) {
1343 //cerr << "switching from input" << __FILE__ << __LINE__ << endl << endl;
1344 (*i)->monitor_input (false);
1352 Session::maybe_enable_record ()
1354 g_atomic_int_set (&_record_status, Enabled);
1356 /* this function is currently called from somewhere other than an RT thread.
1357 this save_state() call therefore doesn't impact anything.
1360 save_state ("", true);
1362 if (_transport_speed) {
1363 if (!Config->get_punch_in()) {
1367 send_mmc_in_another_thread (MIDI::MachineControl::cmdRecordPause);
1368 RecordStateChanged (); /* EMIT SIGNAL */
1375 Session::audible_frame () const
1381 if (_transport_speed == 0.0f && non_realtime_work_pending()) {
1382 return last_stop_frame;
1385 /* the first of these two possible settings for "offset"
1386 mean that the audible frame is stationary until
1387 audio emerges from the latency compensation
1390 the second means that the audible frame is stationary
1391 until audio would emerge from a physical port
1392 in the absence of any plugin latency compensation
1395 offset = _worst_output_latency;
1397 if (offset > current_block_size) {
1398 offset -= current_block_size;
1400 /* XXX is this correct? if we have no external
1401 physical connections and everything is internal
1402 then surely this is zero? still, how
1403 likely is that anyway?
1405 offset = current_block_size;
1408 if (synced_to_jack()) {
1409 tf = _engine.transport_frame();
1411 tf = _transport_frame;
1416 if (!non_realtime_work_pending()) {
1420 /* check to see if we have passed the first guaranteed
1421 audible frame past our last stopping position. if not,
1422 the return that last stopping point because in terms
1423 of audible frames, we have not moved yet.
1426 if (_transport_speed > 0.0f) {
1428 if (!play_loop || !have_looped) {
1429 if (tf < last_stop_frame + offset) {
1430 return last_stop_frame;
1439 } else if (_transport_speed < 0.0f) {
1441 /* XXX wot? no backward looping? */
1443 if (tf > last_stop_frame - offset) {
1444 return last_stop_frame;
1456 Session::set_frame_rate (nframes_t frames_per_second)
1458 /** \fn void Session::set_frame_size(nframes_t)
1459 the AudioEngine object that calls this guarantees
1460 that it will not be called while we are also in
1461 ::process(). Its fine to do things that block
1465 _base_frame_rate = frames_per_second;
1469 IO::set_automation_interval ((jack_nframes_t) ceil ((double) frames_per_second * (0.001 * Config->get_automation_interval())));
1473 // XXX we need some equivalent to this, somehow
1474 // SndFileSource::setup_standard_crossfades (frames_per_second);
1478 /* XXX need to reset/reinstantiate all LADSPA plugins */
1482 Session::set_block_size (nframes_t nframes)
1484 /* the AudioEngine guarantees
1485 that it will not be called while we are also in
1486 ::process(). It is therefore fine to do things that block
1491 vector<Sample*>::iterator i;
1494 current_block_size = nframes;
1496 for (np = 0, i = _passthru_buffers.begin(); i != _passthru_buffers.end(); ++i, ++np) {
1500 for (vector<Sample*>::iterator i = _silent_buffers.begin(); i != _silent_buffers.end(); ++i) {
1504 _passthru_buffers.clear ();
1505 _silent_buffers.clear ();
1507 ensure_passthru_buffers (np);
1509 for (vector<Sample*>::iterator i = _send_buffers.begin(); i != _send_buffers.end(); ++i) {
1513 #ifdef NO_POSIX_MEMALIGN
1514 buf = (Sample *) malloc(current_block_size * sizeof(Sample));
1516 posix_memalign((void **)&buf,CPU_CACHE_ALIGN,current_block_size * sizeof(Sample));
1520 memset (*i, 0, sizeof (Sample) * current_block_size);
1524 if (_gain_automation_buffer) {
1525 delete [] _gain_automation_buffer;
1527 _gain_automation_buffer = new gain_t[nframes];
1529 allocate_pan_automation_buffers (nframes, _npan_buffers, true);
1531 boost::shared_ptr<RouteList> r = routes.reader ();
1533 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
1534 (*i)->set_block_size (nframes);
1537 boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
1538 for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
1539 (*i)->set_block_size (nframes);
1542 set_worst_io_latencies ();
1547 Session::set_default_fade (float steepness, float fade_msecs)
1550 nframes_t fade_frames;
1552 /* Don't allow fade of less 1 frame */
1554 if (fade_msecs < (1000.0 * (1.0/_current_frame_rate))) {
1561 fade_frames = (nframes_t) floor (fade_msecs * _current_frame_rate * 0.001);
1565 default_fade_msecs = fade_msecs;
1566 default_fade_steepness = steepness;
1569 // jlc, WTF is this!
1570 Glib::RWLock::ReaderLock lm (route_lock);
1571 AudioRegion::set_default_fade (steepness, fade_frames);
1576 /* XXX have to do this at some point */
1577 /* foreach region using default fade, reset, then
1578 refill_all_diskstream_buffers ();
1583 struct RouteSorter {
1584 bool operator() (boost::shared_ptr<Route> r1, boost::shared_ptr<Route> r2) {
1585 if (r1->fed_by.find (r2) != r1->fed_by.end()) {
1587 } else if (r2->fed_by.find (r1) != r2->fed_by.end()) {
1590 if (r1->fed_by.empty()) {
1591 if (r2->fed_by.empty()) {
1592 /* no ardour-based connections inbound to either route. just use signal order */
1593 return r1->order_key(N_("signal")) < r2->order_key(N_("signal"));
1595 /* r2 has connections, r1 does not; run r1 early */
1599 return r1->order_key(N_("signal")) < r2->order_key(N_("signal"));
1606 trace_terminal (shared_ptr<Route> r1, shared_ptr<Route> rbase)
1608 shared_ptr<Route> r2;
1610 if ((r1->fed_by.find (rbase) != r1->fed_by.end()) && (rbase->fed_by.find (r1) != rbase->fed_by.end())) {
1611 info << string_compose(_("feedback loop setup between %1 and %2"), r1->name(), rbase->name()) << endmsg;
1615 /* make a copy of the existing list of routes that feed r1 */
1617 set<shared_ptr<Route> > existing = r1->fed_by;
1619 /* for each route that feeds r1, recurse, marking it as feeding
1623 for (set<shared_ptr<Route> >::iterator i = existing.begin(); i != existing.end(); ++i) {
1626 /* r2 is a route that feeds r1 which somehow feeds base. mark
1627 base as being fed by r2
1630 rbase->fed_by.insert (r2);
1634 /* 2nd level feedback loop detection. if r1 feeds or is fed by r2,
1638 if ((r1->fed_by.find (r2) != r1->fed_by.end()) && (r2->fed_by.find (r1) != r2->fed_by.end())) {
1642 /* now recurse, so that we can mark base as being fed by
1643 all routes that feed r2
1646 trace_terminal (r2, rbase);
1653 Session::resort_routes ()
1655 /* don't do anything here with signals emitted
1656 by Routes while we are being destroyed.
1659 if (_state_of_the_state & Deletion) {
1666 RCUWriter<RouteList> writer (routes);
1667 shared_ptr<RouteList> r = writer.get_copy ();
1668 resort_routes_using (r);
1669 /* writer goes out of scope and forces update */
1674 Session::resort_routes_using (shared_ptr<RouteList> r)
1676 RouteList::iterator i, j;
1678 for (i = r->begin(); i != r->end(); ++i) {
1680 (*i)->fed_by.clear ();
1682 for (j = r->begin(); j != r->end(); ++j) {
1684 /* although routes can feed themselves, it will
1685 cause an endless recursive descent if we
1686 detect it. so don't bother checking for
1694 if ((*j)->feeds (*i)) {
1695 (*i)->fed_by.insert (*j);
1700 for (i = r->begin(); i != r->end(); ++i) {
1701 trace_terminal (*i, *i);
1707 /* don't leave dangling references to routes in Route::fed_by */
1709 for (i = r->begin(); i != r->end(); ++i) {
1710 (*i)->fed_by.clear ();
1714 cerr << "finished route resort\n";
1716 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
1717 cerr << " " << (*i)->name() << " signal order = " << (*i)->order_key ("signal") << endl;
1724 list<boost::shared_ptr<AudioTrack> >
1725 Session::new_audio_track (int input_channels, int output_channels, TrackMode mode, uint32_t how_many)
1727 char track_name[32];
1728 uint32_t track_id = 0;
1730 uint32_t channels_used = 0;
1732 RouteList new_routes;
1733 list<boost::shared_ptr<AudioTrack> > ret;
1734 uint32_t control_id;
1736 /* count existing audio tracks */
1739 shared_ptr<RouteList> r = routes.reader ();
1741 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
1742 if (dynamic_cast<AudioTrack*>((*i).get()) != 0) {
1743 if (!(*i)->hidden()) {
1745 channels_used += (*i)->n_inputs();
1751 vector<string> physinputs;
1752 vector<string> physoutputs;
1753 uint32_t nphysical_in;
1754 uint32_t nphysical_out;
1756 _engine.get_physical_audio_outputs (physoutputs);
1757 _engine.get_physical_audio_inputs (physinputs);
1758 control_id = ntracks() + nbusses() + 1;
1762 /* check for duplicate route names, since we might have pre-existing
1763 routes with this name (e.g. create Audio1, Audio2, delete Audio1,
1764 save, close,restart,add new route - first named route is now
1772 snprintf (track_name, sizeof(track_name), "Audio %" PRIu32, track_id);
1774 if (route_by_name (track_name) == 0) {
1778 } while (track_id < (UINT_MAX-1));
1780 if (Config->get_input_auto_connect() & AutoConnectPhysical) {
1781 nphysical_in = min (n_physical_audio_inputs, (uint32_t) physinputs.size());
1786 if (Config->get_output_auto_connect() & AutoConnectPhysical) {
1787 nphysical_out = min (n_physical_audio_outputs, (uint32_t) physinputs.size());
1792 shared_ptr<AudioTrack> track;
1795 track = boost::shared_ptr<AudioTrack>((new AudioTrack (*this, track_name, Route::Flag (0), mode)));
1797 if (track->ensure_io (input_channels, output_channels, false, this)) {
1798 error << string_compose (_("cannot configure %1 in/%2 out configuration for new audio track"),
1799 input_channels, output_channels)
1805 for (uint32_t x = 0; x < track->n_inputs() && x < nphysical_in; ++x) {
1809 if (Config->get_input_auto_connect() & AutoConnectPhysical) {
1810 port = physinputs[(channels_used+x)%nphysical_in];
1813 if (port.length() && track->connect_input (track->input (x), port, this)) {
1819 for (uint32_t x = 0; x < track->n_outputs(); ++x) {
1823 if (nphysical_out && (Config->get_output_auto_connect() & AutoConnectPhysical)) {
1824 port = physoutputs[(channels_used+x)%nphysical_out];
1825 } else if (Config->get_output_auto_connect() & AutoConnectMaster) {
1827 port = _master_out->input (x%_master_out->n_inputs())->name();
1831 if (port.length() && track->connect_output (track->output (x), port, this)) {
1836 channels_used += track->n_inputs ();
1838 track->audio_diskstream()->non_realtime_input_change();
1840 track->DiskstreamChanged.connect (mem_fun (this, &Session::resort_routes));
1841 track->set_remote_control_id (control_id);
1844 new_routes.push_back (track);
1845 ret.push_back (track);
1849 catch (failed_constructor &err) {
1850 error << _("Session: could not create new audio track.") << endmsg;
1853 /* we need to get rid of this, since the track failed to be created */
1854 /* XXX arguably, AudioTrack::AudioTrack should not do the Session::add_diskstream() */
1857 RCUWriter<DiskstreamList> writer (diskstreams);
1858 boost::shared_ptr<DiskstreamList> ds = writer.get_copy();
1859 ds->remove (track->audio_diskstream());
1866 catch (AudioEngine::PortRegistrationFailure& pfe) {
1868 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;
1871 /* we need to get rid of this, since the track failed to be created */
1872 /* XXX arguably, AudioTrack::AudioTrack should not do the Session::add_diskstream() */
1875 RCUWriter<DiskstreamList> writer (diskstreams);
1876 boost::shared_ptr<DiskstreamList> ds = writer.get_copy();
1877 ds->remove (track->audio_diskstream());
1888 if (!new_routes.empty()) {
1889 add_routes (new_routes, true);
1896 Session::set_remote_control_ids ()
1898 RemoteModel m = Config->get_remote_model();
1900 shared_ptr<RouteList> r = routes.reader ();
1902 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
1903 if ( MixerOrdered == m) {
1904 long order = (*i)->order_key(N_("signal"));
1905 (*i)->set_remote_control_id( order+1 );
1906 } else if ( EditorOrdered == m) {
1907 long order = (*i)->order_key(N_("editor"));
1908 (*i)->set_remote_control_id( order+1 );
1909 } else if ( UserOrdered == m) {
1910 //do nothing ... only changes to remote id's are initiated by user
1917 Session::new_audio_route (int input_channels, int output_channels, uint32_t how_many)
1920 uint32_t bus_id = 1;
1924 uint32_t control_id;
1926 /* count existing audio busses */
1929 shared_ptr<RouteList> r = routes.reader ();
1931 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
1932 if (dynamic_cast<AudioTrack*>((*i).get()) == 0) {
1933 if (!(*i)->hidden() && (*i)->name() != _("master")) {
1940 vector<string> physinputs;
1941 vector<string> physoutputs;
1943 _engine.get_physical_audio_outputs (physoutputs);
1944 _engine.get_physical_audio_inputs (physinputs);
1945 control_id = ntracks() + nbusses() + 1;
1950 snprintf (bus_name, sizeof(bus_name), "Bus %" PRIu32, bus_id);
1954 if (route_by_name (bus_name) == 0) {
1958 } while (bus_id < (UINT_MAX-1));
1961 shared_ptr<Route> bus (new Route (*this, bus_name, -1, -1, -1, -1, Route::Flag(0), DataType::AUDIO));
1963 if (bus->ensure_io (input_channels, output_channels, false, this)) {
1964 error << string_compose (_("cannot configure %1 in/%2 out configuration for new audio track"),
1965 input_channels, output_channels)
1970 for (uint32_t x = 0; n_physical_audio_inputs && x < bus->n_inputs(); ++x) {
1974 if (Config->get_input_auto_connect() & AutoConnectPhysical) {
1975 port = physinputs[((n+x)%n_physical_audio_inputs)];
1978 if (port.length() && bus->connect_input (bus->input (x), port, this)) {
1983 for (uint32_t x = 0; n_physical_audio_outputs && x < bus->n_outputs(); ++x) {
1987 if (Config->get_output_auto_connect() & AutoConnectPhysical) {
1988 port = physoutputs[((n+x)%n_physical_audio_outputs)];
1989 } else if (Config->get_output_auto_connect() & AutoConnectMaster) {
1991 port = _master_out->input (x%_master_out->n_inputs())->name();
1995 if (port.length() && bus->connect_output (bus->output (x), port, this)) {
2000 bus->set_remote_control_id (control_id);
2003 ret.push_back (bus);
2007 catch (failed_constructor &err) {
2008 error << _("Session: could not create new audio route.") << endmsg;
2012 catch (AudioEngine::PortRegistrationFailure& pfe) {
2013 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;
2023 add_routes (ret, true);
2031 Session::add_routes (RouteList& new_routes, bool save)
2034 RCUWriter<RouteList> writer (routes);
2035 shared_ptr<RouteList> r = writer.get_copy ();
2036 r->insert (r->end(), new_routes.begin(), new_routes.end());
2037 resort_routes_using (r);
2040 for (RouteList::iterator x = new_routes.begin(); x != new_routes.end(); ++x) {
2042 boost::weak_ptr<Route> wpr (*x);
2044 (*x)->solo_changed.connect (sigc::bind (mem_fun (*this, &Session::route_solo_changed), wpr));
2045 (*x)->mute_changed.connect (mem_fun (*this, &Session::route_mute_changed));
2046 (*x)->output_changed.connect (mem_fun (*this, &Session::set_worst_io_latencies_x));
2047 (*x)->redirects_changed.connect (mem_fun (*this, &Session::update_latency_compensation_proxy));
2049 if ((*x)->master()) {
2053 if ((*x)->control()) {
2054 _control_out = (*x);
2058 if (_control_out && IO::connecting_legal) {
2060 vector<string> cports;
2061 uint32_t ni = _control_out->n_inputs();
2064 for (n = 0; n < ni; ++n) {
2065 cports.push_back (_control_out->input(n)->name());
2068 for (RouteList::iterator x = new_routes.begin(); x != new_routes.end(); ++x) {
2069 (*x)->set_control_outs (cports);
2076 save_state (_current_snapshot_name);
2079 RouteAdded (new_routes); /* EMIT SIGNAL */
2083 Session::add_diskstream (boost::shared_ptr<Diskstream> dstream)
2085 /* need to do this in case we're rolling at the time, to prevent false underruns */
2086 dstream->do_refill_with_alloc ();
2088 dstream->set_block_size (current_block_size);
2091 RCUWriter<DiskstreamList> writer (diskstreams);
2092 boost::shared_ptr<DiskstreamList> ds = writer.get_copy();
2093 ds->push_back (dstream);
2094 /* writer goes out of scope, copies ds back to main */
2097 dstream->PlaylistChanged.connect (sigc::bind (mem_fun (*this, &Session::diskstream_playlist_changed),
2098 boost::weak_ptr<Diskstream> (dstream)));
2099 /* this will connect to future changes, and check the current length */
2100 diskstream_playlist_changed (dstream);
2102 dstream->prepare ();
2106 Session::remove_route (shared_ptr<Route> route)
2109 RCUWriter<RouteList> writer (routes);
2110 shared_ptr<RouteList> rs = writer.get_copy ();
2114 /* deleting the master out seems like a dumb
2115 idea, but its more of a UI policy issue
2119 if (route == _master_out) {
2120 _master_out = shared_ptr<Route> ();
2123 if (route == _control_out) {
2124 _control_out = shared_ptr<Route> ();
2126 /* cancel control outs for all routes */
2128 vector<string> empty;
2130 for (RouteList::iterator r = rs->begin(); r != rs->end(); ++r) {
2131 (*r)->set_control_outs (empty);
2135 update_route_solo_state ();
2137 /* writer goes out of scope, forces route list update */
2140 // FIXME: audio specific
2142 boost::shared_ptr<AudioDiskstream> ds;
2144 if ((at = dynamic_cast<AudioTrack*>(route.get())) != 0) {
2145 ds = at->audio_diskstream();
2151 RCUWriter<DiskstreamList> dsl (diskstreams);
2152 boost::shared_ptr<DiskstreamList> d = dsl.get_copy();
2156 diskstreams.flush ();
2159 find_current_end ();
2161 // We need to disconnect the routes inputs and outputs
2163 route->disconnect_inputs (0);
2164 route->disconnect_outputs (0);
2166 update_latency_compensation (false, false);
2169 /* get rid of it from the dead wood collection in the route list manager */
2171 /* XXX i think this is unsafe as it currently stands, but i am not sure. (pd, october 2nd, 2006) */
2175 /* try to cause everyone to drop their references */
2177 route->drop_references ();
2179 sync_order_keys (N_("session"));
2181 /* save the new state of the world */
2183 if (save_state (_current_snapshot_name)) {
2184 save_history (_current_snapshot_name);
2189 Session::route_mute_changed (void* src)
2195 Session::route_solo_changed (void* src, boost::weak_ptr<Route> wpr)
2197 if (solo_update_disabled) {
2203 boost::shared_ptr<Route> route = wpr.lock ();
2206 /* should not happen */
2207 error << string_compose (_("programming error: %1"), X_("invalid route weak ptr passed to route_solo_changed")) << endmsg;
2211 is_track = (boost::dynamic_pointer_cast<AudioTrack>(route) != 0);
2213 shared_ptr<RouteList> r = routes.reader ();
2215 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2217 /* soloing a track mutes all other tracks, soloing a bus mutes all other busses */
2221 /* don't mess with busses */
2223 if (dynamic_cast<AudioTrack*>((*i).get()) == 0) {
2229 /* don't mess with tracks */
2231 if (dynamic_cast<AudioTrack*>((*i).get()) != 0) {
2236 if ((*i) != route &&
2237 ((*i)->mix_group () == 0 ||
2238 (*i)->mix_group () != route->mix_group () ||
2239 !route->mix_group ()->is_active())) {
2241 if ((*i)->soloed()) {
2243 /* if its already soloed, and solo latching is enabled,
2244 then leave it as it is.
2247 if (Config->get_solo_latched()) {
2254 solo_update_disabled = true;
2255 (*i)->set_solo (false, src);
2256 solo_update_disabled = false;
2260 bool something_soloed = false;
2261 bool same_thing_soloed = false;
2262 bool signal = false;
2264 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2265 if ((*i)->soloed()) {
2266 something_soloed = true;
2267 if (dynamic_cast<AudioTrack*>((*i).get())) {
2269 same_thing_soloed = true;
2274 same_thing_soloed = true;
2282 if (something_soloed != currently_soloing) {
2284 currently_soloing = something_soloed;
2287 modify_solo_mute (is_track, same_thing_soloed);
2290 SoloActive (currently_soloing); /* EMIT SIGNAL */
2293 SoloChanged (); /* EMIT SIGNAL */
2299 Session::update_route_solo_state ()
2302 bool is_track = false;
2303 bool signal = false;
2305 /* this is where we actually implement solo by changing
2306 the solo mute setting of each track.
2309 shared_ptr<RouteList> r = routes.reader ();
2311 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2312 if ((*i)->soloed()) {
2314 if (dynamic_cast<AudioTrack*>((*i).get())) {
2321 if (mute != currently_soloing) {
2323 currently_soloing = mute;
2326 if (!is_track && !mute) {
2328 /* nothing is soloed */
2330 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2331 (*i)->set_solo_mute (false);
2341 modify_solo_mute (is_track, mute);
2344 SoloActive (currently_soloing);
2349 Session::modify_solo_mute (bool is_track, bool mute)
2351 shared_ptr<RouteList> r = routes.reader ();
2353 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2357 /* only alter track solo mute */
2359 if (dynamic_cast<AudioTrack*>((*i).get())) {
2360 if ((*i)->soloed()) {
2361 (*i)->set_solo_mute (!mute);
2363 (*i)->set_solo_mute (mute);
2369 /* only alter bus solo mute */
2371 if (!dynamic_cast<AudioTrack*>((*i).get())) {
2373 if ((*i)->soloed()) {
2375 (*i)->set_solo_mute (false);
2379 /* don't mute master or control outs
2380 in response to another bus solo
2383 if ((*i) != _master_out &&
2384 (*i) != _control_out) {
2385 (*i)->set_solo_mute (mute);
2396 Session::catch_up_on_solo ()
2398 /* this is called after set_state() to catch the full solo
2399 state, which can't be correctly determined on a per-route
2400 basis, but needs the global overview that only the session
2403 update_route_solo_state();
2407 Session::catch_up_on_solo_mute_override ()
2409 if (Config->get_solo_model() != InverseMute) {
2413 /* this is called whenever the param solo-mute-override is
2416 shared_ptr<RouteList> r = routes.reader ();
2418 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2419 (*i)->catch_up_on_solo_mute_override ();
2424 Session::route_by_name (string name)
2426 shared_ptr<RouteList> r = routes.reader ();
2428 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2429 if ((*i)->name() == name) {
2434 return shared_ptr<Route> ((Route*) 0);
2438 Session::route_by_id (PBD::ID id)
2440 shared_ptr<RouteList> r = routes.reader ();
2442 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2443 if ((*i)->id() == id) {
2448 return shared_ptr<Route> ((Route*) 0);
2452 Session::route_by_remote_id (uint32_t id)
2454 shared_ptr<RouteList> r = routes.reader ();
2456 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2457 if ((*i)->remote_control_id() == id) {
2462 return shared_ptr<Route> ((Route*) 0);
2466 Session::find_current_end ()
2468 if (_state_of_the_state & Loading) {
2472 nframes_t max = get_maximum_extent ();
2474 if (max > end_location->end()) {
2475 end_location->set_end (max);
2477 DurationChanged(); /* EMIT SIGNAL */
2482 Session::get_maximum_extent () const
2487 boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
2489 for (DiskstreamList::const_iterator i = dsl->begin(); i != dsl->end(); ++i) {
2490 if ((*i)->destructive()) //ignore tape tracks when getting max extents
2492 boost::shared_ptr<Playlist> pl = (*i)->playlist();
2493 if ((me = pl->get_maximum_extent()) > max) {
2501 boost::shared_ptr<Diskstream>
2502 Session::diskstream_by_name (string name)
2504 boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
2506 for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
2507 if ((*i)->name() == name) {
2512 return boost::shared_ptr<Diskstream>((Diskstream*) 0);
2515 boost::shared_ptr<Diskstream>
2516 Session::diskstream_by_id (const PBD::ID& id)
2518 boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
2520 for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
2521 if ((*i)->id() == id) {
2526 return boost::shared_ptr<Diskstream>((Diskstream*) 0);
2529 /* AudioRegion management */
2532 Session::new_region_name (string old)
2534 string::size_type last_period;
2536 string::size_type len = old.length() + 64;
2539 if ((last_period = old.find_last_of ('.')) == string::npos) {
2541 /* no period present - add one explicitly */
2544 last_period = old.length() - 1;
2549 number = atoi (old.substr (last_period+1).c_str());
2553 while (number < (UINT_MAX-1)) {
2555 AudioRegionList::const_iterator i;
2560 snprintf (buf, len, "%s%" PRIu32, old.substr (0, last_period + 1).c_str(), number);
2563 for (i = audio_regions.begin(); i != audio_regions.end(); ++i) {
2564 if (i->second->name() == sbuf) {
2569 if (i == audio_regions.end()) {
2574 if (number != (UINT_MAX-1)) {
2578 error << string_compose (_("cannot create new name for region \"%1\""), old) << endmsg;
2583 Session::region_name (string& result, string base, bool newlevel)
2590 Glib::Mutex::Lock lm (region_lock);
2592 snprintf (buf, sizeof (buf), "%d", (int)audio_regions.size() + 1);
2601 string::size_type pos;
2603 pos = base.find_last_of ('.');
2605 /* pos may be npos, but then we just use entire base */
2607 subbase = base.substr (0, pos);
2612 Glib::Mutex::Lock lm (region_lock);
2614 map<string,uint32_t>::iterator x;
2618 if ((x = region_name_map.find (subbase)) == region_name_map.end()) {
2620 region_name_map[subbase] = 1;
2623 snprintf (buf, sizeof (buf), ".%d", x->second);
2633 Session::add_region (boost::shared_ptr<Region> region)
2635 vector<boost::shared_ptr<Region> > v;
2636 v.push_back (region);
2641 Session::add_regions (vector<boost::shared_ptr<Region> >& new_regions)
2643 boost::shared_ptr<AudioRegion> ar;
2644 boost::shared_ptr<AudioRegion> oar;
2648 Glib::Mutex::Lock lm (region_lock);
2650 for (vector<boost::shared_ptr<Region> >::iterator ii = new_regions.begin(); ii != new_regions.end(); ++ii) {
2652 boost::shared_ptr<Region> region = *ii;
2656 error << _("Session::add_region() ignored a null region. Warning: you might have lost a region.") << endmsg;
2658 } else if ((ar = boost::dynamic_pointer_cast<AudioRegion> (region)) != 0) {
2660 AudioRegionList::iterator x;
2662 for (x = audio_regions.begin(); x != audio_regions.end(); ++x) {
2664 oar = boost::dynamic_pointer_cast<AudioRegion> (x->second);
2666 if (ar->region_list_equivalent (oar)) {
2671 if (x == audio_regions.end()) {
2673 pair<AudioRegionList::key_type,AudioRegionList::mapped_type> entry;
2675 entry.first = region->id();
2678 pair<AudioRegionList::iterator,bool> x = audio_regions.insert (entry);
2689 fatal << _("programming error: ")
2690 << X_("unknown region type passed to Session::add_region()")
2698 /* mark dirty because something has changed even if we didn't
2699 add the region to the region list.
2706 vector<boost::weak_ptr<AudioRegion> > v;
2707 boost::shared_ptr<AudioRegion> first_ar;
2709 for (vector<boost::shared_ptr<Region> >::iterator ii = new_regions.begin(); ii != new_regions.end(); ++ii) {
2711 boost::shared_ptr<Region> region = *ii;
2712 boost::shared_ptr<AudioRegion> ar;
2716 error << _("Session::add_region() ignored a null region. Warning: you might have lost a region.") << endmsg;
2718 } else if ((ar = boost::dynamic_pointer_cast<AudioRegion> (region)) != 0) {
2726 region->StateChanged.connect (sigc::bind (mem_fun (*this, &Session::region_changed), boost::weak_ptr<Region>(region)));
2727 region->GoingAway.connect (sigc::bind (mem_fun (*this, &Session::remove_region), boost::weak_ptr<Region>(region)));
2729 update_region_name_map (region);
2733 AudioRegionsAdded (v); /* EMIT SIGNAL */
2739 Session::update_region_name_map (boost::shared_ptr<Region> region)
2741 string::size_type last_period = region->name().find_last_of ('.');
2743 if (last_period != string::npos && last_period < region->name().length() - 1) {
2745 string base = region->name().substr (0, last_period);
2746 string number = region->name().substr (last_period+1);
2747 map<string,uint32_t>::iterator x;
2749 /* note that if there is no number, we get zero from atoi,
2753 region_name_map[base] = atoi (number);
2758 Session::region_changed (Change what_changed, boost::weak_ptr<Region> weak_region)
2760 boost::shared_ptr<Region> region (weak_region.lock ());
2766 if (what_changed & Region::HiddenChanged) {
2767 /* relay hidden changes */
2768 RegionHiddenChange (region);
2771 if (what_changed & NameChanged) {
2772 update_region_name_map (region);
2777 Session::remove_region (boost::weak_ptr<Region> weak_region)
2779 AudioRegionList::iterator i;
2780 boost::shared_ptr<Region> region (weak_region.lock ());
2786 boost::shared_ptr<AudioRegion> ar;
2787 bool removed = false;
2790 Glib::Mutex::Lock lm (region_lock);
2792 if ((ar = boost::dynamic_pointer_cast<AudioRegion> (region)) != 0) {
2793 if ((i = audio_regions.find (region->id())) != audio_regions.end()) {
2794 audio_regions.erase (i);
2800 fatal << _("programming error: ")
2801 << X_("unknown region type passed to Session::remove_region()")
2807 /* mark dirty because something has changed even if we didn't
2808 remove the region from the region list.
2814 AudioRegionRemoved (ar); /* EMIT SIGNAL */
2818 boost::shared_ptr<AudioRegion>
2819 Session::find_whole_file_parent (boost::shared_ptr<AudioRegion const> child)
2821 AudioRegionList::iterator i;
2822 boost::shared_ptr<AudioRegion> region;
2823 Glib::Mutex::Lock lm (region_lock);
2825 for (i = audio_regions.begin(); i != audio_regions.end(); ++i) {
2829 if (region->whole_file()) {
2831 if (child->source_equivalent (region)) {
2837 return boost::shared_ptr<AudioRegion> ();
2841 Session::find_equivalent_playlist_regions (boost::shared_ptr<Region> region, vector<boost::shared_ptr<Region> >& result)
2843 for (PlaylistList::iterator i = playlists.begin(); i != playlists.end(); ++i)
2844 (*i)->get_region_list_equivalent_regions (region, result);
2848 Session::destroy_region (boost::shared_ptr<Region> region)
2850 vector<boost::shared_ptr<Source> > srcs;
2853 boost::shared_ptr<AudioRegion> aregion;
2855 if ((aregion = boost::dynamic_pointer_cast<AudioRegion> (region)) == 0) {
2859 if (aregion->playlist()) {
2860 aregion->playlist()->destroy_region (region);
2863 for (uint32_t n = 0; n < aregion->n_channels(); ++n) {
2864 srcs.push_back (aregion->source (n));
2868 region->drop_references ();
2870 for (vector<boost::shared_ptr<Source> >::iterator i = srcs.begin(); i != srcs.end(); ++i) {
2872 if (!(*i)->used()) {
2873 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*i);
2876 (afs)->mark_for_remove ();
2879 (*i)->drop_references ();
2881 cerr << "source was not used by any playlist\n";
2889 Session::destroy_regions (list<boost::shared_ptr<Region> > regions)
2891 for (list<boost::shared_ptr<Region> >::iterator i = regions.begin(); i != regions.end(); ++i) {
2892 destroy_region (*i);
2898 Session::remove_last_capture ()
2900 list<boost::shared_ptr<Region> > r;
2902 boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
2904 for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
2905 list<boost::shared_ptr<Region> >& l = (*i)->last_capture_regions();
2908 r.insert (r.end(), l.begin(), l.end());
2913 destroy_regions (r);
2915 save_state (_current_snapshot_name);
2921 Session::remove_region_from_region_list (boost::shared_ptr<Region> r)
2927 /* Source Management */
2930 Session::add_source (boost::shared_ptr<Source> source)
2932 boost::shared_ptr<AudioFileSource> afs;
2934 if ((afs = boost::dynamic_pointer_cast<AudioFileSource>(source)) != 0) {
2936 pair<AudioSourceList::key_type, AudioSourceList::mapped_type> entry;
2937 pair<AudioSourceList::iterator,bool> result;
2939 entry.first = source->id();
2943 Glib::Mutex::Lock lm (audio_source_lock);
2944 result = audio_sources.insert (entry);
2947 if (result.second) {
2948 source->GoingAway.connect (sigc::bind (mem_fun (this, &Session::remove_source), boost::weak_ptr<Source> (source)));
2952 if (Config->get_auto_analyse_audio()) {
2953 Analyser::queue_source_for_analysis (source, false);
2959 Session::remove_source (boost::weak_ptr<Source> src)
2961 AudioSourceList::iterator i;
2962 boost::shared_ptr<Source> source = src.lock();
2969 Glib::Mutex::Lock lm (audio_source_lock);
2971 if ((i = audio_sources.find (source->id())) != audio_sources.end()) {
2972 audio_sources.erase (i);
2976 if (!_state_of_the_state & InCleanup) {
2978 /* save state so we don't end up with a session file
2979 referring to non-existent sources.
2982 save_state (_current_snapshot_name);
2986 boost::shared_ptr<Source>
2987 Session::source_by_id (const PBD::ID& id)
2989 Glib::Mutex::Lock lm (audio_source_lock);
2990 AudioSourceList::iterator i;
2991 boost::shared_ptr<Source> source;
2993 if ((i = audio_sources.find (id)) != audio_sources.end()) {
2997 /* XXX search MIDI or other searches here */
3003 boost::shared_ptr<Source>
3004 Session::source_by_path_and_channel (const Glib::ustring& path, uint16_t chn)
3006 Glib::Mutex::Lock lm (audio_source_lock);
3008 for (AudioSourceList::iterator i = audio_sources.begin(); i != audio_sources.end(); ++i) {
3009 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(i->second);
3011 if (afs && afs->path() == path && chn == afs->channel()) {
3016 return boost::shared_ptr<Source>();
3020 Session::peak_path (Glib::ustring base) const
3022 return Glib::build_filename(peak_dir (), base + ".peak");
3026 Session::change_audio_path_by_name (string path, string oldname, string newname, bool destructive)
3029 string old_basename = PBD::basename_nosuffix (oldname);
3030 string new_legalized = legalize_for_path (newname);
3032 /* note: we know (or assume) the old path is already valid */
3036 /* destructive file sources have a name of the form:
3038 /path/to/Tnnnn-NAME(%[LR])?.wav
3040 the task here is to replace NAME with the new name.
3043 /* find last slash */
3047 string::size_type slash;
3048 string::size_type dash;
3050 if ((slash = path.find_last_of ('/')) == string::npos) {
3054 dir = path.substr (0, slash+1);
3056 /* '-' is not a legal character for the NAME part of the path */
3058 if ((dash = path.find_last_of ('-')) == string::npos) {
3062 prefix = path.substr (slash+1, dash-(slash+1));
3067 path += new_legalized;
3068 path += ".wav"; /* XXX gag me with a spoon */
3072 /* non-destructive file sources have a name of the form:
3074 /path/to/NAME-nnnnn(%[LR])?.wav
3076 the task here is to replace NAME with the new name.
3081 string::size_type slash;
3082 string::size_type dash;
3083 string::size_type postfix;
3085 /* find last slash */
3087 if ((slash = path.find_last_of ('/')) == string::npos) {
3091 dir = path.substr (0, slash+1);
3093 /* '-' is not a legal character for the NAME part of the path */
3095 if ((dash = path.find_last_of ('-')) == string::npos) {
3099 suffix = path.substr (dash+1);
3101 // Suffix is now everything after the dash. Now we need to eliminate
3102 // the nnnnn part, which is done by either finding a '%' or a '.'
3104 postfix = suffix.find_last_of ("%");
3105 if (postfix == string::npos) {
3106 postfix = suffix.find_last_of ('.');
3109 if (postfix != string::npos) {
3110 suffix = suffix.substr (postfix);
3112 error << "Logic error in Session::change_audio_path_by_name(), please report to the developers" << endl;
3116 const uint32_t limit = 10000;
3117 char buf[PATH_MAX+1];
3119 for (uint32_t cnt = 1; cnt <= limit; ++cnt) {
3121 snprintf (buf, sizeof(buf), "%s%s-%u%s", dir.c_str(), newname.c_str(), cnt, suffix.c_str());
3123 if (access (buf, F_OK) != 0) {
3131 error << "FATAL ERROR! Could not find a " << endl;
3140 Session::audio_path_from_name (string name, uint32_t nchan, uint32_t chan, bool destructive)
3144 char buf[PATH_MAX+1];
3145 const uint32_t limit = 10000;
3149 legalized = legalize_for_path (name);
3151 /* find a "version" of the file name that doesn't exist in
3152 any of the possible directories.
3155 for (cnt = (destructive ? ++destructive_index : 1); cnt <= limit; ++cnt) {
3157 vector<space_and_path>::iterator i;
3158 uint32_t existing = 0;
3160 for (i = session_dirs.begin(); i != session_dirs.end(); ++i) {
3164 spath += sound_dir (false);
3168 snprintf (buf, sizeof(buf), "%s/T%04d-%s.wav", spath.c_str(), cnt, legalized.c_str());
3169 } else if (nchan == 2) {
3171 snprintf (buf, sizeof(buf), "%s/T%04d-%s%%L.wav", spath.c_str(), cnt, legalized.c_str());
3173 snprintf (buf, sizeof(buf), "%s/T%04d-%s%%R.wav", spath.c_str(), cnt, legalized.c_str());
3175 } else if (nchan < 26) {
3176 snprintf (buf, sizeof(buf), "%s/T%04d-%s%%%c.wav", spath.c_str(), cnt, legalized.c_str(), 'a' + chan);
3178 snprintf (buf, sizeof(buf), "%s/T%04d-%s.wav", spath.c_str(), cnt, legalized.c_str());
3187 snprintf (buf, sizeof(buf), "%s-%u.wav", spath.c_str(), cnt);
3188 } else if (nchan == 2) {
3190 snprintf (buf, sizeof(buf), "%s-%u%%L.wav", spath.c_str(), cnt);
3192 snprintf (buf, sizeof(buf), "%s-%u%%R.wav", spath.c_str(), cnt);
3194 } else if (nchan < 26) {
3195 snprintf (buf, sizeof(buf), "%s-%u%%%c.wav", spath.c_str(), cnt, 'a' + chan);
3197 snprintf (buf, sizeof(buf), "%s-%u.wav", spath.c_str(), cnt);
3201 if (g_file_test (buf, G_FILE_TEST_EXISTS)) {
3207 if (existing == 0) {
3212 error << string_compose(_("There are already %1 recordings for %2, which I consider too many."), limit, name) << endmsg;
3214 throw failed_constructor();
3218 /* we now have a unique name for the file, but figure out where to
3224 spath = discover_best_sound_dir ();
3227 string::size_type pos = foo.find_last_of ('/');
3229 if (pos == string::npos) {
3232 spath += foo.substr (pos + 1);
3238 boost::shared_ptr<AudioFileSource>
3239 Session::create_audio_source_for_session (AudioDiskstream& ds, uint32_t chan, bool destructive)
3241 string spath = audio_path_from_name (ds.name(), ds.n_channels(), chan, destructive);
3242 return boost::dynamic_pointer_cast<AudioFileSource> (SourceFactory::createWritable (*this, spath, destructive, frame_rate()));
3245 /* Playlist management */
3247 boost::shared_ptr<Playlist>
3248 Session::playlist_by_name (string name)
3250 Glib::Mutex::Lock lm (playlist_lock);
3251 for (PlaylistList::iterator i = playlists.begin(); i != playlists.end(); ++i) {
3252 if ((*i)->name() == name) {
3256 for (PlaylistList::iterator i = unused_playlists.begin(); i != unused_playlists.end(); ++i) {
3257 if ((*i)->name() == name) {
3262 return boost::shared_ptr<Playlist>();
3266 Session::add_playlist (boost::shared_ptr<Playlist> playlist)
3268 if (playlist->hidden()) {
3273 Glib::Mutex::Lock lm (playlist_lock);
3274 if (find (playlists.begin(), playlists.end(), playlist) == playlists.end()) {
3275 playlists.insert (playlists.begin(), playlist);
3276 playlist->InUse.connect (sigc::bind (mem_fun (*this, &Session::track_playlist), boost::weak_ptr<Playlist>(playlist)));
3277 playlist->GoingAway.connect (sigc::bind (mem_fun (*this, &Session::remove_playlist), boost::weak_ptr<Playlist>(playlist)));
3283 PlaylistAdded (playlist); /* EMIT SIGNAL */
3287 Session::get_playlists (vector<boost::shared_ptr<Playlist> >& s)
3290 Glib::Mutex::Lock lm (playlist_lock);
3291 for (PlaylistList::iterator i = playlists.begin(); i != playlists.end(); ++i) {
3294 for (PlaylistList::iterator i = unused_playlists.begin(); i != unused_playlists.end(); ++i) {
3301 Session::track_playlist (bool inuse, boost::weak_ptr<Playlist> wpl)
3303 boost::shared_ptr<Playlist> pl(wpl.lock());
3309 PlaylistList::iterator x;
3312 /* its not supposed to be visible */
3317 Glib::Mutex::Lock lm (playlist_lock);
3321 unused_playlists.insert (pl);
3323 if ((x = playlists.find (pl)) != playlists.end()) {
3324 playlists.erase (x);
3330 playlists.insert (pl);
3332 if ((x = unused_playlists.find (pl)) != unused_playlists.end()) {
3333 unused_playlists.erase (x);
3340 Session::remove_playlist (boost::weak_ptr<Playlist> weak_playlist)
3342 if (_state_of_the_state & Deletion) {
3346 boost::shared_ptr<Playlist> playlist (weak_playlist.lock());
3353 Glib::Mutex::Lock lm (playlist_lock);
3355 PlaylistList::iterator i;
3357 i = find (playlists.begin(), playlists.end(), playlist);
3358 if (i != playlists.end()) {
3359 playlists.erase (i);
3362 i = find (unused_playlists.begin(), unused_playlists.end(), playlist);
3363 if (i != unused_playlists.end()) {
3364 unused_playlists.erase (i);
3371 PlaylistRemoved (playlist); /* EMIT SIGNAL */
3375 Session::set_audition (boost::shared_ptr<Region> r)
3377 pending_audition_region = r;
3378 post_transport_work = PostTransportWork (post_transport_work | PostTransportAudition);
3379 schedule_butler_transport_work ();
3383 Session::audition_playlist ()
3385 Event* ev = new Event (Event::Audition, Event::Add, Event::Immediate, 0, 0.0);
3386 ev->region.reset ();
3391 Session::non_realtime_set_audition ()
3393 if (!pending_audition_region) {
3394 auditioner->audition_current_playlist ();
3396 auditioner->audition_region (pending_audition_region);
3397 pending_audition_region.reset ();
3399 AuditionActive (true); /* EMIT SIGNAL */
3403 Session::audition_region (boost::shared_ptr<Region> r)
3405 Event* ev = new Event (Event::Audition, Event::Add, Event::Immediate, 0, 0.0);
3411 Session::cancel_audition ()
3413 if (auditioner->active()) {
3414 auditioner->cancel_audition ();
3415 AuditionActive (false); /* EMIT SIGNAL */
3420 Session::RoutePublicOrderSorter::operator() (boost::shared_ptr<Route> a, boost::shared_ptr<Route> b)
3422 return a->order_key(N_("signal")) < b->order_key(N_("signal"));
3426 Session::remove_empty_sounds ()
3428 PathScanner scanner;
3430 vector<string *>* possible_audiofiles = scanner (sound_dir(), "\\.(wav|aiff|caf|w64|L|R)$", false, true);
3432 Glib::Mutex::Lock lm (audio_source_lock);
3434 regex_t compiled_tape_track_pattern;
3437 if ((err = regcomp (&compiled_tape_track_pattern, "/T[0-9][0-9][0-9][0-9]-", REG_EXTENDED|REG_NOSUB))) {
3441 regerror (err, &compiled_tape_track_pattern, msg, sizeof (msg));
3443 error << string_compose (_("Cannot compile tape track regexp for use (%1)"), msg) << endmsg;
3447 for (vector<string *>::iterator i = possible_audiofiles->begin(); i != possible_audiofiles->end(); ++i) {
3449 /* never remove files that appear to be a tape track */
3451 if (regexec (&compiled_tape_track_pattern, (*i)->c_str(), 0, 0, 0) == 0) {
3456 if (AudioFileSource::is_empty (*this, **i)) {
3458 unlink ((*i)->c_str());
3460 Glib::ustring peakpath = peak_path (PBD::basename_nosuffix (**i));
3461 unlink (peakpath.c_str());
3467 delete possible_audiofiles;
3471 Session::is_auditioning () const
3473 /* can be called before we have an auditioner object */
3475 return auditioner->active();
3482 Session::set_all_solo (bool yn)
3484 shared_ptr<RouteList> r = routes.reader ();
3486 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3487 if (!(*i)->hidden()) {
3488 (*i)->set_solo (yn, this);
3496 Session::set_all_mute (bool yn)
3498 shared_ptr<RouteList> r = routes.reader ();
3500 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3501 if (!(*i)->hidden()) {
3502 (*i)->set_mute (yn, this);
3510 Session::n_diskstreams () const
3514 boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
3516 for (DiskstreamList::const_iterator i = dsl->begin(); i != dsl->end(); ++i) {
3517 if (!(*i)->hidden()) {
3525 Session::graph_reordered ()
3527 /* don't do this stuff if we are setting up connections
3528 from a set_state() call or creating new tracks.
3531 if (_state_of_the_state & InitialConnecting) {
3535 /* every track/bus asked for this to be handled but it was deferred because
3536 we were connecting. do it now.
3539 request_input_change_handling ();
3543 /* force all diskstreams to update their capture offset values to
3544 reflect any changes in latencies within the graph.
3547 boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
3549 for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
3550 (*i)->set_capture_offset ();
3555 Session::record_disenable_all ()
3557 record_enable_change_all (false);
3561 Session::record_enable_all ()
3563 record_enable_change_all (true);
3567 Session::record_enable_change_all (bool yn)
3569 shared_ptr<RouteList> r = routes.reader ();
3571 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3574 if ((at = dynamic_cast<AudioTrack*>((*i).get())) != 0) {
3575 at->set_record_enable (yn, this);
3579 /* since we don't keep rec-enable state, don't mark session dirty */
3583 Session::add_redirect (Redirect* redirect)
3587 PortInsert* port_insert;
3588 PluginInsert* plugin_insert;
3590 if ((insert = dynamic_cast<Insert *> (redirect)) != 0) {
3591 if ((port_insert = dynamic_cast<PortInsert *> (insert)) != 0) {
3592 _port_inserts.insert (_port_inserts.begin(), port_insert);
3593 } else if ((plugin_insert = dynamic_cast<PluginInsert *> (insert)) != 0) {
3594 _plugin_inserts.insert (_plugin_inserts.begin(), plugin_insert);
3596 fatal << _("programming error: unknown type of Insert created!") << endmsg;
3599 } else if ((send = dynamic_cast<Send *> (redirect)) != 0) {
3600 _sends.insert (_sends.begin(), send);
3602 fatal << _("programming error: unknown type of Redirect created!") << endmsg;
3606 redirect->GoingAway.connect (sigc::bind (mem_fun (*this, &Session::remove_redirect), redirect));
3612 Session::remove_redirect (Redirect* redirect)
3616 PortInsert* port_insert;
3617 PluginInsert* plugin_insert;
3619 if ((insert = dynamic_cast<Insert *> (redirect)) != 0) {
3620 if ((port_insert = dynamic_cast<PortInsert *> (insert)) != 0) {
3621 list<PortInsert*>::iterator x = find (_port_inserts.begin(), _port_inserts.end(), port_insert);
3622 if (x != _port_inserts.end()) {
3623 insert_bitset[port_insert->bit_slot()] = false;
3624 _port_inserts.erase (x);
3626 } else if ((plugin_insert = dynamic_cast<PluginInsert *> (insert)) != 0) {
3627 _plugin_inserts.remove (plugin_insert);
3629 fatal << string_compose (_("programming error: %1"),
3630 X_("unknown type of Insert deleted!"))
3634 } else if ((send = dynamic_cast<Send *> (redirect)) != 0) {
3635 list<Send*>::iterator x = find (_sends.begin(), _sends.end(), send);
3636 if (x != _sends.end()) {
3637 send_bitset[send->bit_slot()] = false;
3641 fatal << _("programming error: unknown type of Redirect deleted!") << endmsg;
3649 Session::available_capture_duration ()
3651 float sample_bytes_on_disk = 4.0; // keep gcc happy
3653 switch (Config->get_native_file_data_format()) {
3655 sample_bytes_on_disk = 4.0;
3659 sample_bytes_on_disk = 3.0;
3663 sample_bytes_on_disk = 2.0;
3667 /* impossible, but keep some gcc versions happy */
3668 fatal << string_compose (_("programming error: %1"),
3669 X_("illegal native file data format"))
3674 double scale = 4096.0 / sample_bytes_on_disk;
3676 if (_total_free_4k_blocks * scale > (double) max_frames) {
3680 return (nframes_t) floor (_total_free_4k_blocks * scale);
3684 Session::add_connection (ARDOUR::Connection* connection)
3687 Glib::Mutex::Lock guard (connection_lock);
3688 _connections.push_back (connection);
3691 ConnectionAdded (connection); /* EMIT SIGNAL */
3697 Session::remove_connection (ARDOUR::Connection* connection)
3699 bool removed = false;
3702 Glib::Mutex::Lock guard (connection_lock);
3703 ConnectionList::iterator i = find (_connections.begin(), _connections.end(), connection);
3705 if (i != _connections.end()) {
3706 _connections.erase (i);
3712 ConnectionRemoved (connection); /* EMIT SIGNAL */
3718 ARDOUR::Connection *
3719 Session::connection_by_name (string name) const
3721 Glib::Mutex::Lock lm (connection_lock);
3723 for (ConnectionList::const_iterator i = _connections.begin(); i != _connections.end(); ++i) {
3724 if ((*i)->name() == name) {
3733 Session::tempo_map_changed (Change ignored)
3737 for (PlaylistList::iterator i = playlists.begin(); i != playlists.end(); ++i) {
3738 (*i)->update_after_tempo_map_change ();
3741 for (PlaylistList::iterator i = unused_playlists.begin(); i != unused_playlists.end(); ++i) {
3742 (*i)->update_after_tempo_map_change ();
3749 Session::ensure_passthru_buffers (uint32_t howmany)
3751 if (current_block_size == 0) {
3755 while (howmany > _passthru_buffers.size()) {
3757 #ifdef NO_POSIX_MEMALIGN
3758 p = (Sample *) malloc(current_block_size * sizeof(Sample));
3760 if (posix_memalign((void **)&p,CPU_CACHE_ALIGN,current_block_size * sizeof(Sample)) != 0) {
3761 fatal << string_compose (_("Memory allocation error: posix_memalign (%1 * %2) failed (%3)"),
3762 current_block_size, sizeof (Sample), strerror (errno))
3767 _passthru_buffers.push_back (p);
3771 #ifdef NO_POSIX_MEMALIGN
3772 p = (Sample *) malloc(current_block_size * sizeof(Sample));
3774 if (posix_memalign((void **)&p,CPU_CACHE_ALIGN,current_block_size * sizeof(Sample)) != 0) {
3775 fatal << string_compose (_("Memory allocation error: posix_memalign (%1 * %2) failed (%3)"),
3776 current_block_size, sizeof (Sample), strerror (errno))
3781 memset (p, 0, sizeof (Sample) * current_block_size);
3782 _silent_buffers.push_back (p);
3786 #ifdef NO_POSIX_MEMALIGN
3787 p = (Sample *) malloc(current_block_size * sizeof(Sample));
3789 posix_memalign((void **)&p,CPU_CACHE_ALIGN,current_block_size * sizeof(Sample));
3791 memset (p, 0, sizeof (Sample) * current_block_size);
3792 _send_buffers.push_back (p);
3795 allocate_pan_automation_buffers (current_block_size, howmany, false);
3799 Session::next_insert_id ()
3801 /* this doesn't really loop forever. just think about it */
3804 for (boost::dynamic_bitset<uint32_t>::size_type n = 0; n < insert_bitset.size(); ++n) {
3805 if (!insert_bitset[n]) {
3806 insert_bitset[n] = true;
3812 /* none available, so resize and try again */
3814 insert_bitset.resize (insert_bitset.size() + 16, false);
3819 Session::next_send_id ()
3821 /* this doesn't really loop forever. just think about it */
3824 for (boost::dynamic_bitset<uint32_t>::size_type n = 0; n < send_bitset.size(); ++n) {
3825 if (!send_bitset[n]) {
3826 send_bitset[n] = true;
3832 /* none available, so resize and try again */
3834 send_bitset.resize (send_bitset.size() + 16, false);
3839 Session::mark_send_id (uint32_t id)
3841 if (id >= send_bitset.size()) {
3842 send_bitset.resize (id+16, false);
3844 if (send_bitset[id]) {
3845 warning << string_compose (_("send ID %1 appears to be in use already"), id) << endmsg;
3847 send_bitset[id] = true;
3851 Session::mark_insert_id (uint32_t id)
3853 if (id >= insert_bitset.size()) {
3854 insert_bitset.resize (id+16, false);
3856 if (insert_bitset[id]) {
3857 warning << string_compose (_("insert ID %1 appears to be in use already"), id) << endmsg;
3859 insert_bitset[id] = true;
3862 /* Named Selection management */
3865 Session::named_selection_by_name (string name)
3867 Glib::Mutex::Lock lm (named_selection_lock);
3868 for (NamedSelectionList::iterator i = named_selections.begin(); i != named_selections.end(); ++i) {
3869 if ((*i)->name == name) {
3877 Session::add_named_selection (NamedSelection* named_selection)
3880 Glib::Mutex::Lock lm (named_selection_lock);
3881 named_selections.insert (named_selections.begin(), named_selection);
3884 for (list<boost::shared_ptr<Playlist> >::iterator i = named_selection->playlists.begin(); i != named_selection->playlists.end(); ++i) {
3890 NamedSelectionAdded (); /* EMIT SIGNAL */
3894 Session::remove_named_selection (NamedSelection* named_selection)
3896 bool removed = false;
3899 Glib::Mutex::Lock lm (named_selection_lock);
3901 NamedSelectionList::iterator i = find (named_selections.begin(), named_selections.end(), named_selection);
3903 if (i != named_selections.end()) {
3905 named_selections.erase (i);
3912 NamedSelectionRemoved (); /* EMIT SIGNAL */
3917 Session::reset_native_file_format ()
3919 boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
3921 for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
3922 (*i)->reset_write_sources (false);
3927 Session::route_name_unique (string n) const
3929 shared_ptr<RouteList> r = routes.reader ();
3931 for (RouteList::const_iterator i = r->begin(); i != r->end(); ++i) {
3932 if ((*i)->name() == n) {
3941 Session::n_playlists () const
3943 Glib::Mutex::Lock lm (playlist_lock);
3944 return playlists.size();
3948 Session::allocate_pan_automation_buffers (nframes_t nframes, uint32_t howmany, bool force)
3950 if (!force && howmany <= _npan_buffers) {
3954 if (_pan_automation_buffer) {
3956 for (uint32_t i = 0; i < _npan_buffers; ++i) {
3957 delete [] _pan_automation_buffer[i];
3960 delete [] _pan_automation_buffer;
3963 _pan_automation_buffer = new pan_t*[howmany];
3965 for (uint32_t i = 0; i < howmany; ++i) {
3966 _pan_automation_buffer[i] = new pan_t[nframes];
3969 _npan_buffers = howmany;
3973 Session::freeze (InterThreadInfo& itt)
3975 shared_ptr<RouteList> r = routes.reader ();
3977 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3981 if ((at = dynamic_cast<AudioTrack*>((*i).get())) != 0) {
3982 /* XXX this is wrong because itt.progress will keep returning to zero at the start
3992 boost::shared_ptr<Region>
3993 Session::write_one_audio_track (AudioTrack& track, nframes_t start, nframes_t end,
3994 bool overwrite, vector<boost::shared_ptr<AudioSource> >& srcs, InterThreadInfo& itt)
3996 boost::shared_ptr<Region> result;
3997 boost::shared_ptr<Playlist> playlist;
3998 boost::shared_ptr<AudioFileSource> fsource;
4000 char buf[PATH_MAX+1];
4004 nframes_t this_chunk;
4006 nframes_t len = end - start;
4007 vector<Sample*> buffers;
4010 error << string_compose (_("Cannot write a range where end <= start (e.g. %1 <= %2)"),
4011 end, start) << endmsg;
4015 // any bigger than this seems to cause stack overflows in called functions
4016 const nframes_t chunk_size = (128 * 1024)/4;
4018 g_atomic_int_set (&processing_prohibited, 1);
4020 /* call tree *MUST* hold route_lock */
4022 if ((playlist = track.diskstream()->playlist()) == 0) {
4026 /* external redirects will be a problem */
4028 if (track.has_external_redirects()) {
4032 nchans = track.audio_diskstream()->n_channels();
4034 dir = discover_best_sound_dir ();
4036 for (uint32_t chan_n=0; chan_n < nchans; ++chan_n) {
4038 for (x = 0; x < 99999; ++x) {
4039 snprintf (buf, sizeof(buf), "%s/%s-%d-bounce-%" PRIu32 ".wav", dir.c_str(), playlist->name().c_str(), chan_n, x+1);
4040 if (access (buf, F_OK) != 0) {
4046 error << string_compose (_("too many bounced versions of playlist \"%1\""), playlist->name()) << endmsg;
4051 fsource = boost::dynamic_pointer_cast<AudioFileSource> (SourceFactory::createWritable (*this, buf, false, frame_rate()));
4054 catch (failed_constructor& err) {
4055 error << string_compose (_("cannot create new audio file \"%1\" for %2"), buf, track.name()) << endmsg;
4059 srcs.push_back (fsource);
4062 /* XXX need to flush all redirects */
4067 /* create a set of reasonably-sized buffers */
4069 for (vector<Sample*>::iterator i = _passthru_buffers.begin(); i != _passthru_buffers.end(); ++i) {
4071 #ifdef NO_POSIX_MEMALIGN
4072 b = (Sample *) malloc(chunk_size * sizeof(Sample));
4074 posix_memalign((void **)&b,4096,chunk_size * sizeof(Sample));
4076 buffers.push_back (b);
4079 for (vector<boost::shared_ptr<AudioSource> >::iterator src=srcs.begin(); src != srcs.end(); ++src) {
4080 (*src)->prepare_for_peakfile_writes ();
4083 while (to_do && !itt.cancel) {
4085 this_chunk = min (to_do, chunk_size);
4087 if (track.export_stuff (buffers, nchans, start, this_chunk)) {
4092 for (vector<boost::shared_ptr<AudioSource> >::iterator src=srcs.begin(); src != srcs.end(); ++src, ++n) {
4093 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
4096 if (afs->write (buffers[n], this_chunk) != this_chunk) {
4102 start += this_chunk;
4103 to_do -= this_chunk;
4105 itt.progress = (float) (1.0 - ((double) to_do / len));
4114 xnow = localtime (&now);
4116 for (vector<boost::shared_ptr<AudioSource> >::iterator src=srcs.begin(); src != srcs.end(); ++src) {
4117 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
4120 afs->update_header (position, *xnow, now);
4121 afs->flush_header ();
4125 /* construct a region to represent the bounced material */
4127 result = RegionFactory::create (srcs, 0, srcs.front()->length(),
4128 region_name_from_path (srcs.front()->name(), true));
4133 for (vector<boost::shared_ptr<AudioSource> >::iterator src = srcs.begin(); src != srcs.end(); ++src) {
4134 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
4137 afs->mark_for_remove ();
4140 (*src)->drop_references ();
4144 for (vector<boost::shared_ptr<AudioSource> >::iterator src = srcs.begin(); src != srcs.end(); ++src) {
4145 (*src)->done_with_peakfile_writes ();
4149 for (vector<Sample*>::iterator i = buffers.begin(); i != buffers.end(); ++i) {
4153 g_atomic_int_set (&processing_prohibited, 0);
4161 Session::get_silent_buffers (uint32_t howmany)
4163 if (howmany > _silent_buffers.size()) {
4165 error << string_compose (_("Programming error: get_silent_buffers() called for %1 buffers but only %2 exist"),
4166 howmany, _silent_buffers.size()) << endmsg;
4168 if (howmany > 1000) {
4169 cerr << "ABSURD: more than 1000 silent buffers requested!\n";
4173 while (howmany > _silent_buffers.size()) {
4176 #ifdef NO_POSIX_MEMALIGN
4177 p = (Sample *) malloc(current_block_size * sizeof(Sample));
4179 if (posix_memalign((void **)&p,CPU_CACHE_ALIGN,current_block_size * sizeof(Sample)) != 0) {
4180 fatal << string_compose (_("Memory allocation error: posix_memalign (%1 * %2) failed (%3)"),
4181 current_block_size, sizeof (Sample), strerror (errno))
4186 _silent_buffers.push_back (p);
4190 for (uint32_t i = 0; i < howmany; ++i) {
4191 memset (_silent_buffers[i], 0, sizeof (Sample) * current_block_size);
4194 return _silent_buffers;
4198 Session::ntracks () const
4201 shared_ptr<RouteList> r = routes.reader ();
4203 for (RouteList::const_iterator i = r->begin(); i != r->end(); ++i) {
4204 if (dynamic_cast<AudioTrack*> ((*i).get())) {
4213 Session::nbusses () const
4216 shared_ptr<RouteList> r = routes.reader ();
4218 for (RouteList::const_iterator i = r->begin(); i != r->end(); ++i) {
4219 if (dynamic_cast<AudioTrack*> ((*i).get()) == 0) {
4228 Session::add_automation_list(AutomationList *al)
4230 automation_lists[al->id()] = al;
4234 Session::compute_initial_length ()
4236 return _engine.frame_rate() * 60 * 5;
4240 Session::sync_order_keys (const char* base)
4242 if (!Config->get_sync_all_route_ordering()) {
4243 /* leave order keys as they are */
4247 boost::shared_ptr<RouteList> r = routes.reader ();
4249 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4250 (*i)->sync_order_keys (base);
4253 Route::SyncOrderKeys (base); // EMIT SIGNAL