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<int> Session::AskAboutPendingState;
111 sigc::signal<int,nframes_t,nframes_t> Session::AskAboutSampleRateMismatch;
112 sigc::signal<void> Session::SendFeedback;
114 sigc::signal<void> Session::SMPTEOffsetChanged;
115 sigc::signal<void> Session::StartTimeChanged;
116 sigc::signal<void> Session::EndTimeChanged;
118 Session::Session (AudioEngine &eng,
119 const string& fullpath,
120 const string& snapshot_name,
124 _scratch_buffers(new BufferSet()),
125 _silent_buffers(new BufferSet()),
126 _mix_buffers(new BufferSet()),
127 _mmc_port (default_mmc_port),
128 _mtc_port (default_mtc_port),
129 _midi_port (default_midi_port),
130 _session_dir (new SessionDirectory(fullpath)),
131 pending_events (2048),
132 //midi_requests (128), // the size of this should match the midi request pool size
133 post_transport_work((PostTransportWork)0),
134 _send_smpte_update (false),
135 diskstreams (new DiskstreamList),
136 routes (new RouteList),
137 auditioner ((Auditioner*) 0),
138 _bundle_xml_node (0),
144 if (!eng.connected()) {
145 throw failed_constructor();
148 cerr << "Loading session " << fullpath << " using snapshot " << snapshot_name << " (1)" << endl;
150 n_physical_outputs = _engine.n_physical_outputs();
151 n_physical_inputs = _engine.n_physical_inputs();
153 first_stage_init (fullpath, snapshot_name);
155 new_session = !Glib::file_test (_path, Glib::FileTest (G_FILE_TEST_EXISTS | G_FILE_TEST_IS_DIR));
158 if (create (new_session, mix_template, compute_initial_length())) {
160 throw failed_constructor ();
164 if (second_stage_init (new_session)) {
166 throw failed_constructor ();
169 store_recent_sessions(_name, _path);
171 bool was_dirty = dirty();
173 _state_of_the_state = StateOfTheState (_state_of_the_state & ~Dirty);
175 Config->ParameterChanged.connect (mem_fun (*this, &Session::config_changed));
178 DirtyChanged (); /* EMIT SIGNAL */
182 Session::Session (AudioEngine &eng,
184 string snapshot_name,
185 AutoConnectOption input_ac,
186 AutoConnectOption output_ac,
187 uint32_t control_out_channels,
188 uint32_t master_out_channels,
189 uint32_t requested_physical_in,
190 uint32_t requested_physical_out,
191 nframes_t initial_length)
194 _scratch_buffers(new BufferSet()),
195 _silent_buffers(new BufferSet()),
196 _mix_buffers(new BufferSet()),
197 _mmc_port (default_mmc_port),
198 _mtc_port (default_mtc_port),
199 _midi_port (default_midi_port),
200 _session_dir ( new SessionDirectory(fullpath)),
201 pending_events (2048),
202 //midi_requests (16),
203 _send_smpte_update (false),
204 diskstreams (new DiskstreamList),
205 routes (new RouteList),
206 _bundle_xml_node (0),
212 if (!eng.connected()) {
213 throw failed_constructor();
216 cerr << "Loading session " << fullpath << " using snapshot " << snapshot_name << " (2)" << endl;
218 n_physical_outputs = _engine.n_physical_outputs();
219 n_physical_inputs = _engine.n_physical_inputs();
221 if (n_physical_inputs) {
222 n_physical_inputs = max (requested_physical_in, n_physical_inputs);
225 if (n_physical_outputs) {
226 n_physical_outputs = max (requested_physical_out, n_physical_outputs);
229 first_stage_init (fullpath, snapshot_name);
231 new_session = !g_file_test (_path.c_str(), GFileTest (G_FILE_TEST_EXISTS | G_FILE_TEST_IS_DIR));
234 if (create (new_session, string(), initial_length)) {
236 throw failed_constructor ();
241 /* set up Master Out and Control Out if necessary */
246 if (control_out_channels) {
247 shared_ptr<Route> r (new Route (*this, _("monitor"), -1, control_out_channels, -1, control_out_channels, Route::ControlOut));
248 r->set_remote_control_id (control_id++);
253 if (master_out_channels) {
254 shared_ptr<Route> r (new Route (*this, _("master"), -1, master_out_channels, -1, master_out_channels, Route::MasterOut));
255 r->set_remote_control_id (control_id);
259 /* prohibit auto-connect to master, because there isn't one */
260 output_ac = AutoConnectOption (output_ac & ~AutoConnectMaster);
264 add_routes (rl, false);
269 Config->set_input_auto_connect (input_ac);
270 Config->set_output_auto_connect (output_ac);
272 if (second_stage_init (new_session)) {
274 throw failed_constructor ();
277 store_recent_sessions (_name, _path);
279 _state_of_the_state = StateOfTheState (_state_of_the_state & ~Dirty);
281 Config->ParameterChanged.connect (mem_fun (*this, &Session::config_changed));
292 /* if we got to here, leaving pending capture state around
296 remove_pending_capture_state ();
298 _state_of_the_state = StateOfTheState (CannotSave|Deletion);
300 _engine.remove_session ();
302 GoingAway (); /* EMIT SIGNAL */
308 /* clear history so that no references to objects are held any more */
312 /* clear state tree so that no references to objects are held any more */
318 terminate_butler_thread ();
319 //terminate_midi_thread ();
321 if (click_data && click_data != default_click) {
322 delete [] click_data;
325 if (click_emphasis_data && click_emphasis_data != default_click_emphasis) {
326 delete [] click_emphasis_data;
331 delete _scratch_buffers;
332 delete _silent_buffers;
335 AudioDiskstream::free_working_buffers();
337 Route::SyncOrderKeys.clear();
339 #undef TRACK_DESTRUCTION
340 #ifdef TRACK_DESTRUCTION
341 cerr << "delete named selections\n";
342 #endif /* TRACK_DESTRUCTION */
343 for (NamedSelectionList::iterator i = named_selections.begin(); i != named_selections.end(); ) {
344 NamedSelectionList::iterator tmp;
353 #ifdef TRACK_DESTRUCTION
354 cerr << "delete playlists\n";
355 #endif /* TRACK_DESTRUCTION */
356 for (PlaylistList::iterator i = playlists.begin(); i != playlists.end(); ) {
357 PlaylistList::iterator tmp;
362 (*i)->drop_references ();
367 for (PlaylistList::iterator i = unused_playlists.begin(); i != unused_playlists.end(); ) {
368 PlaylistList::iterator tmp;
373 (*i)->drop_references ();
379 unused_playlists.clear ();
381 #ifdef TRACK_DESTRUCTION
382 cerr << "delete regions\n";
383 #endif /* TRACK_DESTRUCTION */
385 for (RegionList::iterator i = regions.begin(); i != regions.end(); ) {
386 RegionList::iterator tmp;
391 i->second->drop_references ();
398 #ifdef TRACK_DESTRUCTION
399 cerr << "delete routes\n";
400 #endif /* TRACK_DESTRUCTION */
402 RCUWriter<RouteList> writer (routes);
403 boost::shared_ptr<RouteList> r = writer.get_copy ();
404 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
405 (*i)->drop_references ();
408 /* writer goes out of scope and updates master */
413 #ifdef TRACK_DESTRUCTION
414 cerr << "delete diskstreams\n";
415 #endif /* TRACK_DESTRUCTION */
417 RCUWriter<DiskstreamList> dwriter (diskstreams);
418 boost::shared_ptr<DiskstreamList> dsl = dwriter.get_copy();
419 for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
420 (*i)->drop_references ();
424 diskstreams.flush ();
426 #ifdef TRACK_DESTRUCTION
427 cerr << "delete audio sources\n";
428 #endif /* TRACK_DESTRUCTION */
429 for (SourceMap::iterator i = sources.begin(); i != sources.end(); ) {
430 SourceMap::iterator tmp;
435 i->second->drop_references ();
441 #ifdef TRACK_DESTRUCTION
442 cerr << "delete mix groups\n";
443 #endif /* TRACK_DESTRUCTION */
444 for (list<RouteGroup *>::iterator i = mix_groups.begin(); i != mix_groups.end(); ) {
445 list<RouteGroup*>::iterator tmp;
455 #ifdef TRACK_DESTRUCTION
456 cerr << "delete edit groups\n";
457 #endif /* TRACK_DESTRUCTION */
458 for (list<RouteGroup *>::iterator i = edit_groups.begin(); i != edit_groups.end(); ) {
459 list<RouteGroup*>::iterator tmp;
469 if (butler_mixdown_buffer) {
470 delete [] butler_mixdown_buffer;
473 if (butler_gain_buffer) {
474 delete [] butler_gain_buffer;
477 Crossfade::set_buffer_size (0);
485 Session::set_worst_io_latencies ()
487 _worst_output_latency = 0;
488 _worst_input_latency = 0;
490 if (!_engine.connected()) {
494 boost::shared_ptr<RouteList> r = routes.reader ();
496 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
497 _worst_output_latency = max (_worst_output_latency, (*i)->output_latency());
498 _worst_input_latency = max (_worst_input_latency, (*i)->input_latency());
503 Session::when_engine_running ()
505 string first_physical_output;
507 /* we don't want to run execute this again */
509 BootMessage (_("Set block size and sample rate"));
511 set_block_size (_engine.frames_per_cycle());
512 set_frame_rate (_engine.frame_rate());
514 BootMessage (_("Using configuration"));
516 Config->map_parameters (mem_fun (*this, &Session::config_changed));
518 /* every time we reconnect, recompute worst case output latencies */
520 _engine.Running.connect (mem_fun (*this, &Session::set_worst_io_latencies));
522 if (synced_to_jack()) {
523 _engine.transport_stop ();
526 if (Config->get_jack_time_master()) {
527 _engine.transport_locate (_transport_frame);
535 _click_io.reset (new ClickIO (*this, "click", 0, 0, -1, -1));
537 if (state_tree && (child = find_named_node (*state_tree->root(), "Click")) != 0) {
539 /* existing state for Click */
541 if (_click_io->set_state (*child->children().front()) == 0) {
543 _clicking = Config->get_clicking ();
547 error << _("could not setup Click I/O") << endmsg;
553 /* default state for Click */
555 first_physical_output = _engine.get_nth_physical_output (DataType::AUDIO, 0);
557 if (first_physical_output.length()) {
558 if (_click_io->add_output_port (first_physical_output, this)) {
559 // relax, even though its an error
561 _clicking = Config->get_clicking ();
567 catch (failed_constructor& err) {
568 error << _("cannot setup Click I/O") << endmsg;
571 BootMessage (_("Compute I/O Latencies"));
573 set_worst_io_latencies ();
576 // XXX HOW TO ALERT UI TO THIS ? DO WE NEED TO?
579 /* Create a set of Bundle objects that map
580 to the physical outputs currently available
583 BootMessage (_("Set up standard connections"));
587 for (uint32_t np = 0; np < n_physical_outputs; ++np) {
589 snprintf (buf, sizeof (buf), _("out %" PRIu32), np+1);
591 shared_ptr<AutoBundle> c (new AutoBundle (buf, true));
593 c->set_port (0, _engine.get_nth_physical_output (DataType::AUDIO, np));
598 for (uint32_t np = 0; np < n_physical_inputs; ++np) {
600 snprintf (buf, sizeof (buf), _("in %" PRIu32), np+1);
602 shared_ptr<AutoBundle> c (new AutoBundle (buf, false));
604 c->set_port (0, _engine.get_nth_physical_input (DataType::AUDIO, np));
611 for (uint32_t np = 0; np < n_physical_outputs; np +=2) {
613 snprintf (buf, sizeof (buf), _("out %" PRIu32 "+%" PRIu32), np+1, np+2);
615 shared_ptr<AutoBundle> c (new AutoBundle (buf, true));
617 c->set_port (0, _engine.get_nth_physical_output (DataType::AUDIO, np));
618 c->set_port (1, _engine.get_nth_physical_output (DataType::AUDIO, np + 1));
623 for (uint32_t np = 0; np < n_physical_inputs; np +=2) {
625 snprintf (buf, sizeof (buf), _("in %" PRIu32 "+%" PRIu32), np+1, np+2);
627 shared_ptr<AutoBundle> c (new AutoBundle (buf, false));
629 c->set_port (0, _engine.get_nth_physical_input (DataType::AUDIO, np));
630 c->set_port (1, _engine.get_nth_physical_input (DataType::AUDIO, np + 1));
639 /* create master/control ports */
644 /* force the master to ignore any later call to this */
646 if (_master_out->pending_state_node) {
647 _master_out->ports_became_legal();
650 /* no panner resets till we are through */
652 _master_out->defer_pan_reset ();
654 while (_master_out->n_inputs().n_audio()
655 < _master_out->input_maximum().n_audio()) {
656 if (_master_out->add_input_port ("", this, DataType::AUDIO)) {
657 error << _("cannot setup master inputs")
663 while (_master_out->n_outputs().n_audio()
664 < _master_out->output_maximum().n_audio()) {
665 if (_master_out->add_output_port (_engine.get_nth_physical_output (DataType::AUDIO, n), this, DataType::AUDIO)) {
666 error << _("cannot setup master outputs")
673 _master_out->allow_pan_reset ();
677 shared_ptr<AutoBundle> c (new AutoBundle (_("Master Out"), true));
679 c->set_channels (_master_out->n_inputs().n_total());
680 for (uint32_t n = 0; n < _master_out->n_inputs ().n_total(); ++n) {
681 c->set_port (n, _master_out->input(n)->name());
686 BootMessage (_("Setup signal flow and plugins"));
690 /* catch up on send+insert cnts */
692 BootMessage (_("Catch up with send/insert state"));
696 for (list<PortInsert*>::iterator i = _port_inserts.begin(); i != _port_inserts.end(); ++i) {
699 if (sscanf ((*i)->name().c_str(), "%*s %u", &id) == 1) {
700 if (id > insert_cnt) {
708 for (list<Send*>::iterator i = _sends.begin(); i != _sends.end(); ++i) {
711 if (sscanf ((*i)->name().c_str(), "%*s %u", &id) == 1) {
719 _state_of_the_state = StateOfTheState (_state_of_the_state & ~(CannotSave|Dirty));
721 /* hook us up to the engine */
723 BootMessage (_("Connect to engine"));
725 _engine.set_session (this);
730 BootMessage (_("OSC startup"));
732 osc->set_session (*this);
738 Session::hookup_io ()
740 /* stop graph reordering notifications from
741 causing resorts, etc.
744 _state_of_the_state = StateOfTheState (_state_of_the_state | InitialConnecting);
747 if (auditioner == 0) {
749 /* we delay creating the auditioner till now because
750 it makes its own connections to ports.
751 the engine has to be running for this to work.
755 auditioner.reset (new Auditioner (*this));
758 catch (failed_constructor& err) {
759 warning << _("cannot create Auditioner: no auditioning of regions possible") << endmsg;
763 /* Tell all IO objects to create their ports */
769 vector<string> cports;
771 while (_control_out->n_inputs().n_audio() < _control_out->input_maximum().n_audio()) {
772 if (_control_out->add_input_port ("", this)) {
773 error << _("cannot setup control inputs")
779 while (_control_out->n_outputs().n_audio() < _control_out->output_maximum().n_audio()) {
780 if (_control_out->add_output_port (_engine.get_nth_physical_output (DataType::AUDIO, n), this)) {
781 error << _("cannot set up master outputs")
789 uint32_t ni = _control_out->n_inputs().get (DataType::AUDIO);
791 for (n = 0; n < ni; ++n) {
792 cports.push_back (_control_out->input(n)->name());
795 boost::shared_ptr<RouteList> r = routes.reader ();
797 for (RouteList::iterator x = r->begin(); x != r->end(); ++x) {
798 (*x)->set_control_outs (cports);
802 /* load bundles, which we may have postponed earlier on */
803 if (_bundle_xml_node) {
804 load_bundles (*_bundle_xml_node);
805 delete _bundle_xml_node;
808 /* Tell all IO objects to connect themselves together */
810 IO::enable_connecting ();
812 /* Now reset all panners */
814 IO::reset_panners ();
816 /* Anyone who cares about input state, wake up and do something */
818 IOConnectionsComplete (); /* EMIT SIGNAL */
820 _state_of_the_state = StateOfTheState (_state_of_the_state & ~InitialConnecting);
823 /* now handle the whole enchilada as if it was one
829 /* update mixer solo state */
835 Session::playlist_length_changed ()
837 /* we can't just increase end_location->end() if pl->get_maximum_extent()
838 if larger. if the playlist used to be the longest playlist,
839 and its now shorter, we have to decrease end_location->end(). hence,
840 we have to iterate over all diskstreams and check the
841 playlists currently in use.
847 Session::diskstream_playlist_changed (boost::shared_ptr<Diskstream> dstream)
849 boost::shared_ptr<Playlist> playlist;
851 if ((playlist = dstream->playlist()) != 0) {
852 playlist->LengthChanged.connect (mem_fun (this, &Session::playlist_length_changed));
855 /* see comment in playlist_length_changed () */
860 Session::record_enabling_legal () const
862 /* this used to be in here, but survey says.... we don't need to restrict it */
863 // if (record_status() == Recording) {
867 if (Config->get_all_safe()) {
874 Session::reset_input_monitor_state ()
876 if (transport_rolling()) {
878 boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
880 for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
881 if ((*i)->record_enabled ()) {
882 //cerr << "switching to input = " << !auto_input << __FILE__ << __LINE__ << endl << endl;
883 (*i)->monitor_input (Config->get_monitoring_model() == HardwareMonitoring && !Config->get_auto_input());
887 boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
889 for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
890 if ((*i)->record_enabled ()) {
891 //cerr << "switching to input = " << !Config->get_auto_input() << __FILE__ << __LINE__ << endl << endl;
892 (*i)->monitor_input (Config->get_monitoring_model() == HardwareMonitoring);
899 Session::auto_punch_start_changed (Location* location)
901 replace_event (Event::PunchIn, location->start());
903 if (get_record_enabled() && Config->get_punch_in()) {
904 /* capture start has been changed, so save new pending state */
905 save_state ("", true);
910 Session::auto_punch_end_changed (Location* location)
912 nframes_t when_to_stop = location->end();
913 // when_to_stop += _worst_output_latency + _worst_input_latency;
914 replace_event (Event::PunchOut, when_to_stop);
918 Session::auto_punch_changed (Location* location)
920 nframes_t when_to_stop = location->end();
922 replace_event (Event::PunchIn, location->start());
923 //when_to_stop += _worst_output_latency + _worst_input_latency;
924 replace_event (Event::PunchOut, when_to_stop);
928 Session::auto_loop_changed (Location* location)
930 replace_event (Event::AutoLoop, location->end(), location->start());
932 if (transport_rolling() && play_loop) {
934 //if (_transport_frame < location->start() || _transport_frame > location->end()) {
936 if (_transport_frame > location->end()) {
937 // relocate to beginning of loop
938 clear_events (Event::LocateRoll);
940 request_locate (location->start(), true);
943 else if (Config->get_seamless_loop() && !loop_changing) {
945 // schedule a locate-roll to refill the diskstreams at the
947 loop_changing = true;
949 if (location->end() > last_loopend) {
950 clear_events (Event::LocateRoll);
951 Event *ev = new Event (Event::LocateRoll, Event::Add, last_loopend, last_loopend, 0, true);
958 last_loopend = location->end();
963 Session::set_auto_punch_location (Location* location)
967 if ((existing = _locations.auto_punch_location()) != 0 && existing != location) {
968 auto_punch_start_changed_connection.disconnect();
969 auto_punch_end_changed_connection.disconnect();
970 auto_punch_changed_connection.disconnect();
971 existing->set_auto_punch (false, this);
972 remove_event (existing->start(), Event::PunchIn);
973 clear_events (Event::PunchOut);
974 auto_punch_location_changed (0);
983 if (location->end() <= location->start()) {
984 error << _("Session: you can't use that location for auto punch (start <= end)") << endmsg;
988 auto_punch_start_changed_connection.disconnect();
989 auto_punch_end_changed_connection.disconnect();
990 auto_punch_changed_connection.disconnect();
992 auto_punch_start_changed_connection = location->start_changed.connect (mem_fun (this, &Session::auto_punch_start_changed));
993 auto_punch_end_changed_connection = location->end_changed.connect (mem_fun (this, &Session::auto_punch_end_changed));
994 auto_punch_changed_connection = location->changed.connect (mem_fun (this, &Session::auto_punch_changed));
996 location->set_auto_punch (true, this);
997 auto_punch_location_changed (location);
1001 Session::set_auto_loop_location (Location* location)
1005 if ((existing = _locations.auto_loop_location()) != 0 && existing != location) {
1006 auto_loop_start_changed_connection.disconnect();
1007 auto_loop_end_changed_connection.disconnect();
1008 auto_loop_changed_connection.disconnect();
1009 existing->set_auto_loop (false, this);
1010 remove_event (existing->end(), Event::AutoLoop);
1011 auto_loop_location_changed (0);
1016 if (location == 0) {
1020 if (location->end() <= location->start()) {
1021 error << _("Session: you can't use a mark for auto loop") << endmsg;
1025 last_loopend = location->end();
1027 auto_loop_start_changed_connection.disconnect();
1028 auto_loop_end_changed_connection.disconnect();
1029 auto_loop_changed_connection.disconnect();
1031 auto_loop_start_changed_connection = location->start_changed.connect (mem_fun (this, &Session::auto_loop_changed));
1032 auto_loop_end_changed_connection = location->end_changed.connect (mem_fun (this, &Session::auto_loop_changed));
1033 auto_loop_changed_connection = location->changed.connect (mem_fun (this, &Session::auto_loop_changed));
1035 location->set_auto_loop (true, this);
1036 auto_loop_location_changed (location);
1040 Session::locations_added (Location* ignored)
1046 Session::locations_changed ()
1048 _locations.apply (*this, &Session::handle_locations_changed);
1052 Session::handle_locations_changed (Locations::LocationList& locations)
1054 Locations::LocationList::iterator i;
1056 bool set_loop = false;
1057 bool set_punch = false;
1059 for (i = locations.begin(); i != locations.end(); ++i) {
1063 if (location->is_auto_punch()) {
1064 set_auto_punch_location (location);
1067 if (location->is_auto_loop()) {
1068 set_auto_loop_location (location);
1075 set_auto_loop_location (0);
1078 set_auto_punch_location (0);
1085 Session::enable_record ()
1087 /* XXX really atomic compare+swap here */
1088 if (g_atomic_int_get (&_record_status) != Recording) {
1089 g_atomic_int_set (&_record_status, Recording);
1090 _last_record_location = _transport_frame;
1091 deliver_mmc(MIDI::MachineControl::cmdRecordStrobe, _last_record_location);
1093 if (Config->get_monitoring_model() == HardwareMonitoring && Config->get_auto_input()) {
1094 boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
1095 for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
1096 if ((*i)->record_enabled ()) {
1097 (*i)->monitor_input (true);
1102 RecordStateChanged ();
1107 Session::disable_record (bool rt_context, bool force)
1111 if ((rs = (RecordState) g_atomic_int_get (&_record_status)) != Disabled) {
1113 if ((!Config->get_latched_record_enable () && !play_loop) || force) {
1114 g_atomic_int_set (&_record_status, Disabled);
1116 if (rs == Recording) {
1117 g_atomic_int_set (&_record_status, Enabled);
1121 // FIXME: timestamp correct? [DR]
1122 // FIXME FIXME FIXME: rt_context? this must be called in the process thread.
1123 // does this /need/ to be sent in all cases?
1125 deliver_mmc (MIDI::MachineControl::cmdRecordExit, _transport_frame);
1127 if (Config->get_monitoring_model() == HardwareMonitoring && Config->get_auto_input()) {
1128 boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
1130 for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
1131 if ((*i)->record_enabled ()) {
1132 (*i)->monitor_input (false);
1137 RecordStateChanged (); /* emit signal */
1140 remove_pending_capture_state ();
1146 Session::step_back_from_record ()
1148 /* XXX really atomic compare+swap here */
1149 if (g_atomic_int_get (&_record_status) == Recording) {
1150 g_atomic_int_set (&_record_status, Enabled);
1152 if (Config->get_monitoring_model() == HardwareMonitoring && Config->get_auto_input()) {
1153 boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
1155 for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
1156 if ((*i)->record_enabled ()) {
1157 //cerr << "switching from input" << __FILE__ << __LINE__ << endl << endl;
1158 (*i)->monitor_input (false);
1166 Session::maybe_enable_record ()
1168 g_atomic_int_set (&_record_status, Enabled);
1170 /* this function is currently called from somewhere other than an RT thread.
1171 this save_state() call therefore doesn't impact anything.
1174 save_state ("", true);
1176 if (_transport_speed) {
1177 if (!Config->get_punch_in()) {
1181 deliver_mmc (MIDI::MachineControl::cmdRecordPause, _transport_frame);
1182 RecordStateChanged (); /* EMIT SIGNAL */
1189 Session::audible_frame () const
1195 /* the first of these two possible settings for "offset"
1196 mean that the audible frame is stationary until
1197 audio emerges from the latency compensation
1200 the second means that the audible frame is stationary
1201 until audio would emerge from a physical port
1202 in the absence of any plugin latency compensation
1205 offset = _worst_output_latency;
1207 if (offset > current_block_size) {
1208 offset -= current_block_size;
1210 /* XXX is this correct? if we have no external
1211 physical connections and everything is internal
1212 then surely this is zero? still, how
1213 likely is that anyway?
1215 offset = current_block_size;
1218 if (synced_to_jack()) {
1219 tf = _engine.transport_frame();
1221 tf = _transport_frame;
1224 if (_transport_speed == 0) {
1234 if (!non_realtime_work_pending()) {
1238 /* take latency into account */
1247 Session::set_frame_rate (nframes_t frames_per_second)
1249 /** \fn void Session::set_frame_size(nframes_t)
1250 the AudioEngine object that calls this guarantees
1251 that it will not be called while we are also in
1252 ::process(). Its fine to do things that block
1256 _base_frame_rate = frames_per_second;
1260 Automatable::set_automation_interval ((jack_nframes_t) ceil ((double) frames_per_second * (0.001 * Config->get_automation_interval())));
1264 // XXX we need some equivalent to this, somehow
1265 // SndFileSource::setup_standard_crossfades (frames_per_second);
1269 /* XXX need to reset/reinstantiate all LADSPA plugins */
1273 Session::set_block_size (nframes_t nframes)
1275 /* the AudioEngine guarantees
1276 that it will not be called while we are also in
1277 ::process(). It is therefore fine to do things that block
1283 current_block_size = nframes;
1285 ensure_buffers(_scratch_buffers->available());
1287 if (_gain_automation_buffer) {
1288 delete [] _gain_automation_buffer;
1290 _gain_automation_buffer = new gain_t[nframes];
1292 allocate_pan_automation_buffers (nframes, _npan_buffers, true);
1294 boost::shared_ptr<RouteList> r = routes.reader ();
1296 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
1297 (*i)->set_block_size (nframes);
1300 boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
1301 for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
1302 (*i)->set_block_size (nframes);
1305 set_worst_io_latencies ();
1310 Session::set_default_fade (float steepness, float fade_msecs)
1313 nframes_t fade_frames;
1315 /* Don't allow fade of less 1 frame */
1317 if (fade_msecs < (1000.0 * (1.0/_current_frame_rate))) {
1324 fade_frames = (nframes_t) floor (fade_msecs * _current_frame_rate * 0.001);
1328 default_fade_msecs = fade_msecs;
1329 default_fade_steepness = steepness;
1332 // jlc, WTF is this!
1333 Glib::RWLock::ReaderLock lm (route_lock);
1334 AudioRegion::set_default_fade (steepness, fade_frames);
1339 /* XXX have to do this at some point */
1340 /* foreach region using default fade, reset, then
1341 refill_all_diskstream_buffers ();
1346 struct RouteSorter {
1347 bool operator() (boost::shared_ptr<Route> r1, boost::shared_ptr<Route> r2) {
1348 if (r1->fed_by.find (r2) != r1->fed_by.end()) {
1350 } else if (r2->fed_by.find (r1) != r2->fed_by.end()) {
1353 if (r1->fed_by.empty()) {
1354 if (r2->fed_by.empty()) {
1355 /* no ardour-based connections inbound to either route. just use signal order */
1356 return r1->order_key(N_("signal")) < r2->order_key(N_("signal"));
1358 /* r2 has connections, r1 does not; run r1 early */
1362 return r1->order_key(N_("signal")) < r2->order_key(N_("signal"));
1369 trace_terminal (shared_ptr<Route> r1, shared_ptr<Route> rbase)
1371 shared_ptr<Route> r2;
1373 if ((r1->fed_by.find (rbase) != r1->fed_by.end()) && (rbase->fed_by.find (r1) != rbase->fed_by.end())) {
1374 info << string_compose(_("feedback loop setup between %1 and %2"), r1->name(), rbase->name()) << endmsg;
1378 /* make a copy of the existing list of routes that feed r1 */
1380 set<shared_ptr<Route> > existing = r1->fed_by;
1382 /* for each route that feeds r1, recurse, marking it as feeding
1386 for (set<shared_ptr<Route> >::iterator i = existing.begin(); i != existing.end(); ++i) {
1389 /* r2 is a route that feeds r1 which somehow feeds base. mark
1390 base as being fed by r2
1393 rbase->fed_by.insert (r2);
1397 /* 2nd level feedback loop detection. if r1 feeds or is fed by r2,
1401 if ((r1->fed_by.find (r2) != r1->fed_by.end()) && (r2->fed_by.find (r1) != r2->fed_by.end())) {
1405 /* now recurse, so that we can mark base as being fed by
1406 all routes that feed r2
1409 trace_terminal (r2, rbase);
1416 Session::resort_routes ()
1418 /* don't do anything here with signals emitted
1419 by Routes while we are being destroyed.
1422 if (_state_of_the_state & Deletion) {
1429 RCUWriter<RouteList> writer (routes);
1430 shared_ptr<RouteList> r = writer.get_copy ();
1431 resort_routes_using (r);
1432 /* writer goes out of scope and forces update */
1437 Session::resort_routes_using (shared_ptr<RouteList> r)
1439 RouteList::iterator i, j;
1441 for (i = r->begin(); i != r->end(); ++i) {
1443 (*i)->fed_by.clear ();
1445 for (j = r->begin(); j != r->end(); ++j) {
1447 /* although routes can feed themselves, it will
1448 cause an endless recursive descent if we
1449 detect it. so don't bother checking for
1457 if ((*j)->feeds (*i)) {
1458 (*i)->fed_by.insert (*j);
1463 for (i = r->begin(); i != r->end(); ++i) {
1464 trace_terminal (*i, *i);
1471 cerr << "finished route resort\n";
1473 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
1474 cerr << " " << (*i)->name() << " signal order = " << (*i)->order_key ("signal") << endl;
1481 list<boost::shared_ptr<MidiTrack> >
1482 Session::new_midi_track (TrackMode mode, uint32_t how_many)
1484 char track_name[32];
1485 uint32_t track_id = 0;
1488 RouteList new_routes;
1489 list<boost::shared_ptr<MidiTrack> > ret;
1490 //uint32_t control_id;
1492 // FIXME: need physical I/O and autoconnect stuff for MIDI
1494 /* count existing midi tracks */
1497 shared_ptr<RouteList> r = routes.reader ();
1499 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
1500 if (dynamic_cast<MidiTrack*>((*i).get()) != 0) {
1501 if (!(*i)->is_hidden()) {
1503 //channels_used += (*i)->n_inputs().n_midi();
1510 vector<string> physinputs;
1511 vector<string> physoutputs;
1512 uint32_t nphysical_in;
1513 uint32_t nphysical_out;
1515 _engine.get_physical_outputs (physoutputs);
1516 _engine.get_physical_inputs (physinputs);
1517 control_id = ntracks() + nbusses() + 1;
1522 /* check for duplicate route names, since we might have pre-existing
1523 routes with this name (e.g. create Audio1, Audio2, delete Audio1,
1524 save, close,restart,add new route - first named route is now
1532 snprintf (track_name, sizeof(track_name), "Midi %" PRIu32, track_id);
1534 if (route_by_name (track_name) == 0) {
1538 } while (track_id < (UINT_MAX-1));
1541 if (Config->get_input_auto_connect() & AutoConnectPhysical) {
1542 nphysical_in = min (n_physical_inputs, (uint32_t) physinputs.size());
1547 if (Config->get_output_auto_connect() & AutoConnectPhysical) {
1548 nphysical_out = min (n_physical_outputs, (uint32_t) physinputs.size());
1554 shared_ptr<MidiTrack> track;
1557 track = boost::shared_ptr<MidiTrack>((new MidiTrack (*this, track_name, Route::Flag (0), mode)));
1559 if (track->ensure_io (ChanCount(DataType::MIDI, 1), ChanCount(DataType::AUDIO, 1), false, this)) {
1560 error << "cannot configure 1 in/1 out configuration for new midi track" << endmsg;
1566 for (uint32_t x = 0; x < track->n_inputs().n_midi() && x < nphysical_in; ++x) {
1570 if (Config->get_input_auto_connect() & AutoConnectPhysical) {
1571 port = physinputs[(channels_used+x)%nphysical_in];
1574 if (port.length() && track->connect_input (track->input (x), port, this)) {
1580 for (uint32_t x = 0; x < track->n_outputs().n_midi(); ++x) {
1584 if (nphysical_out && (Config->get_output_auto_connect() & AutoConnectPhysical)) {
1585 port = physoutputs[(channels_used+x)%nphysical_out];
1586 } else if (Config->get_output_auto_connect() & AutoConnectMaster) {
1588 port = _master_out->input (x%_master_out->n_inputs().n_midi())->name();
1592 if (port.length() && track->connect_output (track->output (x), port, this)) {
1597 channels_used += track->n_inputs ().n_midi();
1601 track->midi_diskstream()->non_realtime_input_change();
1603 track->DiskstreamChanged.connect (mem_fun (this, &Session::resort_routes));
1604 //track->set_remote_control_id (control_id);
1606 new_routes.push_back (track);
1607 ret.push_back (track);
1610 catch (failed_constructor &err) {
1611 error << _("Session: could not create new midi track.") << endmsg;
1614 /* we need to get rid of this, since the track failed to be created */
1615 /* XXX arguably, AudioTrack::AudioTrack should not do the Session::add_diskstream() */
1618 RCUWriter<DiskstreamList> writer (diskstreams);
1619 boost::shared_ptr<DiskstreamList> ds = writer.get_copy();
1620 ds->remove (track->midi_diskstream());
1627 catch (AudioEngine::PortRegistrationFailure& pfe) {
1629 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;
1632 /* we need to get rid of this, since the track failed to be created */
1633 /* XXX arguably, MidiTrack::MidiTrack should not do the Session::add_diskstream() */
1636 RCUWriter<DiskstreamList> writer (diskstreams);
1637 boost::shared_ptr<DiskstreamList> ds = writer.get_copy();
1638 ds->remove (track->midi_diskstream());
1649 if (!new_routes.empty()) {
1650 add_routes (new_routes, false);
1651 save_state (_current_snapshot_name);
1657 list<boost::shared_ptr<AudioTrack> >
1658 Session::new_audio_track (int input_channels, int output_channels, TrackMode mode, uint32_t how_many)
1660 char track_name[32];
1661 uint32_t track_id = 0;
1663 uint32_t channels_used = 0;
1665 RouteList new_routes;
1666 list<boost::shared_ptr<AudioTrack> > ret;
1667 uint32_t control_id;
1669 /* count existing audio tracks */
1672 shared_ptr<RouteList> r = routes.reader ();
1674 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
1675 if (dynamic_cast<AudioTrack*>((*i).get()) != 0) {
1676 if (!(*i)->is_hidden()) {
1678 channels_used += (*i)->n_inputs().n_audio();
1684 vector<string> physinputs;
1685 vector<string> physoutputs;
1686 uint32_t nphysical_in;
1687 uint32_t nphysical_out;
1689 _engine.get_physical_outputs (physoutputs);
1690 _engine.get_physical_inputs (physinputs);
1691 control_id = ntracks() + nbusses() + 1;
1695 /* check for duplicate route names, since we might have pre-existing
1696 routes with this name (e.g. create Audio1, Audio2, delete Audio1,
1697 save, close,restart,add new route - first named route is now
1705 snprintf (track_name, sizeof(track_name), "Audio %" PRIu32, track_id);
1707 if (route_by_name (track_name) == 0) {
1711 } while (track_id < (UINT_MAX-1));
1713 if (Config->get_input_auto_connect() & AutoConnectPhysical) {
1714 nphysical_in = min (n_physical_inputs, (uint32_t) physinputs.size());
1719 if (Config->get_output_auto_connect() & AutoConnectPhysical) {
1720 nphysical_out = min (n_physical_outputs, (uint32_t) physinputs.size());
1725 shared_ptr<AudioTrack> track;
1728 track = boost::shared_ptr<AudioTrack>((new AudioTrack (*this, track_name, Route::Flag (0), mode)));
1730 if (track->ensure_io (ChanCount(DataType::AUDIO, input_channels), ChanCount(DataType::AUDIO, output_channels), false, this)) {
1731 error << string_compose (_("cannot configure %1 in/%2 out configuration for new audio track"),
1732 input_channels, output_channels)
1738 for (uint32_t x = 0; x < track->n_inputs().n_audio() && x < nphysical_in; ++x) {
1742 if (Config->get_input_auto_connect() & AutoConnectPhysical) {
1743 port = physinputs[(channels_used+x)%nphysical_in];
1746 if (port.length() && track->connect_input (track->input (x), port, this)) {
1752 for (uint32_t x = 0; x < track->n_outputs().n_midi(); ++x) {
1756 if (nphysical_out && (Config->get_output_auto_connect() & AutoConnectPhysical)) {
1757 port = physoutputs[(channels_used+x)%nphysical_out];
1758 } else if (Config->get_output_auto_connect() & AutoConnectMaster) {
1760 port = _master_out->input (x%_master_out->n_inputs().n_audio())->name();
1764 if (port.length() && track->connect_output (track->output (x), port, this)) {
1769 channels_used += track->n_inputs ().n_audio();
1771 track->audio_diskstream()->non_realtime_input_change();
1773 track->DiskstreamChanged.connect (mem_fun (this, &Session::resort_routes));
1774 track->set_remote_control_id (control_id);
1777 new_routes.push_back (track);
1778 ret.push_back (track);
1781 catch (failed_constructor &err) {
1782 error << _("Session: could not create new audio track.") << endmsg;
1785 /* we need to get rid of this, since the track failed to be created */
1786 /* XXX arguably, AudioTrack::AudioTrack should not do the Session::add_diskstream() */
1789 RCUWriter<DiskstreamList> writer (diskstreams);
1790 boost::shared_ptr<DiskstreamList> ds = writer.get_copy();
1791 ds->remove (track->audio_diskstream());
1798 catch (AudioEngine::PortRegistrationFailure& pfe) {
1800 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;
1803 /* we need to get rid of this, since the track failed to be created */
1804 /* XXX arguably, AudioTrack::AudioTrack should not do the Session::add_diskstream() */
1807 RCUWriter<DiskstreamList> writer (diskstreams);
1808 boost::shared_ptr<DiskstreamList> ds = writer.get_copy();
1809 ds->remove (track->audio_diskstream());
1820 if (!new_routes.empty()) {
1821 add_routes (new_routes, true);
1828 Session::set_remote_control_ids ()
1830 RemoteModel m = Config->get_remote_model();
1832 shared_ptr<RouteList> r = routes.reader ();
1834 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
1835 if ( MixerOrdered == m) {
1836 long order = (*i)->order_key(N_("signal"));
1837 (*i)->set_remote_control_id( order+1 );
1838 } else if ( EditorOrdered == m) {
1839 long order = (*i)->order_key(N_("editor"));
1840 (*i)->set_remote_control_id( order+1 );
1841 } else if ( UserOrdered == m) {
1842 //do nothing ... only changes to remote id's are initiated by user
1849 Session::new_audio_route (int input_channels, int output_channels, uint32_t how_many)
1852 uint32_t bus_id = 1;
1856 uint32_t control_id;
1858 /* count existing audio busses */
1861 shared_ptr<RouteList> r = routes.reader ();
1863 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
1864 if (dynamic_cast<AudioTrack*>((*i).get()) == 0) {
1865 if (!(*i)->is_hidden() && (*i)->name() != _("master")) {
1872 vector<string> physinputs;
1873 vector<string> physoutputs;
1875 _engine.get_physical_outputs (physoutputs);
1876 _engine.get_physical_inputs (physinputs);
1877 control_id = ntracks() + nbusses() + 1;
1882 snprintf (bus_name, sizeof(bus_name), "Bus %" PRIu32, bus_id);
1886 if (route_by_name (bus_name) == 0) {
1890 } while (bus_id < (UINT_MAX-1));
1893 shared_ptr<Route> bus (new Route (*this, bus_name, -1, -1, -1, -1, Route::Flag(0), DataType::AUDIO));
1895 if (bus->ensure_io (ChanCount(DataType::AUDIO, input_channels), ChanCount(DataType::AUDIO, output_channels), false, this)) {
1896 error << string_compose (_("cannot configure %1 in/%2 out configuration for new audio track"),
1897 input_channels, output_channels)
1902 for (uint32_t x = 0; n_physical_inputs && x < bus->n_inputs().n_audio(); ++x) {
1906 if (Config->get_input_auto_connect() & AutoConnectPhysical) {
1907 port = physinputs[((n+x)%n_physical_inputs)];
1910 if (port.length() && bus->connect_input (bus->input (x), port, this)) {
1915 for (uint32_t x = 0; n_physical_outputs && x < bus->n_outputs().n_audio(); ++x) {
1919 if (Config->get_output_auto_connect() & AutoConnectPhysical) {
1920 port = physoutputs[((n+x)%n_physical_outputs)];
1921 } else if (Config->get_output_auto_connect() & AutoConnectMaster) {
1923 port = _master_out->input (x%_master_out->n_inputs().n_audio())->name();
1927 if (port.length() && bus->connect_output (bus->output (x), port, this)) {
1932 bus->set_remote_control_id (control_id);
1935 ret.push_back (bus);
1939 catch (failed_constructor &err) {
1940 error << _("Session: could not create new audio route.") << endmsg;
1944 catch (AudioEngine::PortRegistrationFailure& pfe) {
1945 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;
1955 add_routes (ret, true);
1963 Session::add_routes (RouteList& new_routes, bool save)
1966 RCUWriter<RouteList> writer (routes);
1967 shared_ptr<RouteList> r = writer.get_copy ();
1968 r->insert (r->end(), new_routes.begin(), new_routes.end());
1969 resort_routes_using (r);
1972 for (RouteList::iterator x = new_routes.begin(); x != new_routes.end(); ++x) {
1974 boost::weak_ptr<Route> wpr (*x);
1976 (*x)->solo_changed.connect (sigc::bind (mem_fun (*this, &Session::route_solo_changed), wpr));
1977 (*x)->mute_changed.connect (mem_fun (*this, &Session::route_mute_changed));
1978 (*x)->output_changed.connect (mem_fun (*this, &Session::set_worst_io_latencies_x));
1979 (*x)->processors_changed.connect (bind (mem_fun (*this, &Session::update_latency_compensation), false, false));
1981 if ((*x)->is_master()) {
1985 if ((*x)->is_control()) {
1986 _control_out = (*x);
1989 add_bundle ((*x)->bundle_for_inputs());
1990 add_bundle ((*x)->bundle_for_outputs());
1993 if (_control_out && IO::connecting_legal) {
1995 vector<string> cports;
1996 uint32_t ni = _control_out->n_inputs().n_audio();
1998 for (uint32_t n = 0; n < ni; ++n) {
1999 cports.push_back (_control_out->input(n)->name());
2002 for (RouteList::iterator x = new_routes.begin(); x != new_routes.end(); ++x) {
2003 (*x)->set_control_outs (cports);
2010 save_state (_current_snapshot_name);
2013 RouteAdded (new_routes); /* EMIT SIGNAL */
2017 Session::add_diskstream (boost::shared_ptr<Diskstream> dstream)
2019 /* need to do this in case we're rolling at the time, to prevent false underruns */
2020 dstream->do_refill_with_alloc ();
2022 dstream->set_block_size (current_block_size);
2025 RCUWriter<DiskstreamList> writer (diskstreams);
2026 boost::shared_ptr<DiskstreamList> ds = writer.get_copy();
2027 ds->push_back (dstream);
2028 /* writer goes out of scope, copies ds back to main */
2031 dstream->PlaylistChanged.connect (sigc::bind (mem_fun (*this, &Session::diskstream_playlist_changed), dstream));
2032 /* this will connect to future changes, and check the current length */
2033 diskstream_playlist_changed (dstream);
2035 dstream->prepare ();
2040 Session::remove_route (shared_ptr<Route> route)
2043 RCUWriter<RouteList> writer (routes);
2044 shared_ptr<RouteList> rs = writer.get_copy ();
2048 /* deleting the master out seems like a dumb
2049 idea, but its more of a UI policy issue
2053 if (route == _master_out) {
2054 _master_out = shared_ptr<Route> ();
2057 if (route == _control_out) {
2058 _control_out = shared_ptr<Route> ();
2060 /* cancel control outs for all routes */
2062 vector<string> empty;
2064 for (RouteList::iterator r = rs->begin(); r != rs->end(); ++r) {
2065 (*r)->set_control_outs (empty);
2069 update_route_solo_state ();
2071 /* writer goes out of scope, forces route list update */
2075 boost::shared_ptr<Diskstream> ds;
2077 if ((t = dynamic_cast<Track*>(route.get())) != 0) {
2078 ds = t->diskstream();
2084 RCUWriter<DiskstreamList> dsl (diskstreams);
2085 boost::shared_ptr<DiskstreamList> d = dsl.get_copy();
2090 find_current_end ();
2092 // We need to disconnect the routes inputs and outputs
2094 route->disconnect_inputs (0);
2095 route->disconnect_outputs (0);
2097 update_latency_compensation (false, false);
2100 /* get rid of it from the dead wood collection in the route list manager */
2102 /* XXX i think this is unsafe as it currently stands, but i am not sure. (pd, october 2nd, 2006) */
2106 /* try to cause everyone to drop their references */
2108 route->drop_references ();
2110 /* save the new state of the world */
2112 if (save_state (_current_snapshot_name)) {
2113 save_history (_current_snapshot_name);
2118 Session::route_mute_changed (void* src)
2124 Session::route_solo_changed (void* src, boost::weak_ptr<Route> wpr)
2126 if (solo_update_disabled) {
2132 boost::shared_ptr<Route> route = wpr.lock ();
2135 /* should not happen */
2136 error << string_compose (_("programming error: %1"), X_("invalid route weak ptr passed to route_solo_changed")) << endmsg;
2140 is_track = (boost::dynamic_pointer_cast<AudioTrack>(route) != 0);
2142 shared_ptr<RouteList> r = routes.reader ();
2144 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2146 /* soloing a track mutes all other tracks, soloing a bus mutes all other busses */
2150 /* don't mess with busses */
2152 if (dynamic_cast<Track*>((*i).get()) == 0) {
2158 /* don't mess with tracks */
2160 if (dynamic_cast<Track*>((*i).get()) != 0) {
2165 if ((*i) != route &&
2166 ((*i)->mix_group () == 0 ||
2167 (*i)->mix_group () != route->mix_group () ||
2168 !route->mix_group ()->is_active())) {
2170 if ((*i)->soloed()) {
2172 /* if its already soloed, and solo latching is enabled,
2173 then leave it as it is.
2176 if (Config->get_solo_latched()) {
2183 solo_update_disabled = true;
2184 (*i)->set_solo (false, src);
2185 solo_update_disabled = false;
2189 bool something_soloed = false;
2190 bool same_thing_soloed = false;
2191 bool signal = false;
2193 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2194 if ((*i)->soloed()) {
2195 something_soloed = true;
2196 if (dynamic_cast<Track*>((*i).get())) {
2198 same_thing_soloed = true;
2203 same_thing_soloed = true;
2211 if (something_soloed != currently_soloing) {
2213 currently_soloing = something_soloed;
2216 modify_solo_mute (is_track, same_thing_soloed);
2219 SoloActive (currently_soloing); /* EMIT SIGNAL */
2222 SoloChanged (); /* EMIT SIGNAL */
2228 Session::update_route_solo_state ()
2231 bool is_track = false;
2232 bool signal = false;
2234 /* caller must hold RouteLock */
2236 /* this is where we actually implement solo by changing
2237 the solo mute setting of each track.
2240 shared_ptr<RouteList> r = routes.reader ();
2242 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2243 if ((*i)->soloed()) {
2245 if (dynamic_cast<Track*>((*i).get())) {
2252 if (mute != currently_soloing) {
2254 currently_soloing = mute;
2257 if (!is_track && !mute) {
2259 /* nothing is soloed */
2261 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2262 (*i)->set_solo_mute (false);
2272 modify_solo_mute (is_track, mute);
2275 SoloActive (currently_soloing);
2280 Session::modify_solo_mute (bool is_track, bool mute)
2282 shared_ptr<RouteList> r = routes.reader ();
2284 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2288 /* only alter track solo mute */
2290 if (dynamic_cast<Track*>((*i).get())) {
2291 if ((*i)->soloed()) {
2292 (*i)->set_solo_mute (!mute);
2294 (*i)->set_solo_mute (mute);
2300 /* only alter bus solo mute */
2302 if (!dynamic_cast<Track*>((*i).get())) {
2304 if ((*i)->soloed()) {
2306 (*i)->set_solo_mute (false);
2310 /* don't mute master or control outs
2311 in response to another bus solo
2314 if ((*i) != _master_out &&
2315 (*i) != _control_out) {
2316 (*i)->set_solo_mute (mute);
2327 Session::catch_up_on_solo ()
2329 /* this is called after set_state() to catch the full solo
2330 state, which can't be correctly determined on a per-route
2331 basis, but needs the global overview that only the session
2334 update_route_solo_state();
2338 Session::route_by_name (string name)
2340 shared_ptr<RouteList> r = routes.reader ();
2342 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2343 if ((*i)->name() == name) {
2348 return shared_ptr<Route> ((Route*) 0);
2352 Session::route_by_id (PBD::ID id)
2354 shared_ptr<RouteList> r = routes.reader ();
2356 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2357 if ((*i)->id() == id) {
2362 return shared_ptr<Route> ((Route*) 0);
2366 Session::route_by_remote_id (uint32_t id)
2368 shared_ptr<RouteList> r = routes.reader ();
2370 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2371 if ((*i)->remote_control_id() == id) {
2376 return shared_ptr<Route> ((Route*) 0);
2380 Session::find_current_end ()
2382 if (_state_of_the_state & Loading) {
2386 nframes_t max = get_maximum_extent ();
2388 if (max > end_location->end()) {
2389 end_location->set_end (max);
2391 DurationChanged(); /* EMIT SIGNAL */
2396 Session::get_maximum_extent () const
2401 boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
2403 for (DiskstreamList::const_iterator i = dsl->begin(); i != dsl->end(); ++i) {
2404 boost::shared_ptr<Playlist> pl = (*i)->playlist();
2405 if ((me = pl->get_maximum_extent()) > max) {
2413 boost::shared_ptr<Diskstream>
2414 Session::diskstream_by_name (string name)
2416 boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
2418 for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
2419 if ((*i)->name() == name) {
2424 return boost::shared_ptr<Diskstream>((Diskstream*) 0);
2427 boost::shared_ptr<Diskstream>
2428 Session::diskstream_by_id (const PBD::ID& id)
2430 boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
2432 for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
2433 if ((*i)->id() == id) {
2438 return boost::shared_ptr<Diskstream>((Diskstream*) 0);
2441 /* Region management */
2444 Session::new_region_name (string old)
2446 string::size_type last_period;
2448 string::size_type len = old.length() + 64;
2451 if ((last_period = old.find_last_of ('.')) == string::npos) {
2453 /* no period present - add one explicitly */
2456 last_period = old.length() - 1;
2461 number = atoi (old.substr (last_period+1).c_str());
2465 while (number < (UINT_MAX-1)) {
2467 RegionList::const_iterator i;
2472 snprintf (buf, len, "%s%" PRIu32, old.substr (0, last_period + 1).c_str(), number);
2475 for (i = regions.begin(); i != regions.end(); ++i) {
2476 if (i->second->name() == sbuf) {
2481 if (i == regions.end()) {
2486 if (number != (UINT_MAX-1)) {
2490 error << string_compose (_("cannot create new name for region \"%1\""), old) << endmsg;
2495 Session::region_name (string& result, string base, bool newlevel) const
2500 assert(base.find("/") == string::npos);
2504 Glib::Mutex::Lock lm (region_lock);
2506 snprintf (buf, sizeof (buf), "%d", (int)regions.size() + 1);
2514 /* XXX this is going to be slow. optimize me later */
2519 string::size_type pos;
2521 pos = base.find_last_of ('.');
2523 /* pos may be npos, but then we just use entire base */
2525 subbase = base.substr (0, pos);
2529 bool name_taken = true;
2532 Glib::Mutex::Lock lm (region_lock);
2534 for (int n = 1; n < 5000; ++n) {
2537 snprintf (buf, sizeof (buf), ".%d", n);
2542 for (RegionList::const_iterator i = regions.begin(); i != regions.end(); ++i) {
2543 if (i->second->name() == result) {
2556 fatal << string_compose(_("too many regions with names like %1"), base) << endmsg;
2564 Session::add_region (boost::shared_ptr<Region> region)
2566 vector<boost::shared_ptr<Region> > v;
2567 v.push_back (region);
2572 Session::add_regions (vector<boost::shared_ptr<Region> >& new_regions)
2577 Glib::Mutex::Lock lm (region_lock);
2579 for (vector<boost::shared_ptr<Region> >::iterator ii = new_regions.begin(); ii != new_regions.end(); ++ii) {
2581 boost::shared_ptr<Region> region = *ii;
2585 error << _("Session::add_region() ignored a null region. Warning: you might have lost a region.") << endmsg;
2589 RegionList::iterator x;
2591 for (x = regions.begin(); x != regions.end(); ++x) {
2593 if (region->region_list_equivalent (x->second)) {
2598 if (x == regions.end()) {
2600 pair<RegionList::key_type,RegionList::mapped_type> entry;
2602 entry.first = region->id();
2603 entry.second = region;
2605 pair<RegionList::iterator,bool> x = regions.insert (entry);
2617 /* mark dirty because something has changed even if we didn't
2618 add the region to the region list.
2625 vector<boost::weak_ptr<Region> > v;
2626 boost::shared_ptr<Region> first_r;
2628 for (vector<boost::shared_ptr<Region> >::iterator ii = new_regions.begin(); ii != new_regions.end(); ++ii) {
2630 boost::shared_ptr<Region> region = *ii;
2634 error << _("Session::add_region() ignored a null region. Warning: you might have lost a region.") << endmsg;
2637 v.push_back (region);
2644 region->StateChanged.connect (sigc::bind (mem_fun (*this, &Session::region_changed), boost::weak_ptr<Region>(region)));
2645 region->GoingAway.connect (sigc::bind (mem_fun (*this, &Session::remove_region), boost::weak_ptr<Region>(region)));
2649 RegionsAdded (v); /* EMIT SIGNAL */
2655 Session::region_changed (Change what_changed, boost::weak_ptr<Region> weak_region)
2657 boost::shared_ptr<Region> region (weak_region.lock ());
2663 if (what_changed & Region::HiddenChanged) {
2664 /* relay hidden changes */
2665 RegionHiddenChange (region);
2670 Session::remove_region (boost::weak_ptr<Region> weak_region)
2672 RegionList::iterator i;
2673 boost::shared_ptr<Region> region (weak_region.lock ());
2679 bool removed = false;
2682 Glib::Mutex::Lock lm (region_lock);
2684 if ((i = regions.find (region->id())) != regions.end()) {
2690 /* mark dirty because something has changed even if we didn't
2691 remove the region from the region list.
2697 RegionRemoved(region); /* EMIT SIGNAL */
2701 boost::shared_ptr<Region>
2702 Session::find_whole_file_parent (boost::shared_ptr<Region const> child)
2704 RegionList::iterator i;
2705 boost::shared_ptr<Region> region;
2707 Glib::Mutex::Lock lm (region_lock);
2709 for (i = regions.begin(); i != regions.end(); ++i) {
2713 if (region->whole_file()) {
2715 if (child->source_equivalent (region)) {
2721 return boost::shared_ptr<Region> ();
2725 Session::find_equivalent_playlist_regions (boost::shared_ptr<Region> region, vector<boost::shared_ptr<Region> >& result)
2727 for (PlaylistList::iterator i = playlists.begin(); i != playlists.end(); ++i)
2728 (*i)->get_region_list_equivalent_regions (region, result);
2732 Session::destroy_region (boost::shared_ptr<Region> region)
2734 vector<boost::shared_ptr<Source> > srcs;
2737 if (region->playlist()) {
2738 region->playlist()->destroy_region (region);
2741 for (uint32_t n = 0; n < region->n_channels(); ++n) {
2742 srcs.push_back (region->source (n));
2746 region->drop_references ();
2748 for (vector<boost::shared_ptr<Source> >::iterator i = srcs.begin(); i != srcs.end(); ++i) {
2750 (*i)->mark_for_remove ();
2751 (*i)->drop_references ();
2753 cerr << "source was not used by any playlist\n";
2760 Session::destroy_regions (list<boost::shared_ptr<Region> > regions)
2762 for (list<boost::shared_ptr<Region> >::iterator i = regions.begin(); i != regions.end(); ++i) {
2763 destroy_region (*i);
2769 Session::remove_last_capture ()
2771 list<boost::shared_ptr<Region> > r;
2773 boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
2775 for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
2776 list<boost::shared_ptr<Region> >& l = (*i)->last_capture_regions();
2779 r.insert (r.end(), l.begin(), l.end());
2784 destroy_regions (r);
2786 save_state (_current_snapshot_name);
2792 Session::remove_region_from_region_list (boost::shared_ptr<Region> r)
2798 /* Source Management */
2800 Session::add_source (boost::shared_ptr<Source> source)
2802 pair<SourceMap::key_type, SourceMap::mapped_type> entry;
2803 pair<SourceMap::iterator,bool> result;
2805 entry.first = source->id();
2806 entry.second = source;
2809 Glib::Mutex::Lock lm (source_lock);
2810 result = sources.insert (entry);
2813 if (result.second) {
2814 source->GoingAway.connect (sigc::bind (mem_fun (this, &Session::remove_source), boost::weak_ptr<Source> (source)));
2818 boost::shared_ptr<AudioFileSource> afs;
2820 if ((afs = boost::dynamic_pointer_cast<AudioFileSource>(source)) != 0) {
2821 if (Config->get_auto_analyse_audio()) {
2822 Analyser::queue_source_for_analysis (source, false);
2828 Session::remove_source (boost::weak_ptr<Source> src)
2830 SourceMap::iterator i;
2831 boost::shared_ptr<Source> source = src.lock();
2837 cerr << "remove source for " << source->name() << endl;
2840 Glib::Mutex::Lock lm (source_lock);
2842 if ((i = sources.find (source->id())) != sources.end()) {
2847 if (!_state_of_the_state & InCleanup) {
2849 /* save state so we don't end up with a session file
2850 referring to non-existent sources.
2853 save_state (_current_snapshot_name);
2857 boost::shared_ptr<Source>
2858 Session::source_by_id (const PBD::ID& id)
2860 Glib::Mutex::Lock lm (source_lock);
2861 SourceMap::iterator i;
2862 boost::shared_ptr<Source> source;
2864 if ((i = sources.find (id)) != sources.end()) {
2872 boost::shared_ptr<Source>
2873 Session::source_by_path_and_channel (const Glib::ustring& path, uint16_t chn)
2875 Glib::Mutex::Lock lm (source_lock);
2877 for (SourceMap::iterator i = sources.begin(); i != sources.end(); ++i) {
2878 cerr << "comparing " << path << " with " << i->second->name() << endl;
2879 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(i->second);
2881 if (afs && afs->path() == path && chn == afs->channel()) {
2886 return boost::shared_ptr<Source>();
2890 Session::peak_path (Glib::ustring base) const
2892 sys::path peakfile_path(_session_dir->peak_path());
2893 peakfile_path /= basename_nosuffix (base) + peakfile_suffix;
2894 return peakfile_path.to_string();
2898 Session::change_audio_path_by_name (string path, string oldname, string newname, bool destructive)
2901 string old_basename = PBD::basename_nosuffix (oldname);
2902 string new_legalized = legalize_for_path (newname);
2904 /* note: we know (or assume) the old path is already valid */
2908 /* destructive file sources have a name of the form:
2910 /path/to/Tnnnn-NAME(%[LR])?.wav
2912 the task here is to replace NAME with the new name.
2915 /* find last slash */
2919 string::size_type slash;
2920 string::size_type dash;
2922 if ((slash = path.find_last_of ('/')) == string::npos) {
2926 dir = path.substr (0, slash+1);
2928 /* '-' is not a legal character for the NAME part of the path */
2930 if ((dash = path.find_last_of ('-')) == string::npos) {
2934 prefix = path.substr (slash+1, dash-(slash+1));
2939 path += new_legalized;
2940 path += ".wav"; /* XXX gag me with a spoon */
2944 /* non-destructive file sources have a name of the form:
2946 /path/to/NAME-nnnnn(%[LR])?.wav
2948 the task here is to replace NAME with the new name.
2953 string::size_type slash;
2954 string::size_type dash;
2955 string::size_type postfix;
2957 /* find last slash */
2959 if ((slash = path.find_last_of ('/')) == string::npos) {
2963 dir = path.substr (0, slash+1);
2965 /* '-' is not a legal character for the NAME part of the path */
2967 if ((dash = path.find_last_of ('-')) == string::npos) {
2971 suffix = path.substr (dash+1);
2973 // Suffix is now everything after the dash. Now we need to eliminate
2974 // the nnnnn part, which is done by either finding a '%' or a '.'
2976 postfix = suffix.find_last_of ("%");
2977 if (postfix == string::npos) {
2978 postfix = suffix.find_last_of ('.');
2981 if (postfix != string::npos) {
2982 suffix = suffix.substr (postfix);
2984 error << "Logic error in Session::change_audio_path_by_name(), please report to the developers" << endl;
2988 const uint32_t limit = 10000;
2989 char buf[PATH_MAX+1];
2991 for (uint32_t cnt = 1; cnt <= limit; ++cnt) {
2993 snprintf (buf, sizeof(buf), "%s%s-%u%s", dir.c_str(), newname.c_str(), cnt, suffix.c_str());
2995 if (access (buf, F_OK) != 0) {
3003 error << "FATAL ERROR! Could not find a " << endl;
3012 Session::audio_path_from_name (string name, uint32_t nchan, uint32_t chan, bool destructive)
3016 char buf[PATH_MAX+1];
3017 const uint32_t limit = 10000;
3021 legalized = legalize_for_path (name);
3023 /* find a "version" of the file name that doesn't exist in
3024 any of the possible directories.
3027 for (cnt = (destructive ? ++destructive_index : 1); cnt <= limit; ++cnt) {
3029 vector<space_and_path>::iterator i;
3030 uint32_t existing = 0;
3032 for (i = session_dirs.begin(); i != session_dirs.end(); ++i) {
3034 SessionDirectory sdir((*i).path);
3036 spath = sdir.sound_path().to_string();
3040 snprintf (buf, sizeof(buf), "%s/T%04d-%s.wav", spath.c_str(), cnt, legalized.c_str());
3041 } else if (nchan == 2) {
3043 snprintf (buf, sizeof(buf), "%s/T%04d-%s%%L.wav", spath.c_str(), cnt, legalized.c_str());
3045 snprintf (buf, sizeof(buf), "%s/T%04d-%s%%R.wav", spath.c_str(), cnt, legalized.c_str());
3047 } else if (nchan < 26) {
3048 snprintf (buf, sizeof(buf), "%s/T%04d-%s%%%c.wav", spath.c_str(), cnt, legalized.c_str(), 'a' + chan);
3050 snprintf (buf, sizeof(buf), "%s/T%04d-%s.wav", spath.c_str(), cnt, legalized.c_str());
3059 snprintf (buf, sizeof(buf), "%s-%u.wav", spath.c_str(), cnt);
3060 } else if (nchan == 2) {
3062 snprintf (buf, sizeof(buf), "%s-%u%%L.wav", spath.c_str(), cnt);
3064 snprintf (buf, sizeof(buf), "%s-%u%%R.wav", spath.c_str(), cnt);
3066 } else if (nchan < 26) {
3067 snprintf (buf, sizeof(buf), "%s-%u%%%c.wav", spath.c_str(), cnt, 'a' + chan);
3069 snprintf (buf, sizeof(buf), "%s-%u.wav", spath.c_str(), cnt);
3073 if (sys::exists(buf)) {
3079 if (existing == 0) {
3084 error << string_compose(_("There are already %1 recordings for %2, which I consider too many."), limit, name) << endmsg;
3086 throw failed_constructor();
3090 /* we now have a unique name for the file, but figure out where to
3096 SessionDirectory sdir(get_best_session_directory_for_new_source ());
3098 spath = sdir.sound_path().to_string();
3101 string::size_type pos = foo.find_last_of ('/');
3103 if (pos == string::npos) {
3106 spath += foo.substr (pos + 1);
3112 boost::shared_ptr<AudioFileSource>
3113 Session::create_audio_source_for_session (AudioDiskstream& ds, uint32_t chan, bool destructive)
3115 string spath = audio_path_from_name (ds.name(), ds.n_channels().n_audio(), chan, destructive);
3116 return boost::dynamic_pointer_cast<AudioFileSource> (
3117 SourceFactory::createWritable (DataType::AUDIO, *this, spath, destructive, frame_rate()));
3120 // FIXME: _terrible_ code duplication
3122 Session::change_midi_path_by_name (string path, string oldname, string newname, bool destructive)
3125 string old_basename = PBD::basename_nosuffix (oldname);
3126 string new_legalized = legalize_for_path (newname);
3128 /* note: we know (or assume) the old path is already valid */
3132 /* destructive file sources have a name of the form:
3134 /path/to/Tnnnn-NAME(%[LR])?.wav
3136 the task here is to replace NAME with the new name.
3139 /* find last slash */
3143 string::size_type slash;
3144 string::size_type dash;
3146 if ((slash = path.find_last_of ('/')) == string::npos) {
3150 dir = path.substr (0, slash+1);
3152 /* '-' is not a legal character for the NAME part of the path */
3154 if ((dash = path.find_last_of ('-')) == string::npos) {
3158 prefix = path.substr (slash+1, dash-(slash+1));
3163 path += new_legalized;
3164 path += ".mid"; /* XXX gag me with a spoon */
3168 /* non-destructive file sources have a name of the form:
3170 /path/to/NAME-nnnnn(%[LR])?.wav
3172 the task here is to replace NAME with the new name.
3177 string::size_type slash;
3178 string::size_type dash;
3179 string::size_type postfix;
3181 /* find last slash */
3183 if ((slash = path.find_last_of ('/')) == string::npos) {
3187 dir = path.substr (0, slash+1);
3189 /* '-' is not a legal character for the NAME part of the path */
3191 if ((dash = path.find_last_of ('-')) == string::npos) {
3195 suffix = path.substr (dash+1);
3197 // Suffix is now everything after the dash. Now we need to eliminate
3198 // the nnnnn part, which is done by either finding a '%' or a '.'
3200 postfix = suffix.find_last_of ("%");
3201 if (postfix == string::npos) {
3202 postfix = suffix.find_last_of ('.');
3205 if (postfix != string::npos) {
3206 suffix = suffix.substr (postfix);
3208 error << "Logic error in Session::change_midi_path_by_name(), please report to the developers" << endl;
3212 const uint32_t limit = 10000;
3213 char buf[PATH_MAX+1];
3215 for (uint32_t cnt = 1; cnt <= limit; ++cnt) {
3217 snprintf (buf, sizeof(buf), "%s%s-%u%s", dir.c_str(), newname.c_str(), cnt, suffix.c_str());
3219 if (access (buf, F_OK) != 0) {
3227 error << "FATAL ERROR! Could not find a " << endl;
3236 Session::midi_path_from_name (string name)
3240 char buf[PATH_MAX+1];
3241 const uint32_t limit = 10000;
3245 legalized = legalize_for_path (name);
3247 /* find a "version" of the file name that doesn't exist in
3248 any of the possible directories.
3251 for (cnt = 1; cnt <= limit; ++cnt) {
3253 vector<space_and_path>::iterator i;
3254 uint32_t existing = 0;
3256 for (i = session_dirs.begin(); i != session_dirs.end(); ++i) {
3258 SessionDirectory sdir((*i).path);
3260 sys::path p = sdir.midi_path();
3264 spath = p.to_string();
3266 snprintf (buf, sizeof(buf), "%s-%u.mid", spath.c_str(), cnt);
3268 if (sys::exists (buf)) {
3273 if (existing == 0) {
3278 error << string_compose(_("There are already %1 recordings for %2, which I consider too many."), limit, name) << endmsg;
3279 throw failed_constructor();
3283 /* we now have a unique name for the file, but figure out where to
3289 SessionDirectory sdir(get_best_session_directory_for_new_source ());
3291 spath = sdir.midi_path().to_string();
3294 string::size_type pos = foo.find_last_of ('/');
3296 if (pos == string::npos) {
3299 spath += foo.substr (pos + 1);
3305 boost::shared_ptr<MidiSource>
3306 Session::create_midi_source_for_session (MidiDiskstream& ds)
3308 string mpath = midi_path_from_name (ds.name());
3310 return boost::dynamic_pointer_cast<SMFSource> (SourceFactory::createWritable (DataType::MIDI, *this, mpath, false, frame_rate()));
3314 /* Playlist management */
3316 boost::shared_ptr<Playlist>
3317 Session::playlist_by_name (string name)
3319 Glib::Mutex::Lock lm (playlist_lock);
3320 for (PlaylistList::iterator i = playlists.begin(); i != playlists.end(); ++i) {
3321 if ((*i)->name() == name) {
3325 for (PlaylistList::iterator i = unused_playlists.begin(); i != unused_playlists.end(); ++i) {
3326 if ((*i)->name() == name) {
3331 return boost::shared_ptr<Playlist>();
3335 Session::add_playlist (boost::shared_ptr<Playlist> playlist)
3337 if (playlist->hidden()) {
3342 Glib::Mutex::Lock lm (playlist_lock);
3343 if (find (playlists.begin(), playlists.end(), playlist) == playlists.end()) {
3344 playlists.insert (playlists.begin(), playlist);
3345 playlist->InUse.connect (sigc::bind (mem_fun (*this, &Session::track_playlist), boost::weak_ptr<Playlist>(playlist)));
3346 playlist->GoingAway.connect (sigc::bind (mem_fun (*this, &Session::remove_playlist), boost::weak_ptr<Playlist>(playlist)));
3352 PlaylistAdded (playlist); /* EMIT SIGNAL */
3356 Session::get_playlists (vector<boost::shared_ptr<Playlist> >& s)
3359 Glib::Mutex::Lock lm (playlist_lock);
3360 for (PlaylistList::iterator i = playlists.begin(); i != playlists.end(); ++i) {
3363 for (PlaylistList::iterator i = unused_playlists.begin(); i != unused_playlists.end(); ++i) {
3370 Session::track_playlist (bool inuse, boost::weak_ptr<Playlist> wpl)
3372 boost::shared_ptr<Playlist> pl(wpl.lock());
3378 PlaylistList::iterator x;
3381 /* its not supposed to be visible */
3386 Glib::Mutex::Lock lm (playlist_lock);
3390 unused_playlists.insert (pl);
3392 if ((x = playlists.find (pl)) != playlists.end()) {
3393 playlists.erase (x);
3399 playlists.insert (pl);
3401 if ((x = unused_playlists.find (pl)) != unused_playlists.end()) {
3402 unused_playlists.erase (x);
3409 Session::remove_playlist (boost::weak_ptr<Playlist> weak_playlist)
3411 if (_state_of_the_state & Deletion) {
3415 boost::shared_ptr<Playlist> playlist (weak_playlist.lock());
3422 Glib::Mutex::Lock lm (playlist_lock);
3424 PlaylistList::iterator i;
3426 i = find (playlists.begin(), playlists.end(), playlist);
3427 if (i != playlists.end()) {
3428 playlists.erase (i);
3431 i = find (unused_playlists.begin(), unused_playlists.end(), playlist);
3432 if (i != unused_playlists.end()) {
3433 unused_playlists.erase (i);
3440 PlaylistRemoved (playlist); /* EMIT SIGNAL */
3444 Session::set_audition (boost::shared_ptr<Region> r)
3446 pending_audition_region = r;
3447 post_transport_work = PostTransportWork (post_transport_work | PostTransportAudition);
3448 schedule_butler_transport_work ();
3452 Session::audition_playlist ()
3454 Event* ev = new Event (Event::Audition, Event::Add, Event::Immediate, 0, 0.0);
3455 ev->region.reset ();
3460 Session::non_realtime_set_audition ()
3462 if (!pending_audition_region) {
3463 auditioner->audition_current_playlist ();
3465 auditioner->audition_region (pending_audition_region);
3466 pending_audition_region.reset ();
3468 AuditionActive (true); /* EMIT SIGNAL */
3472 Session::audition_region (boost::shared_ptr<Region> r)
3474 Event* ev = new Event (Event::Audition, Event::Add, Event::Immediate, 0, 0.0);
3480 Session::cancel_audition ()
3482 if (auditioner->active()) {
3483 auditioner->cancel_audition ();
3484 AuditionActive (false); /* EMIT SIGNAL */
3489 Session::RoutePublicOrderSorter::operator() (boost::shared_ptr<Route> a, boost::shared_ptr<Route> b)
3491 return a->order_key(N_("signal")) < b->order_key(N_("signal"));
3495 Session::remove_empty_sounds ()
3497 vector<string> audio_filenames;
3499 get_files_in_directory (_session_dir->sound_path(), audio_filenames);
3501 Glib::Mutex::Lock lm (source_lock);
3503 TapeFileMatcher tape_file_matcher;
3505 remove_if (audio_filenames.begin(), audio_filenames.end(),
3506 sigc::mem_fun (tape_file_matcher, &TapeFileMatcher::matches));
3508 for (vector<string>::iterator i = audio_filenames.begin(); i != audio_filenames.end(); ++i) {
3510 sys::path audio_file_path (_session_dir->sound_path());
3512 audio_file_path /= *i;
3514 if (AudioFileSource::is_empty (*this, audio_file_path.to_string())) {
3518 sys::remove (audio_file_path);
3519 const string peakfile = peak_path (audio_file_path.to_string());
3520 sys::remove (peakfile);
3522 catch (const sys::filesystem_error& err)
3524 error << err.what() << endmsg;
3531 Session::is_auditioning () const
3533 /* can be called before we have an auditioner object */
3535 return auditioner->active();
3542 Session::set_all_solo (bool yn)
3544 shared_ptr<RouteList> r = routes.reader ();
3546 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3547 if (!(*i)->is_hidden()) {
3548 (*i)->set_solo (yn, this);
3556 Session::set_all_mute (bool yn)
3558 shared_ptr<RouteList> r = routes.reader ();
3560 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3561 if (!(*i)->is_hidden()) {
3562 (*i)->set_mute (yn, this);
3570 Session::n_diskstreams () const
3574 boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
3576 for (DiskstreamList::const_iterator i = dsl->begin(); i != dsl->end(); ++i) {
3577 if (!(*i)->hidden()) {
3585 Session::graph_reordered ()
3587 /* don't do this stuff if we are setting up connections
3588 from a set_state() call or creating new tracks.
3591 if (_state_of_the_state & InitialConnecting) {
3595 /* every track/bus asked for this to be handled but it was deferred because
3596 we were connecting. do it now.
3599 request_input_change_handling ();
3603 /* force all diskstreams to update their capture offset values to
3604 reflect any changes in latencies within the graph.
3607 boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
3609 for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
3610 (*i)->set_capture_offset ();
3615 Session::record_disenable_all ()
3617 record_enable_change_all (false);
3621 Session::record_enable_all ()
3623 record_enable_change_all (true);
3627 Session::record_enable_change_all (bool yn)
3629 shared_ptr<RouteList> r = routes.reader ();
3631 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3634 if ((at = dynamic_cast<Track*>((*i).get())) != 0) {
3635 at->set_record_enable (yn, this);
3639 /* since we don't keep rec-enable state, don't mark session dirty */
3643 Session::add_processor (Processor* processor)
3646 PortInsert* port_insert;
3647 PluginInsert* plugin_insert;
3649 if ((port_insert = dynamic_cast<PortInsert *> (processor)) != 0) {
3650 _port_inserts.insert (_port_inserts.begin(), port_insert);
3651 } else if ((plugin_insert = dynamic_cast<PluginInsert *> (processor)) != 0) {
3652 _plugin_inserts.insert (_plugin_inserts.begin(), plugin_insert);
3653 } else if ((send = dynamic_cast<Send *> (processor)) != 0) {
3654 _sends.insert (_sends.begin(), send);
3656 fatal << _("programming error: unknown type of Insert created!") << endmsg;
3660 processor->GoingAway.connect (sigc::bind (mem_fun (*this, &Session::remove_processor), processor));
3666 Session::remove_processor (Processor* processor)
3669 PortInsert* port_insert;
3670 PluginInsert* plugin_insert;
3672 if ((port_insert = dynamic_cast<PortInsert *> (processor)) != 0) {
3673 list<PortInsert*>::iterator x = find (_port_inserts.begin(), _port_inserts.end(), port_insert);
3674 if (x != _port_inserts.end()) {
3675 insert_bitset[port_insert->bit_slot()] = false;
3676 _port_inserts.erase (x);
3678 } else if ((plugin_insert = dynamic_cast<PluginInsert *> (processor)) != 0) {
3679 _plugin_inserts.remove (plugin_insert);
3680 } else if ((send = dynamic_cast<Send *> (processor)) != 0) {
3681 list<Send*>::iterator x = find (_sends.begin(), _sends.end(), send);
3682 if (x != _sends.end()) {
3683 send_bitset[send->bit_slot()] = false;
3687 fatal << _("programming error: unknown type of Insert deleted!") << endmsg;
3695 Session::available_capture_duration ()
3697 float sample_bytes_on_disk = 4.0; // keep gcc happy
3699 switch (Config->get_native_file_data_format()) {
3701 sample_bytes_on_disk = 4.0;
3705 sample_bytes_on_disk = 3.0;
3709 sample_bytes_on_disk = 2.0;
3713 /* impossible, but keep some gcc versions happy */
3714 fatal << string_compose (_("programming error: %1"),
3715 X_("illegal native file data format"))
3720 double scale = 4096.0 / sample_bytes_on_disk;
3722 if (_total_free_4k_blocks * scale > (double) max_frames) {
3726 return (nframes_t) floor (_total_free_4k_blocks * scale);
3730 Session::add_bundle (shared_ptr<Bundle> bundle)
3733 Glib::Mutex::Lock guard (bundle_lock);
3734 _bundles.push_back (bundle);
3737 BundleAdded (bundle); /* EMIT SIGNAL */
3743 Session::remove_bundle (shared_ptr<Bundle> bundle)
3745 bool removed = false;
3748 Glib::Mutex::Lock guard (bundle_lock);
3749 BundleList::iterator i = find (_bundles.begin(), _bundles.end(), bundle);
3751 if (i != _bundles.end()) {
3758 BundleRemoved (bundle); /* EMIT SIGNAL */
3765 Session::bundle_by_name (string name) const
3767 Glib::Mutex::Lock lm (bundle_lock);
3769 for (BundleList::const_iterator i = _bundles.begin(); i != _bundles.end(); ++i) {
3770 if ((*i)->name() == name) {
3775 return boost::shared_ptr<Bundle> ();
3779 Session::tempo_map_changed (Change ignored)
3783 for (PlaylistList::iterator i = playlists.begin(); i != playlists.end(); ++i) {
3784 (*i)->update_after_tempo_map_change ();
3787 for (PlaylistList::iterator i = unused_playlists.begin(); i != unused_playlists.end(); ++i) {
3788 (*i)->update_after_tempo_map_change ();
3794 /** Ensures that all buffers (scratch, send, silent, etc) are allocated for
3795 * the given count with the current block size.
3798 Session::ensure_buffers (ChanCount howmany)
3800 if (current_block_size == 0)
3801 return; // too early? (is this ok?)
3803 // We need at least 2 MIDI scratch buffers to mix/merge
3804 if (howmany.n_midi() < 2)
3805 howmany.set_midi(2);
3807 // FIXME: JACK needs to tell us maximum MIDI buffer size
3808 // Using nasty assumption (max # events == nframes) for now
3809 _scratch_buffers->ensure_buffers(howmany, current_block_size);
3810 _mix_buffers->ensure_buffers(howmany, current_block_size);
3811 _silent_buffers->ensure_buffers(howmany, current_block_size);
3813 allocate_pan_automation_buffers (current_block_size, howmany.n_audio(), false);
3817 Session::next_insert_id ()
3819 /* this doesn't really loop forever. just think about it */
3822 for (boost::dynamic_bitset<uint32_t>::size_type n = 0; n < insert_bitset.size(); ++n) {
3823 if (!insert_bitset[n]) {
3824 insert_bitset[n] = true;
3830 /* none available, so resize and try again */
3832 insert_bitset.resize (insert_bitset.size() + 16, false);
3837 Session::next_send_id ()
3839 /* this doesn't really loop forever. just think about it */
3842 for (boost::dynamic_bitset<uint32_t>::size_type n = 0; n < send_bitset.size(); ++n) {
3843 if (!send_bitset[n]) {
3844 send_bitset[n] = true;
3850 /* none available, so resize and try again */
3852 send_bitset.resize (send_bitset.size() + 16, false);
3857 Session::mark_send_id (uint32_t id)
3859 if (id >= send_bitset.size()) {
3860 send_bitset.resize (id+16, false);
3862 if (send_bitset[id]) {
3863 warning << string_compose (_("send ID %1 appears to be in use already"), id) << endmsg;
3865 send_bitset[id] = true;
3869 Session::mark_insert_id (uint32_t id)
3871 if (id >= insert_bitset.size()) {
3872 insert_bitset.resize (id+16, false);
3874 if (insert_bitset[id]) {
3875 warning << string_compose (_("insert ID %1 appears to be in use already"), id) << endmsg;
3877 insert_bitset[id] = true;
3880 /* Named Selection management */
3883 Session::named_selection_by_name (string name)
3885 Glib::Mutex::Lock lm (named_selection_lock);
3886 for (NamedSelectionList::iterator i = named_selections.begin(); i != named_selections.end(); ++i) {
3887 if ((*i)->name == name) {
3895 Session::add_named_selection (NamedSelection* named_selection)
3898 Glib::Mutex::Lock lm (named_selection_lock);
3899 named_selections.insert (named_selections.begin(), named_selection);
3902 for (list<boost::shared_ptr<Playlist> >::iterator i = named_selection->playlists.begin(); i != named_selection->playlists.end(); ++i) {
3908 NamedSelectionAdded (); /* EMIT SIGNAL */
3912 Session::remove_named_selection (NamedSelection* named_selection)
3914 bool removed = false;
3917 Glib::Mutex::Lock lm (named_selection_lock);
3919 NamedSelectionList::iterator i = find (named_selections.begin(), named_selections.end(), named_selection);
3921 if (i != named_selections.end()) {
3923 named_selections.erase (i);
3930 NamedSelectionRemoved (); /* EMIT SIGNAL */
3935 Session::reset_native_file_format ()
3937 boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
3939 for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
3940 (*i)->reset_write_sources (false);
3945 Session::route_name_unique (string n) const
3947 shared_ptr<RouteList> r = routes.reader ();
3949 for (RouteList::const_iterator i = r->begin(); i != r->end(); ++i) {
3950 if ((*i)->name() == n) {
3959 Session::n_playlists () const
3961 Glib::Mutex::Lock lm (playlist_lock);
3962 return playlists.size();
3966 Session::allocate_pan_automation_buffers (nframes_t nframes, uint32_t howmany, bool force)
3968 if (!force && howmany <= _npan_buffers) {
3972 if (_pan_automation_buffer) {
3974 for (uint32_t i = 0; i < _npan_buffers; ++i) {
3975 delete [] _pan_automation_buffer[i];
3978 delete [] _pan_automation_buffer;
3981 _pan_automation_buffer = new pan_t*[howmany];
3983 for (uint32_t i = 0; i < howmany; ++i) {
3984 _pan_automation_buffer[i] = new pan_t[nframes];
3987 _npan_buffers = howmany;
3991 Session::freeze (InterThreadInfo& itt)
3993 shared_ptr<RouteList> r = routes.reader ();
3995 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3999 if ((at = dynamic_cast<Track*>((*i).get())) != 0) {
4000 /* XXX this is wrong because itt.progress will keep returning to zero at the start
4011 Session::write_one_audio_track (AudioTrack& track, nframes_t start, nframes_t len,
4012 bool overwrite, vector<boost::shared_ptr<Source> >& srcs, InterThreadInfo& itt)
4015 boost::shared_ptr<Playlist> playlist;
4016 boost::shared_ptr<AudioFileSource> fsource;
4018 char buf[PATH_MAX+1];
4019 ChanCount nchans(track.audio_diskstream()->n_channels());
4021 nframes_t this_chunk;
4024 SessionDirectory sdir(get_best_session_directory_for_new_source ());
4025 const string sound_dir = sdir.sound_path().to_string();
4027 // any bigger than this seems to cause stack overflows in called functions
4028 const nframes_t chunk_size = (128 * 1024)/4;
4030 g_atomic_int_set (&processing_prohibited, 1);
4032 /* call tree *MUST* hold route_lock */
4034 if ((playlist = track.diskstream()->playlist()) == 0) {
4038 /* external redirects will be a problem */
4040 if (track.has_external_redirects()) {
4044 for (uint32_t chan_n=0; chan_n < nchans.n_audio(); ++chan_n) {
4046 for (x = 0; x < 99999; ++x) {
4047 snprintf (buf, sizeof(buf), "%s/%s-%d-bounce-%" PRIu32 ".wav", sound_dir.c_str(), playlist->name().c_str(), chan_n, x+1);
4048 if (access (buf, F_OK) != 0) {
4054 error << string_compose (_("too many bounced versions of playlist \"%1\""), playlist->name()) << endmsg;
4059 fsource = boost::dynamic_pointer_cast<AudioFileSource> (
4060 SourceFactory::createWritable (DataType::AUDIO, *this, buf, false, frame_rate()));
4063 catch (failed_constructor& err) {
4064 error << string_compose (_("cannot create new audio file \"%1\" for %2"), buf, track.name()) << endmsg;
4068 srcs.push_back (fsource);
4071 /* XXX need to flush all redirects */
4076 /* create a set of reasonably-sized buffers */
4077 buffers.ensure_buffers(nchans, chunk_size);
4078 buffers.set_count(nchans);
4080 for (vector<boost::shared_ptr<Source> >::iterator src=srcs.begin(); src != srcs.end(); ++src) {
4081 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
4083 afs->prepare_for_peakfile_writes ();
4086 while (to_do && !itt.cancel) {
4088 this_chunk = min (to_do, chunk_size);
4090 if (track.export_stuff (buffers, start, this_chunk)) {
4095 for (vector<boost::shared_ptr<Source> >::iterator src=srcs.begin(); src != srcs.end(); ++src, ++n) {
4096 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
4099 if (afs->write (buffers.get_audio(n).data(), this_chunk) != this_chunk) {
4105 start += this_chunk;
4106 to_do -= this_chunk;
4108 itt.progress = (float) (1.0 - ((double) to_do / len));
4117 xnow = localtime (&now);
4119 for (vector<boost::shared_ptr<Source> >::iterator src=srcs.begin(); src != srcs.end(); ++src) {
4120 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
4123 afs->update_header (position, *xnow, now);
4124 afs->flush_header ();
4128 /* construct a region to represent the bounced material */
4130 boost::shared_ptr<Region> aregion = RegionFactory::create (srcs, 0, srcs.front()->length(),
4131 region_name_from_path (srcs.front()->name(), true));
4138 for (vector<boost::shared_ptr<Source> >::iterator src = srcs.begin(); src != srcs.end(); ++src) {
4139 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
4142 afs->mark_for_remove ();
4145 (*src)->drop_references ();
4149 for (vector<boost::shared_ptr<Source> >::iterator src = srcs.begin(); src != srcs.end(); ++src) {
4150 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
4153 afs->done_with_peakfile_writes ();
4157 g_atomic_int_set (&processing_prohibited, 0);
4163 Session::get_silent_buffers (ChanCount count)
4165 assert(_silent_buffers->available() >= count);
4166 _silent_buffers->set_count(count);
4168 for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
4169 for (size_t i= 0; i < count.get(*t); ++i) {
4170 _silent_buffers->get(*t, i).clear();
4174 return *_silent_buffers;
4178 Session::get_scratch_buffers (ChanCount count)
4180 assert(_scratch_buffers->available() >= count);
4181 _scratch_buffers->set_count(count);
4182 return *_scratch_buffers;
4186 Session::get_mix_buffers (ChanCount count)
4188 assert(_mix_buffers->available() >= count);
4189 _mix_buffers->set_count(count);
4190 return *_mix_buffers;
4194 Session::ntracks () const
4197 shared_ptr<RouteList> r = routes.reader ();
4199 for (RouteList::const_iterator i = r->begin(); i != r->end(); ++i) {
4200 if (dynamic_cast<Track*> ((*i).get())) {
4209 Session::nbusses () const
4212 shared_ptr<RouteList> r = routes.reader ();
4214 for (RouteList::const_iterator i = r->begin(); i != r->end(); ++i) {
4215 if (dynamic_cast<Track*> ((*i).get()) == 0) {
4224 Session::add_automation_list(AutomationList *al)
4226 automation_lists[al->id()] = al;
4230 Session::compute_initial_length ()
4232 return _engine.frame_rate() * 60 * 5;
4236 Session::sync_order_keys ()
4238 if (!Config->get_sync_all_route_ordering()) {
4239 /* leave order keys as they are */
4243 boost::shared_ptr<RouteList> r = routes.reader ();
4245 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4246 (*i)->sync_order_keys ();
4249 Route::SyncOrderKeys (); // EMIT SIGNAL
4253 Session::foreach_bundle (sigc::slot<void, boost::shared_ptr<Bundle> > sl)
4255 Glib::Mutex::Lock lm (bundle_lock);
4256 for (BundleList::iterator i = _bundles.begin(); i != _bundles.end(); ++i) {