2 Copyright (C) 1999-2004 Paul Davis
4 This program is free software; you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation; either version 2 of the License, or
7 (at your option) any later version.
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
14 You should have received a copy of the GNU General Public License
15 along with this program; if not, write to the Free Software
16 Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
25 #include <cstdio> /* sprintf(3) ... grrr */
31 #include <sigc++/bind.h>
32 #include <sigc++/retype.h>
34 #include <glibmm/thread.h>
35 #include <glibmm/miscutils.h>
36 #include <glibmm/fileutils.h>
38 #include <pbd/error.h>
39 #include <glibmm/thread.h>
40 #include <pbd/pathscanner.h>
41 #include <pbd/stl_delete.h>
42 #include <pbd/basename.h>
43 #include <pbd/stacktrace.h>
44 #include <pbd/file_utils.h>
46 #include <ardour/audioengine.h>
47 #include <ardour/configuration.h>
48 #include <ardour/session.h>
49 #include <ardour/session_directory.h>
50 #include <ardour/utils.h>
51 #include <ardour/audio_diskstream.h>
52 #include <ardour/audioplaylist.h>
53 #include <ardour/audioregion.h>
54 #include <ardour/audiofilesource.h>
55 #include <ardour/midi_diskstream.h>
56 #include <ardour/midi_playlist.h>
57 #include <ardour/midi_region.h>
58 #include <ardour/smf_source.h>
59 #include <ardour/auditioner.h>
60 #include <ardour/recent_sessions.h>
61 #include <ardour/io_processor.h>
62 #include <ardour/send.h>
63 #include <ardour/processor.h>
64 #include <ardour/plugin_insert.h>
65 #include <ardour/port_insert.h>
66 #include <ardour/auto_bundle.h>
67 #include <ardour/slave.h>
68 #include <ardour/tempo.h>
69 #include <ardour/audio_track.h>
70 #include <ardour/midi_track.h>
71 #include <ardour/cycle_timer.h>
72 #include <ardour/named_selection.h>
73 #include <ardour/crossfade.h>
74 #include <ardour/playlist.h>
75 #include <ardour/click.h>
76 #include <ardour/data_type.h>
77 #include <ardour/buffer_set.h>
78 #include <ardour/source_factory.h>
79 #include <ardour/region_factory.h>
80 #include <ardour/filename_extensions.h>
81 #include <ardour/session_directory.h>
82 #include <ardour/tape_file_matcher.h>
83 #include <ardour/analyser.h>
86 #include <ardour/osc.h>
92 using namespace ARDOUR;
94 using boost::shared_ptr;
97 static const int CPU_CACHE_ALIGN = 64;
99 static const int CPU_CACHE_ALIGN = 16; /* arguably 32 on most arches, but it matters less */
102 bool Session::_disable_all_loaded_plugins = false;
104 Session::compute_peak_t Session::compute_peak = 0;
105 Session::find_peaks_t Session::find_peaks = 0;
106 Session::apply_gain_to_buffer_t Session::apply_gain_to_buffer = 0;
107 Session::mix_buffers_with_gain_t Session::mix_buffers_with_gain = 0;
108 Session::mix_buffers_no_gain_t Session::mix_buffers_no_gain = 0;
110 sigc::signal<void,std::string> Session::Dialog;
111 sigc::signal<int> Session::AskAboutPendingState;
112 sigc::signal<int,nframes_t,nframes_t> Session::AskAboutSampleRateMismatch;
113 sigc::signal<void> Session::SendFeedback;
115 sigc::signal<void> Session::SMPTEOffsetChanged;
116 sigc::signal<void> Session::StartTimeChanged;
117 sigc::signal<void> Session::EndTimeChanged;
119 sigc::signal<void> Session::AutoBindingOn;
120 sigc::signal<void> Session::AutoBindingOff;
122 Session::Session (AudioEngine &eng,
123 const string& fullpath,
124 const string& snapshot_name,
128 _scratch_buffers(new BufferSet()),
129 _silent_buffers(new BufferSet()),
130 _mix_buffers(new BufferSet()),
131 _mmc_port (default_mmc_port),
132 _mtc_port (default_mtc_port),
133 _midi_port (default_midi_port),
134 _session_dir (new SessionDirectory(fullpath)),
135 pending_events (2048),
136 post_transport_work((PostTransportWork)0),
138 _send_smpte_update (false),
139 diskstreams (new DiskstreamList),
140 routes (new RouteList),
141 auditioner ((Auditioner*) 0),
142 _bundle_xml_node (0),
148 if (!eng.connected()) {
149 throw failed_constructor();
152 cerr << "Loading session " << fullpath << " using snapshot " << snapshot_name << " (1)" << endl;
154 n_physical_outputs = _engine.n_physical_outputs();
155 n_physical_inputs = _engine.n_physical_inputs();
157 first_stage_init (fullpath, snapshot_name);
159 new_session = !Glib::file_test (_path, Glib::FileTest (G_FILE_TEST_EXISTS | G_FILE_TEST_IS_DIR));
162 if (create (new_session, mix_template, compute_initial_length())) {
164 throw failed_constructor ();
168 if (second_stage_init (new_session)) {
170 throw failed_constructor ();
173 store_recent_sessions(_name, _path);
175 bool was_dirty = dirty();
177 _state_of_the_state = StateOfTheState (_state_of_the_state & ~Dirty);
179 Config->ParameterChanged.connect (mem_fun (*this, &Session::config_changed));
182 DirtyChanged (); /* EMIT SIGNAL */
186 Session::Session (AudioEngine &eng,
188 string snapshot_name,
189 AutoConnectOption input_ac,
190 AutoConnectOption output_ac,
191 uint32_t control_out_channels,
192 uint32_t master_out_channels,
193 uint32_t requested_physical_in,
194 uint32_t requested_physical_out,
195 nframes_t initial_length)
198 _scratch_buffers(new BufferSet()),
199 _silent_buffers(new BufferSet()),
200 _mix_buffers(new BufferSet()),
201 _mmc_port (default_mmc_port),
202 _mtc_port (default_mtc_port),
203 _midi_port (default_midi_port),
204 _session_dir ( new SessionDirectory(fullpath)),
205 pending_events (2048),
206 post_transport_work((PostTransportWork)0),
208 _send_smpte_update (false),
209 diskstreams (new DiskstreamList),
210 routes (new RouteList),
211 _bundle_xml_node (0),
217 if (!eng.connected()) {
218 throw failed_constructor();
221 cerr << "Loading session " << fullpath << " using snapshot " << snapshot_name << " (2)" << endl;
223 n_physical_outputs = _engine.n_physical_outputs();
224 n_physical_inputs = _engine.n_physical_inputs();
226 if (n_physical_inputs) {
227 n_physical_inputs = max (requested_physical_in, n_physical_inputs);
230 if (n_physical_outputs) {
231 n_physical_outputs = max (requested_physical_out, n_physical_outputs);
234 first_stage_init (fullpath, snapshot_name);
236 new_session = !g_file_test (_path.c_str(), GFileTest (G_FILE_TEST_EXISTS | G_FILE_TEST_IS_DIR));
239 if (create (new_session, string(), initial_length)) {
241 throw failed_constructor ();
246 /* set up Master Out and Control Out if necessary */
251 if (control_out_channels) {
252 shared_ptr<Route> r (new Route (*this, _("monitor"), -1, control_out_channels, -1, control_out_channels, Route::ControlOut));
253 r->set_remote_control_id (control_id++);
258 if (master_out_channels) {
259 shared_ptr<Route> r (new Route (*this, _("master"), -1, master_out_channels, -1, master_out_channels, Route::MasterOut));
260 r->set_remote_control_id (control_id);
264 /* prohibit auto-connect to master, because there isn't one */
265 output_ac = AutoConnectOption (output_ac & ~AutoConnectMaster);
269 add_routes (rl, false);
274 Config->set_input_auto_connect (input_ac);
275 Config->set_output_auto_connect (output_ac);
277 if (second_stage_init (new_session)) {
279 throw failed_constructor ();
282 store_recent_sessions (_name, _path);
284 _state_of_the_state = StateOfTheState (_state_of_the_state & ~Dirty);
286 Config->ParameterChanged.connect (mem_fun (*this, &Session::config_changed));
297 /* if we got to here, leaving pending capture state around
301 remove_pending_capture_state ();
303 _state_of_the_state = StateOfTheState (CannotSave|Deletion);
305 _engine.remove_session ();
307 GoingAway (); /* EMIT SIGNAL */
313 /* clear history so that no references to objects are held any more */
317 /* clear state tree so that no references to objects are held any more */
323 terminate_butler_thread ();
324 //terminate_midi_thread ();
326 if (click_data && click_data != default_click) {
327 delete [] click_data;
330 if (click_emphasis_data && click_emphasis_data != default_click_emphasis) {
331 delete [] click_emphasis_data;
336 delete _scratch_buffers;
337 delete _silent_buffers;
340 AudioDiskstream::free_working_buffers();
342 Route::SyncOrderKeys.clear();
344 #undef TRACK_DESTRUCTION
345 #ifdef TRACK_DESTRUCTION
346 cerr << "delete named selections\n";
347 #endif /* TRACK_DESTRUCTION */
348 for (NamedSelectionList::iterator i = named_selections.begin(); i != named_selections.end(); ) {
349 NamedSelectionList::iterator tmp;
358 #ifdef TRACK_DESTRUCTION
359 cerr << "delete playlists\n";
360 #endif /* TRACK_DESTRUCTION */
361 for (PlaylistList::iterator i = playlists.begin(); i != playlists.end(); ) {
362 PlaylistList::iterator tmp;
367 (*i)->drop_references ();
372 for (PlaylistList::iterator i = unused_playlists.begin(); i != unused_playlists.end(); ) {
373 PlaylistList::iterator tmp;
378 (*i)->drop_references ();
384 unused_playlists.clear ();
386 #ifdef TRACK_DESTRUCTION
387 cerr << "delete regions\n";
388 #endif /* TRACK_DESTRUCTION */
390 for (RegionList::iterator i = regions.begin(); i != regions.end(); ) {
391 RegionList::iterator tmp;
396 i->second->drop_references ();
403 #ifdef TRACK_DESTRUCTION
404 cerr << "delete routes\n";
405 #endif /* TRACK_DESTRUCTION */
407 RCUWriter<RouteList> writer (routes);
408 boost::shared_ptr<RouteList> r = writer.get_copy ();
409 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
410 (*i)->drop_references ();
413 /* writer goes out of scope and updates master */
418 #ifdef TRACK_DESTRUCTION
419 cerr << "delete diskstreams\n";
420 #endif /* TRACK_DESTRUCTION */
422 RCUWriter<DiskstreamList> dwriter (diskstreams);
423 boost::shared_ptr<DiskstreamList> dsl = dwriter.get_copy();
424 for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
425 (*i)->drop_references ();
429 diskstreams.flush ();
431 #ifdef TRACK_DESTRUCTION
432 cerr << "delete audio sources\n";
433 #endif /* TRACK_DESTRUCTION */
434 for (SourceMap::iterator i = sources.begin(); i != sources.end(); ) {
435 SourceMap::iterator tmp;
440 i->second->drop_references ();
446 #ifdef TRACK_DESTRUCTION
447 cerr << "delete mix groups\n";
448 #endif /* TRACK_DESTRUCTION */
449 for (list<RouteGroup *>::iterator i = mix_groups.begin(); i != mix_groups.end(); ) {
450 list<RouteGroup*>::iterator tmp;
460 #ifdef TRACK_DESTRUCTION
461 cerr << "delete edit groups\n";
462 #endif /* TRACK_DESTRUCTION */
463 for (list<RouteGroup *>::iterator i = edit_groups.begin(); i != edit_groups.end(); ) {
464 list<RouteGroup*>::iterator tmp;
474 if (butler_mixdown_buffer) {
475 delete [] butler_mixdown_buffer;
478 if (butler_gain_buffer) {
479 delete [] butler_gain_buffer;
482 Crossfade::set_buffer_size (0);
490 Session::set_worst_io_latencies ()
492 _worst_output_latency = 0;
493 _worst_input_latency = 0;
495 if (!_engine.connected()) {
499 boost::shared_ptr<RouteList> r = routes.reader ();
501 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
502 _worst_output_latency = max (_worst_output_latency, (*i)->output_latency());
503 _worst_input_latency = max (_worst_input_latency, (*i)->input_latency());
508 Session::when_engine_running ()
510 string first_physical_output;
512 /* we don't want to run execute this again */
514 BootMessage (_("Set block size and sample rate"));
516 set_block_size (_engine.frames_per_cycle());
517 set_frame_rate (_engine.frame_rate());
519 BootMessage (_("Using configuration"));
521 Config->map_parameters (mem_fun (*this, &Session::config_changed));
523 /* every time we reconnect, recompute worst case output latencies */
525 _engine.Running.connect (mem_fun (*this, &Session::set_worst_io_latencies));
527 if (synced_to_jack()) {
528 _engine.transport_stop ();
531 if (Config->get_jack_time_master()) {
532 _engine.transport_locate (_transport_frame);
540 _click_io.reset (new ClickIO (*this, "click", 0, 0, -1, -1));
542 if (state_tree && (child = find_named_node (*state_tree->root(), "Click")) != 0) {
544 /* existing state for Click */
546 if (_click_io->set_state (*child->children().front()) == 0) {
548 _clicking = Config->get_clicking ();
552 error << _("could not setup Click I/O") << endmsg;
558 /* default state for Click */
560 first_physical_output = _engine.get_nth_physical_output (DataType::AUDIO, 0);
562 if (first_physical_output.length()) {
563 if (_click_io->add_output_port (first_physical_output, this)) {
564 // relax, even though its an error
566 _clicking = Config->get_clicking ();
572 catch (failed_constructor& err) {
573 error << _("cannot setup Click I/O") << endmsg;
576 BootMessage (_("Compute I/O Latencies"));
578 set_worst_io_latencies ();
581 // XXX HOW TO ALERT UI TO THIS ? DO WE NEED TO?
584 /* Create a set of Bundle objects that map
585 to the physical outputs currently available
588 BootMessage (_("Set up standard connections"));
592 for (uint32_t np = 0; np < n_physical_outputs; ++np) {
594 snprintf (buf, sizeof (buf), _("out %" PRIu32), np+1);
596 shared_ptr<AutoBundle> c (new AutoBundle (buf, true));
598 c->set_port (0, _engine.get_nth_physical_output (DataType::AUDIO, np));
603 for (uint32_t np = 0; np < n_physical_inputs; ++np) {
605 snprintf (buf, sizeof (buf), _("in %" PRIu32), np+1);
607 shared_ptr<AutoBundle> c (new AutoBundle (buf, false));
609 c->set_port (0, _engine.get_nth_physical_input (DataType::AUDIO, np));
616 for (uint32_t np = 0; np < n_physical_outputs; np +=2) {
618 snprintf (buf, sizeof (buf), _("out %" PRIu32 "+%" PRIu32), np+1, np+2);
620 shared_ptr<AutoBundle> c (new AutoBundle (buf, true));
622 c->set_port (0, _engine.get_nth_physical_output (DataType::AUDIO, np));
623 c->set_port (1, _engine.get_nth_physical_output (DataType::AUDIO, np + 1));
628 for (uint32_t np = 0; np < n_physical_inputs; np +=2) {
630 snprintf (buf, sizeof (buf), _("in %" PRIu32 "+%" PRIu32), np+1, np+2);
632 shared_ptr<AutoBundle> c (new AutoBundle (buf, false));
634 c->set_port (0, _engine.get_nth_physical_input (DataType::AUDIO, np));
635 c->set_port (1, _engine.get_nth_physical_input (DataType::AUDIO, np + 1));
644 /* create master/control ports */
649 /* force the master to ignore any later call to this */
651 if (_master_out->pending_state_node) {
652 _master_out->ports_became_legal();
655 /* no panner resets till we are through */
657 _master_out->defer_pan_reset ();
659 while (_master_out->n_inputs().n_audio()
660 < _master_out->input_maximum().n_audio()) {
661 if (_master_out->add_input_port ("", this, DataType::AUDIO)) {
662 error << _("cannot setup master inputs")
668 while (_master_out->n_outputs().n_audio()
669 < _master_out->output_maximum().n_audio()) {
670 if (_master_out->add_output_port (_engine.get_nth_physical_output (DataType::AUDIO, n), this, DataType::AUDIO)) {
671 error << _("cannot setup master outputs")
678 _master_out->allow_pan_reset ();
682 shared_ptr<AutoBundle> c (new AutoBundle (_("Master Out"), true));
684 c->set_channels (_master_out->n_inputs().n_total());
685 for (uint32_t n = 0; n < _master_out->n_inputs ().n_total(); ++n) {
686 c->set_port (n, _master_out->input(n)->name());
691 BootMessage (_("Setup signal flow and plugins"));
695 /* catch up on send+insert cnts */
697 BootMessage (_("Catch up with send/insert state"));
701 for (list<PortInsert*>::iterator i = _port_inserts.begin(); i != _port_inserts.end(); ++i) {
704 if (sscanf ((*i)->name().c_str(), "%*s %u", &id) == 1) {
705 if (id > insert_cnt) {
713 for (list<Send*>::iterator i = _sends.begin(); i != _sends.end(); ++i) {
716 if (sscanf ((*i)->name().c_str(), "%*s %u", &id) == 1) {
724 _state_of_the_state = StateOfTheState (_state_of_the_state & ~(CannotSave|Dirty));
726 /* hook us up to the engine */
728 BootMessage (_("Connect to engine"));
730 _engine.set_session (this);
735 BootMessage (_("OSC startup"));
737 osc->set_session (*this);
743 Session::hookup_io ()
745 /* stop graph reordering notifications from
746 causing resorts, etc.
749 _state_of_the_state = StateOfTheState (_state_of_the_state | InitialConnecting);
752 if (auditioner == 0) {
754 /* we delay creating the auditioner till now because
755 it makes its own connections to ports.
756 the engine has to be running for this to work.
760 auditioner.reset (new Auditioner (*this));
763 catch (failed_constructor& err) {
764 warning << _("cannot create Auditioner: no auditioning of regions possible") << endmsg;
768 /* Tell all IO objects to create their ports */
774 vector<string> cports;
776 while (_control_out->n_inputs().n_audio() < _control_out->input_maximum().n_audio()) {
777 if (_control_out->add_input_port ("", this)) {
778 error << _("cannot setup control inputs")
784 while (_control_out->n_outputs().n_audio() < _control_out->output_maximum().n_audio()) {
785 if (_control_out->add_output_port (_engine.get_nth_physical_output (DataType::AUDIO, n), this)) {
786 error << _("cannot set up master outputs")
794 uint32_t ni = _control_out->n_inputs().get (DataType::AUDIO);
796 for (n = 0; n < ni; ++n) {
797 cports.push_back (_control_out->input(n)->name());
800 boost::shared_ptr<RouteList> r = routes.reader ();
802 for (RouteList::iterator x = r->begin(); x != r->end(); ++x) {
803 (*x)->set_control_outs (cports);
807 /* load bundles, which we may have postponed earlier on */
808 if (_bundle_xml_node) {
809 load_bundles (*_bundle_xml_node);
810 delete _bundle_xml_node;
813 /* Tell all IO objects to connect themselves together */
815 IO::enable_connecting ();
817 /* Now reset all panners */
819 IO::reset_panners ();
821 /* Anyone who cares about input state, wake up and do something */
823 IOConnectionsComplete (); /* EMIT SIGNAL */
825 _state_of_the_state = StateOfTheState (_state_of_the_state & ~InitialConnecting);
828 /* now handle the whole enchilada as if it was one
834 /* update mixer solo state */
840 Session::playlist_length_changed ()
842 /* we can't just increase end_location->end() if pl->get_maximum_extent()
843 if larger. if the playlist used to be the longest playlist,
844 and its now shorter, we have to decrease end_location->end(). hence,
845 we have to iterate over all diskstreams and check the
846 playlists currently in use.
852 Session::diskstream_playlist_changed (boost::shared_ptr<Diskstream> dstream)
854 boost::shared_ptr<Playlist> playlist;
856 if ((playlist = dstream->playlist()) != 0) {
857 playlist->LengthChanged.connect (mem_fun (this, &Session::playlist_length_changed));
860 /* see comment in playlist_length_changed () */
865 Session::record_enabling_legal () const
867 /* this used to be in here, but survey says.... we don't need to restrict it */
868 // if (record_status() == Recording) {
872 if (Config->get_all_safe()) {
879 Session::reset_input_monitor_state ()
881 if (transport_rolling()) {
883 boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
885 for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
886 if ((*i)->record_enabled ()) {
887 //cerr << "switching to input = " << !auto_input << __FILE__ << __LINE__ << endl << endl;
888 (*i)->monitor_input (Config->get_monitoring_model() == HardwareMonitoring && !Config->get_auto_input());
892 boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
894 for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
895 if ((*i)->record_enabled ()) {
896 //cerr << "switching to input = " << !Config->get_auto_input() << __FILE__ << __LINE__ << endl << endl;
897 (*i)->monitor_input (Config->get_monitoring_model() == HardwareMonitoring);
904 Session::auto_punch_start_changed (Location* location)
906 replace_event (Event::PunchIn, location->start());
908 if (get_record_enabled() && Config->get_punch_in()) {
909 /* capture start has been changed, so save new pending state */
910 save_state ("", true);
915 Session::auto_punch_end_changed (Location* location)
917 nframes_t when_to_stop = location->end();
918 // when_to_stop += _worst_output_latency + _worst_input_latency;
919 replace_event (Event::PunchOut, when_to_stop);
923 Session::auto_punch_changed (Location* location)
925 nframes_t when_to_stop = location->end();
927 replace_event (Event::PunchIn, location->start());
928 //when_to_stop += _worst_output_latency + _worst_input_latency;
929 replace_event (Event::PunchOut, when_to_stop);
933 Session::auto_loop_changed (Location* location)
935 replace_event (Event::AutoLoop, location->end(), location->start());
937 if (transport_rolling() && play_loop) {
939 //if (_transport_frame < location->start() || _transport_frame > location->end()) {
941 if (_transport_frame > location->end()) {
942 // relocate to beginning of loop
943 clear_events (Event::LocateRoll);
945 request_locate (location->start(), true);
948 else if (Config->get_seamless_loop() && !loop_changing) {
950 // schedule a locate-roll to refill the diskstreams at the
952 loop_changing = true;
954 if (location->end() > last_loopend) {
955 clear_events (Event::LocateRoll);
956 Event *ev = new Event (Event::LocateRoll, Event::Add, last_loopend, last_loopend, 0, true);
963 last_loopend = location->end();
967 Session::set_auto_punch_location (Location* location)
971 if ((existing = _locations.auto_punch_location()) != 0 && existing != location) {
972 auto_punch_start_changed_connection.disconnect();
973 auto_punch_end_changed_connection.disconnect();
974 auto_punch_changed_connection.disconnect();
975 existing->set_auto_punch (false, this);
976 remove_event (existing->start(), Event::PunchIn);
977 clear_events (Event::PunchOut);
978 auto_punch_location_changed (0);
987 if (location->end() <= location->start()) {
988 error << _("Session: you can't use that location for auto punch (start <= end)") << endmsg;
992 auto_punch_start_changed_connection.disconnect();
993 auto_punch_end_changed_connection.disconnect();
994 auto_punch_changed_connection.disconnect();
996 auto_punch_start_changed_connection = location->start_changed.connect (mem_fun (this, &Session::auto_punch_start_changed));
997 auto_punch_end_changed_connection = location->end_changed.connect (mem_fun (this, &Session::auto_punch_end_changed));
998 auto_punch_changed_connection = location->changed.connect (mem_fun (this, &Session::auto_punch_changed));
1000 location->set_auto_punch (true, this);
1003 auto_punch_changed (location);
1005 auto_punch_location_changed (location);
1009 Session::set_auto_loop_location (Location* location)
1013 if ((existing = _locations.auto_loop_location()) != 0 && existing != location) {
1014 auto_loop_start_changed_connection.disconnect();
1015 auto_loop_end_changed_connection.disconnect();
1016 auto_loop_changed_connection.disconnect();
1017 existing->set_auto_loop (false, this);
1018 remove_event (existing->end(), Event::AutoLoop);
1019 auto_loop_location_changed (0);
1024 if (location == 0) {
1028 if (location->end() <= location->start()) {
1029 error << _("Session: you can't use a mark for auto loop") << endmsg;
1033 last_loopend = location->end();
1035 auto_loop_start_changed_connection.disconnect();
1036 auto_loop_end_changed_connection.disconnect();
1037 auto_loop_changed_connection.disconnect();
1039 auto_loop_start_changed_connection = location->start_changed.connect (mem_fun (this, &Session::auto_loop_changed));
1040 auto_loop_end_changed_connection = location->end_changed.connect (mem_fun (this, &Session::auto_loop_changed));
1041 auto_loop_changed_connection = location->changed.connect (mem_fun (this, &Session::auto_loop_changed));
1043 location->set_auto_loop (true, this);
1045 /* take care of our stuff first */
1047 auto_loop_changed (location);
1049 /* now tell everyone else */
1051 auto_loop_location_changed (location);
1055 Session::locations_added (Location* ignored)
1061 Session::locations_changed ()
1063 _locations.apply (*this, &Session::handle_locations_changed);
1067 Session::handle_locations_changed (Locations::LocationList& locations)
1069 Locations::LocationList::iterator i;
1071 bool set_loop = false;
1072 bool set_punch = false;
1074 for (i = locations.begin(); i != locations.end(); ++i) {
1078 if (location->is_auto_punch()) {
1079 set_auto_punch_location (location);
1082 if (location->is_auto_loop()) {
1083 set_auto_loop_location (location);
1090 set_auto_loop_location (0);
1093 set_auto_punch_location (0);
1100 Session::enable_record ()
1102 /* XXX really atomic compare+swap here */
1103 if (g_atomic_int_get (&_record_status) != Recording) {
1104 g_atomic_int_set (&_record_status, Recording);
1105 _last_record_location = _transport_frame;
1106 deliver_mmc(MIDI::MachineControl::cmdRecordStrobe, _last_record_location);
1108 if (Config->get_monitoring_model() == HardwareMonitoring && Config->get_auto_input()) {
1109 boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
1110 for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
1111 if ((*i)->record_enabled ()) {
1112 (*i)->monitor_input (true);
1117 RecordStateChanged ();
1122 Session::disable_record (bool rt_context, bool force)
1126 if ((rs = (RecordState) g_atomic_int_get (&_record_status)) != Disabled) {
1128 if ((!Config->get_latched_record_enable () && !play_loop) || force) {
1129 g_atomic_int_set (&_record_status, Disabled);
1131 if (rs == Recording) {
1132 g_atomic_int_set (&_record_status, Enabled);
1136 // FIXME: timestamp correct? [DR]
1137 // FIXME FIXME FIXME: rt_context? this must be called in the process thread.
1138 // does this /need/ to be sent in all cases?
1140 deliver_mmc (MIDI::MachineControl::cmdRecordExit, _transport_frame);
1142 if (Config->get_monitoring_model() == HardwareMonitoring && Config->get_auto_input()) {
1143 boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
1145 for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
1146 if ((*i)->record_enabled ()) {
1147 (*i)->monitor_input (false);
1152 RecordStateChanged (); /* emit signal */
1155 remove_pending_capture_state ();
1161 Session::step_back_from_record ()
1163 /* XXX really atomic compare+swap here */
1164 if (g_atomic_int_get (&_record_status) == Recording) {
1165 g_atomic_int_set (&_record_status, Enabled);
1167 if (Config->get_monitoring_model() == HardwareMonitoring && Config->get_auto_input()) {
1168 boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
1170 for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
1171 if ((*i)->record_enabled ()) {
1172 //cerr << "switching from input" << __FILE__ << __LINE__ << endl << endl;
1173 (*i)->monitor_input (false);
1181 Session::maybe_enable_record ()
1183 g_atomic_int_set (&_record_status, Enabled);
1185 /* this function is currently called from somewhere other than an RT thread.
1186 this save_state() call therefore doesn't impact anything.
1189 save_state ("", true);
1191 if (_transport_speed) {
1192 if (!Config->get_punch_in()) {
1196 deliver_mmc (MIDI::MachineControl::cmdRecordPause, _transport_frame);
1197 RecordStateChanged (); /* EMIT SIGNAL */
1204 Session::audible_frame () const
1210 /* the first of these two possible settings for "offset"
1211 mean that the audible frame is stationary until
1212 audio emerges from the latency compensation
1215 the second means that the audible frame is stationary
1216 until audio would emerge from a physical port
1217 in the absence of any plugin latency compensation
1220 offset = _worst_output_latency;
1222 if (offset > current_block_size) {
1223 offset -= current_block_size;
1225 /* XXX is this correct? if we have no external
1226 physical connections and everything is internal
1227 then surely this is zero? still, how
1228 likely is that anyway?
1230 offset = current_block_size;
1233 if (synced_to_jack()) {
1234 tf = _engine.transport_frame();
1236 tf = _transport_frame;
1239 if (_transport_speed == 0) {
1249 if (!non_realtime_work_pending()) {
1253 /* take latency into account */
1262 Session::set_frame_rate (nframes_t frames_per_second)
1264 /** \fn void Session::set_frame_size(nframes_t)
1265 the AudioEngine object that calls this guarantees
1266 that it will not be called while we are also in
1267 ::process(). Its fine to do things that block
1271 _base_frame_rate = frames_per_second;
1275 Automatable::set_automation_interval ((jack_nframes_t) ceil ((double) frames_per_second * (0.001 * Config->get_automation_interval())));
1279 // XXX we need some equivalent to this, somehow
1280 // SndFileSource::setup_standard_crossfades (frames_per_second);
1284 /* XXX need to reset/reinstantiate all LADSPA plugins */
1288 Session::set_block_size (nframes_t nframes)
1290 /* the AudioEngine guarantees
1291 that it will not be called while we are also in
1292 ::process(). It is therefore fine to do things that block
1298 current_block_size = nframes;
1300 ensure_buffers(_scratch_buffers->available());
1302 if (_gain_automation_buffer) {
1303 delete [] _gain_automation_buffer;
1305 _gain_automation_buffer = new gain_t[nframes];
1307 allocate_pan_automation_buffers (nframes, _npan_buffers, true);
1309 boost::shared_ptr<RouteList> r = routes.reader ();
1311 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
1312 (*i)->set_block_size (nframes);
1315 boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
1316 for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
1317 (*i)->set_block_size (nframes);
1320 set_worst_io_latencies ();
1325 Session::set_default_fade (float steepness, float fade_msecs)
1328 nframes_t fade_frames;
1330 /* Don't allow fade of less 1 frame */
1332 if (fade_msecs < (1000.0 * (1.0/_current_frame_rate))) {
1339 fade_frames = (nframes_t) floor (fade_msecs * _current_frame_rate * 0.001);
1343 default_fade_msecs = fade_msecs;
1344 default_fade_steepness = steepness;
1347 // jlc, WTF is this!
1348 Glib::RWLock::ReaderLock lm (route_lock);
1349 AudioRegion::set_default_fade (steepness, fade_frames);
1354 /* XXX have to do this at some point */
1355 /* foreach region using default fade, reset, then
1356 refill_all_diskstream_buffers ();
1361 struct RouteSorter {
1362 bool operator() (boost::shared_ptr<Route> r1, boost::shared_ptr<Route> r2) {
1363 if (r1->fed_by.find (r2) != r1->fed_by.end()) {
1365 } else if (r2->fed_by.find (r1) != r2->fed_by.end()) {
1368 if (r1->fed_by.empty()) {
1369 if (r2->fed_by.empty()) {
1370 /* no ardour-based connections inbound to either route. just use signal order */
1371 return r1->order_key(N_("signal")) < r2->order_key(N_("signal"));
1373 /* r2 has connections, r1 does not; run r1 early */
1377 return r1->order_key(N_("signal")) < r2->order_key(N_("signal"));
1384 trace_terminal (shared_ptr<Route> r1, shared_ptr<Route> rbase)
1386 shared_ptr<Route> r2;
1388 if ((r1->fed_by.find (rbase) != r1->fed_by.end()) && (rbase->fed_by.find (r1) != rbase->fed_by.end())) {
1389 info << string_compose(_("feedback loop setup between %1 and %2"), r1->name(), rbase->name()) << endmsg;
1393 /* make a copy of the existing list of routes that feed r1 */
1395 set<shared_ptr<Route> > existing = r1->fed_by;
1397 /* for each route that feeds r1, recurse, marking it as feeding
1401 for (set<shared_ptr<Route> >::iterator i = existing.begin(); i != existing.end(); ++i) {
1404 /* r2 is a route that feeds r1 which somehow feeds base. mark
1405 base as being fed by r2
1408 rbase->fed_by.insert (r2);
1412 /* 2nd level feedback loop detection. if r1 feeds or is fed by r2,
1416 if ((r1->fed_by.find (r2) != r1->fed_by.end()) && (r2->fed_by.find (r1) != r2->fed_by.end())) {
1420 /* now recurse, so that we can mark base as being fed by
1421 all routes that feed r2
1424 trace_terminal (r2, rbase);
1431 Session::resort_routes ()
1433 /* don't do anything here with signals emitted
1434 by Routes while we are being destroyed.
1437 if (_state_of_the_state & Deletion) {
1444 RCUWriter<RouteList> writer (routes);
1445 shared_ptr<RouteList> r = writer.get_copy ();
1446 resort_routes_using (r);
1447 /* writer goes out of scope and forces update */
1452 Session::resort_routes_using (shared_ptr<RouteList> r)
1454 RouteList::iterator i, j;
1456 for (i = r->begin(); i != r->end(); ++i) {
1458 (*i)->fed_by.clear ();
1460 for (j = r->begin(); j != r->end(); ++j) {
1462 /* although routes can feed themselves, it will
1463 cause an endless recursive descent if we
1464 detect it. so don't bother checking for
1472 if ((*j)->feeds (*i)) {
1473 (*i)->fed_by.insert (*j);
1478 for (i = r->begin(); i != r->end(); ++i) {
1479 trace_terminal (*i, *i);
1486 cerr << "finished route resort\n";
1488 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
1489 cerr << " " << (*i)->name() << " signal order = " << (*i)->order_key ("signal") << endl;
1496 list<boost::shared_ptr<MidiTrack> >
1497 Session::new_midi_track (TrackMode mode, uint32_t how_many)
1499 char track_name[32];
1500 uint32_t track_id = 0;
1503 RouteList new_routes;
1504 list<boost::shared_ptr<MidiTrack> > ret;
1505 //uint32_t control_id;
1507 // FIXME: need physical I/O and autoconnect stuff for MIDI
1509 /* count existing midi tracks */
1512 shared_ptr<RouteList> r = routes.reader ();
1514 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
1515 if (dynamic_cast<MidiTrack*>((*i).get()) != 0) {
1516 if (!(*i)->is_hidden()) {
1518 //channels_used += (*i)->n_inputs().n_midi();
1525 vector<string> physinputs;
1526 vector<string> physoutputs;
1527 uint32_t nphysical_in;
1528 uint32_t nphysical_out;
1530 _engine.get_physical_outputs (physoutputs);
1531 _engine.get_physical_inputs (physinputs);
1532 control_id = ntracks() + nbusses() + 1;
1537 /* check for duplicate route names, since we might have pre-existing
1538 routes with this name (e.g. create Audio1, Audio2, delete Audio1,
1539 save, close,restart,add new route - first named route is now
1547 snprintf (track_name, sizeof(track_name), "Midi %" PRIu32, track_id);
1549 if (route_by_name (track_name) == 0) {
1553 } while (track_id < (UINT_MAX-1));
1556 if (Config->get_input_auto_connect() & AutoConnectPhysical) {
1557 nphysical_in = min (n_physical_inputs, (uint32_t) physinputs.size());
1562 if (Config->get_output_auto_connect() & AutoConnectPhysical) {
1563 nphysical_out = min (n_physical_outputs, (uint32_t) physinputs.size());
1569 shared_ptr<MidiTrack> track;
1572 track = boost::shared_ptr<MidiTrack>((new MidiTrack (*this, track_name, Route::Flag (0), mode)));
1574 if (track->ensure_io (ChanCount(DataType::MIDI, 1), ChanCount(DataType::AUDIO, 1), false, this)) {
1575 error << "cannot configure 1 in/1 out configuration for new midi track" << endmsg;
1581 for (uint32_t x = 0; x < track->n_inputs().n_midi() && x < nphysical_in; ++x) {
1585 if (Config->get_input_auto_connect() & AutoConnectPhysical) {
1586 port = physinputs[(channels_used+x)%nphysical_in];
1589 if (port.length() && track->connect_input (track->input (x), port, this)) {
1595 for (uint32_t x = 0; x < track->n_outputs().n_midi(); ++x) {
1599 if (nphysical_out && (Config->get_output_auto_connect() & AutoConnectPhysical)) {
1600 port = physoutputs[(channels_used+x)%nphysical_out];
1601 } else if (Config->get_output_auto_connect() & AutoConnectMaster) {
1603 port = _master_out->input (x%_master_out->n_inputs().n_midi())->name();
1607 if (port.length() && track->connect_output (track->output (x), port, this)) {
1612 channels_used += track->n_inputs ().n_midi();
1616 track->midi_diskstream()->non_realtime_input_change();
1618 track->DiskstreamChanged.connect (mem_fun (this, &Session::resort_routes));
1619 //track->set_remote_control_id (control_id);
1621 new_routes.push_back (track);
1622 ret.push_back (track);
1625 catch (failed_constructor &err) {
1626 error << _("Session: could not create new midi track.") << endmsg;
1629 /* we need to get rid of this, since the track failed to be created */
1630 /* XXX arguably, AudioTrack::AudioTrack should not do the Session::add_diskstream() */
1633 RCUWriter<DiskstreamList> writer (diskstreams);
1634 boost::shared_ptr<DiskstreamList> ds = writer.get_copy();
1635 ds->remove (track->midi_diskstream());
1642 catch (AudioEngine::PortRegistrationFailure& pfe) {
1644 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;
1647 /* we need to get rid of this, since the track failed to be created */
1648 /* XXX arguably, MidiTrack::MidiTrack should not do the Session::add_diskstream() */
1651 RCUWriter<DiskstreamList> writer (diskstreams);
1652 boost::shared_ptr<DiskstreamList> ds = writer.get_copy();
1653 ds->remove (track->midi_diskstream());
1664 if (!new_routes.empty()) {
1665 add_routes (new_routes, false);
1666 save_state (_current_snapshot_name);
1672 list<boost::shared_ptr<AudioTrack> >
1673 Session::new_audio_track (int input_channels, int output_channels, TrackMode mode, uint32_t how_many)
1675 char track_name[32];
1676 uint32_t track_id = 0;
1678 uint32_t channels_used = 0;
1680 RouteList new_routes;
1681 list<boost::shared_ptr<AudioTrack> > ret;
1682 uint32_t control_id;
1684 /* count existing audio tracks */
1687 shared_ptr<RouteList> r = routes.reader ();
1689 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
1690 if (dynamic_cast<AudioTrack*>((*i).get()) != 0) {
1691 if (!(*i)->is_hidden()) {
1693 channels_used += (*i)->n_inputs().n_audio();
1699 vector<string> physinputs;
1700 vector<string> physoutputs;
1701 uint32_t nphysical_in;
1702 uint32_t nphysical_out;
1704 _engine.get_physical_outputs (physoutputs);
1705 _engine.get_physical_inputs (physinputs);
1706 control_id = ntracks() + nbusses() + 1;
1710 /* check for duplicate route names, since we might have pre-existing
1711 routes with this name (e.g. create Audio1, Audio2, delete Audio1,
1712 save, close,restart,add new route - first named route is now
1720 snprintf (track_name, sizeof(track_name), "Audio %" PRIu32, track_id);
1722 if (route_by_name (track_name) == 0) {
1726 } while (track_id < (UINT_MAX-1));
1728 if (Config->get_input_auto_connect() & AutoConnectPhysical) {
1729 nphysical_in = min (n_physical_inputs, (uint32_t) physinputs.size());
1734 if (Config->get_output_auto_connect() & AutoConnectPhysical) {
1735 nphysical_out = min (n_physical_outputs, (uint32_t) physinputs.size());
1740 shared_ptr<AudioTrack> track;
1743 track = boost::shared_ptr<AudioTrack>((new AudioTrack (*this, track_name, Route::Flag (0), mode)));
1745 if (track->ensure_io (ChanCount(DataType::AUDIO, input_channels), ChanCount(DataType::AUDIO, output_channels), false, this)) {
1746 error << string_compose (_("cannot configure %1 in/%2 out configuration for new audio track"),
1747 input_channels, output_channels)
1753 for (uint32_t x = 0; x < track->n_inputs().n_audio() && x < nphysical_in; ++x) {
1757 if (Config->get_input_auto_connect() & AutoConnectPhysical) {
1758 port = physinputs[(channels_used+x)%nphysical_in];
1761 if (port.length() && track->connect_input (track->input (x), port, this)) {
1767 for (uint32_t x = 0; x < track->n_outputs().n_midi(); ++x) {
1771 if (nphysical_out && (Config->get_output_auto_connect() & AutoConnectPhysical)) {
1772 port = physoutputs[(channels_used+x)%nphysical_out];
1773 } else if (Config->get_output_auto_connect() & AutoConnectMaster) {
1775 port = _master_out->input (x%_master_out->n_inputs().n_audio())->name();
1779 if (port.length() && track->connect_output (track->output (x), port, this)) {
1784 channels_used += track->n_inputs ().n_audio();
1786 track->audio_diskstream()->non_realtime_input_change();
1788 track->DiskstreamChanged.connect (mem_fun (this, &Session::resort_routes));
1789 track->set_remote_control_id (control_id);
1792 new_routes.push_back (track);
1793 ret.push_back (track);
1796 catch (failed_constructor &err) {
1797 error << _("Session: could not create new audio track.") << endmsg;
1800 /* we need to get rid of this, since the track failed to be created */
1801 /* XXX arguably, AudioTrack::AudioTrack should not do the Session::add_diskstream() */
1804 RCUWriter<DiskstreamList> writer (diskstreams);
1805 boost::shared_ptr<DiskstreamList> ds = writer.get_copy();
1806 ds->remove (track->audio_diskstream());
1813 catch (AudioEngine::PortRegistrationFailure& pfe) {
1815 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;
1818 /* we need to get rid of this, since the track failed to be created */
1819 /* XXX arguably, AudioTrack::AudioTrack should not do the Session::add_diskstream() */
1822 RCUWriter<DiskstreamList> writer (diskstreams);
1823 boost::shared_ptr<DiskstreamList> ds = writer.get_copy();
1824 ds->remove (track->audio_diskstream());
1835 if (!new_routes.empty()) {
1836 add_routes (new_routes, true);
1843 Session::set_remote_control_ids ()
1845 RemoteModel m = Config->get_remote_model();
1847 shared_ptr<RouteList> r = routes.reader ();
1849 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
1850 if ( MixerOrdered == m) {
1851 long order = (*i)->order_key(N_("signal"));
1852 (*i)->set_remote_control_id( order+1 );
1853 } else if ( EditorOrdered == m) {
1854 long order = (*i)->order_key(N_("editor"));
1855 (*i)->set_remote_control_id( order+1 );
1856 } else if ( UserOrdered == m) {
1857 //do nothing ... only changes to remote id's are initiated by user
1864 Session::new_audio_route (int input_channels, int output_channels, uint32_t how_many)
1867 uint32_t bus_id = 1;
1871 uint32_t control_id;
1873 /* count existing audio busses */
1876 shared_ptr<RouteList> r = routes.reader ();
1878 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
1879 if (dynamic_cast<AudioTrack*>((*i).get()) == 0) {
1880 if (!(*i)->is_hidden() && (*i)->name() != _("master")) {
1887 vector<string> physinputs;
1888 vector<string> physoutputs;
1890 _engine.get_physical_outputs (physoutputs);
1891 _engine.get_physical_inputs (physinputs);
1892 control_id = ntracks() + nbusses() + 1;
1897 snprintf (bus_name, sizeof(bus_name), "Bus %" PRIu32, bus_id);
1901 if (route_by_name (bus_name) == 0) {
1905 } while (bus_id < (UINT_MAX-1));
1908 shared_ptr<Route> bus (new Route (*this, bus_name, -1, -1, -1, -1, Route::Flag(0), DataType::AUDIO));
1910 if (bus->ensure_io (ChanCount(DataType::AUDIO, input_channels), ChanCount(DataType::AUDIO, output_channels), false, this)) {
1911 error << string_compose (_("cannot configure %1 in/%2 out configuration for new audio track"),
1912 input_channels, output_channels)
1917 for (uint32_t x = 0; n_physical_inputs && x < bus->n_inputs().n_audio(); ++x) {
1921 if (Config->get_input_auto_connect() & AutoConnectPhysical) {
1922 port = physinputs[((n+x)%n_physical_inputs)];
1925 if (port.length() && bus->connect_input (bus->input (x), port, this)) {
1930 for (uint32_t x = 0; n_physical_outputs && x < bus->n_outputs().n_audio(); ++x) {
1934 if (Config->get_output_auto_connect() & AutoConnectPhysical) {
1935 port = physoutputs[((n+x)%n_physical_outputs)];
1936 } else if (Config->get_output_auto_connect() & AutoConnectMaster) {
1938 port = _master_out->input (x%_master_out->n_inputs().n_audio())->name();
1942 if (port.length() && bus->connect_output (bus->output (x), port, this)) {
1947 bus->set_remote_control_id (control_id);
1950 ret.push_back (bus);
1954 catch (failed_constructor &err) {
1955 error << _("Session: could not create new audio route.") << endmsg;
1959 catch (AudioEngine::PortRegistrationFailure& pfe) {
1960 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;
1970 add_routes (ret, true);
1978 Session::add_routes (RouteList& new_routes, bool save)
1981 RCUWriter<RouteList> writer (routes);
1982 shared_ptr<RouteList> r = writer.get_copy ();
1983 r->insert (r->end(), new_routes.begin(), new_routes.end());
1984 resort_routes_using (r);
1987 for (RouteList::iterator x = new_routes.begin(); x != new_routes.end(); ++x) {
1989 boost::weak_ptr<Route> wpr (*x);
1991 (*x)->solo_changed.connect (sigc::bind (mem_fun (*this, &Session::route_solo_changed), wpr));
1992 (*x)->mute_changed.connect (mem_fun (*this, &Session::route_mute_changed));
1993 (*x)->output_changed.connect (mem_fun (*this, &Session::set_worst_io_latencies_x));
1994 (*x)->processors_changed.connect (bind (mem_fun (*this, &Session::update_latency_compensation), false, false));
1996 if ((*x)->is_master()) {
2000 if ((*x)->is_control()) {
2001 _control_out = (*x);
2004 add_bundle ((*x)->bundle_for_inputs());
2005 add_bundle ((*x)->bundle_for_outputs());
2008 if (_control_out && IO::connecting_legal) {
2010 vector<string> cports;
2011 uint32_t ni = _control_out->n_inputs().n_audio();
2013 for (uint32_t n = 0; n < ni; ++n) {
2014 cports.push_back (_control_out->input(n)->name());
2017 for (RouteList::iterator x = new_routes.begin(); x != new_routes.end(); ++x) {
2018 (*x)->set_control_outs (cports);
2025 save_state (_current_snapshot_name);
2028 RouteAdded (new_routes); /* EMIT SIGNAL */
2032 Session::add_diskstream (boost::shared_ptr<Diskstream> dstream)
2034 /* need to do this in case we're rolling at the time, to prevent false underruns */
2035 dstream->do_refill_with_alloc ();
2037 dstream->set_block_size (current_block_size);
2040 RCUWriter<DiskstreamList> writer (diskstreams);
2041 boost::shared_ptr<DiskstreamList> ds = writer.get_copy();
2042 ds->push_back (dstream);
2043 /* writer goes out of scope, copies ds back to main */
2046 dstream->PlaylistChanged.connect (sigc::bind (mem_fun (*this, &Session::diskstream_playlist_changed), dstream));
2047 /* this will connect to future changes, and check the current length */
2048 diskstream_playlist_changed (dstream);
2050 dstream->prepare ();
2055 Session::remove_route (shared_ptr<Route> route)
2058 RCUWriter<RouteList> writer (routes);
2059 shared_ptr<RouteList> rs = writer.get_copy ();
2063 /* deleting the master out seems like a dumb
2064 idea, but its more of a UI policy issue
2068 if (route == _master_out) {
2069 _master_out = shared_ptr<Route> ();
2072 if (route == _control_out) {
2073 _control_out = shared_ptr<Route> ();
2075 /* cancel control outs for all routes */
2077 vector<string> empty;
2079 for (RouteList::iterator r = rs->begin(); r != rs->end(); ++r) {
2080 (*r)->set_control_outs (empty);
2084 update_route_solo_state ();
2086 /* writer goes out of scope, forces route list update */
2090 boost::shared_ptr<Diskstream> ds;
2092 if ((t = dynamic_cast<Track*>(route.get())) != 0) {
2093 ds = t->diskstream();
2099 RCUWriter<DiskstreamList> dsl (diskstreams);
2100 boost::shared_ptr<DiskstreamList> d = dsl.get_copy();
2105 find_current_end ();
2107 // We need to disconnect the routes inputs and outputs
2109 route->disconnect_inputs (0);
2110 route->disconnect_outputs (0);
2112 update_latency_compensation (false, false);
2115 /* get rid of it from the dead wood collection in the route list manager */
2117 /* XXX i think this is unsafe as it currently stands, but i am not sure. (pd, october 2nd, 2006) */
2121 /* try to cause everyone to drop their references */
2123 route->drop_references ();
2125 /* save the new state of the world */
2127 if (save_state (_current_snapshot_name)) {
2128 save_history (_current_snapshot_name);
2133 Session::route_mute_changed (void* src)
2139 Session::route_solo_changed (void* src, boost::weak_ptr<Route> wpr)
2141 if (solo_update_disabled) {
2147 boost::shared_ptr<Route> route = wpr.lock ();
2150 /* should not happen */
2151 error << string_compose (_("programming error: %1"), X_("invalid route weak ptr passed to route_solo_changed")) << endmsg;
2155 is_track = (boost::dynamic_pointer_cast<AudioTrack>(route) != 0);
2157 shared_ptr<RouteList> r = routes.reader ();
2159 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2161 /* soloing a track mutes all other tracks, soloing a bus mutes all other busses */
2165 /* don't mess with busses */
2167 if (dynamic_cast<Track*>((*i).get()) == 0) {
2173 /* don't mess with tracks */
2175 if (dynamic_cast<Track*>((*i).get()) != 0) {
2180 if ((*i) != route &&
2181 ((*i)->mix_group () == 0 ||
2182 (*i)->mix_group () != route->mix_group () ||
2183 !route->mix_group ()->is_active())) {
2185 if ((*i)->soloed()) {
2187 /* if its already soloed, and solo latching is enabled,
2188 then leave it as it is.
2191 if (Config->get_solo_latched()) {
2198 solo_update_disabled = true;
2199 (*i)->set_solo (false, src);
2200 solo_update_disabled = false;
2204 bool something_soloed = false;
2205 bool same_thing_soloed = false;
2206 bool signal = false;
2208 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2209 if ((*i)->soloed()) {
2210 something_soloed = true;
2211 if (dynamic_cast<Track*>((*i).get())) {
2213 same_thing_soloed = true;
2218 same_thing_soloed = true;
2226 if (something_soloed != currently_soloing) {
2228 currently_soloing = something_soloed;
2231 modify_solo_mute (is_track, same_thing_soloed);
2234 SoloActive (currently_soloing); /* EMIT SIGNAL */
2237 SoloChanged (); /* EMIT SIGNAL */
2243 Session::update_route_solo_state ()
2246 bool is_track = false;
2247 bool signal = false;
2249 /* caller must hold RouteLock */
2251 /* this is where we actually implement solo by changing
2252 the solo mute setting of each track.
2255 shared_ptr<RouteList> r = routes.reader ();
2257 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2258 if ((*i)->soloed()) {
2260 if (dynamic_cast<Track*>((*i).get())) {
2267 if (mute != currently_soloing) {
2269 currently_soloing = mute;
2272 if (!is_track && !mute) {
2274 /* nothing is soloed */
2276 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2277 (*i)->set_solo_mute (false);
2287 modify_solo_mute (is_track, mute);
2290 SoloActive (currently_soloing);
2295 Session::modify_solo_mute (bool is_track, bool mute)
2297 shared_ptr<RouteList> r = routes.reader ();
2299 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2303 /* only alter track solo mute */
2305 if (dynamic_cast<Track*>((*i).get())) {
2306 if ((*i)->soloed()) {
2307 (*i)->set_solo_mute (!mute);
2309 (*i)->set_solo_mute (mute);
2315 /* only alter bus solo mute */
2317 if (!dynamic_cast<Track*>((*i).get())) {
2319 if ((*i)->soloed()) {
2321 (*i)->set_solo_mute (false);
2325 /* don't mute master or control outs
2326 in response to another bus solo
2329 if ((*i) != _master_out &&
2330 (*i) != _control_out) {
2331 (*i)->set_solo_mute (mute);
2342 Session::catch_up_on_solo ()
2344 /* this is called after set_state() to catch the full solo
2345 state, which can't be correctly determined on a per-route
2346 basis, but needs the global overview that only the session
2349 update_route_solo_state();
2353 Session::route_by_name (string name)
2355 shared_ptr<RouteList> r = routes.reader ();
2357 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2358 if ((*i)->name() == name) {
2363 return shared_ptr<Route> ((Route*) 0);
2367 Session::route_by_id (PBD::ID id)
2369 shared_ptr<RouteList> r = routes.reader ();
2371 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2372 if ((*i)->id() == id) {
2377 return shared_ptr<Route> ((Route*) 0);
2381 Session::route_by_remote_id (uint32_t id)
2383 shared_ptr<RouteList> r = routes.reader ();
2385 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2386 if ((*i)->remote_control_id() == id) {
2391 return shared_ptr<Route> ((Route*) 0);
2395 Session::find_current_end ()
2397 if (_state_of_the_state & Loading) {
2401 nframes_t max = get_maximum_extent ();
2403 if (max > end_location->end()) {
2404 end_location->set_end (max);
2406 DurationChanged(); /* EMIT SIGNAL */
2411 Session::get_maximum_extent () const
2416 boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
2418 for (DiskstreamList::const_iterator i = dsl->begin(); i != dsl->end(); ++i) {
2419 boost::shared_ptr<Playlist> pl = (*i)->playlist();
2420 if ((me = pl->get_maximum_extent()) > max) {
2428 boost::shared_ptr<Diskstream>
2429 Session::diskstream_by_name (string name)
2431 boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
2433 for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
2434 if ((*i)->name() == name) {
2439 return boost::shared_ptr<Diskstream>((Diskstream*) 0);
2442 boost::shared_ptr<Diskstream>
2443 Session::diskstream_by_id (const PBD::ID& id)
2445 boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
2447 for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
2448 if ((*i)->id() == id) {
2453 return boost::shared_ptr<Diskstream>((Diskstream*) 0);
2456 /* Region management */
2459 Session::new_region_name (string old)
2461 string::size_type last_period;
2463 string::size_type len = old.length() + 64;
2466 if ((last_period = old.find_last_of ('.')) == string::npos) {
2468 /* no period present - add one explicitly */
2471 last_period = old.length() - 1;
2476 number = atoi (old.substr (last_period+1).c_str());
2480 while (number < (UINT_MAX-1)) {
2482 RegionList::const_iterator i;
2487 snprintf (buf, len, "%s%" PRIu32, old.substr (0, last_period + 1).c_str(), number);
2490 for (i = regions.begin(); i != regions.end(); ++i) {
2491 if (i->second->name() == sbuf) {
2496 if (i == regions.end()) {
2501 if (number != (UINT_MAX-1)) {
2505 error << string_compose (_("cannot create new name for region \"%1\""), old) << endmsg;
2510 Session::region_name (string& result, string base, bool newlevel) const
2515 assert(base.find("/") == string::npos);
2519 Glib::Mutex::Lock lm (region_lock);
2521 snprintf (buf, sizeof (buf), "%d", (int)regions.size() + 1);
2529 /* XXX this is going to be slow. optimize me later */
2534 string::size_type pos;
2536 pos = base.find_last_of ('.');
2538 /* pos may be npos, but then we just use entire base */
2540 subbase = base.substr (0, pos);
2544 bool name_taken = true;
2547 Glib::Mutex::Lock lm (region_lock);
2549 for (int n = 1; n < 5000; ++n) {
2552 snprintf (buf, sizeof (buf), ".%d", n);
2557 for (RegionList::const_iterator i = regions.begin(); i != regions.end(); ++i) {
2558 if (i->second->name() == result) {
2571 fatal << string_compose(_("too many regions with names like %1"), base) << endmsg;
2579 Session::add_region (boost::shared_ptr<Region> region)
2581 vector<boost::shared_ptr<Region> > v;
2582 v.push_back (region);
2587 Session::add_regions (vector<boost::shared_ptr<Region> >& new_regions)
2592 Glib::Mutex::Lock lm (region_lock);
2594 for (vector<boost::shared_ptr<Region> >::iterator ii = new_regions.begin(); ii != new_regions.end(); ++ii) {
2596 boost::shared_ptr<Region> region = *ii;
2600 error << _("Session::add_region() ignored a null region. Warning: you might have lost a region.") << endmsg;
2604 RegionList::iterator x;
2606 for (x = regions.begin(); x != regions.end(); ++x) {
2608 if (region->region_list_equivalent (x->second)) {
2613 if (x == regions.end()) {
2615 pair<RegionList::key_type,RegionList::mapped_type> entry;
2617 entry.first = region->id();
2618 entry.second = region;
2620 pair<RegionList::iterator,bool> x = regions.insert (entry);
2632 /* mark dirty because something has changed even if we didn't
2633 add the region to the region list.
2640 vector<boost::weak_ptr<Region> > v;
2641 boost::shared_ptr<Region> first_r;
2643 for (vector<boost::shared_ptr<Region> >::iterator ii = new_regions.begin(); ii != new_regions.end(); ++ii) {
2645 boost::shared_ptr<Region> region = *ii;
2649 error << _("Session::add_region() ignored a null region. Warning: you might have lost a region.") << endmsg;
2652 v.push_back (region);
2659 region->StateChanged.connect (sigc::bind (mem_fun (*this, &Session::region_changed), boost::weak_ptr<Region>(region)));
2660 region->GoingAway.connect (sigc::bind (mem_fun (*this, &Session::remove_region), boost::weak_ptr<Region>(region)));
2664 RegionsAdded (v); /* EMIT SIGNAL */
2670 Session::region_changed (Change what_changed, boost::weak_ptr<Region> weak_region)
2672 boost::shared_ptr<Region> region (weak_region.lock ());
2678 if (what_changed & Region::HiddenChanged) {
2679 /* relay hidden changes */
2680 RegionHiddenChange (region);
2685 Session::remove_region (boost::weak_ptr<Region> weak_region)
2687 RegionList::iterator i;
2688 boost::shared_ptr<Region> region (weak_region.lock ());
2694 bool removed = false;
2697 Glib::Mutex::Lock lm (region_lock);
2699 if ((i = regions.find (region->id())) != regions.end()) {
2705 /* mark dirty because something has changed even if we didn't
2706 remove the region from the region list.
2712 RegionRemoved(region); /* EMIT SIGNAL */
2716 boost::shared_ptr<Region>
2717 Session::find_whole_file_parent (boost::shared_ptr<Region const> child)
2719 RegionList::iterator i;
2720 boost::shared_ptr<Region> region;
2722 Glib::Mutex::Lock lm (region_lock);
2724 for (i = regions.begin(); i != regions.end(); ++i) {
2728 if (region->whole_file()) {
2730 if (child->source_equivalent (region)) {
2736 return boost::shared_ptr<Region> ();
2740 Session::find_equivalent_playlist_regions (boost::shared_ptr<Region> region, vector<boost::shared_ptr<Region> >& result)
2742 for (PlaylistList::iterator i = playlists.begin(); i != playlists.end(); ++i)
2743 (*i)->get_region_list_equivalent_regions (region, result);
2747 Session::destroy_region (boost::shared_ptr<Region> region)
2749 vector<boost::shared_ptr<Source> > srcs;
2752 if (region->playlist()) {
2753 region->playlist()->destroy_region (region);
2756 for (uint32_t n = 0; n < region->n_channels(); ++n) {
2757 srcs.push_back (region->source (n));
2761 region->drop_references ();
2763 for (vector<boost::shared_ptr<Source> >::iterator i = srcs.begin(); i != srcs.end(); ++i) {
2765 (*i)->mark_for_remove ();
2766 (*i)->drop_references ();
2768 cerr << "source was not used by any playlist\n";
2775 Session::destroy_regions (list<boost::shared_ptr<Region> > regions)
2777 for (list<boost::shared_ptr<Region> >::iterator i = regions.begin(); i != regions.end(); ++i) {
2778 destroy_region (*i);
2784 Session::remove_last_capture ()
2786 list<boost::shared_ptr<Region> > r;
2788 boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
2790 for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
2791 list<boost::shared_ptr<Region> >& l = (*i)->last_capture_regions();
2794 r.insert (r.end(), l.begin(), l.end());
2799 destroy_regions (r);
2801 save_state (_current_snapshot_name);
2807 Session::remove_region_from_region_list (boost::shared_ptr<Region> r)
2813 /* Source Management */
2815 Session::add_source (boost::shared_ptr<Source> source)
2817 pair<SourceMap::key_type, SourceMap::mapped_type> entry;
2818 pair<SourceMap::iterator,bool> result;
2820 entry.first = source->id();
2821 entry.second = source;
2824 Glib::Mutex::Lock lm (source_lock);
2825 result = sources.insert (entry);
2828 if (result.second) {
2829 source->GoingAway.connect (sigc::bind (mem_fun (this, &Session::remove_source), boost::weak_ptr<Source> (source)));
2833 boost::shared_ptr<AudioFileSource> afs;
2835 if ((afs = boost::dynamic_pointer_cast<AudioFileSource>(source)) != 0) {
2836 if (Config->get_auto_analyse_audio()) {
2837 Analyser::queue_source_for_analysis (source, false);
2843 Session::remove_source (boost::weak_ptr<Source> src)
2845 SourceMap::iterator i;
2846 boost::shared_ptr<Source> source = src.lock();
2853 Glib::Mutex::Lock lm (source_lock);
2855 if ((i = sources.find (source->id())) != sources.end()) {
2860 if (!_state_of_the_state & InCleanup) {
2862 /* save state so we don't end up with a session file
2863 referring to non-existent sources.
2866 save_state (_current_snapshot_name);
2870 boost::shared_ptr<Source>
2871 Session::source_by_id (const PBD::ID& id)
2873 Glib::Mutex::Lock lm (source_lock);
2874 SourceMap::iterator i;
2875 boost::shared_ptr<Source> source;
2877 if ((i = sources.find (id)) != sources.end()) {
2885 boost::shared_ptr<Source>
2886 Session::source_by_path_and_channel (const Glib::ustring& path, uint16_t chn)
2888 Glib::Mutex::Lock lm (source_lock);
2890 for (SourceMap::iterator i = sources.begin(); i != sources.end(); ++i) {
2891 cerr << "comparing " << path << " with " << i->second->name() << endl;
2892 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(i->second);
2894 if (afs && afs->path() == path && chn == afs->channel()) {
2899 return boost::shared_ptr<Source>();
2903 Session::peak_path (Glib::ustring base) const
2905 sys::path peakfile_path(_session_dir->peak_path());
2906 peakfile_path /= basename_nosuffix (base) + peakfile_suffix;
2907 return peakfile_path.to_string();
2911 Session::change_audio_path_by_name (string path, string oldname, string newname, bool destructive)
2914 string old_basename = PBD::basename_nosuffix (oldname);
2915 string new_legalized = legalize_for_path (newname);
2917 /* note: we know (or assume) the old path is already valid */
2921 /* destructive file sources have a name of the form:
2923 /path/to/Tnnnn-NAME(%[LR])?.wav
2925 the task here is to replace NAME with the new name.
2928 /* find last slash */
2932 string::size_type slash;
2933 string::size_type dash;
2935 if ((slash = path.find_last_of ('/')) == string::npos) {
2939 dir = path.substr (0, slash+1);
2941 /* '-' is not a legal character for the NAME part of the path */
2943 if ((dash = path.find_last_of ('-')) == string::npos) {
2947 prefix = path.substr (slash+1, dash-(slash+1));
2952 path += new_legalized;
2953 path += ".wav"; /* XXX gag me with a spoon */
2957 /* non-destructive file sources have a name of the form:
2959 /path/to/NAME-nnnnn(%[LR])?.wav
2961 the task here is to replace NAME with the new name.
2966 string::size_type slash;
2967 string::size_type dash;
2968 string::size_type postfix;
2970 /* find last slash */
2972 if ((slash = path.find_last_of ('/')) == string::npos) {
2976 dir = path.substr (0, slash+1);
2978 /* '-' is not a legal character for the NAME part of the path */
2980 if ((dash = path.find_last_of ('-')) == string::npos) {
2984 suffix = path.substr (dash+1);
2986 // Suffix is now everything after the dash. Now we need to eliminate
2987 // the nnnnn part, which is done by either finding a '%' or a '.'
2989 postfix = suffix.find_last_of ("%");
2990 if (postfix == string::npos) {
2991 postfix = suffix.find_last_of ('.');
2994 if (postfix != string::npos) {
2995 suffix = suffix.substr (postfix);
2997 error << "Logic error in Session::change_audio_path_by_name(), please report to the developers" << endl;
3001 const uint32_t limit = 10000;
3002 char buf[PATH_MAX+1];
3004 for (uint32_t cnt = 1; cnt <= limit; ++cnt) {
3006 snprintf (buf, sizeof(buf), "%s%s-%u%s", dir.c_str(), newname.c_str(), cnt, suffix.c_str());
3008 if (access (buf, F_OK) != 0) {
3016 error << "FATAL ERROR! Could not find a " << endl;
3025 Session::audio_path_from_name (string name, uint32_t nchan, uint32_t chan, bool destructive)
3029 char buf[PATH_MAX+1];
3030 const uint32_t limit = 10000;
3034 legalized = legalize_for_path (name);
3036 /* find a "version" of the file name that doesn't exist in
3037 any of the possible directories.
3040 for (cnt = (destructive ? ++destructive_index : 1); cnt <= limit; ++cnt) {
3042 vector<space_and_path>::iterator i;
3043 uint32_t existing = 0;
3045 for (i = session_dirs.begin(); i != session_dirs.end(); ++i) {
3047 SessionDirectory sdir((*i).path);
3049 spath = sdir.sound_path().to_string();
3053 snprintf (buf, sizeof(buf), "%s/T%04d-%s.wav", spath.c_str(), cnt, legalized.c_str());
3054 } else if (nchan == 2) {
3056 snprintf (buf, sizeof(buf), "%s/T%04d-%s%%L.wav", spath.c_str(), cnt, legalized.c_str());
3058 snprintf (buf, sizeof(buf), "%s/T%04d-%s%%R.wav", spath.c_str(), cnt, legalized.c_str());
3060 } else if (nchan < 26) {
3061 snprintf (buf, sizeof(buf), "%s/T%04d-%s%%%c.wav", spath.c_str(), cnt, legalized.c_str(), 'a' + chan);
3063 snprintf (buf, sizeof(buf), "%s/T%04d-%s.wav", spath.c_str(), cnt, legalized.c_str());
3072 snprintf (buf, sizeof(buf), "%s-%u.wav", spath.c_str(), cnt);
3073 } else if (nchan == 2) {
3075 snprintf (buf, sizeof(buf), "%s-%u%%L.wav", spath.c_str(), cnt);
3077 snprintf (buf, sizeof(buf), "%s-%u%%R.wav", spath.c_str(), cnt);
3079 } else if (nchan < 26) {
3080 snprintf (buf, sizeof(buf), "%s-%u%%%c.wav", spath.c_str(), cnt, 'a' + chan);
3082 snprintf (buf, sizeof(buf), "%s-%u.wav", spath.c_str(), cnt);
3086 if (sys::exists(buf)) {
3092 if (existing == 0) {
3097 error << string_compose(_("There are already %1 recordings for %2, which I consider too many."), limit, name) << endmsg;
3099 throw failed_constructor();
3103 /* we now have a unique name for the file, but figure out where to
3109 SessionDirectory sdir(get_best_session_directory_for_new_source ());
3111 spath = sdir.sound_path().to_string();
3114 string::size_type pos = foo.find_last_of ('/');
3116 if (pos == string::npos) {
3119 spath += foo.substr (pos + 1);
3125 boost::shared_ptr<AudioFileSource>
3126 Session::create_audio_source_for_session (AudioDiskstream& ds, uint32_t chan, bool destructive)
3128 string spath = audio_path_from_name (ds.name(), ds.n_channels().n_audio(), chan, destructive);
3129 return boost::dynamic_pointer_cast<AudioFileSource> (
3130 SourceFactory::createWritable (DataType::AUDIO, *this, spath, destructive, frame_rate()));
3133 // FIXME: _terrible_ code duplication
3135 Session::change_midi_path_by_name (string path, string oldname, string newname, bool destructive)
3138 string old_basename = PBD::basename_nosuffix (oldname);
3139 string new_legalized = legalize_for_path (newname);
3141 /* note: we know (or assume) the old path is already valid */
3145 /* destructive file sources have a name of the form:
3147 /path/to/Tnnnn-NAME(%[LR])?.wav
3149 the task here is to replace NAME with the new name.
3152 /* find last slash */
3156 string::size_type slash;
3157 string::size_type dash;
3159 if ((slash = path.find_last_of ('/')) == string::npos) {
3163 dir = path.substr (0, slash+1);
3165 /* '-' is not a legal character for the NAME part of the path */
3167 if ((dash = path.find_last_of ('-')) == string::npos) {
3171 prefix = path.substr (slash+1, dash-(slash+1));
3176 path += new_legalized;
3177 path += ".mid"; /* XXX gag me with a spoon */
3181 /* non-destructive file sources have a name of the form:
3183 /path/to/NAME-nnnnn(%[LR])?.wav
3185 the task here is to replace NAME with the new name.
3190 string::size_type slash;
3191 string::size_type dash;
3192 string::size_type postfix;
3194 /* find last slash */
3196 if ((slash = path.find_last_of ('/')) == string::npos) {
3200 dir = path.substr (0, slash+1);
3202 /* '-' is not a legal character for the NAME part of the path */
3204 if ((dash = path.find_last_of ('-')) == string::npos) {
3208 suffix = path.substr (dash+1);
3210 // Suffix is now everything after the dash. Now we need to eliminate
3211 // the nnnnn part, which is done by either finding a '%' or a '.'
3213 postfix = suffix.find_last_of ("%");
3214 if (postfix == string::npos) {
3215 postfix = suffix.find_last_of ('.');
3218 if (postfix != string::npos) {
3219 suffix = suffix.substr (postfix);
3221 error << "Logic error in Session::change_midi_path_by_name(), please report to the developers" << endl;
3225 const uint32_t limit = 10000;
3226 char buf[PATH_MAX+1];
3228 for (uint32_t cnt = 1; cnt <= limit; ++cnt) {
3230 snprintf (buf, sizeof(buf), "%s%s-%u%s", dir.c_str(), newname.c_str(), cnt, suffix.c_str());
3232 if (access (buf, F_OK) != 0) {
3240 error << "FATAL ERROR! Could not find a " << endl;
3249 Session::midi_path_from_name (string name)
3253 char buf[PATH_MAX+1];
3254 const uint32_t limit = 10000;
3258 legalized = legalize_for_path (name);
3260 /* find a "version" of the file name that doesn't exist in
3261 any of the possible directories.
3264 for (cnt = 1; cnt <= limit; ++cnt) {
3266 vector<space_and_path>::iterator i;
3267 uint32_t existing = 0;
3269 for (i = session_dirs.begin(); i != session_dirs.end(); ++i) {
3271 SessionDirectory sdir((*i).path);
3273 sys::path p = sdir.midi_path();
3277 spath = p.to_string();
3279 snprintf (buf, sizeof(buf), "%s-%u.mid", spath.c_str(), cnt);
3281 if (sys::exists (buf)) {
3286 if (existing == 0) {
3291 error << string_compose(_("There are already %1 recordings for %2, which I consider too many."), limit, name) << endmsg;
3292 throw failed_constructor();
3296 /* we now have a unique name for the file, but figure out where to
3302 SessionDirectory sdir(get_best_session_directory_for_new_source ());
3304 spath = sdir.midi_path().to_string();
3307 string::size_type pos = foo.find_last_of ('/');
3309 if (pos == string::npos) {
3312 spath += foo.substr (pos + 1);
3318 boost::shared_ptr<MidiSource>
3319 Session::create_midi_source_for_session (MidiDiskstream& ds)
3321 string mpath = midi_path_from_name (ds.name());
3323 return boost::dynamic_pointer_cast<SMFSource> (SourceFactory::createWritable (DataType::MIDI, *this, mpath, false, frame_rate()));
3327 /* Playlist management */
3329 boost::shared_ptr<Playlist>
3330 Session::playlist_by_name (string name)
3332 Glib::Mutex::Lock lm (playlist_lock);
3333 for (PlaylistList::iterator i = playlists.begin(); i != playlists.end(); ++i) {
3334 if ((*i)->name() == name) {
3338 for (PlaylistList::iterator i = unused_playlists.begin(); i != unused_playlists.end(); ++i) {
3339 if ((*i)->name() == name) {
3344 return boost::shared_ptr<Playlist>();
3348 Session::add_playlist (boost::shared_ptr<Playlist> playlist)
3350 if (playlist->hidden()) {
3355 Glib::Mutex::Lock lm (playlist_lock);
3356 if (find (playlists.begin(), playlists.end(), playlist) == playlists.end()) {
3357 playlists.insert (playlists.begin(), playlist);
3358 playlist->InUse.connect (sigc::bind (mem_fun (*this, &Session::track_playlist), boost::weak_ptr<Playlist>(playlist)));
3359 playlist->GoingAway.connect (sigc::bind (mem_fun (*this, &Session::remove_playlist), boost::weak_ptr<Playlist>(playlist)));
3365 PlaylistAdded (playlist); /* EMIT SIGNAL */
3369 Session::get_playlists (vector<boost::shared_ptr<Playlist> >& s)
3372 Glib::Mutex::Lock lm (playlist_lock);
3373 for (PlaylistList::iterator i = playlists.begin(); i != playlists.end(); ++i) {
3376 for (PlaylistList::iterator i = unused_playlists.begin(); i != unused_playlists.end(); ++i) {
3383 Session::track_playlist (bool inuse, boost::weak_ptr<Playlist> wpl)
3385 boost::shared_ptr<Playlist> pl(wpl.lock());
3391 PlaylistList::iterator x;
3394 /* its not supposed to be visible */
3399 Glib::Mutex::Lock lm (playlist_lock);
3403 unused_playlists.insert (pl);
3405 if ((x = playlists.find (pl)) != playlists.end()) {
3406 playlists.erase (x);
3412 playlists.insert (pl);
3414 if ((x = unused_playlists.find (pl)) != unused_playlists.end()) {
3415 unused_playlists.erase (x);
3422 Session::remove_playlist (boost::weak_ptr<Playlist> weak_playlist)
3424 if (_state_of_the_state & Deletion) {
3428 boost::shared_ptr<Playlist> playlist (weak_playlist.lock());
3435 Glib::Mutex::Lock lm (playlist_lock);
3437 PlaylistList::iterator i;
3439 i = find (playlists.begin(), playlists.end(), playlist);
3440 if (i != playlists.end()) {
3441 playlists.erase (i);
3444 i = find (unused_playlists.begin(), unused_playlists.end(), playlist);
3445 if (i != unused_playlists.end()) {
3446 unused_playlists.erase (i);
3453 PlaylistRemoved (playlist); /* EMIT SIGNAL */
3457 Session::set_audition (boost::shared_ptr<Region> r)
3459 pending_audition_region = r;
3460 post_transport_work = PostTransportWork (post_transport_work | PostTransportAudition);
3461 schedule_butler_transport_work ();
3465 Session::audition_playlist ()
3467 Event* ev = new Event (Event::Audition, Event::Add, Event::Immediate, 0, 0.0);
3468 ev->region.reset ();
3473 Session::non_realtime_set_audition ()
3475 if (!pending_audition_region) {
3476 auditioner->audition_current_playlist ();
3478 auditioner->audition_region (pending_audition_region);
3479 pending_audition_region.reset ();
3481 AuditionActive (true); /* EMIT SIGNAL */
3485 Session::audition_region (boost::shared_ptr<Region> r)
3487 Event* ev = new Event (Event::Audition, Event::Add, Event::Immediate, 0, 0.0);
3493 Session::cancel_audition ()
3495 if (auditioner->active()) {
3496 auditioner->cancel_audition ();
3497 AuditionActive (false); /* EMIT SIGNAL */
3502 Session::RoutePublicOrderSorter::operator() (boost::shared_ptr<Route> a, boost::shared_ptr<Route> b)
3504 return a->order_key(N_("signal")) < b->order_key(N_("signal"));
3508 Session::remove_empty_sounds ()
3510 vector<string> audio_filenames;
3512 get_files_in_directory (_session_dir->sound_path(), audio_filenames);
3514 Glib::Mutex::Lock lm (source_lock);
3516 TapeFileMatcher tape_file_matcher;
3518 remove_if (audio_filenames.begin(), audio_filenames.end(),
3519 sigc::mem_fun (tape_file_matcher, &TapeFileMatcher::matches));
3521 for (vector<string>::iterator i = audio_filenames.begin(); i != audio_filenames.end(); ++i) {
3523 sys::path audio_file_path (_session_dir->sound_path());
3525 audio_file_path /= *i;
3527 if (AudioFileSource::is_empty (*this, audio_file_path.to_string())) {
3531 sys::remove (audio_file_path);
3532 const string peakfile = peak_path (audio_file_path.to_string());
3533 sys::remove (peakfile);
3535 catch (const sys::filesystem_error& err)
3537 error << err.what() << endmsg;
3544 Session::is_auditioning () const
3546 /* can be called before we have an auditioner object */
3548 return auditioner->active();
3555 Session::set_all_solo (bool yn)
3557 shared_ptr<RouteList> r = routes.reader ();
3559 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3560 if (!(*i)->is_hidden()) {
3561 (*i)->set_solo (yn, this);
3569 Session::set_all_mute (bool yn)
3571 shared_ptr<RouteList> r = routes.reader ();
3573 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3574 if (!(*i)->is_hidden()) {
3575 (*i)->set_mute (yn, this);
3583 Session::n_diskstreams () const
3587 boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
3589 for (DiskstreamList::const_iterator i = dsl->begin(); i != dsl->end(); ++i) {
3590 if (!(*i)->hidden()) {
3598 Session::graph_reordered ()
3600 /* don't do this stuff if we are setting up connections
3601 from a set_state() call or creating new tracks.
3604 if (_state_of_the_state & InitialConnecting) {
3608 /* every track/bus asked for this to be handled but it was deferred because
3609 we were connecting. do it now.
3612 request_input_change_handling ();
3616 /* force all diskstreams to update their capture offset values to
3617 reflect any changes in latencies within the graph.
3620 boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
3622 for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
3623 (*i)->set_capture_offset ();
3628 Session::record_disenable_all ()
3630 record_enable_change_all (false);
3634 Session::record_enable_all ()
3636 record_enable_change_all (true);
3640 Session::record_enable_change_all (bool yn)
3642 shared_ptr<RouteList> r = routes.reader ();
3644 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3647 if ((at = dynamic_cast<Track*>((*i).get())) != 0) {
3648 at->set_record_enable (yn, this);
3652 /* since we don't keep rec-enable state, don't mark session dirty */
3656 Session::add_processor (Processor* processor)
3659 PortInsert* port_insert;
3660 PluginInsert* plugin_insert;
3662 if ((port_insert = dynamic_cast<PortInsert *> (processor)) != 0) {
3663 _port_inserts.insert (_port_inserts.begin(), port_insert);
3664 } else if ((plugin_insert = dynamic_cast<PluginInsert *> (processor)) != 0) {
3665 _plugin_inserts.insert (_plugin_inserts.begin(), plugin_insert);
3666 } else if ((send = dynamic_cast<Send *> (processor)) != 0) {
3667 _sends.insert (_sends.begin(), send);
3669 fatal << _("programming error: unknown type of Insert created!") << endmsg;
3673 processor->GoingAway.connect (sigc::bind (mem_fun (*this, &Session::remove_processor), processor));
3679 Session::remove_processor (Processor* processor)
3682 PortInsert* port_insert;
3683 PluginInsert* plugin_insert;
3685 if ((port_insert = dynamic_cast<PortInsert *> (processor)) != 0) {
3686 list<PortInsert*>::iterator x = find (_port_inserts.begin(), _port_inserts.end(), port_insert);
3687 if (x != _port_inserts.end()) {
3688 insert_bitset[port_insert->bit_slot()] = false;
3689 _port_inserts.erase (x);
3691 } else if ((plugin_insert = dynamic_cast<PluginInsert *> (processor)) != 0) {
3692 _plugin_inserts.remove (plugin_insert);
3693 } else if ((send = dynamic_cast<Send *> (processor)) != 0) {
3694 list<Send*>::iterator x = find (_sends.begin(), _sends.end(), send);
3695 if (x != _sends.end()) {
3696 send_bitset[send->bit_slot()] = false;
3700 fatal << _("programming error: unknown type of Insert deleted!") << endmsg;
3708 Session::available_capture_duration ()
3710 float sample_bytes_on_disk = 4.0; // keep gcc happy
3712 switch (Config->get_native_file_data_format()) {
3714 sample_bytes_on_disk = 4.0;
3718 sample_bytes_on_disk = 3.0;
3722 sample_bytes_on_disk = 2.0;
3726 /* impossible, but keep some gcc versions happy */
3727 fatal << string_compose (_("programming error: %1"),
3728 X_("illegal native file data format"))
3733 double scale = 4096.0 / sample_bytes_on_disk;
3735 if (_total_free_4k_blocks * scale > (double) max_frames) {
3739 return (nframes_t) floor (_total_free_4k_blocks * scale);
3743 Session::add_bundle (shared_ptr<Bundle> bundle)
3746 Glib::Mutex::Lock guard (bundle_lock);
3747 _bundles.push_back (bundle);
3750 BundleAdded (bundle); /* EMIT SIGNAL */
3756 Session::remove_bundle (shared_ptr<Bundle> bundle)
3758 bool removed = false;
3761 Glib::Mutex::Lock guard (bundle_lock);
3762 BundleList::iterator i = find (_bundles.begin(), _bundles.end(), bundle);
3764 if (i != _bundles.end()) {
3771 BundleRemoved (bundle); /* EMIT SIGNAL */
3778 Session::bundle_by_name (string name) const
3780 Glib::Mutex::Lock lm (bundle_lock);
3782 for (BundleList::const_iterator i = _bundles.begin(); i != _bundles.end(); ++i) {
3783 if ((*i)->name() == name) {
3788 return boost::shared_ptr<Bundle> ();
3792 Session::tempo_map_changed (Change ignored)
3796 for (PlaylistList::iterator i = playlists.begin(); i != playlists.end(); ++i) {
3797 (*i)->update_after_tempo_map_change ();
3800 for (PlaylistList::iterator i = unused_playlists.begin(); i != unused_playlists.end(); ++i) {
3801 (*i)->update_after_tempo_map_change ();
3807 /** Ensures that all buffers (scratch, send, silent, etc) are allocated for
3808 * the given count with the current block size.
3811 Session::ensure_buffers (ChanCount howmany)
3813 if (current_block_size == 0)
3814 return; // too early? (is this ok?)
3816 // We need at least 2 MIDI scratch buffers to mix/merge
3817 if (howmany.n_midi() < 2)
3818 howmany.set_midi(2);
3820 // FIXME: JACK needs to tell us maximum MIDI buffer size
3821 // Using nasty assumption (max # events == nframes) for now
3822 _scratch_buffers->ensure_buffers(howmany, current_block_size);
3823 _mix_buffers->ensure_buffers(howmany, current_block_size);
3824 _silent_buffers->ensure_buffers(howmany, current_block_size);
3826 allocate_pan_automation_buffers (current_block_size, howmany.n_audio(), false);
3830 Session::next_insert_id ()
3832 /* this doesn't really loop forever. just think about it */
3835 for (boost::dynamic_bitset<uint32_t>::size_type n = 0; n < insert_bitset.size(); ++n) {
3836 if (!insert_bitset[n]) {
3837 insert_bitset[n] = true;
3843 /* none available, so resize and try again */
3845 insert_bitset.resize (insert_bitset.size() + 16, false);
3850 Session::next_send_id ()
3852 /* this doesn't really loop forever. just think about it */
3855 for (boost::dynamic_bitset<uint32_t>::size_type n = 0; n < send_bitset.size(); ++n) {
3856 if (!send_bitset[n]) {
3857 send_bitset[n] = true;
3863 /* none available, so resize and try again */
3865 send_bitset.resize (send_bitset.size() + 16, false);
3870 Session::mark_send_id (uint32_t id)
3872 if (id >= send_bitset.size()) {
3873 send_bitset.resize (id+16, false);
3875 if (send_bitset[id]) {
3876 warning << string_compose (_("send ID %1 appears to be in use already"), id) << endmsg;
3878 send_bitset[id] = true;
3882 Session::mark_insert_id (uint32_t id)
3884 if (id >= insert_bitset.size()) {
3885 insert_bitset.resize (id+16, false);
3887 if (insert_bitset[id]) {
3888 warning << string_compose (_("insert ID %1 appears to be in use already"), id) << endmsg;
3890 insert_bitset[id] = true;
3893 /* Named Selection management */
3896 Session::named_selection_by_name (string name)
3898 Glib::Mutex::Lock lm (named_selection_lock);
3899 for (NamedSelectionList::iterator i = named_selections.begin(); i != named_selections.end(); ++i) {
3900 if ((*i)->name == name) {
3908 Session::add_named_selection (NamedSelection* named_selection)
3911 Glib::Mutex::Lock lm (named_selection_lock);
3912 named_selections.insert (named_selections.begin(), named_selection);
3915 for (list<boost::shared_ptr<Playlist> >::iterator i = named_selection->playlists.begin(); i != named_selection->playlists.end(); ++i) {
3921 NamedSelectionAdded (); /* EMIT SIGNAL */
3925 Session::remove_named_selection (NamedSelection* named_selection)
3927 bool removed = false;
3930 Glib::Mutex::Lock lm (named_selection_lock);
3932 NamedSelectionList::iterator i = find (named_selections.begin(), named_selections.end(), named_selection);
3934 if (i != named_selections.end()) {
3936 named_selections.erase (i);
3943 NamedSelectionRemoved (); /* EMIT SIGNAL */
3948 Session::reset_native_file_format ()
3950 boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
3952 for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
3953 (*i)->reset_write_sources (false);
3958 Session::route_name_unique (string n) const
3960 shared_ptr<RouteList> r = routes.reader ();
3962 for (RouteList::const_iterator i = r->begin(); i != r->end(); ++i) {
3963 if ((*i)->name() == n) {
3972 Session::n_playlists () const
3974 Glib::Mutex::Lock lm (playlist_lock);
3975 return playlists.size();
3979 Session::allocate_pan_automation_buffers (nframes_t nframes, uint32_t howmany, bool force)
3981 if (!force && howmany <= _npan_buffers) {
3985 if (_pan_automation_buffer) {
3987 for (uint32_t i = 0; i < _npan_buffers; ++i) {
3988 delete [] _pan_automation_buffer[i];
3991 delete [] _pan_automation_buffer;
3994 _pan_automation_buffer = new pan_t*[howmany];
3996 for (uint32_t i = 0; i < howmany; ++i) {
3997 _pan_automation_buffer[i] = new pan_t[nframes];
4000 _npan_buffers = howmany;
4004 Session::freeze (InterThreadInfo& itt)
4006 shared_ptr<RouteList> r = routes.reader ();
4008 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4012 if ((at = dynamic_cast<Track*>((*i).get())) != 0) {
4013 /* XXX this is wrong because itt.progress will keep returning to zero at the start
4024 Session::write_one_audio_track (AudioTrack& track, nframes_t start, nframes_t len,
4025 bool overwrite, vector<boost::shared_ptr<Source> >& srcs, InterThreadInfo& itt)
4028 boost::shared_ptr<Playlist> playlist;
4029 boost::shared_ptr<AudioFileSource> fsource;
4031 char buf[PATH_MAX+1];
4032 ChanCount nchans(track.audio_diskstream()->n_channels());
4034 nframes_t this_chunk;
4037 SessionDirectory sdir(get_best_session_directory_for_new_source ());
4038 const string sound_dir = sdir.sound_path().to_string();
4040 // any bigger than this seems to cause stack overflows in called functions
4041 const nframes_t chunk_size = (128 * 1024)/4;
4043 g_atomic_int_set (&processing_prohibited, 1);
4045 /* call tree *MUST* hold route_lock */
4047 if ((playlist = track.diskstream()->playlist()) == 0) {
4051 /* external redirects will be a problem */
4053 if (track.has_external_redirects()) {
4057 for (uint32_t chan_n=0; chan_n < nchans.n_audio(); ++chan_n) {
4059 for (x = 0; x < 99999; ++x) {
4060 snprintf (buf, sizeof(buf), "%s/%s-%d-bounce-%" PRIu32 ".wav", sound_dir.c_str(), playlist->name().c_str(), chan_n, x+1);
4061 if (access (buf, F_OK) != 0) {
4067 error << string_compose (_("too many bounced versions of playlist \"%1\""), playlist->name()) << endmsg;
4072 fsource = boost::dynamic_pointer_cast<AudioFileSource> (
4073 SourceFactory::createWritable (DataType::AUDIO, *this, buf, false, frame_rate()));
4076 catch (failed_constructor& err) {
4077 error << string_compose (_("cannot create new audio file \"%1\" for %2"), buf, track.name()) << endmsg;
4081 srcs.push_back (fsource);
4084 /* XXX need to flush all redirects */
4089 /* create a set of reasonably-sized buffers */
4090 buffers.ensure_buffers(nchans, chunk_size);
4091 buffers.set_count(nchans);
4093 for (vector<boost::shared_ptr<Source> >::iterator src=srcs.begin(); src != srcs.end(); ++src) {
4094 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
4096 afs->prepare_for_peakfile_writes ();
4099 while (to_do && !itt.cancel) {
4101 this_chunk = min (to_do, chunk_size);
4103 if (track.export_stuff (buffers, start, this_chunk)) {
4108 for (vector<boost::shared_ptr<Source> >::iterator src=srcs.begin(); src != srcs.end(); ++src, ++n) {
4109 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
4112 if (afs->write (buffers.get_audio(n).data(), this_chunk) != this_chunk) {
4118 start += this_chunk;
4119 to_do -= this_chunk;
4121 itt.progress = (float) (1.0 - ((double) to_do / len));
4130 xnow = localtime (&now);
4132 for (vector<boost::shared_ptr<Source> >::iterator src=srcs.begin(); src != srcs.end(); ++src) {
4133 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
4136 afs->update_header (position, *xnow, now);
4137 afs->flush_header ();
4141 /* construct a region to represent the bounced material */
4143 boost::shared_ptr<Region> aregion = RegionFactory::create (srcs, 0, srcs.front()->length(),
4144 region_name_from_path (srcs.front()->name(), true));
4151 for (vector<boost::shared_ptr<Source> >::iterator src = srcs.begin(); src != srcs.end(); ++src) {
4152 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
4155 afs->mark_for_remove ();
4158 (*src)->drop_references ();
4162 for (vector<boost::shared_ptr<Source> >::iterator src = srcs.begin(); src != srcs.end(); ++src) {
4163 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
4166 afs->done_with_peakfile_writes ();
4170 g_atomic_int_set (&processing_prohibited, 0);
4176 Session::get_silent_buffers (ChanCount count)
4178 assert(_silent_buffers->available() >= count);
4179 _silent_buffers->set_count(count);
4181 for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
4182 for (size_t i= 0; i < count.get(*t); ++i) {
4183 _silent_buffers->get(*t, i).clear();
4187 return *_silent_buffers;
4191 Session::get_scratch_buffers (ChanCount count)
4193 assert(_scratch_buffers->available() >= count);
4194 _scratch_buffers->set_count(count);
4195 return *_scratch_buffers;
4199 Session::get_mix_buffers (ChanCount count)
4201 assert(_mix_buffers->available() >= count);
4202 _mix_buffers->set_count(count);
4203 return *_mix_buffers;
4207 Session::ntracks () const
4210 shared_ptr<RouteList> r = routes.reader ();
4212 for (RouteList::const_iterator i = r->begin(); i != r->end(); ++i) {
4213 if (dynamic_cast<Track*> ((*i).get())) {
4222 Session::nbusses () const
4225 shared_ptr<RouteList> r = routes.reader ();
4227 for (RouteList::const_iterator i = r->begin(); i != r->end(); ++i) {
4228 if (dynamic_cast<Track*> ((*i).get()) == 0) {
4237 Session::add_automation_list(AutomationList *al)
4239 automation_lists[al->id()] = al;
4243 Session::compute_initial_length ()
4245 return _engine.frame_rate() * 60 * 5;
4249 Session::sync_order_keys ()
4251 if (!Config->get_sync_all_route_ordering()) {
4252 /* leave order keys as they are */
4256 boost::shared_ptr<RouteList> r = routes.reader ();
4258 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4259 (*i)->sync_order_keys ();
4262 Route::SyncOrderKeys (); // EMIT SIGNAL
4266 Session::foreach_bundle (sigc::slot<void, boost::shared_ptr<Bundle> > sl)
4268 Glib::Mutex::Lock lm (bundle_lock);
4269 for (BundleList::iterator i = _bundles.begin(); i != _bundles.end(); ++i) {