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.
26 #include <cstdio> /* sprintf(3) ... grrr */
32 #include <sigc++/bind.h>
33 #include <sigc++/retype.h>
35 #include <pbd/error.h>
36 #include <pbd/lockmonitor.h>
37 #include <pbd/pathscanner.h>
38 #include <pbd/stl_delete.h>
39 #include <pbd/basename.h>
40 #include <pbd/dirname.h>
42 #include <ardour/audioengine.h>
43 #include <ardour/configuration.h>
44 #include <ardour/session.h>
45 #include <ardour/diskstream.h>
46 #include <ardour/utils.h>
47 #include <ardour/audioplaylist.h>
48 #include <ardour/audioregion.h>
49 #include <ardour/source.h>
50 #include <ardour/filesource.h>
51 #include <ardour/sndfilesource.h>
52 #include <ardour/auditioner.h>
53 #include <ardour/recent_sessions.h>
54 #include <ardour/redirect.h>
55 #include <ardour/send.h>
56 #include <ardour/insert.h>
57 #include <ardour/connection.h>
58 #include <ardour/slave.h>
59 #include <ardour/tempo.h>
60 #include <ardour/audio_track.h>
61 #include <ardour/cycle_timer.h>
62 #include <ardour/named_selection.h>
63 #include <ardour/crossfade.h>
64 #include <ardour/playlist.h>
65 #include <ardour/click.h>
66 #include <ardour/timestamps.h>
71 using namespace ARDOUR;
72 //using namespace sigc;
74 const char* Session::_template_suffix = X_(".template");
75 const char* Session::_statefile_suffix = X_(".ardour");
76 const char* Session::_pending_suffix = X_(".pending");
77 const char* Session::sound_dir_name = X_("sounds");
78 const char* Session::peak_dir_name = X_("peaks");
79 const char* Session::dead_sound_dir_name = X_("dead_sounds");
81 Session::compute_peak_t Session::compute_peak = 0;
82 Session::apply_gain_to_buffer_t Session::apply_gain_to_buffer = 0;
83 Session::mix_buffers_with_gain_t Session::mix_buffers_with_gain = 0;
84 Session::mix_buffers_no_gain_t Session::mix_buffers_no_gain = 0;
86 sigc::signal<int> Session::AskAboutPendingState;
89 Session::find_session (string str, string& path, string& snapshot, bool& isnew)
96 if (!realpath (str.c_str(), buf) && (errno != ENOENT && errno != ENOTDIR)) {
97 error << string_compose (_("Could not resolve path: %1 (%2)"), buf, strerror(errno)) << endmsg;
103 /* check to see if it exists, and what it is */
105 if (stat (str.c_str(), &statbuf)) {
106 if (errno == ENOENT) {
109 error << string_compose (_("cannot check session path %1 (%2)"), str, strerror (errno))
117 /* it exists, so it must either be the name
118 of the directory, or the name of the statefile
122 if (S_ISDIR (statbuf.st_mode)) {
124 string::size_type slash = str.find_last_of ('/');
126 if (slash == string::npos) {
128 /* a subdirectory of cwd, so statefile should be ... */
134 tmp += _statefile_suffix;
138 if (stat (tmp.c_str(), &statbuf)) {
139 error << string_compose (_("cannot check statefile %1 (%2)"), tmp, strerror (errno))
149 /* some directory someplace in the filesystem.
150 the snapshot name is the directory name
155 snapshot = str.substr (slash+1);
159 } else if (S_ISREG (statbuf.st_mode)) {
161 string::size_type slash = str.find_last_of ('/');
162 string::size_type suffix;
164 /* remove the suffix */
166 if (slash != string::npos) {
167 snapshot = str.substr (slash+1);
172 suffix = snapshot.find (_statefile_suffix);
174 if (suffix == string::npos) {
175 error << string_compose (_("%1 is not an Ardour snapshot file"), str) << endmsg;
181 snapshot = snapshot.substr (0, suffix);
183 if (slash == string::npos) {
185 /* we must be in the directory where the
186 statefile lives. get it using cwd().
189 char cwd[PATH_MAX+1];
191 if (getcwd (cwd, sizeof (cwd)) == 0) {
192 error << string_compose (_("cannot determine current working directory (%1)"), strerror (errno))
201 /* full path to the statefile */
203 path = str.substr (0, slash);
208 /* what type of file is it? */
209 error << string_compose (_("unknown file type for session %1"), str) << endmsg;
215 /* its the name of a new directory. get the name
219 string::size_type slash = str.find_last_of ('/');
221 if (slash == string::npos) {
223 /* no slash, just use the name, but clean it up */
225 path = legalize_for_path (str);
231 snapshot = str.substr (slash+1);
238 Session::Session (AudioEngine &eng,
240 string snapshot_name,
241 string* mix_template)
244 _mmc_port (default_mmc_port),
245 _mtc_port (default_mtc_port),
246 _midi_port (default_midi_port),
247 pending_events (2048),
248 midi_requests (128), // the size of this should match the midi request pool size
253 cerr << "Loading session " << fullpath << " using snapshot " << snapshot_name << endl;
255 n_physical_outputs = _engine.n_physical_outputs();
256 n_physical_inputs = _engine.n_physical_inputs();
258 first_stage_init (fullpath, snapshot_name);
260 if (create (new_session, mix_template, _engine.frame_rate() * 60 * 5)) {
261 throw failed_constructor ();
264 if (second_stage_init (new_session)) {
265 throw failed_constructor ();
268 store_recent_sessions(_name, _path);
270 bool was_dirty = dirty();
272 _state_of_the_state = StateOfTheState (_state_of_the_state & ~Dirty);
275 DirtyChanged (); /* EMIT SIGNAL */
279 Session::Session (AudioEngine &eng,
281 string snapshot_name,
282 AutoConnectOption input_ac,
283 AutoConnectOption output_ac,
284 uint32_t control_out_channels,
285 uint32_t master_out_channels,
286 uint32_t requested_physical_in,
287 uint32_t requested_physical_out,
288 jack_nframes_t initial_length)
291 _mmc_port (default_mmc_port),
292 _mtc_port (default_mtc_port),
293 _midi_port (default_midi_port),
294 pending_events (2048),
301 cerr << "Loading session " << fullpath << " using snapshot " << snapshot_name << endl;
303 n_physical_outputs = max (requested_physical_out, _engine.n_physical_outputs());
304 n_physical_inputs = max (requested_physical_in, _engine.n_physical_inputs());
306 first_stage_init (fullpath, snapshot_name);
308 if (create (new_session, 0, initial_length)) {
309 throw failed_constructor ();
312 if (control_out_channels) {
314 r = new Route (*this, _("monitor"), -1, control_out_channels, -1, control_out_channels, Route::ControlOut);
319 if (master_out_channels) {
321 r = new Route (*this, _("master"), -1, master_out_channels, -1, master_out_channels, Route::MasterOut);
325 /* prohibit auto-connect to master, because there isn't one */
326 output_ac = AutoConnectOption (output_ac & ~AutoConnectMaster);
329 input_auto_connect = input_ac;
330 output_auto_connect = output_ac;
332 if (second_stage_init (new_session)) {
333 throw failed_constructor ();
336 store_recent_sessions(_name, _path);
338 bool was_dirty = dirty ();
340 _state_of_the_state = StateOfTheState (_state_of_the_state & ~Dirty);
343 DirtyChanged (); /* EMIT SIGNAL */
349 /* if we got to here, leaving pending capture state around
353 remove_pending_capture_state ();
355 _state_of_the_state = StateOfTheState (CannotSave|Deletion);
356 _engine.remove_session ();
358 going_away (); /* EMIT SIGNAL */
360 terminate_butler_thread ();
361 terminate_midi_thread ();
362 terminate_feedback ();
364 if (click_data && click_data != default_click) {
365 delete [] click_data;
368 if (click_emphasis_data && click_emphasis_data != default_click_emphasis) {
369 delete [] click_emphasis_data;
383 for (vector<Sample*>::iterator i = _passthru_buffers.begin(); i != _passthru_buffers.end(); ++i) {
387 for (vector<Sample*>::iterator i = _silent_buffers.begin(); i != _silent_buffers.end(); ++i) {
391 #undef TRACK_DESTRUCTION
392 #ifdef TRACK_DESTRUCTION
393 cerr << "delete named selections\n";
394 #endif /* TRACK_DESTRUCTION */
395 for (NamedSelectionList::iterator i = named_selections.begin(); i != named_selections.end(); ) {
396 NamedSelectionList::iterator tmp;
405 #ifdef TRACK_DESTRUCTION
406 cerr << "delete playlists\n";
407 #endif /* TRACK_DESTRUCTION */
408 for (PlaylistList::iterator i = playlists.begin(); i != playlists.end(); ) {
409 PlaylistList::iterator tmp;
419 #ifdef TRACK_DESTRUCTION
420 cerr << "delete audio regions\n";
421 #endif /* TRACK_DESTRUCTION */
422 for (AudioRegionList::iterator i = audio_regions.begin(); i != audio_regions.end(); ) {
423 AudioRegionList::iterator tmp;
433 #ifdef TRACK_DESTRUCTION
434 cerr << "delete routes\n";
435 #endif /* TRACK_DESTRUCTION */
436 for (RouteList::iterator i = routes.begin(); i != routes.end(); ) {
437 RouteList::iterator tmp;
444 #ifdef TRACK_DESTRUCTION
445 cerr << "delete diskstreams\n";
446 #endif /* TRACK_DESTRUCTION */
447 for (DiskStreamList::iterator i = diskstreams.begin(); i != diskstreams.end(); ) {
448 DiskStreamList::iterator tmp;
458 #ifdef TRACK_DESTRUCTION
459 cerr << "delete sources\n";
460 #endif /* TRACK_DESTRUCTION */
461 for (SourceList::iterator i = sources.begin(); i != sources.end(); ) {
462 SourceList::iterator tmp;
472 #ifdef TRACK_DESTRUCTION
473 cerr << "delete mix groups\n";
474 #endif /* TRACK_DESTRUCTION */
475 for (list<RouteGroup *>::iterator i = mix_groups.begin(); i != mix_groups.end(); ) {
476 list<RouteGroup*>::iterator tmp;
486 #ifdef TRACK_DESTRUCTION
487 cerr << "delete edit groups\n";
488 #endif /* TRACK_DESTRUCTION */
489 for (list<RouteGroup *>::iterator i = edit_groups.begin(); i != edit_groups.end(); ) {
490 list<RouteGroup*>::iterator tmp;
500 #ifdef TRACK_DESTRUCTION
501 cerr << "delete connections\n";
502 #endif /* TRACK_DESTRUCTION */
503 for (ConnectionList::iterator i = _connections.begin(); i != _connections.end(); ) {
504 ConnectionList::iterator tmp;
514 if (butler_mixdown_buffer) {
515 delete [] butler_mixdown_buffer;
518 if (butler_gain_buffer) {
519 delete [] butler_gain_buffer;
522 Crossfade::set_buffer_size (0);
534 Session::set_worst_io_latencies (bool take_lock)
536 _worst_output_latency = 0;
537 _worst_input_latency = 0;
539 if (!_engine.connected()) {
547 for (RouteList::iterator i = routes.begin(); i != routes.end(); ++i) {
548 _worst_output_latency = max (_worst_output_latency, (*i)->output_latency());
549 _worst_input_latency = max (_worst_input_latency, (*i)->input_latency());
553 route_lock.unlock ();
558 Session::when_engine_running ()
560 string first_physical_output;
562 /* we don't want to run execute this again */
564 first_time_running.disconnect ();
566 set_block_size (_engine.frames_per_cycle());
567 set_frame_rate (_engine.frame_rate());
569 /* every time we reconnect, recompute worst case output latencies */
571 _engine.Running.connect (sigc::bind (mem_fun (*this, &Session::set_worst_io_latencies), true));
573 if (synced_to_jack()) {
574 _engine.transport_stop ();
577 if (Config->get_jack_time_master()) {
578 _engine.transport_locate (_transport_frame);
586 _click_io = new ClickIO (*this, "click", 0, 0, -1, -1);
588 if (state_tree && (child = find_named_node (*state_tree->root(), "Click")) != 0) {
590 /* existing state for Click */
592 if (_click_io->set_state (*child->children().front()) == 0) {
594 _clicking = click_requested;
598 error << _("could not setup Click I/O") << endmsg;
604 /* default state for Click */
606 first_physical_output = _engine.get_nth_physical_output (0);
608 if (first_physical_output.length()) {
609 if (_click_io->add_output_port (first_physical_output, this)) {
610 // relax, even though its an error
612 _clicking = click_requested;
618 catch (failed_constructor& err) {
619 error << _("cannot setup Click I/O") << endmsg;
622 set_worst_io_latencies (true);
625 ControlChanged (Clicking); /* EMIT SIGNAL */
628 if (auditioner == 0) {
630 /* we delay creating the auditioner till now because
631 it makes its own connections to ports named
632 in the ARDOUR_RC config file. the engine has
633 to be running for this to work.
637 auditioner = new Auditioner (*this);
640 catch (failed_constructor& err) {
641 warning << _("cannot create Auditioner: no auditioning of regions possible") << endmsg;
645 /* Create a set of Connection objects that map
646 to the physical outputs currently available
651 for (uint32_t np = 0; np < n_physical_outputs; ++np) {
653 snprintf (buf, sizeof (buf), _("out %" PRIu32), np+1);
655 Connection* c = new OutputConnection (buf, true);
658 c->add_connection (0, _engine.get_nth_physical_output (np));
663 for (uint32_t np = 0; np < n_physical_inputs; ++np) {
665 snprintf (buf, sizeof (buf), _("in %" PRIu32), np+1);
667 Connection* c = new InputConnection (buf, true);
670 c->add_connection (0, _engine.get_nth_physical_input (np));
677 for (uint32_t np = 0; np < n_physical_outputs; np +=2) {
679 snprintf (buf, sizeof (buf), _("out %" PRIu32 "+%" PRIu32), np+1, np+2);
681 Connection* c = new OutputConnection (buf, true);
685 c->add_connection (0, _engine.get_nth_physical_output (np));
686 c->add_connection (1, _engine.get_nth_physical_output (np+1));
691 for (uint32_t np = 0; np < n_physical_inputs; np +=2) {
693 snprintf (buf, sizeof (buf), _("in %" PRIu32 "+%" PRIu32), np+1, np+2);
695 Connection* c = new InputConnection (buf, true);
699 c->add_connection (0, _engine.get_nth_physical_input (np));
700 c->add_connection (1, _engine.get_nth_physical_input (np+1));
709 /* create master/control ports */
714 /* force the master to ignore any later call to this */
716 if (_master_out->pending_state_node) {
717 _master_out->ports_became_legal();
720 /* no panner resets till we are through */
722 _master_out->defer_pan_reset ();
724 while ((int) _master_out->n_inputs() < _master_out->input_maximum()) {
725 if (_master_out->add_input_port ("", this)) {
726 error << _("cannot setup master inputs")
732 while ((int) _master_out->n_outputs() < _master_out->output_maximum()) {
733 if (_master_out->add_output_port (_engine.get_nth_physical_output (n), this)) {
734 error << _("cannot setup master outputs")
741 _master_out->allow_pan_reset ();
745 Connection* c = new OutputConnection (_("Master Out"), true);
747 for (uint32_t n = 0; n < _master_out->n_inputs (); ++n) {
749 c->add_connection ((int) n, _master_out->input(n)->name());
756 /* catch up on send+insert cnts */
760 for (slist<PortInsert*>::iterator i = _port_inserts.begin(); i != _port_inserts.end(); ++i) {
763 if (sscanf ((*i)->name().c_str(), "%*s %u", &id) == 1) {
764 if (id > insert_cnt) {
772 for (slist<Send*>::iterator i = _sends.begin(); i != _sends.end(); ++i) {
775 if (sscanf ((*i)->name().c_str(), "%*s %u", &id) == 1) {
782 _state_of_the_state = StateOfTheState (_state_of_the_state & ~(CannotSave|Dirty));
784 /* hook us up to the engine */
786 _engine.set_session (this);
788 _state_of_the_state = Clean;
790 DirtyChanged (); /* EMIT SIGNAL */
794 Session::hookup_io ()
796 /* stop graph reordering notifications from
797 causing resorts, etc.
800 _state_of_the_state = StateOfTheState (_state_of_the_state | InitialConnecting);
802 /* Tell all IO objects to create their ports */
809 while ((int) _control_out->n_inputs() < _control_out->input_maximum()) {
810 if (_control_out->add_input_port ("", this)) {
811 error << _("cannot setup control inputs")
817 while ((int) _control_out->n_outputs() < _control_out->output_maximum()) {
818 if (_control_out->add_output_port (_engine.get_nth_physical_output (n), this)) {
819 error << _("cannot set up master outputs")
827 /* Tell all IO objects to connect themselves together */
829 IO::enable_connecting ();
831 /* Now reset all panners */
833 IO::reset_panners ();
835 /* Anyone who cares about input state, wake up and do something */
837 IOConnectionsComplete (); /* EMIT SIGNAL */
839 _state_of_the_state = StateOfTheState (_state_of_the_state & ~InitialConnecting);
841 /* now handle the whole enchilada as if it was one
847 /* update mixer solo state */
853 Session::playlist_length_changed (Playlist* pl)
855 /* we can't just increase end_location->end() if pl->get_maximum_extent()
856 if larger. if the playlist used to be the longest playlist,
857 and its now shorter, we have to decrease end_location->end(). hence,
858 we have to iterate over all diskstreams and check the
859 playlists currently in use.
865 Session::diskstream_playlist_changed (DiskStream* dstream)
869 if ((playlist = dstream->playlist()) != 0) {
870 playlist->LengthChanged.connect (sigc::bind (mem_fun (this, &Session::playlist_length_changed), playlist));
873 /* see comment in playlist_length_changed () */
878 Session::record_enabling_legal () const
880 /* this used to be in here, but survey says.... we don't need to restrict it */
881 // if (record_status() == Recording) {
892 Session::set_auto_play (bool yn)
894 if (auto_play != yn) {
897 ControlChanged (AutoPlay);
902 Session::set_auto_return (bool yn)
904 if (auto_return != yn) {
907 ControlChanged (AutoReturn);
912 Session::set_crossfades_active (bool yn)
914 if (crossfades_active != yn) {
915 crossfades_active = yn;
917 ControlChanged (CrossFadesActive);
922 Session::set_recording_plugins (bool yn)
924 if (recording_plugins != yn) {
925 recording_plugins = yn;
927 ControlChanged (RecordingPlugins);
932 Session::set_auto_input (bool yn)
934 if (auto_input != yn) {
937 ControlChanged (AutoInput);
942 Session::set_input_auto_connect (bool yn)
945 input_auto_connect = AutoConnectOption (input_auto_connect|AutoConnectPhysical);
947 input_auto_connect = AutoConnectOption (input_auto_connect|~AutoConnectPhysical);
953 Session::set_output_auto_connect (AutoConnectOption aco)
955 output_auto_connect = aco;
960 Session::auto_punch_start_changed (Location* location)
962 replace_event (Event::PunchIn, location->start());
964 if (get_record_enabled() && get_punch_in()) {
965 /* capture start has been changed, so save new pending state */
966 save_state ("", true);
971 Session::auto_punch_end_changed (Location* location)
973 jack_nframes_t when_to_stop = location->end();
974 // when_to_stop += _worst_output_latency + _worst_input_latency;
975 replace_event (Event::PunchOut, when_to_stop);
979 Session::auto_punch_changed (Location* location)
981 jack_nframes_t when_to_stop = location->end();
983 replace_event (Event::PunchIn, location->start());
984 //when_to_stop += _worst_output_latency + _worst_input_latency;
985 replace_event (Event::PunchOut, when_to_stop);
989 Session::auto_loop_changed (Location* location)
991 replace_event (Event::AutoLoop, location->end(), location->start());
993 if (transport_rolling() && get_auto_loop()) {
995 //if (_transport_frame < location->start() || _transport_frame > location->end()) {
997 if (_transport_frame > location->end()) {
998 // relocate to beginning of loop
999 clear_events (Event::LocateRoll);
1001 request_locate (location->start(), true);
1004 else if (seamless_loop && !loop_changing) {
1006 // schedule a locate-roll to refill the diskstreams at the
1007 // previous loop end
1008 loop_changing = true;
1010 if (location->end() > last_loopend) {
1011 clear_events (Event::LocateRoll);
1012 Event *ev = new Event (Event::LocateRoll, Event::Add, last_loopend, last_loopend, 0, true);
1019 last_loopend = location->end();
1024 Session::set_auto_punch_location (Location* location)
1028 if ((existing = _locations.auto_punch_location()) != 0 && existing != location) {
1029 auto_punch_start_changed_connection.disconnect();
1030 auto_punch_end_changed_connection.disconnect();
1031 auto_punch_changed_connection.disconnect();
1032 existing->set_auto_punch (false, this);
1033 remove_event (existing->start(), Event::PunchIn);
1034 clear_events (Event::PunchOut);
1035 auto_punch_location_changed (0);
1040 if (location == 0) {
1044 if (location->end() <= location->start()) {
1045 error << _("Session: you can't use that location for auto punch (start <= end)") << endmsg;
1049 auto_punch_start_changed_connection.disconnect();
1050 auto_punch_end_changed_connection.disconnect();
1051 auto_punch_changed_connection.disconnect();
1053 auto_punch_start_changed_connection = location->start_changed.connect (mem_fun (this, &Session::auto_punch_start_changed));
1054 auto_punch_end_changed_connection = location->end_changed.connect (mem_fun (this, &Session::auto_punch_end_changed));
1055 auto_punch_changed_connection = location->changed.connect (mem_fun (this, &Session::auto_punch_changed));
1057 location->set_auto_punch (true, this);
1058 auto_punch_location_changed (location);
1062 Session::set_punch_in (bool yn)
1064 if (punch_in == yn) {
1070 if ((location = _locations.auto_punch_location()) != 0) {
1071 if ((punch_in = yn) == true) {
1072 replace_event (Event::PunchIn, location->start());
1074 remove_event (location->start(), Event::PunchIn);
1079 ControlChanged (PunchIn); /* EMIT SIGNAL */
1083 Session::set_punch_out (bool yn)
1085 if (punch_out == yn) {
1091 if ((location = _locations.auto_punch_location()) != 0) {
1092 if ((punch_out = yn) == true) {
1093 replace_event (Event::PunchOut, location->end());
1095 clear_events (Event::PunchOut);
1100 ControlChanged (PunchOut); /* EMIT SIGNAL */
1104 Session::set_auto_loop_location (Location* location)
1108 if ((existing = _locations.auto_loop_location()) != 0 && existing != location) {
1109 auto_loop_start_changed_connection.disconnect();
1110 auto_loop_end_changed_connection.disconnect();
1111 auto_loop_changed_connection.disconnect();
1112 existing->set_auto_loop (false, this);
1113 remove_event (existing->end(), Event::AutoLoop);
1114 auto_loop_location_changed (0);
1119 if (location == 0) {
1123 if (location->end() <= location->start()) {
1124 error << _("Session: you can't use a mark for auto loop") << endmsg;
1128 last_loopend = location->end();
1130 auto_loop_start_changed_connection.disconnect();
1131 auto_loop_end_changed_connection.disconnect();
1132 auto_loop_changed_connection.disconnect();
1134 auto_loop_start_changed_connection = location->start_changed.connect (mem_fun (this, &Session::auto_loop_changed));
1135 auto_loop_end_changed_connection = location->end_changed.connect (mem_fun (this, &Session::auto_loop_changed));
1136 auto_loop_changed_connection = location->changed.connect (mem_fun (this, &Session::auto_loop_changed));
1138 location->set_auto_loop (true, this);
1139 auto_loop_location_changed (location);
1143 Session::locations_added (Location* ignored)
1149 Session::locations_changed ()
1151 _locations.apply (*this, &Session::handle_locations_changed);
1155 Session::handle_locations_changed (Locations::LocationList& locations)
1157 Locations::LocationList::iterator i;
1159 bool set_loop = false;
1160 bool set_punch = false;
1162 for (i = locations.begin(); i != locations.end(); ++i) {
1166 if (location->is_auto_punch()) {
1167 set_auto_punch_location (location);
1170 if (location->is_auto_loop()) {
1171 set_auto_loop_location (location);
1178 set_auto_loop_location (0);
1181 set_auto_punch_location (0);
1188 Session::enable_record ()
1190 /* XXX really atomic compare+swap here */
1191 if (atomic_read (&_record_status) != Recording) {
1192 atomic_set (&_record_status, Recording);
1193 _last_record_location = _transport_frame;
1194 send_mmc_in_another_thread (MIDI::MachineControl::cmdRecordStrobe);
1200 Session::disable_record ()
1202 if (atomic_read (&_record_status) != Disabled) {
1203 atomic_set (&_record_status, Disabled);
1204 send_mmc_in_another_thread (MIDI::MachineControl::cmdRecordExit);
1206 remove_pending_capture_state ();
1211 Session::step_back_from_record ()
1213 atomic_set (&_record_status, Enabled);
1217 Session::maybe_enable_record ()
1219 atomic_set (&_record_status, Enabled);
1221 save_state ("", true);
1223 if (_transport_speed) {
1228 send_mmc_in_another_thread (MIDI::MachineControl::cmdRecordPause);
1229 RecordEnabled (); /* EMIT SIGNAL */
1236 Session::audible_frame () const
1239 jack_nframes_t offset;
1242 /* the first of these two possible settings for "offset"
1243 mean that the audible frame is stationary until
1244 audio emerges from the latency compensation
1247 the second means that the audible frame is stationary
1248 until audio would emerge from a physical port
1249 in the absence of any plugin latency compensation
1252 offset = _worst_output_latency;
1254 if (offset > current_block_size) {
1255 offset -= current_block_size;
1257 /* XXX is this correct? if we have no external
1258 physical connections and everything is internal
1259 then surely this is zero? still, how
1260 likely is that anyway?
1262 offset = current_block_size;
1265 if (synced_to_jack()) {
1266 tf = _engine.transport_frame();
1268 tf = _transport_frame;
1271 if (_transport_speed == 0) {
1281 if (!non_realtime_work_pending()) {
1285 /* take latency into account */
1294 Session::set_frame_rate (jack_nframes_t frames_per_second)
1296 /** \fn void Session::set_frame_size(jack_nframes_t)
1297 the AudioEngine object that calls this guarantees
1298 that it will not be called while we are also in
1299 ::process(). Its fine to do things that block
1303 _current_frame_rate = frames_per_second;
1304 _frames_per_smpte_frame = (double) _current_frame_rate / (double) smpte_frames_per_second;
1306 Route::set_automation_interval ((jack_nframes_t) ceil ((double) frames_per_second * 0.25));
1310 /* XXX need to reset/reinstantiate all LADSPA plugins */
1314 Session::set_block_size (jack_nframes_t nframes)
1316 /* the AudioEngine guarantees
1317 that it will not be called while we are also in
1318 ::process(). It is therefore fine to do things that block
1323 LockMonitor lm (route_lock, __LINE__, __FILE__);
1324 vector<Sample*>::iterator i;
1327 current_block_size = nframes;
1329 for (np = 0, i = _passthru_buffers.begin(); i != _passthru_buffers.end(); ++i, ++np) {
1333 for (vector<Sample*>::iterator i = _silent_buffers.begin(); i != _silent_buffers.end(); ++i) {
1337 _passthru_buffers.clear ();
1338 _silent_buffers.clear ();
1340 ensure_passthru_buffers (np);
1342 if (_gain_automation_buffer) {
1343 delete [] _gain_automation_buffer;
1345 _gain_automation_buffer = new gain_t[nframes];
1347 allocate_pan_automation_buffers (nframes, _npan_buffers, true);
1349 for (RouteList::iterator i = routes.begin(); i != routes.end(); ++i) {
1350 (*i)->set_block_size (nframes);
1353 for (DiskStreamList::iterator i = diskstreams.begin(); i != diskstreams.end(); ++i) {
1354 (*i)->set_block_size (nframes);
1357 set_worst_io_latencies (false);
1362 Session::set_default_fade (float steepness, float fade_msecs)
1365 jack_nframes_t fade_frames;
1367 /* Don't allow fade of less 1 frame */
1369 if (fade_msecs < (1000.0 * (1.0/_current_frame_rate))) {
1376 fade_frames = (jack_nframes_t) floor (fade_msecs * _current_frame_rate * 0.001);
1380 default_fade_msecs = fade_msecs;
1381 default_fade_steepness = steepness;
1384 LockMonitor lm (route_lock, __LINE__, __FILE__);
1385 AudioRegion::set_default_fade (steepness, fade_frames);
1390 /* XXX have to do this at some point */
1391 /* foreach region using default fade, reset, then
1392 refill_all_diskstream_buffers ();
1397 struct RouteSorter {
1398 bool operator() (Route* r1, Route* r2) {
1399 if (r1->fed_by.find (r2) != r1->fed_by.end()) {
1401 } else if (r2->fed_by.find (r1) != r2->fed_by.end()) {
1404 if (r1->fed_by.empty()) {
1405 if (r2->fed_by.empty()) {
1406 /* no ardour-based connections inbound to either route. just use signal order */
1407 return r1->order_key(N_("signal")) < r2->order_key(N_("signal"));
1409 /* r2 has connections, r1 does not; run r1 early */
1413 return r1->order_key(N_("signal")) < r2->order_key(N_("signal"));
1420 trace_terminal (Route* r1, Route* rbase)
1424 if ((r1->fed_by.find (rbase) != r1->fed_by.end()) && (rbase->fed_by.find (r1) != rbase->fed_by.end())) {
1425 info << string_compose(_("feedback loop setup between %1 and %2"), r1->name(), rbase->name()) << endmsg;
1429 /* make a copy of the existing list of routes that feed r1 */
1431 set<Route *> existing = r1->fed_by;
1433 /* for each route that feeds r1, recurse, marking it as feeding
1437 for (set<Route *>::iterator i = existing.begin(); i != existing.end(); ++i) {
1440 /* r2 is a route that feeds r1 which somehow feeds base. mark
1441 base as being fed by r2
1444 rbase->fed_by.insert (r2);
1448 /* 2nd level feedback loop detection. if r1 feeds or is fed by r2,
1452 if ((r1->fed_by.find (r2) != r1->fed_by.end()) && (r2->fed_by.find (r1) != r2->fed_by.end())) {
1456 /* now recurse, so that we can mark base as being fed by
1457 all routes that feed r2
1460 trace_terminal (r2, rbase);
1467 Session::resort_routes (void* src)
1469 /* don't do anything here with signals emitted
1470 by Routes while we are being destroyed.
1473 if (_state_of_the_state & Deletion) {
1477 /* Caller MUST hold the route_lock */
1479 RouteList::iterator i, j;
1481 for (i = routes.begin(); i != routes.end(); ++i) {
1483 (*i)->fed_by.clear ();
1485 for (j = routes.begin(); j != routes.end(); ++j) {
1487 /* although routes can feed themselves, it will
1488 cause an endless recursive descent if we
1489 detect it. so don't bother checking for
1497 if ((*j)->feeds (*i)) {
1498 (*i)->fed_by.insert (*j);
1503 for (i = routes.begin(); i != routes.end(); ++i) {
1504 trace_terminal (*i, *i);
1511 cerr << "finished route resort\n";
1513 for (i = routes.begin(); i != routes.end(); ++i) {
1514 cerr << " " << (*i)->name() << " signal order = " << (*i)->order_key ("signal") << endl;
1522 Session::new_audio_track (int input_channels, int output_channels)
1525 char track_name[32];
1527 uint32_t channels_used = 0;
1529 uint32_t nphysical_in;
1530 uint32_t nphysical_out;
1532 /* count existing audio tracks */
1535 LockMonitor lm (route_lock, __LINE__, __FILE__);
1536 for (RouteList::iterator i = routes.begin(); i != routes.end(); ++i) {
1537 if (dynamic_cast<AudioTrack*>(*i) != 0) {
1538 if (!(*i)->hidden()) {
1540 channels_used += (*i)->n_inputs();
1546 /* check for duplicate route names, since we might have pre-existing
1547 routes with this name (e.g. create Audio1, Audio2, delete Audio1,
1548 save, close,restart,add new route - first named route is now
1553 snprintf (track_name, sizeof(track_name), "Audio %" PRIu32, n+1);
1554 if (route_by_name (track_name) == 0) {
1559 } while (n < (UINT_MAX-1));
1561 if (input_auto_connect & AutoConnectPhysical) {
1562 nphysical_in = n_physical_inputs;
1567 if (output_auto_connect & AutoConnectPhysical) {
1568 nphysical_out = n_physical_outputs;
1574 track = new AudioTrack (*this, track_name);
1576 if (track->ensure_io (input_channels, output_channels, false, this)) {
1577 error << string_compose (_("cannot configure %1 in/%2 out configuration for new audio track"),
1578 input_channels, output_channels)
1583 for (uint32_t x = 0; x < track->n_inputs() && x < nphysical_in; ++x) {
1587 if (input_auto_connect & AutoConnectPhysical) {
1588 port = _engine.get_nth_physical_input ((channels_used+x)%nphysical_in);
1591 if (port.length() && track->connect_input (track->input (x), port, this)) {
1597 for (uint32_t x = 0; x < track->n_outputs(); ++x) {
1601 if (nphysical_out && (output_auto_connect & AutoConnectPhysical)) {
1602 port = _engine.get_nth_physical_output ((channels_used+x)%nphysical_out);
1603 } else if (output_auto_connect & AutoConnectMaster) {
1605 port = _master_out->input (x%_master_out->n_inputs())->name();
1609 if (port.length() && track->connect_output (track->output (x), port, this)) {
1615 vector<string> cports;
1616 uint32_t ni = _control_out->n_inputs();
1618 for (n = 0; n < ni; ++n) {
1619 cports.push_back (_control_out->input(n)->name());
1622 track->set_control_outs (cports);
1625 track->diskstream_changed.connect (mem_fun (this, &Session::resort_routes));
1630 catch (failed_constructor &err) {
1631 error << _("Session: could not create new audio track.") << endmsg;
1639 Session::new_audio_route (int input_channels, int output_channels)
1646 /* count existing audio busses */
1649 LockMonitor lm (route_lock, __LINE__, __FILE__);
1650 for (RouteList::iterator i = routes.begin(); i != routes.end(); ++i) {
1651 if (dynamic_cast<AudioTrack*>(*i) == 0) {
1652 if (!(*i)->hidden()) {
1660 snprintf (bus_name, sizeof(bus_name), "Bus %" PRIu32, n+1);
1661 if (route_by_name (bus_name) == 0) {
1666 } while (n < (UINT_MAX-1));
1669 bus = new Route (*this, bus_name, -1, -1, -1, -1);
1671 if (bus->ensure_io (input_channels, output_channels, false, this)) {
1672 error << string_compose (_("cannot configure %1 in/%2 out configuration for new audio track"),
1673 input_channels, output_channels)
1677 for (uint32_t x = 0; x < bus->n_inputs(); ++x) {
1681 if (input_auto_connect & AutoConnectPhysical) {
1682 port = _engine.get_nth_physical_input ((n+x)%n_physical_inputs);
1685 if (port.length() && bus->connect_input (bus->input (x), port, this)) {
1690 for (uint32_t x = 0; x < bus->n_outputs(); ++x) {
1694 if (output_auto_connect & AutoConnectPhysical) {
1695 port = _engine.get_nth_physical_input ((n+x)%n_physical_outputs);
1696 } else if (output_auto_connect & AutoConnectMaster) {
1698 port = _master_out->input (x%_master_out->n_inputs())->name();
1702 if (port.length() && bus->connect_output (bus->output (x), port, this)) {
1708 vector<string> cports;
1709 uint32_t ni = _control_out->n_inputs();
1711 for (uint32_t n = 0; n < ni; ++n) {
1712 cports.push_back (_control_out->input(n)->name());
1714 bus->set_control_outs (cports);
1720 catch (failed_constructor &err) {
1721 error << _("Session: could not create new route.") << endmsg;
1729 Session::add_route (Route* route)
1732 LockMonitor lm (route_lock, __LINE__, __FILE__);
1733 routes.push_front (route);
1737 route->solo_changed.connect (sigc::bind (mem_fun (*this, &Session::route_solo_changed), route));
1738 route->mute_changed.connect (mem_fun (*this, &Session::route_mute_changed));
1739 route->output_changed.connect (mem_fun (*this, &Session::set_worst_io_latencies_x));
1740 route->redirects_changed.connect (mem_fun (*this, &Session::update_latency_compensation_proxy));
1742 if (route->master()) {
1743 _master_out = route;
1746 if (route->control()) {
1747 _control_out = route;
1751 save_state (_current_snapshot_name);
1753 RouteAdded (route); /* EMIT SIGNAL */
1757 Session::add_diskstream (DiskStream* dstream)
1760 LockMonitor lm (diskstream_lock, __LINE__, __FILE__);
1761 diskstreams.push_back (dstream);
1764 /* take a reference to the diskstream, preventing it from
1765 ever being deleted until the session itself goes away,
1766 or chooses to remove it for its own purposes.
1770 dstream->set_block_size (current_block_size);
1772 dstream->PlaylistChanged.connect (sigc::bind (mem_fun (*this, &Session::diskstream_playlist_changed), dstream));
1773 /* this will connect to future changes, and check the current length */
1774 diskstream_playlist_changed (dstream);
1776 dstream->prepare ();
1779 save_state (_current_snapshot_name);
1781 DiskStreamAdded (dstream); /* EMIT SIGNAL */
1785 Session::remove_route (Route& route)
1788 LockMonitor lm (route_lock, __LINE__, __FILE__);
1789 routes.remove (&route);
1791 /* deleting the master out seems like a dumb
1792 idea, but its more of a UI policy issue
1796 if (&route == _master_out) {
1800 if (&route == _control_out) {
1803 /* cancel control outs for all routes */
1805 vector<string> empty;
1807 for (RouteList::iterator r = routes.begin(); r != routes.end(); ++r) {
1808 (*r)->set_control_outs (empty);
1812 update_route_solo_state ();
1816 LockMonitor lm (diskstream_lock, __LINE__, __FILE__);
1820 if ((at = dynamic_cast<AudioTrack*>(&route)) != 0) {
1821 diskstreams.remove (&at->disk_stream());
1822 at->disk_stream().unref ();
1825 find_current_end ();
1828 update_latency_compensation (false, false);
1831 /* XXX should we disconnect from the Route's signals ? */
1833 save_state (_current_snapshot_name);
1839 Session::route_mute_changed (void* src)
1845 Session::route_solo_changed (void* src, Route* route)
1847 if (solo_update_disabled) {
1852 LockMonitor lm (route_lock, __LINE__, __FILE__);
1855 is_track = (dynamic_cast<AudioTrack*>(route) != 0);
1857 for (RouteList::iterator i = routes.begin(); i != routes.end(); ++i) {
1859 /* soloing a track mutes all other tracks, soloing a bus mutes all other busses */
1863 /* don't mess with busses */
1865 if (dynamic_cast<AudioTrack*>(*i) == 0) {
1871 /* don't mess with tracks */
1873 if (dynamic_cast<AudioTrack*>(*i) != 0) {
1878 if ((*i) != route &&
1879 ((*i)->mix_group () == 0 ||
1880 (*i)->mix_group () != route->mix_group () ||
1881 !route->mix_group ()->is_active())) {
1883 if ((*i)->soloed()) {
1885 /* if its already soloed, and solo latching is enabled,
1886 then leave it as it is.
1889 if (_solo_latched) {
1896 solo_update_disabled = true;
1897 (*i)->set_solo (false, src);
1898 solo_update_disabled = false;
1902 bool something_soloed = false;
1903 bool same_thing_soloed = false;
1904 bool signal = false;
1906 for (RouteList::iterator i = routes.begin(); i != routes.end(); ++i) {
1907 if ((*i)->soloed()) {
1908 something_soloed = true;
1909 if (dynamic_cast<AudioTrack*>(*i)) {
1911 same_thing_soloed = true;
1916 same_thing_soloed = true;
1924 if (something_soloed != currently_soloing) {
1926 currently_soloing = something_soloed;
1929 modify_solo_mute (is_track, same_thing_soloed);
1932 SoloActive (currently_soloing);
1939 Session::set_solo_latched (bool yn)
1946 Session::update_route_solo_state ()
1949 bool is_track = false;
1950 bool signal = false;
1952 /* caller must hold RouteLock */
1954 /* this is where we actually implement solo by changing
1955 the solo mute setting of each track.
1958 for (RouteList::iterator i = routes.begin(); i != routes.end(); ++i) {
1959 if ((*i)->soloed()) {
1961 if (dynamic_cast<AudioTrack*>(*i)) {
1968 if (mute != currently_soloing) {
1970 currently_soloing = mute;
1973 if (!is_track && !mute) {
1975 /* nothing is soloed */
1977 for (RouteList::iterator i = routes.begin(); i != routes.end(); ++i) {
1978 (*i)->set_solo_mute (false);
1988 modify_solo_mute (is_track, mute);
1991 SoloActive (currently_soloing);
1996 Session::modify_solo_mute (bool is_track, bool mute)
1998 for (RouteList::iterator i = routes.begin(); i != routes.end(); ++i) {
2002 /* only alter track solo mute */
2004 if (dynamic_cast<AudioTrack*>(*i)) {
2005 if ((*i)->soloed()) {
2006 (*i)->set_solo_mute (!mute);
2008 (*i)->set_solo_mute (mute);
2014 /* only alter bus solo mute */
2016 if (!dynamic_cast<AudioTrack*>(*i)) {
2018 if ((*i)->soloed()) {
2020 (*i)->set_solo_mute (false);
2024 /* don't mute master or control outs
2025 in response to another bus solo
2028 if ((*i) != _master_out &&
2029 (*i) != _control_out) {
2030 (*i)->set_solo_mute (mute);
2041 Session::catch_up_on_solo ()
2043 /* this is called after set_state() to catch the full solo
2044 state, which can't be correctly determined on a per-route
2045 basis, but needs the global overview that only the session
2048 LockMonitor lm (route_lock, __LINE__, __FILE__);
2049 update_route_solo_state();
2053 Session::route_by_name (string name)
2055 LockMonitor lm (route_lock, __LINE__, __FILE__);
2057 for (RouteList::iterator i = routes.begin(); i != routes.end(); ++i) {
2058 if ((*i)->name() == name) {
2067 Session::find_current_end ()
2069 jack_nframes_t max = 0;
2072 if (_state_of_the_state & Loading) {
2076 /* Don't take the diskstream lock. Caller must have other ways to
2080 for (DiskStreamList::iterator i = diskstreams.begin(); i != diskstreams.end(); ++i) {
2081 Playlist* pl = (*i)->playlist();
2082 if ((me = pl->get_maximum_extent()) > max) {
2087 if (max > end_location->end()) {
2088 end_location->set_end (max);
2090 DurationChanged(); /* EMIT SIGNAL */
2095 Session::diskstream_by_name (string name)
2097 LockMonitor lm (diskstream_lock, __LINE__, __FILE__);
2099 for (DiskStreamList::iterator i = diskstreams.begin(); i != diskstreams.end(); ++i) {
2100 if ((*i)->name() == name) {
2109 Session::diskstream_by_id (id_t id)
2111 LockMonitor lm (diskstream_lock, __LINE__, __FILE__);
2113 for (DiskStreamList::iterator i = diskstreams.begin(); i != diskstreams.end(); ++i) {
2114 if ((*i)->id() == id) {
2122 /* AudioRegion management */
2125 Session::new_region_name (string old)
2127 string::size_type last_period;
2129 string::size_type len = old.length() + 64;
2132 if ((last_period = old.find_last_of ('.')) == string::npos) {
2134 /* no period present - add one explicitly */
2137 last_period = old.length() - 1;
2142 number = atoi (old.substr (last_period+1).c_str());
2146 while (number < (UINT_MAX-1)) {
2148 AudioRegionList::const_iterator i;
2153 snprintf (buf, len, "%s%" PRIu32, old.substr (0, last_period + 1).c_str(), number);
2156 for (i = audio_regions.begin(); i != audio_regions.end(); ++i) {
2157 if ((*i).second->name() == sbuf) {
2162 if (i == audio_regions.end()) {
2167 if (number != (UINT_MAX-1)) {
2171 error << string_compose (_("cannot create new name for region \"%1\""), old) << endmsg;
2176 Session::region_name (string& result, string base, bool newlevel) const
2183 LockMonitor lm (region_lock, __LINE__, __FILE__);
2185 snprintf (buf, sizeof (buf), "%d", (int)audio_regions.size() + 1);
2193 /* XXX this is going to be slow. optimize me later */
2198 string::size_type pos;
2200 if ((pos = base.find_last_of ('-')) == string::npos) {
2201 pos = base.find_last_of ('.');
2204 /* pos may be npos, but then we just use entire base */
2206 subbase = base.substr (0, pos);
2209 bool name_taken = true;
2212 LockMonitor lm (region_lock, __LINE__, __FILE__);
2214 for (int n = 1; n < 5000; ++n) {
2217 snprintf (buf, sizeof (buf), ".%d", n);
2222 for (AudioRegionList::const_iterator i = audio_regions.begin(); i != audio_regions.end(); ++i) {
2223 if ((*i).second->name() == result) {
2236 fatal << string_compose(_("too many regions with names like %1"), base) << endmsg;
2245 Session::add_region (Region* region)
2247 AudioRegion* ar = 0;
2248 AudioRegion* oar = 0;
2252 LockMonitor lm (region_lock, __LINE__, __FILE__);
2254 if ((ar = dynamic_cast<AudioRegion*> (region)) != 0) {
2256 AudioRegionList::iterator x;
2258 for (x = audio_regions.begin(); x != audio_regions.end(); ++x) {
2260 oar = dynamic_cast<AudioRegion*> (x->second);
2262 if (ar->region_list_equivalent (*oar)) {
2267 if (x == audio_regions.end()) {
2269 pair<AudioRegionList::key_type, AudioRegionList::mapped_type> entry;
2271 entry.first = region->id();
2274 pair<AudioRegionList::iterator,bool> x = audio_regions.insert (entry);
2285 fatal << _("programming error: ")
2286 << X_("unknown region type passed to Session::add_region()")
2293 /* mark dirty because something has changed even if we didn't
2294 add the region to the region list.
2300 region->GoingAway.connect (mem_fun (*this, &Session::remove_region));
2301 region->StateChanged.connect (sigc::bind (mem_fun (*this, &Session::region_changed), region));
2302 AudioRegionAdded (ar); /* EMIT SIGNAL */
2307 Session::region_changed (Change what_changed, Region* region)
2309 if (what_changed & Region::HiddenChanged) {
2310 /* relay hidden changes */
2311 RegionHiddenChange (region);
2316 Session::region_renamed (Region* region)
2318 add_region (region);
2322 Session::remove_region (Region* region)
2324 AudioRegionList::iterator i;
2325 AudioRegion* ar = 0;
2326 bool removed = false;
2329 LockMonitor lm (region_lock, __LINE__, __FILE__);
2331 if ((ar = dynamic_cast<AudioRegion*> (region)) != 0) {
2332 if ((i = audio_regions.find (region->id())) != audio_regions.end()) {
2333 audio_regions.erase (i);
2337 fatal << _("programming error: ")
2338 << X_("unknown region type passed to Session::remove_region()")
2344 /* mark dirty because something has changed even if we didn't
2345 remove the region from the region list.
2351 AudioRegionRemoved(ar); /* EMIT SIGNAL */
2356 Session::find_whole_file_parent (AudioRegion& child)
2358 AudioRegionList::iterator i;
2359 AudioRegion* region;
2360 LockMonitor lm (region_lock, __LINE__, __FILE__);
2362 for (i = audio_regions.begin(); i != audio_regions.end(); ++i) {
2364 region = (*i).second;
2366 if (region->whole_file()) {
2368 if (child.source_equivalent (*region)) {
2378 Session::find_equivalent_playlist_regions (AudioRegion& region, vector<AudioRegion*>& result)
2380 for (PlaylistList::iterator i = playlists.begin(); i != playlists.end(); ++i) {
2384 if ((pl = dynamic_cast<AudioPlaylist*>(*i)) == 0) {
2388 pl->get_region_list_equivalent_regions (region, result);
2393 Session::destroy_region (Region* region)
2395 AudioRegion* aregion;
2397 if ((aregion = dynamic_cast<AudioRegion*> (region)) == 0) {
2401 if (aregion->playlist()) {
2402 aregion->playlist()->destroy_region (region);
2405 vector<Source*> srcs;
2407 for (uint32_t n = 0; n < aregion->n_channels(); ++n) {
2408 srcs.push_back (&aregion->source (n));
2411 for (vector<Source*>::iterator i = srcs.begin(); i != srcs.end(); ++i) {
2413 if ((*i)->use_cnt() == 0) {
2414 (*i)->mark_for_remove ();
2423 Session::destroy_regions (list<Region*> regions)
2425 for (list<Region*>::iterator i = regions.begin(); i != regions.end(); ++i) {
2426 destroy_region (*i);
2432 Session::remove_last_capture ()
2436 for (DiskStreamList::iterator i = diskstreams.begin(); i != diskstreams.end(); ++i) {
2437 list<Region*>& l = (*i)->last_capture_regions();
2440 r.insert (r.end(), l.begin(), l.end());
2445 destroy_regions (r);
2450 Session::remove_region_from_region_list (Region& r)
2456 /* Source Management */
2459 Session::add_source (Source* source)
2461 pair<SourceList::key_type, SourceList::mapped_type> entry;
2464 LockMonitor lm (source_lock, __LINE__, __FILE__);
2465 entry.first = source->id();
2466 entry.second = source;
2467 sources.insert (entry);
2470 source->GoingAway.connect (mem_fun (this, &Session::remove_source));
2473 SourceAdded (source); /* EMIT SIGNAL */
2477 Session::remove_source (Source* source)
2479 SourceList::iterator i;
2482 LockMonitor lm (source_lock, __LINE__, __FILE__);
2484 if ((i = sources.find (source->id())) != sources.end()) {
2489 if (!_state_of_the_state & InCleanup) {
2491 /* save state so we don't end up with a session file
2492 referring to non-existent sources.
2495 save_state (_current_snapshot_name);
2498 SourceRemoved(source); /* EMIT SIGNAL */
2502 Session::get_source (ARDOUR::id_t id)
2504 LockMonitor lm (source_lock, __LINE__, __FILE__);
2505 SourceList::iterator i;
2508 if ((i = sources.find (id)) != sources.end()) {
2509 source = (*i).second;
2516 Session::create_file_source (DiskStream& ds, int32_t chan)
2520 char buf[PATH_MAX+1];
2521 const uint32_t limit = 10000;
2525 legalized = legalize_for_path (ds.name());
2527 /* find a "version" of the file name that doesn't exist in
2528 any of the possible directories.
2531 for (cnt = 1; cnt <= limit; ++cnt) {
2533 vector<space_and_path>::iterator i;
2534 uint32_t existing = 0;
2536 for (i = session_dirs.begin(); i != session_dirs.end(); ++i) {
2539 spath += sound_dir_name;
2543 if (ds.n_channels() < 2) {
2544 snprintf (buf, sizeof(buf), "%s-%u.wav", spath.c_str(), cnt);
2545 } else if (ds.n_channels() == 2) {
2547 snprintf (buf, sizeof(buf), "%s-%u%%L.wav", spath.c_str(), cnt);
2549 snprintf (buf, sizeof(buf), "%s-%u%%R.wav", spath.c_str(), cnt);
2551 } else if (ds.n_channels() < 26) {
2552 snprintf (buf, sizeof(buf), "%s-%u%%%c.wav", spath.c_str(), cnt, 'a' + chan);
2554 snprintf (buf, sizeof(buf), "%s-%u.wav", spath.c_str(), cnt);
2557 if (access (buf, F_OK) == 0) {
2562 if (existing == 0) {
2568 error << string_compose(_("There are already %1 recordings for %2, which I consider too many."), limit, ds.name()) << endmsg;
2569 throw failed_constructor();
2572 /* we now have a unique name for the file, but figure out where to
2578 spath = discover_best_sound_dir ();
2580 string::size_type pos = foo.find_last_of ('/');
2582 if (pos == string::npos) {
2585 spath += foo.substr (pos + 1);
2588 /* this might throw failed_constructor(), which is OK */
2590 return new FileSource (spath, frame_rate());
2593 /* Playlist management */
2596 Session::get_playlist (string name)
2600 if ((ret = playlist_by_name (name)) == 0) {
2601 ret = new AudioPlaylist (*this, name);
2608 Session::playlist_by_name (string name)
2610 LockMonitor lm (playlist_lock, __LINE__, __FILE__);
2611 for (PlaylistList::iterator i = playlists.begin(); i != playlists.end(); ++i) {
2612 if ((*i)->name() == name) {
2616 for (PlaylistList::iterator i = unused_playlists.begin(); i != unused_playlists.end(); ++i) {
2617 if ((*i)->name() == name) {
2625 Session::add_playlist (Playlist* playlist)
2627 if (playlist->hidden()) {
2632 LockMonitor lm (playlist_lock, __LINE__, __FILE__);
2633 if (find (playlists.begin(), playlists.end(), playlist) == playlists.end()) {
2634 playlists.insert (playlists.begin(), playlist);
2636 playlist->InUse.connect (mem_fun (*this, &Session::track_playlist));
2637 playlist->GoingAway.connect (mem_fun (*this, &Session::remove_playlist));
2643 PlaylistAdded (playlist); /* EMIT SIGNAL */
2647 Session::track_playlist (Playlist* pl, bool inuse)
2649 PlaylistList::iterator x;
2652 LockMonitor lm (playlist_lock, __LINE__, __FILE__);
2655 //cerr << "shifting playlist to unused: " << pl->name() << endl;
2657 unused_playlists.insert (pl);
2659 if ((x = playlists.find (pl)) != playlists.end()) {
2660 playlists.erase (x);
2665 //cerr << "shifting playlist to used: " << pl->name() << endl;
2667 playlists.insert (pl);
2669 if ((x = unused_playlists.find (pl)) != unused_playlists.end()) {
2670 unused_playlists.erase (x);
2677 Session::remove_playlist (Playlist* playlist)
2679 if (_state_of_the_state & Deletion) {
2684 LockMonitor lm (playlist_lock, __LINE__, __FILE__);
2685 // cerr << "removing playlist: " << playlist->name() << endl;
2687 PlaylistList::iterator i;
2689 i = find (playlists.begin(), playlists.end(), playlist);
2691 if (i != playlists.end()) {
2692 playlists.erase (i);
2695 i = find (unused_playlists.begin(), unused_playlists.end(), playlist);
2696 if (i != unused_playlists.end()) {
2697 unused_playlists.erase (i);
2704 PlaylistRemoved (playlist); /* EMIT SIGNAL */
2708 Session::set_audition (AudioRegion* r)
2710 pending_audition_region = r;
2711 post_transport_work = PostTransportWork (post_transport_work | PostTransportAudition);
2712 schedule_butler_transport_work ();
2716 Session::non_realtime_set_audition ()
2718 if (pending_audition_region == (AudioRegion*) 0xfeedface) {
2719 auditioner->audition_current_playlist ();
2720 } else if (pending_audition_region) {
2721 auditioner->audition_region (*pending_audition_region);
2723 pending_audition_region = 0;
2724 AuditionActive (true); /* EMIT SIGNAL */
2728 Session::audition_playlist ()
2730 Event* ev = new Event (Event::Audition, Event::Add, Event::Immediate, 0, 0.0);
2731 ev->set_ptr ((void*) 0xfeedface);
2736 Session::audition_region (AudioRegion& r)
2738 Event* ev = new Event (Event::Audition, Event::Add, Event::Immediate, 0, 0.0);
2744 Session::cancel_audition ()
2746 if (auditioner->active()) {
2747 auditioner->cancel_audition ();
2748 AuditionActive (false); /* EMIT SIGNAL */
2753 Session::RoutePublicOrderSorter::operator() (Route* a, Route* b)
2755 return a->order_key(N_("signal")) < b->order_key(N_("signal"));
2759 Session::remove_empty_sounds ()
2762 PathScanner scanner;
2767 vector<string *>* possible_audiofiles = scanner (dir, "\\.wav$", false, true);
2769 for (vector<string *>::iterator i = possible_audiofiles->begin(); i != possible_audiofiles->end(); ++i) {
2771 if (FileSource::is_empty (*(*i))) {
2773 unlink ((*i)->c_str());
2775 string peak_path = peak_path_from_audio_path (**i);
2776 unlink (peak_path.c_str());
2782 delete possible_audiofiles;
2786 Session::is_auditioning () const
2788 /* can be called before we have an auditioner object */
2790 return auditioner->active();
2798 Session::peak_path_from_audio_path (string audio_path)
2800 /* XXX hardly bombproof! fix me */
2804 res = PBD::dirname (audio_path);
2805 res = PBD::dirname (res);
2807 res += peak_dir_name;
2809 res += PBD::basename_nosuffix (audio_path);
2816 Session::old_peak_path_from_audio_path (string audio_path)
2818 /* This is a hangover from when audio and peak files
2819 lived in the same directory. We need it to to
2820 be able to open old sessions.
2823 /* XXX hardly bombproof! fix me */
2825 string res = audio_path.substr (0, audio_path.find_last_of ('.'));
2831 Session::set_all_solo (bool yn)
2833 /* XXX this copy is not safe: the Routes within the list
2834 can still be deleted after the Route lock is released.
2839 LockMonitor lm (route_lock, __LINE__, __FILE__);
2843 for (RouteList::iterator i = copy.begin(); i != copy.end(); ++i) {
2844 if (!(*i)->hidden()) {
2845 (*i)->set_solo (yn, this);
2853 Session::set_all_mute (bool yn)
2857 LockMonitor lm (route_lock, __LINE__, __FILE__);
2861 for (RouteList::iterator i = copy.begin(); i != copy.end(); ++i) {
2862 if (!(*i)->hidden()) {
2863 (*i)->set_mute (yn, this);
2871 Session::n_diskstreams () const
2873 LockMonitor lm (diskstream_lock, __LINE__, __FILE__);
2876 for (DiskStreamList::const_iterator i = diskstreams.begin(); i != diskstreams.end(); ++i) {
2877 if (!(*i)->hidden()) {
2885 Session::foreach_diskstream (void (DiskStream::*func)(void))
2887 LockMonitor lm (diskstream_lock, __LINE__, __FILE__);
2888 for (DiskStreamList::iterator i = diskstreams.begin(); i != diskstreams.end(); ++i) {
2889 if (!(*i)->hidden()) {
2896 Session::graph_reordered ()
2898 /* don't do this stuff if we are setting up connections
2899 from a set_state() call.
2902 if (_state_of_the_state & InitialConnecting) {
2906 LockMonitor lm1 (route_lock, __LINE__, __FILE__);
2907 LockMonitor lm2 (diskstream_lock, __LINE__, __FILE__);
2911 /* force all diskstreams to update their capture offset values to
2912 reflect any changes in latencies within the graph.
2915 for (DiskStreamList::iterator i = diskstreams.begin(); i != diskstreams.end(); ++i) {
2916 (*i)->set_capture_offset ();
2921 Session::record_disenable_all ()
2923 record_enable_change_all (false);
2927 Session::record_enable_all ()
2929 record_enable_change_all (true);
2933 Session::record_enable_change_all (bool yn)
2935 LockMonitor lm1 (route_lock, __LINE__, __FILE__);
2937 for (RouteList::iterator i = routes.begin(); i != routes.end(); ++i) {
2940 if ((at = dynamic_cast<AudioTrack*>(*i)) != 0) {
2941 at->set_record_enable (yn, this);
2945 /* since we don't keep rec-enable state, don't mark session dirty */
2949 Session::add_redirect (Redirect* redirect)
2953 PortInsert* port_insert;
2954 PluginInsert* plugin_insert;
2956 if ((insert = dynamic_cast<Insert *> (redirect)) != 0) {
2957 if ((port_insert = dynamic_cast<PortInsert *> (insert)) != 0) {
2958 _port_inserts.insert (_port_inserts.begin(), port_insert);
2959 } else if ((plugin_insert = dynamic_cast<PluginInsert *> (insert)) != 0) {
2960 _plugin_inserts.insert (_plugin_inserts.begin(), plugin_insert);
2962 fatal << _("programming error: unknown type of Insert created!") << endmsg;
2965 } else if ((send = dynamic_cast<Send *> (redirect)) != 0) {
2966 _sends.insert (_sends.begin(), send);
2968 fatal << _("programming error: unknown type of Redirect created!") << endmsg;
2972 redirect->GoingAway.connect (mem_fun (*this, &Session::remove_redirect));
2978 Session::remove_redirect (Redirect* redirect)
2982 PortInsert* port_insert;
2983 PluginInsert* plugin_insert;
2985 if ((insert = dynamic_cast<Insert *> (redirect)) != 0) {
2986 if ((port_insert = dynamic_cast<PortInsert *> (insert)) != 0) {
2987 _port_inserts.remove (port_insert);
2988 } else if ((plugin_insert = dynamic_cast<PluginInsert *> (insert)) != 0) {
2989 _plugin_inserts.remove (plugin_insert);
2991 fatal << _("programming error: unknown type of Insert deleted!") << endmsg;
2994 } else if ((send = dynamic_cast<Send *> (redirect)) != 0) {
2995 _sends.remove (send);
2997 fatal << _("programming error: unknown type of Redirect deleted!") << endmsg;
3005 Session::available_capture_duration ()
3007 const double scale = 4096.0 / sizeof (Sample);
3009 if (_total_free_4k_blocks * scale > (double) max_frames) {
3013 return (jack_nframes_t) floor (_total_free_4k_blocks * scale);
3017 Session::add_connection (ARDOUR::Connection* connection)
3020 LockMonitor (connection_lock, __LINE__, __FILE__);
3021 _connections.push_back (connection);
3024 ConnectionAdded (connection); /* EMIT SIGNAL */
3030 Session::remove_connection (ARDOUR::Connection* connection)
3032 bool removed = false;
3035 LockMonitor (connection_lock, __LINE__, __FILE__);
3036 ConnectionList::iterator i = find (_connections.begin(), _connections.end(), connection);
3038 if (i != _connections.end()) {
3039 _connections.erase (i);
3045 ConnectionRemoved (connection); /* EMIT SIGNAL */
3051 ARDOUR::Connection *
3052 Session::connection_by_name (string name) const
3054 LockMonitor lm (connection_lock, __LINE__, __FILE__);
3056 for (ConnectionList::const_iterator i = _connections.begin(); i != _connections.end(); ++i) {
3057 if ((*i)->name() == name) {
3066 Session::set_edit_mode (EditMode mode)
3071 LockMonitor lm (playlist_lock, __LINE__, __FILE__);
3073 for (PlaylistList::iterator i = playlists.begin(); i != playlists.end(); ++i) {
3074 (*i)->set_edit_mode (mode);
3079 ControlChanged (EditingMode); /* EMIT SIGNAL */
3083 Session::tempo_map_changed (Change ignored)
3090 Session::ensure_passthru_buffers (uint32_t howmany)
3092 while (howmany > _passthru_buffers.size()) {
3094 #ifdef NO_POSIX_MEMALIGN
3095 p = (Sample *) malloc(current_block_size * sizeof(Sample));
3097 posix_memalign((void **)&p,16,current_block_size * 4);
3099 _passthru_buffers.push_back (p);
3103 #ifdef NO_POSIX_MEMALIGN
3104 p = (Sample *) malloc(current_block_size * sizeof(Sample));
3106 posix_memalign((void **)&p,16,current_block_size * 4);
3108 memset (p, 0, sizeof (Sample) * current_block_size);
3109 _silent_buffers.push_back (p);
3112 allocate_pan_automation_buffers (current_block_size, howmany, false);
3116 Session::next_send_name ()
3119 snprintf (buf, sizeof (buf), "send %" PRIu32, ++send_cnt);
3124 Session::next_insert_name ()
3127 snprintf (buf, sizeof (buf), "insert %" PRIu32, ++insert_cnt);
3131 /* Named Selection management */
3134 Session::named_selection_by_name (string name)
3136 LockMonitor lm (named_selection_lock, __LINE__, __FILE__);
3137 for (NamedSelectionList::iterator i = named_selections.begin(); i != named_selections.end(); ++i) {
3138 if ((*i)->name == name) {
3146 Session::add_named_selection (NamedSelection* named_selection)
3149 LockMonitor lm (named_selection_lock, __LINE__, __FILE__);
3150 named_selections.insert (named_selections.begin(), named_selection);
3155 NamedSelectionAdded (); /* EMIT SIGNAL */
3159 Session::remove_named_selection (NamedSelection* named_selection)
3161 bool removed = false;
3164 LockMonitor lm (named_selection_lock, __LINE__, __FILE__);
3166 NamedSelectionList::iterator i = find (named_selections.begin(), named_selections.end(), named_selection);
3168 if (i != named_selections.end()) {
3170 named_selections.erase (i);
3177 NamedSelectionRemoved (); /* EMIT SIGNAL */
3182 Session::reset_native_file_format ()
3184 LockMonitor lm1 (route_lock, __LINE__, __FILE__);
3185 LockMonitor lm2 (diskstream_lock, __LINE__, __FILE__);
3187 for (DiskStreamList::iterator i = diskstreams.begin(); i != diskstreams.end(); ++i) {
3188 (*i)->reset_write_sources (false);
3193 Session::route_name_unique (string n) const
3195 LockMonitor lm (route_lock, __LINE__, __FILE__);
3197 for (RouteList::const_iterator i = routes.begin(); i != routes.end(); ++i) {
3198 if ((*i)->name() == n) {
3207 Session::remove_file_source (FileSource& fs)
3209 return fs.move_to_trash (dead_sound_dir_name);
3213 Session::n_playlists () const
3215 LockMonitor lm (playlist_lock, __LINE__, __FILE__);
3216 return playlists.size();
3220 Session::set_align_style (AlignStyle style)
3222 align_style = style;
3224 foreach_diskstream (&DiskStream::set_capture_offset);
3227 ControlChanged (AlignChoice);
3231 Session::set_solo_model (SoloModel sm)
3238 Session::allocate_pan_automation_buffers (jack_nframes_t nframes, uint32_t howmany, bool force)
3240 if (!force && howmany <= _npan_buffers) {
3244 if (_pan_automation_buffer) {
3246 for (uint32_t i = 0; i < _npan_buffers; ++i) {
3247 delete [] _pan_automation_buffer[i];
3250 delete [] _pan_automation_buffer;
3253 _pan_automation_buffer = new pan_t*[howmany];
3255 for (uint32_t i = 0; i < howmany; ++i) {
3256 _pan_automation_buffer[i] = new pan_t[nframes];
3259 _npan_buffers = howmany;
3263 Session::add_instant_xml (XMLNode& node, const std::string& dir)
3265 Stateful::add_instant_xml (node, dir);
3266 Config->add_instant_xml (node, Config->get_user_ardour_path());
3270 Session::freeze (InterThreadInfo& itt)
3272 LockMonitor lm (route_lock, __LINE__, __FILE__);
3274 for (RouteList::iterator i = routes.begin(); i != routes.end(); ++i) {
3278 if ((at = dynamic_cast<AudioTrack*>(*i)) != 0) {
3279 /* XXX this is wrong because itt.progress will keep returning to zero at the start
3290 Session::write_one_track (AudioTrack& track, jack_nframes_t start, jack_nframes_t len, bool overwrite, vector<Source*>& srcs,
3291 InterThreadInfo& itt)
3295 FileSource* fsource;
3297 char buf[PATH_MAX+1];
3300 jack_nframes_t position;
3301 jack_nframes_t this_chunk;
3302 jack_nframes_t to_do;
3303 vector<Sample*> buffers;
3304 const jack_nframes_t chunk_size = (256 * 1024)/4;
3306 atomic_set (&processing_prohibited, 1);
3308 /* call tree *MUST* hold route_lock */
3310 if ((playlist = track.disk_stream().playlist()) == 0) {
3314 /* external redirects will be a problem */
3316 if (track.has_external_redirects()) {
3320 nchans = track.disk_stream().n_channels();
3322 dir = discover_best_sound_dir ();
3324 for (uint32_t chan_n=0; chan_n < nchans; ++chan_n) {
3326 for (x = 0; x < 99999; ++x) {
3327 snprintf (buf, sizeof(buf), "%s/%s-%d-bounce-%" PRIu32 ".wav", dir.c_str(), playlist->name().c_str(), chan_n, x+1);
3328 if (access (buf, F_OK) != 0) {
3334 error << string_compose (_("too many bounced versions of playlist \"%1\""), playlist->name()) << endmsg;
3339 fsource = new FileSource (buf, frame_rate());
3342 catch (failed_constructor& err) {
3343 error << string_compose (_("cannot create new audio file \"%1\" for %2"), buf, track.name()) << endmsg;
3347 srcs.push_back(fsource);
3350 /* XXX need to flush all redirects */
3355 /* create a set of reasonably-sized buffers */
3357 for (vector<Sample*>::iterator i = _passthru_buffers.begin(); i != _passthru_buffers.end(); ++i) {
3359 #ifdef NO_POSIX_MEMALIGN
3360 b = (Sample *) malloc(chunk_size * sizeof(Sample));
3362 posix_memalign((void **)&b,16,chunk_size * 4);
3364 buffers.push_back (b);
3367 while (to_do && !itt.cancel) {
3369 this_chunk = min (to_do, chunk_size);
3371 if (track.export_stuff (buffers, nchans, start, this_chunk)) {
3376 for (vector<Source*>::iterator src=srcs.begin(); src != srcs.end(); ++src, ++n) {
3377 if ((*src)->write (buffers[n], this_chunk) != this_chunk) {
3382 start += this_chunk;
3383 to_do -= this_chunk;
3385 itt.progress = (float) (1.0 - ((double) to_do / len));
3394 xnow = localtime (&now);
3396 for (vector<Source*>::iterator src=srcs.begin(); src != srcs.end(); ++src) {
3397 dynamic_cast<FileSource*>((*src))->update_header (position, *xnow, now);
3400 /* build peakfile for new source */
3402 for (vector<Source*>::iterator src=srcs.begin(); src != srcs.end(); ++src) {
3403 dynamic_cast<FileSource*>(*src)->build_peaks ();
3411 for (vector<Source*>::iterator src=srcs.begin(); src != srcs.end(); ++src) {
3412 dynamic_cast<FileSource*>(*src)->mark_for_remove ();
3417 for (vector<Sample*>::iterator i = buffers.begin(); i != buffers.end(); ++i) {
3421 atomic_set (&processing_prohibited, 0);
3429 Session::get_silent_buffers (uint32_t howmany)
3431 for (uint32_t i = 0; i < howmany; ++i) {
3432 memset (_silent_buffers[i], 0, sizeof (Sample) * current_block_size);
3434 return _silent_buffers;
3438 Session::ntracks () const
3441 LockMonitor lm (route_lock, __LINE__, __FILE__);
3443 for (RouteList::const_iterator i = routes.begin(); i != routes.end(); ++i) {
3444 if (dynamic_cast<AudioTrack*> (*i)) {
3453 Session::nbusses () const
3456 LockMonitor lm (route_lock, __LINE__, __FILE__);
3458 for (RouteList::const_iterator i = routes.begin(); i != routes.end(); ++i) {
3459 if (dynamic_cast<AudioTrack*> (*i) == 0) {
3468 Session::set_layer_model (LayerModel lm)
3471 LayerModelChanged (); /* EMIT SIGNAL */
3476 Session::set_xfade_model (CrossfadeModel xm)