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 _send_smpte_update (false),
134 diskstreams (new DiskstreamList),
135 routes (new RouteList),
136 auditioner ((Auditioner*) 0),
137 _bundle_xml_node (0),
143 if (!eng.connected()) {
144 throw failed_constructor();
147 cerr << "Loading session " << fullpath << " using snapshot " << snapshot_name << " (1)" << endl;
149 n_physical_outputs = _engine.n_physical_outputs();
150 n_physical_inputs = _engine.n_physical_inputs();
152 first_stage_init (fullpath, snapshot_name);
154 new_session = !Glib::file_test (_path, Glib::FileTest (G_FILE_TEST_EXISTS | G_FILE_TEST_IS_DIR));
157 if (create (new_session, mix_template, compute_initial_length())) {
159 throw failed_constructor ();
163 if (second_stage_init (new_session)) {
165 throw failed_constructor ();
168 store_recent_sessions(_name, _path);
170 bool was_dirty = dirty();
172 _state_of_the_state = StateOfTheState (_state_of_the_state & ~Dirty);
174 Config->ParameterChanged.connect (mem_fun (*this, &Session::config_changed));
177 DirtyChanged (); /* EMIT SIGNAL */
181 Session::Session (AudioEngine &eng,
183 string snapshot_name,
184 AutoConnectOption input_ac,
185 AutoConnectOption output_ac,
186 uint32_t control_out_channels,
187 uint32_t master_out_channels,
188 uint32_t requested_physical_in,
189 uint32_t requested_physical_out,
190 nframes_t initial_length)
193 _scratch_buffers(new BufferSet()),
194 _silent_buffers(new BufferSet()),
195 _mix_buffers(new BufferSet()),
196 _mmc_port (default_mmc_port),
197 _mtc_port (default_mtc_port),
198 _midi_port (default_midi_port),
199 _session_dir ( new SessionDirectory(fullpath)),
200 pending_events (2048),
201 //midi_requests (16),
202 _send_smpte_update (false),
203 diskstreams (new DiskstreamList),
204 routes (new RouteList),
205 _bundle_xml_node (0),
211 if (!eng.connected()) {
212 throw failed_constructor();
215 cerr << "Loading session " << fullpath << " using snapshot " << snapshot_name << " (2)" << endl;
217 n_physical_outputs = _engine.n_physical_outputs();
218 n_physical_inputs = _engine.n_physical_inputs();
220 if (n_physical_inputs) {
221 n_physical_inputs = max (requested_physical_in, n_physical_inputs);
224 if (n_physical_outputs) {
225 n_physical_outputs = max (requested_physical_out, n_physical_outputs);
228 first_stage_init (fullpath, snapshot_name);
230 new_session = !g_file_test (_path.c_str(), GFileTest (G_FILE_TEST_EXISTS | G_FILE_TEST_IS_DIR));
233 if (create (new_session, string(), initial_length)) {
235 throw failed_constructor ();
240 /* set up Master Out and Control Out if necessary */
245 if (control_out_channels) {
246 shared_ptr<Route> r (new Route (*this, _("monitor"), -1, control_out_channels, -1, control_out_channels, Route::ControlOut));
247 r->set_remote_control_id (control_id++);
252 if (master_out_channels) {
253 shared_ptr<Route> r (new Route (*this, _("master"), -1, master_out_channels, -1, master_out_channels, Route::MasterOut));
254 r->set_remote_control_id (control_id);
258 /* prohibit auto-connect to master, because there isn't one */
259 output_ac = AutoConnectOption (output_ac & ~AutoConnectMaster);
263 add_routes (rl, false);
268 Config->set_input_auto_connect (input_ac);
269 Config->set_output_auto_connect (output_ac);
271 if (second_stage_init (new_session)) {
273 throw failed_constructor ();
276 store_recent_sessions (_name, _path);
278 _state_of_the_state = StateOfTheState (_state_of_the_state & ~Dirty);
280 Config->ParameterChanged.connect (mem_fun (*this, &Session::config_changed));
291 /* if we got to here, leaving pending capture state around
295 remove_pending_capture_state ();
297 _state_of_the_state = StateOfTheState (CannotSave|Deletion);
299 _engine.remove_session ();
301 GoingAway (); /* EMIT SIGNAL */
307 /* clear history so that no references to objects are held any more */
311 /* clear state tree so that no references to objects are held any more */
317 terminate_butler_thread ();
318 //terminate_midi_thread ();
320 if (click_data && click_data != default_click) {
321 delete [] click_data;
324 if (click_emphasis_data && click_emphasis_data != default_click_emphasis) {
325 delete [] click_emphasis_data;
330 delete _scratch_buffers;
331 delete _silent_buffers;
334 AudioDiskstream::free_working_buffers();
336 #undef TRACK_DESTRUCTION
337 #ifdef TRACK_DESTRUCTION
338 cerr << "delete named selections\n";
339 #endif /* TRACK_DESTRUCTION */
340 for (NamedSelectionList::iterator i = named_selections.begin(); i != named_selections.end(); ) {
341 NamedSelectionList::iterator tmp;
350 #ifdef TRACK_DESTRUCTION
351 cerr << "delete playlists\n";
352 #endif /* TRACK_DESTRUCTION */
353 for (PlaylistList::iterator i = playlists.begin(); i != playlists.end(); ) {
354 PlaylistList::iterator tmp;
359 (*i)->drop_references ();
364 for (PlaylistList::iterator i = unused_playlists.begin(); i != unused_playlists.end(); ) {
365 PlaylistList::iterator tmp;
370 (*i)->drop_references ();
376 unused_playlists.clear ();
378 #ifdef TRACK_DESTRUCTION
379 cerr << "delete regions\n";
380 #endif /* TRACK_DESTRUCTION */
382 for (RegionList::iterator i = regions.begin(); i != regions.end(); ) {
383 RegionList::iterator tmp;
388 i->second->drop_references ();
395 #ifdef TRACK_DESTRUCTION
396 cerr << "delete routes\n";
397 #endif /* TRACK_DESTRUCTION */
399 RCUWriter<RouteList> writer (routes);
400 boost::shared_ptr<RouteList> r = writer.get_copy ();
401 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
402 (*i)->drop_references ();
405 /* writer goes out of scope and updates master */
410 #ifdef TRACK_DESTRUCTION
411 cerr << "delete diskstreams\n";
412 #endif /* TRACK_DESTRUCTION */
414 RCUWriter<DiskstreamList> dwriter (diskstreams);
415 boost::shared_ptr<DiskstreamList> dsl = dwriter.get_copy();
416 for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
417 (*i)->drop_references ();
421 diskstreams.flush ();
423 #ifdef TRACK_DESTRUCTION
424 cerr << "delete audio sources\n";
425 #endif /* TRACK_DESTRUCTION */
426 for (SourceMap::iterator i = sources.begin(); i != sources.end(); ) {
427 SourceMap::iterator tmp;
432 i->second->drop_references ();
439 #ifdef TRACK_DESTRUCTION
440 cerr << "delete mix groups\n";
441 #endif /* TRACK_DESTRUCTION */
442 for (list<RouteGroup *>::iterator i = mix_groups.begin(); i != mix_groups.end(); ) {
443 list<RouteGroup*>::iterator tmp;
453 #ifdef TRACK_DESTRUCTION
454 cerr << "delete edit groups\n";
455 #endif /* TRACK_DESTRUCTION */
456 for (list<RouteGroup *>::iterator i = edit_groups.begin(); i != edit_groups.end(); ) {
457 list<RouteGroup*>::iterator tmp;
467 if (butler_mixdown_buffer) {
468 delete [] butler_mixdown_buffer;
471 if (butler_gain_buffer) {
472 delete [] butler_gain_buffer;
475 Crossfade::set_buffer_size (0);
483 Session::set_worst_io_latencies ()
485 _worst_output_latency = 0;
486 _worst_input_latency = 0;
488 if (!_engine.connected()) {
492 boost::shared_ptr<RouteList> r = routes.reader ();
494 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
495 _worst_output_latency = max (_worst_output_latency, (*i)->output_latency());
496 _worst_input_latency = max (_worst_input_latency, (*i)->input_latency());
501 Session::when_engine_running ()
503 string first_physical_output;
505 /* we don't want to run execute this again */
507 set_block_size (_engine.frames_per_cycle());
508 set_frame_rate (_engine.frame_rate());
510 Config->map_parameters (mem_fun (*this, &Session::config_changed));
512 /* every time we reconnect, recompute worst case output latencies */
514 _engine.Running.connect (mem_fun (*this, &Session::set_worst_io_latencies));
516 if (synced_to_jack()) {
517 _engine.transport_stop ();
520 if (Config->get_jack_time_master()) {
521 _engine.transport_locate (_transport_frame);
529 _click_io.reset (new ClickIO (*this, "click", 0, 0, -1, -1));
531 if (state_tree && (child = find_named_node (*state_tree->root(), "Click")) != 0) {
533 /* existing state for Click */
535 if (_click_io->set_state (*child->children().front()) == 0) {
537 _clicking = Config->get_clicking ();
541 error << _("could not setup Click I/O") << endmsg;
547 /* default state for Click */
549 first_physical_output = _engine.get_nth_physical_output (DataType::AUDIO, 0);
551 if (first_physical_output.length()) {
552 if (_click_io->add_output_port (first_physical_output, this)) {
553 // relax, even though its an error
555 _clicking = Config->get_clicking ();
561 catch (failed_constructor& err) {
562 error << _("cannot setup Click I/O") << endmsg;
565 set_worst_io_latencies ();
568 // XXX HOW TO ALERT UI TO THIS ? DO WE NEED TO?
571 /* Create a set of Bundle objects that map
572 to the physical outputs currently available
577 for (uint32_t np = 0; np < n_physical_outputs; ++np) {
579 snprintf (buf, sizeof (buf), _("out %" PRIu32), np+1);
581 shared_ptr<AutoBundle> c (new AutoBundle (buf, true));
583 c->set_port (0, _engine.get_nth_physical_output (DataType::AUDIO, np));
588 for (uint32_t np = 0; np < n_physical_inputs; ++np) {
590 snprintf (buf, sizeof (buf), _("in %" PRIu32), np+1);
592 shared_ptr<AutoBundle> c (new AutoBundle (buf, false));
594 c->set_port (0, _engine.get_nth_physical_input (DataType::AUDIO, np));
601 for (uint32_t np = 0; np < n_physical_outputs; np +=2) {
603 snprintf (buf, sizeof (buf), _("out %" PRIu32 "+%" PRIu32), np+1, np+2);
605 shared_ptr<AutoBundle> c (new AutoBundle (buf, true));
607 c->set_port (0, _engine.get_nth_physical_output (DataType::AUDIO, np));
608 c->set_port (1, _engine.get_nth_physical_output (DataType::AUDIO, np + 1));
613 for (uint32_t np = 0; np < n_physical_inputs; np +=2) {
615 snprintf (buf, sizeof (buf), _("in %" PRIu32 "+%" PRIu32), np+1, np+2);
617 shared_ptr<AutoBundle> c (new AutoBundle (buf, false));
619 c->set_port (0, _engine.get_nth_physical_input (DataType::AUDIO, np));
620 c->set_port (1, _engine.get_nth_physical_input (DataType::AUDIO, np + 1));
629 /* create master/control ports */
634 /* force the master to ignore any later call to this */
636 if (_master_out->pending_state_node) {
637 _master_out->ports_became_legal();
640 /* no panner resets till we are through */
642 _master_out->defer_pan_reset ();
644 while (_master_out->n_inputs().n_audio()
645 < _master_out->input_maximum().n_audio()) {
646 if (_master_out->add_input_port ("", this, DataType::AUDIO)) {
647 error << _("cannot setup master inputs")
653 while (_master_out->n_outputs().n_audio()
654 < _master_out->output_maximum().n_audio()) {
655 if (_master_out->add_output_port (_engine.get_nth_physical_output (DataType::AUDIO, n), this, DataType::AUDIO)) {
656 error << _("cannot setup master outputs")
663 _master_out->allow_pan_reset ();
667 shared_ptr<AutoBundle> c (new AutoBundle (_("Master Out"), true));
669 c->set_channels (_master_out->n_inputs().n_total());
670 for (uint32_t n = 0; n < _master_out->n_inputs ().n_total(); ++n) {
671 c->set_port (n, _master_out->input(n)->name());
678 /* catch up on send+insert cnts */
682 for (list<PortInsert*>::iterator i = _port_inserts.begin(); i != _port_inserts.end(); ++i) {
685 if (sscanf ((*i)->name().c_str(), "%*s %u", &id) == 1) {
686 if (id > insert_cnt) {
694 for (list<Send*>::iterator i = _sends.begin(); i != _sends.end(); ++i) {
697 if (sscanf ((*i)->name().c_str(), "%*s %u", &id) == 1) {
705 _state_of_the_state = StateOfTheState (_state_of_the_state & ~(CannotSave|Dirty));
708 /* hook us up to the engine */
710 _engine.set_session (this);
715 osc->set_session (*this);
721 Session::hookup_io ()
723 /* stop graph reordering notifications from
724 causing resorts, etc.
727 _state_of_the_state = StateOfTheState (_state_of_the_state | InitialConnecting);
730 if (auditioner == 0) {
732 /* we delay creating the auditioner till now because
733 it makes its own connections to ports.
734 the engine has to be running for this to work.
738 auditioner.reset (new Auditioner (*this));
741 catch (failed_constructor& err) {
742 warning << _("cannot create Auditioner: no auditioning of regions possible") << endmsg;
746 /* Tell all IO objects to create their ports */
752 vector<string> cports;
754 while (_control_out->n_inputs().n_audio() < _control_out->input_maximum().n_audio()) {
755 if (_control_out->add_input_port ("", this)) {
756 error << _("cannot setup control inputs")
762 while (_control_out->n_outputs().n_audio() < _control_out->output_maximum().n_audio()) {
763 if (_control_out->add_output_port (_engine.get_nth_physical_output (DataType::AUDIO, n), this)) {
764 error << _("cannot set up master outputs")
772 uint32_t ni = _control_out->n_inputs().get (DataType::AUDIO);
774 for (n = 0; n < ni; ++n) {
775 cports.push_back (_control_out->input(n)->name());
778 boost::shared_ptr<RouteList> r = routes.reader ();
780 for (RouteList::iterator x = r->begin(); x != r->end(); ++x) {
781 (*x)->set_control_outs (cports);
785 /* load bundles, which we may have postponed earlier on */
786 if (_bundle_xml_node) {
787 load_bundles (*_bundle_xml_node);
788 delete _bundle_xml_node;
791 /* Tell all IO objects to connect themselves together */
793 IO::enable_connecting ();
795 /* Now reset all panners */
797 IO::reset_panners ();
799 /* Anyone who cares about input state, wake up and do something */
801 IOConnectionsComplete (); /* EMIT SIGNAL */
803 _state_of_the_state = StateOfTheState (_state_of_the_state & ~InitialConnecting);
806 /* now handle the whole enchilada as if it was one
812 /* update mixer solo state */
818 Session::playlist_length_changed ()
820 /* we can't just increase end_location->end() if pl->get_maximum_extent()
821 if larger. if the playlist used to be the longest playlist,
822 and its now shorter, we have to decrease end_location->end(). hence,
823 we have to iterate over all diskstreams and check the
824 playlists currently in use.
830 Session::diskstream_playlist_changed (boost::shared_ptr<Diskstream> dstream)
832 boost::shared_ptr<Playlist> playlist;
834 if ((playlist = dstream->playlist()) != 0) {
835 playlist->LengthChanged.connect (mem_fun (this, &Session::playlist_length_changed));
838 /* see comment in playlist_length_changed () */
843 Session::record_enabling_legal () const
845 /* this used to be in here, but survey says.... we don't need to restrict it */
846 // if (record_status() == Recording) {
850 if (Config->get_all_safe()) {
857 Session::reset_input_monitor_state ()
859 if (transport_rolling()) {
861 boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
863 for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
864 if ((*i)->record_enabled ()) {
865 //cerr << "switching to input = " << !auto_input << __FILE__ << __LINE__ << endl << endl;
866 (*i)->monitor_input (Config->get_monitoring_model() == HardwareMonitoring && !Config->get_auto_input());
870 boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
872 for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
873 if ((*i)->record_enabled ()) {
874 //cerr << "switching to input = " << !Config->get_auto_input() << __FILE__ << __LINE__ << endl << endl;
875 (*i)->monitor_input (Config->get_monitoring_model() == HardwareMonitoring);
882 Session::auto_punch_start_changed (Location* location)
884 replace_event (Event::PunchIn, location->start());
886 if (get_record_enabled() && Config->get_punch_in()) {
887 /* capture start has been changed, so save new pending state */
888 save_state ("", true);
893 Session::auto_punch_end_changed (Location* location)
895 nframes_t when_to_stop = location->end();
896 // when_to_stop += _worst_output_latency + _worst_input_latency;
897 replace_event (Event::PunchOut, when_to_stop);
901 Session::auto_punch_changed (Location* location)
903 nframes_t when_to_stop = location->end();
905 replace_event (Event::PunchIn, location->start());
906 //when_to_stop += _worst_output_latency + _worst_input_latency;
907 replace_event (Event::PunchOut, when_to_stop);
911 Session::auto_loop_changed (Location* location)
913 replace_event (Event::AutoLoop, location->end(), location->start());
915 if (transport_rolling() && play_loop) {
917 //if (_transport_frame < location->start() || _transport_frame > location->end()) {
919 if (_transport_frame > location->end()) {
920 // relocate to beginning of loop
921 clear_events (Event::LocateRoll);
923 request_locate (location->start(), true);
926 else if (Config->get_seamless_loop() && !loop_changing) {
928 // schedule a locate-roll to refill the diskstreams at the
930 loop_changing = true;
932 if (location->end() > last_loopend) {
933 clear_events (Event::LocateRoll);
934 Event *ev = new Event (Event::LocateRoll, Event::Add, last_loopend, last_loopend, 0, true);
941 last_loopend = location->end();
946 Session::set_auto_punch_location (Location* location)
950 if ((existing = _locations.auto_punch_location()) != 0 && existing != location) {
951 auto_punch_start_changed_connection.disconnect();
952 auto_punch_end_changed_connection.disconnect();
953 auto_punch_changed_connection.disconnect();
954 existing->set_auto_punch (false, this);
955 remove_event (existing->start(), Event::PunchIn);
956 clear_events (Event::PunchOut);
957 auto_punch_location_changed (0);
966 if (location->end() <= location->start()) {
967 error << _("Session: you can't use that location for auto punch (start <= end)") << endmsg;
971 auto_punch_start_changed_connection.disconnect();
972 auto_punch_end_changed_connection.disconnect();
973 auto_punch_changed_connection.disconnect();
975 auto_punch_start_changed_connection = location->start_changed.connect (mem_fun (this, &Session::auto_punch_start_changed));
976 auto_punch_end_changed_connection = location->end_changed.connect (mem_fun (this, &Session::auto_punch_end_changed));
977 auto_punch_changed_connection = location->changed.connect (mem_fun (this, &Session::auto_punch_changed));
979 location->set_auto_punch (true, this);
980 auto_punch_location_changed (location);
984 Session::set_auto_loop_location (Location* location)
988 if ((existing = _locations.auto_loop_location()) != 0 && existing != location) {
989 auto_loop_start_changed_connection.disconnect();
990 auto_loop_end_changed_connection.disconnect();
991 auto_loop_changed_connection.disconnect();
992 existing->set_auto_loop (false, this);
993 remove_event (existing->end(), Event::AutoLoop);
994 auto_loop_location_changed (0);
1003 if (location->end() <= location->start()) {
1004 error << _("Session: you can't use a mark for auto loop") << endmsg;
1008 last_loopend = location->end();
1010 auto_loop_start_changed_connection.disconnect();
1011 auto_loop_end_changed_connection.disconnect();
1012 auto_loop_changed_connection.disconnect();
1014 auto_loop_start_changed_connection = location->start_changed.connect (mem_fun (this, &Session::auto_loop_changed));
1015 auto_loop_end_changed_connection = location->end_changed.connect (mem_fun (this, &Session::auto_loop_changed));
1016 auto_loop_changed_connection = location->changed.connect (mem_fun (this, &Session::auto_loop_changed));
1018 location->set_auto_loop (true, this);
1019 auto_loop_location_changed (location);
1023 Session::locations_added (Location* ignored)
1029 Session::locations_changed ()
1031 _locations.apply (*this, &Session::handle_locations_changed);
1035 Session::handle_locations_changed (Locations::LocationList& locations)
1037 Locations::LocationList::iterator i;
1039 bool set_loop = false;
1040 bool set_punch = false;
1042 for (i = locations.begin(); i != locations.end(); ++i) {
1046 if (location->is_auto_punch()) {
1047 set_auto_punch_location (location);
1050 if (location->is_auto_loop()) {
1051 set_auto_loop_location (location);
1058 set_auto_loop_location (0);
1061 set_auto_punch_location (0);
1068 Session::enable_record ()
1070 /* XXX really atomic compare+swap here */
1071 if (g_atomic_int_get (&_record_status) != Recording) {
1072 g_atomic_int_set (&_record_status, Recording);
1073 _last_record_location = _transport_frame;
1074 deliver_mmc(MIDI::MachineControl::cmdRecordStrobe, _last_record_location);
1076 if (Config->get_monitoring_model() == HardwareMonitoring && Config->get_auto_input()) {
1077 boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
1078 for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
1079 if ((*i)->record_enabled ()) {
1080 (*i)->monitor_input (true);
1085 RecordStateChanged ();
1090 Session::disable_record (bool rt_context, bool force)
1094 if ((rs = (RecordState) g_atomic_int_get (&_record_status)) != Disabled) {
1096 if ((!Config->get_latched_record_enable () && !play_loop) || force) {
1097 g_atomic_int_set (&_record_status, Disabled);
1099 if (rs == Recording) {
1100 g_atomic_int_set (&_record_status, Enabled);
1104 // FIXME: timestamp correct? [DR]
1105 // FIXME FIXME FIXME: rt_context? this must be called in the process thread.
1106 // does this /need/ to be sent in all cases?
1108 deliver_mmc (MIDI::MachineControl::cmdRecordExit, _transport_frame);
1110 if (Config->get_monitoring_model() == HardwareMonitoring && Config->get_auto_input()) {
1111 boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
1113 for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
1114 if ((*i)->record_enabled ()) {
1115 (*i)->monitor_input (false);
1120 RecordStateChanged (); /* emit signal */
1123 remove_pending_capture_state ();
1129 Session::step_back_from_record ()
1131 /* XXX really atomic compare+swap here */
1132 if (g_atomic_int_get (&_record_status) == Recording) {
1133 g_atomic_int_set (&_record_status, Enabled);
1135 if (Config->get_monitoring_model() == HardwareMonitoring) {
1136 boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
1138 for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
1139 if (Config->get_auto_input() && (*i)->record_enabled ()) {
1140 //cerr << "switching from input" << __FILE__ << __LINE__ << endl << endl;
1141 (*i)->monitor_input (false);
1149 Session::maybe_enable_record ()
1151 g_atomic_int_set (&_record_status, Enabled);
1153 /* this function is currently called from somewhere other than an RT thread.
1154 this save_state() call therefore doesn't impact anything.
1157 save_state ("", true);
1159 if (_transport_speed) {
1160 if (!Config->get_punch_in()) {
1164 deliver_mmc (MIDI::MachineControl::cmdRecordPause, _transport_frame);
1165 RecordStateChanged (); /* EMIT SIGNAL */
1172 Session::audible_frame () const
1178 /* the first of these two possible settings for "offset"
1179 mean that the audible frame is stationary until
1180 audio emerges from the latency compensation
1183 the second means that the audible frame is stationary
1184 until audio would emerge from a physical port
1185 in the absence of any plugin latency compensation
1188 offset = _worst_output_latency;
1190 if (offset > current_block_size) {
1191 offset -= current_block_size;
1193 /* XXX is this correct? if we have no external
1194 physical connections and everything is internal
1195 then surely this is zero? still, how
1196 likely is that anyway?
1198 offset = current_block_size;
1201 if (synced_to_jack()) {
1202 tf = _engine.transport_frame();
1204 tf = _transport_frame;
1207 if (_transport_speed == 0) {
1217 if (!non_realtime_work_pending()) {
1221 /* take latency into account */
1230 Session::set_frame_rate (nframes_t frames_per_second)
1232 /** \fn void Session::set_frame_size(nframes_t)
1233 the AudioEngine object that calls this guarantees
1234 that it will not be called while we are also in
1235 ::process(). Its fine to do things that block
1239 _base_frame_rate = frames_per_second;
1243 Automatable::set_automation_interval ((jack_nframes_t) ceil ((double) frames_per_second * (0.001 * Config->get_automation_interval())));
1247 // XXX we need some equivalent to this, somehow
1248 // SndFileSource::setup_standard_crossfades (frames_per_second);
1252 /* XXX need to reset/reinstantiate all LADSPA plugins */
1256 Session::set_block_size (nframes_t nframes)
1258 /* the AudioEngine guarantees
1259 that it will not be called while we are also in
1260 ::process(). It is therefore fine to do things that block
1266 current_block_size = nframes;
1268 ensure_buffers(_scratch_buffers->available());
1270 if (_gain_automation_buffer) {
1271 delete [] _gain_automation_buffer;
1273 _gain_automation_buffer = new gain_t[nframes];
1275 allocate_pan_automation_buffers (nframes, _npan_buffers, true);
1277 boost::shared_ptr<RouteList> r = routes.reader ();
1279 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
1280 (*i)->set_block_size (nframes);
1283 boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
1284 for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
1285 (*i)->set_block_size (nframes);
1288 set_worst_io_latencies ();
1293 Session::set_default_fade (float steepness, float fade_msecs)
1296 nframes_t fade_frames;
1298 /* Don't allow fade of less 1 frame */
1300 if (fade_msecs < (1000.0 * (1.0/_current_frame_rate))) {
1307 fade_frames = (nframes_t) floor (fade_msecs * _current_frame_rate * 0.001);
1311 default_fade_msecs = fade_msecs;
1312 default_fade_steepness = steepness;
1315 // jlc, WTF is this!
1316 Glib::RWLock::ReaderLock lm (route_lock);
1317 AudioRegion::set_default_fade (steepness, fade_frames);
1322 /* XXX have to do this at some point */
1323 /* foreach region using default fade, reset, then
1324 refill_all_diskstream_buffers ();
1329 struct RouteSorter {
1330 bool operator() (boost::shared_ptr<Route> r1, boost::shared_ptr<Route> r2) {
1331 if (r1->fed_by.find (r2) != r1->fed_by.end()) {
1333 } else if (r2->fed_by.find (r1) != r2->fed_by.end()) {
1336 if (r1->fed_by.empty()) {
1337 if (r2->fed_by.empty()) {
1338 /* no ardour-based connections inbound to either route. just use signal order */
1339 return r1->order_key(N_("signal")) < r2->order_key(N_("signal"));
1341 /* r2 has connections, r1 does not; run r1 early */
1345 return r1->order_key(N_("signal")) < r2->order_key(N_("signal"));
1352 trace_terminal (shared_ptr<Route> r1, shared_ptr<Route> rbase)
1354 shared_ptr<Route> r2;
1356 if ((r1->fed_by.find (rbase) != r1->fed_by.end()) && (rbase->fed_by.find (r1) != rbase->fed_by.end())) {
1357 info << string_compose(_("feedback loop setup between %1 and %2"), r1->name(), rbase->name()) << endmsg;
1361 /* make a copy of the existing list of routes that feed r1 */
1363 set<shared_ptr<Route> > existing = r1->fed_by;
1365 /* for each route that feeds r1, recurse, marking it as feeding
1369 for (set<shared_ptr<Route> >::iterator i = existing.begin(); i != existing.end(); ++i) {
1372 /* r2 is a route that feeds r1 which somehow feeds base. mark
1373 base as being fed by r2
1376 rbase->fed_by.insert (r2);
1380 /* 2nd level feedback loop detection. if r1 feeds or is fed by r2,
1384 if ((r1->fed_by.find (r2) != r1->fed_by.end()) && (r2->fed_by.find (r1) != r2->fed_by.end())) {
1388 /* now recurse, so that we can mark base as being fed by
1389 all routes that feed r2
1392 trace_terminal (r2, rbase);
1399 Session::resort_routes ()
1401 /* don't do anything here with signals emitted
1402 by Routes while we are being destroyed.
1405 if (_state_of_the_state & Deletion) {
1412 RCUWriter<RouteList> writer (routes);
1413 shared_ptr<RouteList> r = writer.get_copy ();
1414 resort_routes_using (r);
1415 /* writer goes out of scope and forces update */
1420 Session::resort_routes_using (shared_ptr<RouteList> r)
1422 RouteList::iterator i, j;
1424 for (i = r->begin(); i != r->end(); ++i) {
1426 (*i)->fed_by.clear ();
1428 for (j = r->begin(); j != r->end(); ++j) {
1430 /* although routes can feed themselves, it will
1431 cause an endless recursive descent if we
1432 detect it. so don't bother checking for
1440 if ((*j)->feeds (*i)) {
1441 (*i)->fed_by.insert (*j);
1446 for (i = r->begin(); i != r->end(); ++i) {
1447 trace_terminal (*i, *i);
1454 cerr << "finished route resort\n";
1456 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
1457 cerr << " " << (*i)->name() << " signal order = " << (*i)->order_key ("signal") << endl;
1464 list<boost::shared_ptr<MidiTrack> >
1465 Session::new_midi_track (TrackMode mode, uint32_t how_many)
1467 char track_name[32];
1468 uint32_t track_id = 0;
1471 RouteList new_routes;
1472 list<boost::shared_ptr<MidiTrack> > ret;
1473 //uint32_t control_id;
1475 // FIXME: need physical I/O and autoconnect stuff for MIDI
1477 /* count existing midi tracks */
1480 shared_ptr<RouteList> r = routes.reader ();
1482 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
1483 if (dynamic_cast<MidiTrack*>((*i).get()) != 0) {
1484 if (!(*i)->is_hidden()) {
1486 //channels_used += (*i)->n_inputs().n_midi();
1493 vector<string> physinputs;
1494 vector<string> physoutputs;
1495 uint32_t nphysical_in;
1496 uint32_t nphysical_out;
1498 _engine.get_physical_outputs (physoutputs);
1499 _engine.get_physical_inputs (physinputs);
1500 control_id = ntracks() + nbusses() + 1;
1505 /* check for duplicate route names, since we might have pre-existing
1506 routes with this name (e.g. create Audio1, Audio2, delete Audio1,
1507 save, close,restart,add new route - first named route is now
1515 snprintf (track_name, sizeof(track_name), "Midi %" PRIu32, track_id);
1517 if (route_by_name (track_name) == 0) {
1521 } while (track_id < (UINT_MAX-1));
1524 if (Config->get_input_auto_connect() & AutoConnectPhysical) {
1525 nphysical_in = min (n_physical_inputs, (uint32_t) physinputs.size());
1530 if (Config->get_output_auto_connect() & AutoConnectPhysical) {
1531 nphysical_out = min (n_physical_outputs, (uint32_t) physinputs.size());
1537 shared_ptr<MidiTrack> track;
1540 track = boost::shared_ptr<MidiTrack>((new MidiTrack (*this, track_name, Route::Flag (0), mode)));
1542 if (track->ensure_io (ChanCount(DataType::MIDI, 1), ChanCount(DataType::AUDIO, 1), false, this)) {
1543 error << "cannot configure 1 in/1 out configuration for new midi track" << endmsg;
1549 for (uint32_t x = 0; x < track->n_inputs().n_midi() && x < nphysical_in; ++x) {
1553 if (Config->get_input_auto_connect() & AutoConnectPhysical) {
1554 port = physinputs[(channels_used+x)%nphysical_in];
1557 if (port.length() && track->connect_input (track->input (x), port, this)) {
1563 for (uint32_t x = 0; x < track->n_outputs().n_midi(); ++x) {
1567 if (nphysical_out && (Config->get_output_auto_connect() & AutoConnectPhysical)) {
1568 port = physoutputs[(channels_used+x)%nphysical_out];
1569 } else if (Config->get_output_auto_connect() & AutoConnectMaster) {
1571 port = _master_out->input (x%_master_out->n_inputs().n_midi())->name();
1575 if (port.length() && track->connect_output (track->output (x), port, this)) {
1580 channels_used += track->n_inputs ().n_midi();
1584 track->midi_diskstream()->non_realtime_input_change();
1586 track->DiskstreamChanged.connect (mem_fun (this, &Session::resort_routes));
1587 //track->set_remote_control_id (control_id);
1589 new_routes.push_back (track);
1590 ret.push_back (track);
1593 catch (failed_constructor &err) {
1594 error << _("Session: could not create new midi track.") << endmsg;
1597 /* we need to get rid of this, since the track failed to be created */
1598 /* XXX arguably, AudioTrack::AudioTrack should not do the Session::add_diskstream() */
1601 RCUWriter<DiskstreamList> writer (diskstreams);
1602 boost::shared_ptr<DiskstreamList> ds = writer.get_copy();
1603 ds->remove (track->midi_diskstream());
1610 catch (AudioEngine::PortRegistrationFailure& pfe) {
1612 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;
1615 /* we need to get rid of this, since the track failed to be created */
1616 /* XXX arguably, MidiTrack::MidiTrack should not do the Session::add_diskstream() */
1619 RCUWriter<DiskstreamList> writer (diskstreams);
1620 boost::shared_ptr<DiskstreamList> ds = writer.get_copy();
1621 ds->remove (track->midi_diskstream());
1632 if (!new_routes.empty()) {
1633 add_routes (new_routes, false);
1634 save_state (_current_snapshot_name);
1640 list<boost::shared_ptr<AudioTrack> >
1641 Session::new_audio_track (int input_channels, int output_channels, TrackMode mode, uint32_t how_many)
1643 char track_name[32];
1644 uint32_t track_id = 0;
1646 uint32_t channels_used = 0;
1648 RouteList new_routes;
1649 list<boost::shared_ptr<AudioTrack> > ret;
1650 uint32_t control_id;
1652 /* count existing audio tracks */
1655 shared_ptr<RouteList> r = routes.reader ();
1657 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
1658 if (dynamic_cast<AudioTrack*>((*i).get()) != 0) {
1659 if (!(*i)->is_hidden()) {
1661 channels_used += (*i)->n_inputs().n_audio();
1667 vector<string> physinputs;
1668 vector<string> physoutputs;
1669 uint32_t nphysical_in;
1670 uint32_t nphysical_out;
1672 _engine.get_physical_outputs (physoutputs);
1673 _engine.get_physical_inputs (physinputs);
1674 control_id = ntracks() + nbusses() + 1;
1678 /* check for duplicate route names, since we might have pre-existing
1679 routes with this name (e.g. create Audio1, Audio2, delete Audio1,
1680 save, close,restart,add new route - first named route is now
1688 snprintf (track_name, sizeof(track_name), "Audio %" PRIu32, track_id);
1690 if (route_by_name (track_name) == 0) {
1694 } while (track_id < (UINT_MAX-1));
1696 if (Config->get_input_auto_connect() & AutoConnectPhysical) {
1697 nphysical_in = min (n_physical_inputs, (uint32_t) physinputs.size());
1702 if (Config->get_output_auto_connect() & AutoConnectPhysical) {
1703 nphysical_out = min (n_physical_outputs, (uint32_t) physinputs.size());
1708 shared_ptr<AudioTrack> track;
1711 track = boost::shared_ptr<AudioTrack>((new AudioTrack (*this, track_name, Route::Flag (0), mode)));
1713 if (track->ensure_io (ChanCount(DataType::AUDIO, input_channels), ChanCount(DataType::AUDIO, output_channels), false, this)) {
1714 error << string_compose (_("cannot configure %1 in/%2 out configuration for new audio track"),
1715 input_channels, output_channels)
1721 for (uint32_t x = 0; x < track->n_inputs().n_audio() && x < nphysical_in; ++x) {
1725 if (Config->get_input_auto_connect() & AutoConnectPhysical) {
1726 port = physinputs[(channels_used+x)%nphysical_in];
1729 if (port.length() && track->connect_input (track->input (x), port, this)) {
1735 for (uint32_t x = 0; x < track->n_outputs().n_midi(); ++x) {
1739 if (nphysical_out && (Config->get_output_auto_connect() & AutoConnectPhysical)) {
1740 port = physoutputs[(channels_used+x)%nphysical_out];
1741 } else if (Config->get_output_auto_connect() & AutoConnectMaster) {
1743 port = _master_out->input (x%_master_out->n_inputs().n_audio())->name();
1747 if (port.length() && track->connect_output (track->output (x), port, this)) {
1752 channels_used += track->n_inputs ().n_audio();
1754 track->audio_diskstream()->non_realtime_input_change();
1756 track->DiskstreamChanged.connect (mem_fun (this, &Session::resort_routes));
1757 track->set_remote_control_id (control_id);
1760 new_routes.push_back (track);
1761 ret.push_back (track);
1764 catch (failed_constructor &err) {
1765 error << _("Session: could not create new audio track.") << endmsg;
1768 /* we need to get rid of this, since the track failed to be created */
1769 /* XXX arguably, AudioTrack::AudioTrack should not do the Session::add_diskstream() */
1772 RCUWriter<DiskstreamList> writer (diskstreams);
1773 boost::shared_ptr<DiskstreamList> ds = writer.get_copy();
1774 ds->remove (track->audio_diskstream());
1781 catch (AudioEngine::PortRegistrationFailure& pfe) {
1783 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;
1786 /* we need to get rid of this, since the track failed to be created */
1787 /* XXX arguably, AudioTrack::AudioTrack should not do the Session::add_diskstream() */
1790 RCUWriter<DiskstreamList> writer (diskstreams);
1791 boost::shared_ptr<DiskstreamList> ds = writer.get_copy();
1792 ds->remove (track->audio_diskstream());
1803 if (!new_routes.empty()) {
1804 add_routes (new_routes, true);
1811 Session::set_remote_control_ids ()
1813 RemoteModel m = Config->get_remote_model();
1815 shared_ptr<RouteList> r = routes.reader ();
1817 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
1818 if ( MixerOrdered == m) {
1819 long order = (*i)->order_key(N_("signal"));
1820 (*i)->set_remote_control_id( order+1 );
1821 } else if ( EditorOrdered == m) {
1822 long order = (*i)->order_key(N_("editor"));
1823 (*i)->set_remote_control_id( order+1 );
1824 } else if ( UserOrdered == m) {
1825 //do nothing ... only changes to remote id's are initiated by user
1832 Session::new_audio_route (int input_channels, int output_channels, uint32_t how_many)
1835 uint32_t bus_id = 1;
1839 uint32_t control_id;
1841 /* count existing audio busses */
1844 shared_ptr<RouteList> r = routes.reader ();
1846 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
1847 if (dynamic_cast<AudioTrack*>((*i).get()) == 0) {
1848 if (!(*i)->is_hidden() && (*i)->name() != _("master")) {
1855 vector<string> physinputs;
1856 vector<string> physoutputs;
1858 _engine.get_physical_outputs (physoutputs);
1859 _engine.get_physical_inputs (physinputs);
1860 control_id = ntracks() + nbusses() + 1;
1865 snprintf (bus_name, sizeof(bus_name), "Bus %" PRIu32, bus_id);
1869 if (route_by_name (bus_name) == 0) {
1873 } while (bus_id < (UINT_MAX-1));
1876 shared_ptr<Route> bus (new Route (*this, bus_name, -1, -1, -1, -1, Route::Flag(0), DataType::AUDIO));
1878 if (bus->ensure_io (ChanCount(DataType::AUDIO, input_channels), ChanCount(DataType::AUDIO, output_channels), false, this)) {
1879 error << string_compose (_("cannot configure %1 in/%2 out configuration for new audio track"),
1880 input_channels, output_channels)
1885 for (uint32_t x = 0; n_physical_inputs && x < bus->n_inputs().n_audio(); ++x) {
1889 if (Config->get_input_auto_connect() & AutoConnectPhysical) {
1890 port = physinputs[((n+x)%n_physical_inputs)];
1893 if (port.length() && bus->connect_input (bus->input (x), port, this)) {
1898 for (uint32_t x = 0; n_physical_outputs && x < bus->n_outputs().n_audio(); ++x) {
1902 if (Config->get_output_auto_connect() & AutoConnectPhysical) {
1903 port = physoutputs[((n+x)%n_physical_outputs)];
1904 } else if (Config->get_output_auto_connect() & AutoConnectMaster) {
1906 port = _master_out->input (x%_master_out->n_inputs().n_audio())->name();
1910 if (port.length() && bus->connect_output (bus->output (x), port, this)) {
1915 bus->set_remote_control_id (control_id);
1918 ret.push_back (bus);
1922 catch (failed_constructor &err) {
1923 error << _("Session: could not create new audio route.") << endmsg;
1927 catch (AudioEngine::PortRegistrationFailure& pfe) {
1928 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;
1938 add_routes (ret, true);
1946 Session::add_routes (RouteList& new_routes, bool save)
1949 RCUWriter<RouteList> writer (routes);
1950 shared_ptr<RouteList> r = writer.get_copy ();
1951 r->insert (r->end(), new_routes.begin(), new_routes.end());
1952 resort_routes_using (r);
1955 for (RouteList::iterator x = new_routes.begin(); x != new_routes.end(); ++x) {
1957 boost::weak_ptr<Route> wpr (*x);
1959 (*x)->solo_changed.connect (sigc::bind (mem_fun (*this, &Session::route_solo_changed), wpr));
1960 (*x)->mute_changed.connect (mem_fun (*this, &Session::route_mute_changed));
1961 (*x)->output_changed.connect (mem_fun (*this, &Session::set_worst_io_latencies_x));
1962 (*x)->processors_changed.connect (bind (mem_fun (*this, &Session::update_latency_compensation), false, false));
1964 if ((*x)->is_master()) {
1968 if ((*x)->is_control()) {
1969 _control_out = (*x);
1972 add_bundle ((*x)->bundle_for_inputs());
1973 add_bundle ((*x)->bundle_for_outputs());
1976 if (_control_out && IO::connecting_legal) {
1978 vector<string> cports;
1979 uint32_t ni = _control_out->n_inputs().n_audio();
1981 for (uint32_t n = 0; n < ni; ++n) {
1982 cports.push_back (_control_out->input(n)->name());
1985 for (RouteList::iterator x = new_routes.begin(); x != new_routes.end(); ++x) {
1986 (*x)->set_control_outs (cports);
1993 save_state (_current_snapshot_name);
1996 RouteAdded (new_routes); /* EMIT SIGNAL */
2000 Session::add_diskstream (boost::shared_ptr<Diskstream> dstream)
2002 /* need to do this in case we're rolling at the time, to prevent false underruns */
2003 dstream->do_refill_with_alloc ();
2005 dstream->set_block_size (current_block_size);
2008 RCUWriter<DiskstreamList> writer (diskstreams);
2009 boost::shared_ptr<DiskstreamList> ds = writer.get_copy();
2010 ds->push_back (dstream);
2011 /* writer goes out of scope, copies ds back to main */
2014 dstream->PlaylistChanged.connect (sigc::bind (mem_fun (*this, &Session::diskstream_playlist_changed), dstream));
2015 /* this will connect to future changes, and check the current length */
2016 diskstream_playlist_changed (dstream);
2018 dstream->prepare ();
2023 Session::remove_route (shared_ptr<Route> route)
2026 RCUWriter<RouteList> writer (routes);
2027 shared_ptr<RouteList> rs = writer.get_copy ();
2031 /* deleting the master out seems like a dumb
2032 idea, but its more of a UI policy issue
2036 if (route == _master_out) {
2037 _master_out = shared_ptr<Route> ();
2040 if (route == _control_out) {
2041 _control_out = shared_ptr<Route> ();
2043 /* cancel control outs for all routes */
2045 vector<string> empty;
2047 for (RouteList::iterator r = rs->begin(); r != rs->end(); ++r) {
2048 (*r)->set_control_outs (empty);
2052 update_route_solo_state ();
2054 /* writer goes out of scope, forces route list update */
2058 boost::shared_ptr<Diskstream> ds;
2060 if ((t = dynamic_cast<Track*>(route.get())) != 0) {
2061 ds = t->diskstream();
2067 RCUWriter<DiskstreamList> dsl (diskstreams);
2068 boost::shared_ptr<DiskstreamList> d = dsl.get_copy();
2073 find_current_end ();
2075 // We need to disconnect the routes inputs and outputs
2077 route->disconnect_inputs (0);
2078 route->disconnect_outputs (0);
2080 update_latency_compensation (false, false);
2083 /* get rid of it from the dead wood collection in the route list manager */
2085 /* XXX i think this is unsafe as it currently stands, but i am not sure. (pd, october 2nd, 2006) */
2089 /* try to cause everyone to drop their references */
2091 route->drop_references ();
2093 /* save the new state of the world */
2095 if (save_state (_current_snapshot_name)) {
2096 save_history (_current_snapshot_name);
2101 Session::route_mute_changed (void* src)
2107 Session::route_solo_changed (void* src, boost::weak_ptr<Route> wpr)
2109 if (solo_update_disabled) {
2115 boost::shared_ptr<Route> route = wpr.lock ();
2118 /* should not happen */
2119 error << string_compose (_("programming error: %1"), X_("invalid route weak ptr passed to route_solo_changed")) << endmsg;
2123 is_track = (boost::dynamic_pointer_cast<AudioTrack>(route) != 0);
2125 shared_ptr<RouteList> r = routes.reader ();
2127 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2129 /* soloing a track mutes all other tracks, soloing a bus mutes all other busses */
2133 /* don't mess with busses */
2135 if (dynamic_cast<Track*>((*i).get()) == 0) {
2141 /* don't mess with tracks */
2143 if (dynamic_cast<Track*>((*i).get()) != 0) {
2148 if ((*i) != route &&
2149 ((*i)->mix_group () == 0 ||
2150 (*i)->mix_group () != route->mix_group () ||
2151 !route->mix_group ()->is_active())) {
2153 if ((*i)->soloed()) {
2155 /* if its already soloed, and solo latching is enabled,
2156 then leave it as it is.
2159 if (Config->get_solo_latched()) {
2166 solo_update_disabled = true;
2167 (*i)->set_solo (false, src);
2168 solo_update_disabled = false;
2172 bool something_soloed = false;
2173 bool same_thing_soloed = false;
2174 bool signal = false;
2176 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2177 if ((*i)->soloed()) {
2178 something_soloed = true;
2179 if (dynamic_cast<Track*>((*i).get())) {
2181 same_thing_soloed = true;
2186 same_thing_soloed = true;
2194 if (something_soloed != currently_soloing) {
2196 currently_soloing = something_soloed;
2199 modify_solo_mute (is_track, same_thing_soloed);
2202 SoloActive (currently_soloing); /* EMIT SIGNAL */
2205 SoloChanged (); /* EMIT SIGNAL */
2211 Session::update_route_solo_state ()
2214 bool is_track = false;
2215 bool signal = false;
2217 /* caller must hold RouteLock */
2219 /* this is where we actually implement solo by changing
2220 the solo mute setting of each track.
2223 shared_ptr<RouteList> r = routes.reader ();
2225 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2226 if ((*i)->soloed()) {
2228 if (dynamic_cast<Track*>((*i).get())) {
2235 if (mute != currently_soloing) {
2237 currently_soloing = mute;
2240 if (!is_track && !mute) {
2242 /* nothing is soloed */
2244 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2245 (*i)->set_solo_mute (false);
2255 modify_solo_mute (is_track, mute);
2258 SoloActive (currently_soloing);
2263 Session::modify_solo_mute (bool is_track, bool mute)
2265 shared_ptr<RouteList> r = routes.reader ();
2267 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2271 /* only alter track solo mute */
2273 if (dynamic_cast<Track*>((*i).get())) {
2274 if ((*i)->soloed()) {
2275 (*i)->set_solo_mute (!mute);
2277 (*i)->set_solo_mute (mute);
2283 /* only alter bus solo mute */
2285 if (!dynamic_cast<Track*>((*i).get())) {
2287 if ((*i)->soloed()) {
2289 (*i)->set_solo_mute (false);
2293 /* don't mute master or control outs
2294 in response to another bus solo
2297 if ((*i) != _master_out &&
2298 (*i) != _control_out) {
2299 (*i)->set_solo_mute (mute);
2310 Session::catch_up_on_solo ()
2312 /* this is called after set_state() to catch the full solo
2313 state, which can't be correctly determined on a per-route
2314 basis, but needs the global overview that only the session
2317 update_route_solo_state();
2321 Session::route_by_name (string name)
2323 shared_ptr<RouteList> r = routes.reader ();
2325 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2326 if ((*i)->name() == name) {
2331 return shared_ptr<Route> ((Route*) 0);
2335 Session::route_by_id (PBD::ID id)
2337 shared_ptr<RouteList> r = routes.reader ();
2339 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2340 if ((*i)->id() == id) {
2345 return shared_ptr<Route> ((Route*) 0);
2349 Session::route_by_remote_id (uint32_t id)
2351 shared_ptr<RouteList> r = routes.reader ();
2353 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2354 if ((*i)->remote_control_id() == id) {
2359 return shared_ptr<Route> ((Route*) 0);
2363 Session::find_current_end ()
2365 if (_state_of_the_state & Loading) {
2369 nframes_t max = get_maximum_extent ();
2371 if (max > end_location->end()) {
2372 end_location->set_end (max);
2374 DurationChanged(); /* EMIT SIGNAL */
2379 Session::get_maximum_extent () const
2384 boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
2386 for (DiskstreamList::const_iterator i = dsl->begin(); i != dsl->end(); ++i) {
2387 boost::shared_ptr<Playlist> pl = (*i)->playlist();
2388 if ((me = pl->get_maximum_extent()) > max) {
2396 boost::shared_ptr<Diskstream>
2397 Session::diskstream_by_name (string name)
2399 boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
2401 for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
2402 if ((*i)->name() == name) {
2407 return boost::shared_ptr<Diskstream>((Diskstream*) 0);
2410 boost::shared_ptr<Diskstream>
2411 Session::diskstream_by_id (const PBD::ID& id)
2413 boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
2415 for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
2416 if ((*i)->id() == id) {
2421 return boost::shared_ptr<Diskstream>((Diskstream*) 0);
2424 /* Region management */
2427 Session::new_region_name (string old)
2429 string::size_type last_period;
2431 string::size_type len = old.length() + 64;
2434 if ((last_period = old.find_last_of ('.')) == string::npos) {
2436 /* no period present - add one explicitly */
2439 last_period = old.length() - 1;
2444 number = atoi (old.substr (last_period+1).c_str());
2448 while (number < (UINT_MAX-1)) {
2450 RegionList::const_iterator i;
2455 snprintf (buf, len, "%s%" PRIu32, old.substr (0, last_period + 1).c_str(), number);
2458 for (i = regions.begin(); i != regions.end(); ++i) {
2459 if (i->second->name() == sbuf) {
2464 if (i == regions.end()) {
2469 if (number != (UINT_MAX-1)) {
2473 error << string_compose (_("cannot create new name for region \"%1\""), old) << endmsg;
2478 Session::region_name (string& result, string base, bool newlevel) const
2483 assert(base.find("/") == string::npos);
2487 Glib::Mutex::Lock lm (region_lock);
2489 snprintf (buf, sizeof (buf), "%d", (int)regions.size() + 1);
2497 /* XXX this is going to be slow. optimize me later */
2502 string::size_type pos;
2504 pos = base.find_last_of ('.');
2506 /* pos may be npos, but then we just use entire base */
2508 subbase = base.substr (0, pos);
2512 bool name_taken = true;
2515 Glib::Mutex::Lock lm (region_lock);
2517 for (int n = 1; n < 5000; ++n) {
2520 snprintf (buf, sizeof (buf), ".%d", n);
2525 for (RegionList::const_iterator i = regions.begin(); i != regions.end(); ++i) {
2526 if (i->second->name() == result) {
2539 fatal << string_compose(_("too many regions with names like %1"), base) << endmsg;
2547 Session::add_region (boost::shared_ptr<Region> region)
2552 Glib::Mutex::Lock lm (region_lock);
2555 error << _("Session::add_region() ignored a null region. Warning: you might have lost a region.") << endmsg;
2558 RegionList::iterator x;
2560 for (x = regions.begin(); x != regions.end(); ++x) {
2562 if (region->region_list_equivalent (x->second)) {
2567 if (x == regions.end()) {
2569 pair<RegionList::key_type,RegionList::mapped_type> entry;
2571 entry.first = region->id();
2572 entry.second = region;
2574 pair<RegionList::iterator,bool> x = regions.insert (entry);
2587 /* mark dirty because something has changed even if we didn't
2588 add the region to the region list.
2594 region->GoingAway.connect (sigc::bind (mem_fun (*this, &Session::remove_region), boost::weak_ptr<Region>(region)));
2595 region->StateChanged.connect (sigc::bind (mem_fun (*this, &Session::region_changed), boost::weak_ptr<Region>(region)));
2596 RegionAdded (region); /* EMIT SIGNAL */
2601 Session::region_changed (Change what_changed, boost::weak_ptr<Region> weak_region)
2603 boost::shared_ptr<Region> region (weak_region.lock ());
2609 if (what_changed & Region::HiddenChanged) {
2610 /* relay hidden changes */
2611 RegionHiddenChange (region);
2616 Session::remove_region (boost::weak_ptr<Region> weak_region)
2618 RegionList::iterator i;
2619 boost::shared_ptr<Region> region (weak_region.lock ());
2625 bool removed = false;
2628 Glib::Mutex::Lock lm (region_lock);
2630 if ((i = regions.find (region->id())) != regions.end()) {
2636 /* mark dirty because something has changed even if we didn't
2637 remove the region from the region list.
2643 RegionRemoved(region); /* EMIT SIGNAL */
2647 boost::shared_ptr<Region>
2648 Session::find_whole_file_parent (boost::shared_ptr<Region const> child)
2650 RegionList::iterator i;
2651 boost::shared_ptr<Region> region;
2653 Glib::Mutex::Lock lm (region_lock);
2655 for (i = regions.begin(); i != regions.end(); ++i) {
2659 if (region->whole_file()) {
2661 if (child->source_equivalent (region)) {
2667 return boost::shared_ptr<Region> ();
2671 Session::find_equivalent_playlist_regions (boost::shared_ptr<Region> region, vector<boost::shared_ptr<Region> >& result)
2673 for (PlaylistList::iterator i = playlists.begin(); i != playlists.end(); ++i)
2674 (*i)->get_region_list_equivalent_regions (region, result);
2678 Session::destroy_region (boost::shared_ptr<Region> region)
2680 vector<boost::shared_ptr<Source> > srcs;
2683 boost::shared_ptr<AudioRegion> aregion;
2685 if ((aregion = boost::dynamic_pointer_cast<AudioRegion> (region)) == 0) {
2689 if (aregion->playlist()) {
2690 aregion->playlist()->destroy_region (region);
2693 for (uint32_t n = 0; n < aregion->n_channels(); ++n) {
2694 srcs.push_back (aregion->source (n));
2698 region->drop_references ();
2700 for (vector<boost::shared_ptr<Source> >::iterator i = srcs.begin(); i != srcs.end(); ++i) {
2702 if (!(*i)->used()) {
2703 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*i);
2706 (afs)->mark_for_remove ();
2709 (*i)->drop_references ();
2711 cerr << "source was not used by any playlist\n";
2719 Session::destroy_regions (list<boost::shared_ptr<Region> > regions)
2721 for (list<boost::shared_ptr<Region> >::iterator i = regions.begin(); i != regions.end(); ++i) {
2722 destroy_region (*i);
2728 Session::remove_last_capture ()
2730 list<boost::shared_ptr<Region> > r;
2732 boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
2734 for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
2735 list<boost::shared_ptr<Region> >& l = (*i)->last_capture_regions();
2738 r.insert (r.end(), l.begin(), l.end());
2743 destroy_regions (r);
2745 save_state (_current_snapshot_name);
2751 Session::remove_region_from_region_list (boost::shared_ptr<Region> r)
2757 /* Source Management */
2759 Session::add_source (boost::shared_ptr<Source> source)
2761 pair<SourceMap::key_type, SourceMap::mapped_type> entry;
2762 pair<SourceMap::iterator,bool> result;
2764 entry.first = source->id();
2765 entry.second = source;
2768 Glib::Mutex::Lock lm (source_lock);
2769 result = sources.insert (entry);
2772 if (result.second) {
2773 source->GoingAway.connect (sigc::bind (mem_fun (this, &Session::remove_source), boost::weak_ptr<Source> (source)));
2777 boost::shared_ptr<AudioFileSource> afs;
2779 if ((afs = boost::dynamic_pointer_cast<AudioFileSource>(source)) != 0) {
2780 if (Config->get_auto_analyse_audio()) {
2781 Analyser::queue_source_for_analysis (source, false);
2787 Session::remove_source (boost::weak_ptr<Source> src)
2789 SourceMap::iterator i;
2790 boost::shared_ptr<Source> source = src.lock();
2797 Glib::Mutex::Lock lm (source_lock);
2799 if ((i = sources.find (source->id())) != sources.end()) {
2804 if (!_state_of_the_state & InCleanup) {
2806 /* save state so we don't end up with a session file
2807 referring to non-existent sources.
2810 save_state (_current_snapshot_name);
2814 boost::shared_ptr<Source>
2815 Session::source_by_id (const PBD::ID& id)
2817 Glib::Mutex::Lock lm (source_lock);
2818 SourceMap::iterator i;
2819 boost::shared_ptr<Source> source;
2821 if ((i = sources.find (id)) != sources.end()) {
2829 boost::shared_ptr<Source>
2830 Session::source_by_path_and_channel (const Glib::ustring& path, uint16_t chn)
2832 Glib::Mutex::Lock lm (source_lock);
2834 for (SourceMap::iterator i = sources.begin(); i != sources.end(); ++i) {
2835 cerr << "comparing " << path << " with " << i->second->name() << endl;
2836 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(i->second);
2838 if (afs && afs->path() == path && chn == afs->channel()) {
2843 return boost::shared_ptr<Source>();
2847 Session::peak_path (Glib::ustring base) const
2849 sys::path peakfile_path(_session_dir->peak_path());
2850 peakfile_path /= basename_nosuffix (base) + peakfile_suffix;
2851 return peakfile_path.to_string();
2855 Session::change_audio_path_by_name (string path, string oldname, string newname, bool destructive)
2858 string old_basename = PBD::basename_nosuffix (oldname);
2859 string new_legalized = legalize_for_path (newname);
2861 /* note: we know (or assume) the old path is already valid */
2865 /* destructive file sources have a name of the form:
2867 /path/to/Tnnnn-NAME(%[LR])?.wav
2869 the task here is to replace NAME with the new name.
2872 /* find last slash */
2876 string::size_type slash;
2877 string::size_type dash;
2879 if ((slash = path.find_last_of ('/')) == string::npos) {
2883 dir = path.substr (0, slash+1);
2885 /* '-' is not a legal character for the NAME part of the path */
2887 if ((dash = path.find_last_of ('-')) == string::npos) {
2891 prefix = path.substr (slash+1, dash-(slash+1));
2896 path += new_legalized;
2897 path += ".wav"; /* XXX gag me with a spoon */
2901 /* non-destructive file sources have a name of the form:
2903 /path/to/NAME-nnnnn(%[LR])?.wav
2905 the task here is to replace NAME with the new name.
2910 string::size_type slash;
2911 string::size_type dash;
2912 string::size_type postfix;
2914 /* find last slash */
2916 if ((slash = path.find_last_of ('/')) == string::npos) {
2920 dir = path.substr (0, slash+1);
2922 /* '-' is not a legal character for the NAME part of the path */
2924 if ((dash = path.find_last_of ('-')) == string::npos) {
2928 suffix = path.substr (dash+1);
2930 // Suffix is now everything after the dash. Now we need to eliminate
2931 // the nnnnn part, which is done by either finding a '%' or a '.'
2933 postfix = suffix.find_last_of ("%");
2934 if (postfix == string::npos) {
2935 postfix = suffix.find_last_of ('.');
2938 if (postfix != string::npos) {
2939 suffix = suffix.substr (postfix);
2941 error << "Logic error in Session::change_audio_path_by_name(), please report to the developers" << endl;
2945 const uint32_t limit = 10000;
2946 char buf[PATH_MAX+1];
2948 for (uint32_t cnt = 1; cnt <= limit; ++cnt) {
2950 snprintf (buf, sizeof(buf), "%s%s-%u%s", dir.c_str(), newname.c_str(), cnt, suffix.c_str());
2952 if (access (buf, F_OK) != 0) {
2960 error << "FATAL ERROR! Could not find a " << endl;
2969 Session::audio_path_from_name (string name, uint32_t nchan, uint32_t chan, bool destructive)
2973 char buf[PATH_MAX+1];
2974 const uint32_t limit = 10000;
2978 legalized = legalize_for_path (name);
2980 /* find a "version" of the file name that doesn't exist in
2981 any of the possible directories.
2984 for (cnt = (destructive ? ++destructive_index : 1); cnt <= limit; ++cnt) {
2986 vector<space_and_path>::iterator i;
2987 uint32_t existing = 0;
2989 for (i = session_dirs.begin(); i != session_dirs.end(); ++i) {
2991 SessionDirectory sdir((*i).path);
2993 spath = sdir.sound_path().to_string();
2997 snprintf (buf, sizeof(buf), "%s/T%04d-%s.wav", spath.c_str(), cnt, legalized.c_str());
2998 } else if (nchan == 2) {
3000 snprintf (buf, sizeof(buf), "%s/T%04d-%s%%L.wav", spath.c_str(), cnt, legalized.c_str());
3002 snprintf (buf, sizeof(buf), "%s/T%04d-%s%%R.wav", spath.c_str(), cnt, legalized.c_str());
3004 } else if (nchan < 26) {
3005 snprintf (buf, sizeof(buf), "%s/T%04d-%s%%%c.wav", spath.c_str(), cnt, legalized.c_str(), 'a' + chan);
3007 snprintf (buf, sizeof(buf), "%s/T%04d-%s.wav", spath.c_str(), cnt, legalized.c_str());
3016 snprintf (buf, sizeof(buf), "%s-%u.wav", spath.c_str(), cnt);
3017 } else if (nchan == 2) {
3019 snprintf (buf, sizeof(buf), "%s-%u%%L.wav", spath.c_str(), cnt);
3021 snprintf (buf, sizeof(buf), "%s-%u%%R.wav", spath.c_str(), cnt);
3023 } else if (nchan < 26) {
3024 snprintf (buf, sizeof(buf), "%s-%u%%%c.wav", spath.c_str(), cnt, 'a' + chan);
3026 snprintf (buf, sizeof(buf), "%s-%u.wav", spath.c_str(), cnt);
3030 if (sys::exists(buf)) {
3036 if (existing == 0) {
3041 error << string_compose(_("There are already %1 recordings for %2, which I consider too many."), limit, name) << endmsg;
3043 throw failed_constructor();
3047 /* we now have a unique name for the file, but figure out where to
3053 SessionDirectory sdir(get_best_session_directory_for_new_source ());
3055 spath = sdir.sound_path().to_string();
3058 string::size_type pos = foo.find_last_of ('/');
3060 if (pos == string::npos) {
3063 spath += foo.substr (pos + 1);
3069 boost::shared_ptr<AudioFileSource>
3070 Session::create_audio_source_for_session (AudioDiskstream& ds, uint32_t chan, bool destructive)
3072 string spath = audio_path_from_name (ds.name(), ds.n_channels().n_audio(), chan, destructive);
3073 return boost::dynamic_pointer_cast<AudioFileSource> (
3074 SourceFactory::createWritable (DataType::AUDIO, *this, spath, destructive, frame_rate()));
3077 // FIXME: _terrible_ code duplication
3079 Session::change_midi_path_by_name (string path, string oldname, string newname, bool destructive)
3082 string old_basename = PBD::basename_nosuffix (oldname);
3083 string new_legalized = legalize_for_path (newname);
3085 /* note: we know (or assume) the old path is already valid */
3089 /* destructive file sources have a name of the form:
3091 /path/to/Tnnnn-NAME(%[LR])?.wav
3093 the task here is to replace NAME with the new name.
3096 /* find last slash */
3100 string::size_type slash;
3101 string::size_type dash;
3103 if ((slash = path.find_last_of ('/')) == string::npos) {
3107 dir = path.substr (0, slash+1);
3109 /* '-' is not a legal character for the NAME part of the path */
3111 if ((dash = path.find_last_of ('-')) == string::npos) {
3115 prefix = path.substr (slash+1, dash-(slash+1));
3120 path += new_legalized;
3121 path += ".mid"; /* XXX gag me with a spoon */
3125 /* non-destructive file sources have a name of the form:
3127 /path/to/NAME-nnnnn(%[LR])?.wav
3129 the task here is to replace NAME with the new name.
3134 string::size_type slash;
3135 string::size_type dash;
3136 string::size_type postfix;
3138 /* find last slash */
3140 if ((slash = path.find_last_of ('/')) == string::npos) {
3144 dir = path.substr (0, slash+1);
3146 /* '-' is not a legal character for the NAME part of the path */
3148 if ((dash = path.find_last_of ('-')) == string::npos) {
3152 suffix = path.substr (dash+1);
3154 // Suffix is now everything after the dash. Now we need to eliminate
3155 // the nnnnn part, which is done by either finding a '%' or a '.'
3157 postfix = suffix.find_last_of ("%");
3158 if (postfix == string::npos) {
3159 postfix = suffix.find_last_of ('.');
3162 if (postfix != string::npos) {
3163 suffix = suffix.substr (postfix);
3165 error << "Logic error in Session::change_midi_path_by_name(), please report to the developers" << endl;
3169 const uint32_t limit = 10000;
3170 char buf[PATH_MAX+1];
3172 for (uint32_t cnt = 1; cnt <= limit; ++cnt) {
3174 snprintf (buf, sizeof(buf), "%s%s-%u%s", dir.c_str(), newname.c_str(), cnt, suffix.c_str());
3176 if (access (buf, F_OK) != 0) {
3184 error << "FATAL ERROR! Could not find a " << endl;
3193 Session::midi_path_from_name (string name)
3197 char buf[PATH_MAX+1];
3198 const uint32_t limit = 10000;
3202 legalized = legalize_for_path (name);
3204 /* find a "version" of the file name that doesn't exist in
3205 any of the possible directories.
3208 for (cnt = 1; cnt <= limit; ++cnt) {
3210 vector<space_and_path>::iterator i;
3211 uint32_t existing = 0;
3213 for (i = session_dirs.begin(); i != session_dirs.end(); ++i) {
3215 SessionDirectory sdir((*i).path);
3217 sys::path p = sdir.midi_path();
3221 spath = p.to_string();
3223 snprintf (buf, sizeof(buf), "%s-%u.mid", spath.c_str(), cnt);
3225 if (sys::exists (buf)) {
3230 if (existing == 0) {
3235 error << string_compose(_("There are already %1 recordings for %2, which I consider too many."), limit, name) << endmsg;
3236 throw failed_constructor();
3240 /* we now have a unique name for the file, but figure out where to
3246 SessionDirectory sdir(get_best_session_directory_for_new_source ());
3248 spath = sdir.midi_path().to_string();
3251 string::size_type pos = foo.find_last_of ('/');
3253 if (pos == string::npos) {
3256 spath += foo.substr (pos + 1);
3262 boost::shared_ptr<MidiSource>
3263 Session::create_midi_source_for_session (MidiDiskstream& ds)
3265 string mpath = midi_path_from_name (ds.name());
3267 return boost::dynamic_pointer_cast<SMFSource> (SourceFactory::createWritable (DataType::MIDI, *this, mpath, false, frame_rate()));
3271 /* Playlist management */
3273 boost::shared_ptr<Playlist>
3274 Session::playlist_by_name (string name)
3276 Glib::Mutex::Lock lm (playlist_lock);
3277 for (PlaylistList::iterator i = playlists.begin(); i != playlists.end(); ++i) {
3278 if ((*i)->name() == name) {
3282 for (PlaylistList::iterator i = unused_playlists.begin(); i != unused_playlists.end(); ++i) {
3283 if ((*i)->name() == name) {
3288 return boost::shared_ptr<Playlist>();
3292 Session::add_playlist (boost::shared_ptr<Playlist> playlist)
3294 if (playlist->hidden()) {
3299 Glib::Mutex::Lock lm (playlist_lock);
3300 if (find (playlists.begin(), playlists.end(), playlist) == playlists.end()) {
3301 playlists.insert (playlists.begin(), playlist);
3302 playlist->InUse.connect (sigc::bind (mem_fun (*this, &Session::track_playlist), boost::weak_ptr<Playlist>(playlist)));
3303 playlist->GoingAway.connect (sigc::bind (mem_fun (*this, &Session::remove_playlist), boost::weak_ptr<Playlist>(playlist)));
3309 PlaylistAdded (playlist); /* EMIT SIGNAL */
3313 Session::get_playlists (vector<boost::shared_ptr<Playlist> >& s)
3316 Glib::Mutex::Lock lm (playlist_lock);
3317 for (PlaylistList::iterator i = playlists.begin(); i != playlists.end(); ++i) {
3320 for (PlaylistList::iterator i = unused_playlists.begin(); i != unused_playlists.end(); ++i) {
3327 Session::track_playlist (bool inuse, boost::weak_ptr<Playlist> wpl)
3329 boost::shared_ptr<Playlist> pl(wpl.lock());
3335 PlaylistList::iterator x;
3338 /* its not supposed to be visible */
3343 Glib::Mutex::Lock lm (playlist_lock);
3347 unused_playlists.insert (pl);
3349 if ((x = playlists.find (pl)) != playlists.end()) {
3350 playlists.erase (x);
3356 playlists.insert (pl);
3358 if ((x = unused_playlists.find (pl)) != unused_playlists.end()) {
3359 unused_playlists.erase (x);
3366 Session::remove_playlist (boost::weak_ptr<Playlist> weak_playlist)
3368 if (_state_of_the_state & Deletion) {
3372 boost::shared_ptr<Playlist> playlist (weak_playlist.lock());
3379 Glib::Mutex::Lock lm (playlist_lock);
3381 PlaylistList::iterator i;
3383 i = find (playlists.begin(), playlists.end(), playlist);
3384 if (i != playlists.end()) {
3385 playlists.erase (i);
3388 i = find (unused_playlists.begin(), unused_playlists.end(), playlist);
3389 if (i != unused_playlists.end()) {
3390 unused_playlists.erase (i);
3397 PlaylistRemoved (playlist); /* EMIT SIGNAL */
3401 Session::set_audition (boost::shared_ptr<Region> r)
3403 pending_audition_region = r;
3404 post_transport_work = PostTransportWork (post_transport_work | PostTransportAudition);
3405 schedule_butler_transport_work ();
3409 Session::audition_playlist ()
3411 Event* ev = new Event (Event::Audition, Event::Add, Event::Immediate, 0, 0.0);
3412 ev->region.reset ();
3417 Session::non_realtime_set_audition ()
3419 if (!pending_audition_region) {
3420 auditioner->audition_current_playlist ();
3422 auditioner->audition_region (pending_audition_region);
3423 pending_audition_region.reset ();
3425 AuditionActive (true); /* EMIT SIGNAL */
3429 Session::audition_region (boost::shared_ptr<Region> r)
3431 Event* ev = new Event (Event::Audition, Event::Add, Event::Immediate, 0, 0.0);
3437 Session::cancel_audition ()
3439 if (auditioner->active()) {
3440 auditioner->cancel_audition ();
3441 AuditionActive (false); /* EMIT SIGNAL */
3446 Session::RoutePublicOrderSorter::operator() (boost::shared_ptr<Route> a, boost::shared_ptr<Route> b)
3448 return a->order_key(N_("signal")) < b->order_key(N_("signal"));
3452 Session::remove_empty_sounds ()
3454 vector<string> audio_filenames;
3456 get_files_in_directory (_session_dir->sound_path(), audio_filenames);
3458 Glib::Mutex::Lock lm (source_lock);
3460 TapeFileMatcher tape_file_matcher;
3462 remove_if (audio_filenames.begin(), audio_filenames.end(),
3463 sigc::mem_fun (tape_file_matcher, &TapeFileMatcher::matches));
3465 for (vector<string>::iterator i = audio_filenames.begin(); i != audio_filenames.end(); ++i) {
3467 sys::path audio_file_path (_session_dir->sound_path());
3469 audio_file_path /= *i;
3471 if (AudioFileSource::is_empty (*this, audio_file_path.to_string())) {
3475 sys::remove (audio_file_path);
3476 const string peakfile = peak_path (audio_file_path.to_string());
3477 sys::remove (peakfile);
3479 catch (const sys::filesystem_error& err)
3481 error << err.what() << endmsg;
3488 Session::is_auditioning () const
3490 /* can be called before we have an auditioner object */
3492 return auditioner->active();
3499 Session::set_all_solo (bool yn)
3501 shared_ptr<RouteList> r = routes.reader ();
3503 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3504 if (!(*i)->is_hidden()) {
3505 (*i)->set_solo (yn, this);
3513 Session::set_all_mute (bool yn)
3515 shared_ptr<RouteList> r = routes.reader ();
3517 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3518 if (!(*i)->is_hidden()) {
3519 (*i)->set_mute (yn, this);
3527 Session::n_diskstreams () const
3531 boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
3533 for (DiskstreamList::const_iterator i = dsl->begin(); i != dsl->end(); ++i) {
3534 if (!(*i)->hidden()) {
3542 Session::graph_reordered ()
3544 /* don't do this stuff if we are setting up connections
3545 from a set_state() call or creating new tracks.
3548 if (_state_of_the_state & InitialConnecting) {
3552 /* every track/bus asked for this to be handled but it was deferred because
3553 we were connecting. do it now.
3556 request_input_change_handling ();
3560 /* force all diskstreams to update their capture offset values to
3561 reflect any changes in latencies within the graph.
3564 boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
3566 for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
3567 (*i)->set_capture_offset ();
3572 Session::record_disenable_all ()
3574 record_enable_change_all (false);
3578 Session::record_enable_all ()
3580 record_enable_change_all (true);
3584 Session::record_enable_change_all (bool yn)
3586 shared_ptr<RouteList> r = routes.reader ();
3588 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3591 if ((at = dynamic_cast<Track*>((*i).get())) != 0) {
3592 at->set_record_enable (yn, this);
3596 /* since we don't keep rec-enable state, don't mark session dirty */
3600 Session::add_processor (Processor* processor)
3603 PortInsert* port_insert;
3604 PluginInsert* plugin_insert;
3606 if ((port_insert = dynamic_cast<PortInsert *> (processor)) != 0) {
3607 _port_inserts.insert (_port_inserts.begin(), port_insert);
3608 } else if ((plugin_insert = dynamic_cast<PluginInsert *> (processor)) != 0) {
3609 _plugin_inserts.insert (_plugin_inserts.begin(), plugin_insert);
3610 } else if ((send = dynamic_cast<Send *> (processor)) != 0) {
3611 _sends.insert (_sends.begin(), send);
3613 fatal << _("programming error: unknown type of Insert created!") << endmsg;
3617 processor->GoingAway.connect (sigc::bind (mem_fun (*this, &Session::remove_processor), processor));
3623 Session::remove_processor (Processor* processor)
3626 PortInsert* port_insert;
3627 PluginInsert* plugin_insert;
3629 if ((port_insert = dynamic_cast<PortInsert *> (processor)) != 0) {
3630 list<PortInsert*>::iterator x = find (_port_inserts.begin(), _port_inserts.end(), port_insert);
3631 if (x != _port_inserts.end()) {
3632 insert_bitset[port_insert->bit_slot()] = false;
3633 _port_inserts.erase (x);
3635 } else if ((plugin_insert = dynamic_cast<PluginInsert *> (processor)) != 0) {
3636 _plugin_inserts.remove (plugin_insert);
3637 } else if ((send = dynamic_cast<Send *> (processor)) != 0) {
3638 list<Send*>::iterator x = find (_sends.begin(), _sends.end(), send);
3639 if (x != _sends.end()) {
3640 send_bitset[send->bit_slot()] = false;
3644 fatal << _("programming error: unknown type of Insert deleted!") << endmsg;
3652 Session::available_capture_duration ()
3654 float sample_bytes_on_disk = 4.0; // keep gcc happy
3656 switch (Config->get_native_file_data_format()) {
3658 sample_bytes_on_disk = 4.0;
3662 sample_bytes_on_disk = 3.0;
3666 sample_bytes_on_disk = 2.0;
3670 /* impossible, but keep some gcc versions happy */
3671 fatal << string_compose (_("programming error: %1"),
3672 X_("illegal native file data format"))
3677 double scale = 4096.0 / sample_bytes_on_disk;
3679 if (_total_free_4k_blocks * scale > (double) max_frames) {
3683 return (nframes_t) floor (_total_free_4k_blocks * scale);
3687 Session::add_bundle (shared_ptr<Bundle> bundle)
3690 Glib::Mutex::Lock guard (bundle_lock);
3691 _bundles.push_back (bundle);
3694 BundleAdded (bundle); /* EMIT SIGNAL */
3700 Session::remove_bundle (shared_ptr<Bundle> bundle)
3702 bool removed = false;
3705 Glib::Mutex::Lock guard (bundle_lock);
3706 BundleList::iterator i = find (_bundles.begin(), _bundles.end(), bundle);
3708 if (i != _bundles.end()) {
3715 BundleRemoved (bundle); /* EMIT SIGNAL */
3722 Session::bundle_by_name (string name) const
3724 Glib::Mutex::Lock lm (bundle_lock);
3726 for (BundleList::const_iterator i = _bundles.begin(); i != _bundles.end(); ++i) {
3727 if ((*i)->name() == name) {
3732 return boost::shared_ptr<Bundle> ();
3736 Session::tempo_map_changed (Change ignored)
3740 for (PlaylistList::iterator i = playlists.begin(); i != playlists.end(); ++i) {
3741 (*i)->update_after_tempo_map_change ();
3744 for (PlaylistList::iterator i = unused_playlists.begin(); i != unused_playlists.end(); ++i) {
3745 (*i)->update_after_tempo_map_change ();
3751 /** Ensures that all buffers (scratch, send, silent, etc) are allocated for
3752 * the given count with the current block size.
3755 Session::ensure_buffers (ChanCount howmany)
3757 if (current_block_size == 0)
3758 return; // too early? (is this ok?)
3760 // We need at least 2 MIDI scratch buffers to mix/merge
3761 if (howmany.n_midi() < 2)
3762 howmany.set_midi(2);
3764 // FIXME: JACK needs to tell us maximum MIDI buffer size
3765 // Using nasty assumption (max # events == nframes) for now
3766 _scratch_buffers->ensure_buffers(howmany, current_block_size);
3767 _mix_buffers->ensure_buffers(howmany, current_block_size);
3768 _silent_buffers->ensure_buffers(howmany, current_block_size);
3770 allocate_pan_automation_buffers (current_block_size, howmany.n_audio(), false);
3774 Session::next_insert_id ()
3776 /* this doesn't really loop forever. just think about it */
3779 for (boost::dynamic_bitset<uint32_t>::size_type n = 0; n < insert_bitset.size(); ++n) {
3780 if (!insert_bitset[n]) {
3781 insert_bitset[n] = true;
3787 /* none available, so resize and try again */
3789 insert_bitset.resize (insert_bitset.size() + 16, false);
3794 Session::next_send_id ()
3796 /* this doesn't really loop forever. just think about it */
3799 for (boost::dynamic_bitset<uint32_t>::size_type n = 0; n < send_bitset.size(); ++n) {
3800 if (!send_bitset[n]) {
3801 send_bitset[n] = true;
3807 /* none available, so resize and try again */
3809 send_bitset.resize (send_bitset.size() + 16, false);
3814 Session::mark_send_id (uint32_t id)
3816 if (id >= send_bitset.size()) {
3817 send_bitset.resize (id+16, false);
3819 if (send_bitset[id]) {
3820 warning << string_compose (_("send ID %1 appears to be in use already"), id) << endmsg;
3822 send_bitset[id] = true;
3826 Session::mark_insert_id (uint32_t id)
3828 if (id >= insert_bitset.size()) {
3829 insert_bitset.resize (id+16, false);
3831 if (insert_bitset[id]) {
3832 warning << string_compose (_("insert ID %1 appears to be in use already"), id) << endmsg;
3834 insert_bitset[id] = true;
3837 /* Named Selection management */
3840 Session::named_selection_by_name (string name)
3842 Glib::Mutex::Lock lm (named_selection_lock);
3843 for (NamedSelectionList::iterator i = named_selections.begin(); i != named_selections.end(); ++i) {
3844 if ((*i)->name == name) {
3852 Session::add_named_selection (NamedSelection* named_selection)
3855 Glib::Mutex::Lock lm (named_selection_lock);
3856 named_selections.insert (named_selections.begin(), named_selection);
3859 for (list<boost::shared_ptr<Playlist> >::iterator i = named_selection->playlists.begin(); i != named_selection->playlists.end(); ++i) {
3865 NamedSelectionAdded (); /* EMIT SIGNAL */
3869 Session::remove_named_selection (NamedSelection* named_selection)
3871 bool removed = false;
3874 Glib::Mutex::Lock lm (named_selection_lock);
3876 NamedSelectionList::iterator i = find (named_selections.begin(), named_selections.end(), named_selection);
3878 if (i != named_selections.end()) {
3880 named_selections.erase (i);
3887 NamedSelectionRemoved (); /* EMIT SIGNAL */
3892 Session::reset_native_file_format ()
3894 boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
3896 for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
3897 (*i)->reset_write_sources (false);
3902 Session::route_name_unique (string n) const
3904 shared_ptr<RouteList> r = routes.reader ();
3906 for (RouteList::const_iterator i = r->begin(); i != r->end(); ++i) {
3907 if ((*i)->name() == n) {
3916 Session::n_playlists () const
3918 Glib::Mutex::Lock lm (playlist_lock);
3919 return playlists.size();
3923 Session::allocate_pan_automation_buffers (nframes_t nframes, uint32_t howmany, bool force)
3925 if (!force && howmany <= _npan_buffers) {
3929 if (_pan_automation_buffer) {
3931 for (uint32_t i = 0; i < _npan_buffers; ++i) {
3932 delete [] _pan_automation_buffer[i];
3935 delete [] _pan_automation_buffer;
3938 _pan_automation_buffer = new pan_t*[howmany];
3940 for (uint32_t i = 0; i < howmany; ++i) {
3941 _pan_automation_buffer[i] = new pan_t[nframes];
3944 _npan_buffers = howmany;
3948 Session::freeze (InterThreadInfo& itt)
3950 shared_ptr<RouteList> r = routes.reader ();
3952 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3956 if ((at = dynamic_cast<Track*>((*i).get())) != 0) {
3957 /* XXX this is wrong because itt.progress will keep returning to zero at the start
3968 Session::write_one_audio_track (AudioTrack& track, nframes_t start, nframes_t len,
3969 bool overwrite, vector<boost::shared_ptr<Source> >& srcs, InterThreadInfo& itt)
3972 boost::shared_ptr<Playlist> playlist;
3973 boost::shared_ptr<AudioFileSource> fsource;
3975 char buf[PATH_MAX+1];
3976 ChanCount nchans(track.audio_diskstream()->n_channels());
3978 nframes_t this_chunk;
3981 SessionDirectory sdir(get_best_session_directory_for_new_source ());
3982 const string sound_dir = sdir.sound_path().to_string();
3984 // any bigger than this seems to cause stack overflows in called functions
3985 const nframes_t chunk_size = (128 * 1024)/4;
3987 g_atomic_int_set (&processing_prohibited, 1);
3989 /* call tree *MUST* hold route_lock */
3991 if ((playlist = track.diskstream()->playlist()) == 0) {
3995 /* external redirects will be a problem */
3997 if (track.has_external_redirects()) {
4001 for (uint32_t chan_n=0; chan_n < nchans.n_audio(); ++chan_n) {
4003 for (x = 0; x < 99999; ++x) {
4004 snprintf (buf, sizeof(buf), "%s/%s-%d-bounce-%" PRIu32 ".wav", sound_dir.c_str(), playlist->name().c_str(), chan_n, x+1);
4005 if (access (buf, F_OK) != 0) {
4011 error << string_compose (_("too many bounced versions of playlist \"%1\""), playlist->name()) << endmsg;
4016 fsource = boost::dynamic_pointer_cast<AudioFileSource> (
4017 SourceFactory::createWritable (DataType::AUDIO, *this, buf, false, frame_rate()));
4020 catch (failed_constructor& err) {
4021 error << string_compose (_("cannot create new audio file \"%1\" for %2"), buf, track.name()) << endmsg;
4025 srcs.push_back (fsource);
4028 /* XXX need to flush all redirects */
4033 /* create a set of reasonably-sized buffers */
4034 buffers.ensure_buffers(nchans, chunk_size);
4035 buffers.set_count(nchans);
4037 for (vector<boost::shared_ptr<Source> >::iterator src=srcs.begin(); src != srcs.end(); ++src) {
4038 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
4040 afs->prepare_for_peakfile_writes ();
4043 while (to_do && !itt.cancel) {
4045 this_chunk = min (to_do, chunk_size);
4047 if (track.export_stuff (buffers, start, this_chunk)) {
4052 for (vector<boost::shared_ptr<Source> >::iterator src=srcs.begin(); src != srcs.end(); ++src, ++n) {
4053 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
4056 if (afs->write (buffers.get_audio(n).data(), this_chunk) != this_chunk) {
4062 start += this_chunk;
4063 to_do -= this_chunk;
4065 itt.progress = (float) (1.0 - ((double) to_do / len));
4074 xnow = localtime (&now);
4076 for (vector<boost::shared_ptr<Source> >::iterator src=srcs.begin(); src != srcs.end(); ++src) {
4077 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
4080 afs->update_header (position, *xnow, now);
4081 afs->flush_header ();
4085 /* construct a region to represent the bounced material */
4087 boost::shared_ptr<Region> aregion = RegionFactory::create (srcs, 0, srcs.front()->length(),
4088 region_name_from_path (srcs.front()->name(), true));
4095 for (vector<boost::shared_ptr<Source> >::iterator src = srcs.begin(); src != srcs.end(); ++src) {
4096 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
4099 afs->mark_for_remove ();
4102 (*src)->drop_references ();
4106 for (vector<boost::shared_ptr<Source> >::iterator src = srcs.begin(); src != srcs.end(); ++src) {
4107 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
4110 afs->done_with_peakfile_writes ();
4114 g_atomic_int_set (&processing_prohibited, 0);
4120 Session::get_silent_buffers (ChanCount count)
4122 assert(_silent_buffers->available() >= count);
4123 _silent_buffers->set_count(count);
4125 for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
4126 for (size_t i=0; i < count.get(*t); ++i) {
4127 _silent_buffers->get(*t, i).clear();
4131 return *_silent_buffers;
4135 Session::get_scratch_buffers (ChanCount count)
4137 assert(_scratch_buffers->available() >= count);
4138 _scratch_buffers->set_count(count);
4139 return *_scratch_buffers;
4143 Session::get_mix_buffers (ChanCount count)
4145 assert(_mix_buffers->available() >= count);
4146 _mix_buffers->set_count(count);
4147 return *_mix_buffers;
4151 Session::ntracks () const
4154 shared_ptr<RouteList> r = routes.reader ();
4156 for (RouteList::const_iterator i = r->begin(); i != r->end(); ++i) {
4157 if (dynamic_cast<Track*> ((*i).get())) {
4166 Session::nbusses () const
4169 shared_ptr<RouteList> r = routes.reader ();
4171 for (RouteList::const_iterator i = r->begin(); i != r->end(); ++i) {
4172 if (dynamic_cast<Track*> ((*i).get()) == 0) {
4181 Session::add_automation_list(AutomationList *al)
4183 automation_lists[al->id()] = al;
4187 Session::compute_initial_length ()
4189 return _engine.frame_rate() * 60 * 5;
4193 Session::sync_order_keys ()
4195 if (!Config->get_sync_all_route_ordering()) {
4196 /* leave order keys as they are */
4200 boost::shared_ptr<RouteList> r = routes.reader ();
4202 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4203 (*i)->sync_order_keys ();
4206 Route::SyncOrderKeys (); // EMIT SIGNAL
4210 Session::foreach_bundle (sigc::slot<void, boost::shared_ptr<Bundle> > sl)
4212 Glib::Mutex::Lock lm (bundle_lock);
4213 for (BundleList::iterator i = _bundles.begin(); i != _bundles.end(); ++i) {