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>
37 #include <pbd/error.h>
38 #include <glibmm/thread.h>
39 #include <pbd/pathscanner.h>
40 #include <pbd/stl_delete.h>
41 #include <pbd/basename.h>
42 #include <pbd/stacktrace.h>
43 #include <pbd/file_utils.h>
45 #include <ardour/audioengine.h>
46 #include <ardour/configuration.h>
47 #include <ardour/session.h>
48 #include <ardour/session_directory.h>
49 #include <ardour/utils.h>
50 #include <ardour/audio_diskstream.h>
51 #include <ardour/audioplaylist.h>
52 #include <ardour/audioregion.h>
53 #include <ardour/audiofilesource.h>
54 #include <ardour/midi_diskstream.h>
55 #include <ardour/midi_playlist.h>
56 #include <ardour/midi_region.h>
57 #include <ardour/smf_source.h>
58 #include <ardour/auditioner.h>
59 #include <ardour/recent_sessions.h>
60 #include <ardour/io_processor.h>
61 #include <ardour/send.h>
62 #include <ardour/processor.h>
63 #include <ardour/plugin_insert.h>
64 #include <ardour/port_insert.h>
65 #include <ardour/bundle.h>
66 #include <ardour/slave.h>
67 #include <ardour/tempo.h>
68 #include <ardour/audio_track.h>
69 #include <ardour/midi_track.h>
70 #include <ardour/cycle_timer.h>
71 #include <ardour/named_selection.h>
72 #include <ardour/crossfade.h>
73 #include <ardour/playlist.h>
74 #include <ardour/click.h>
75 #include <ardour/data_type.h>
76 #include <ardour/buffer_set.h>
77 #include <ardour/source_factory.h>
78 #include <ardour/region_factory.h>
79 #include <ardour/filename_extensions.h>
80 #include <ardour/session_directory.h>
81 #include <ardour/tape_file_matcher.h>
84 #include <ardour/osc.h>
90 using namespace ARDOUR;
92 using boost::shared_ptr;
95 static const int CPU_CACHE_ALIGN = 64;
97 static const int CPU_CACHE_ALIGN = 16; /* arguably 32 on most arches, but it matters less */
100 sigc::signal<int> Session::AskAboutPendingState;
101 sigc::signal<void> Session::SendFeedback;
103 sigc::signal<void> Session::SMPTEOffsetChanged;
104 sigc::signal<void> Session::StartTimeChanged;
105 sigc::signal<void> Session::EndTimeChanged;
107 Session::Session (AudioEngine &eng,
109 string snapshot_name,
110 string* mix_template)
113 _scratch_buffers(new BufferSet()),
114 _silent_buffers(new BufferSet()),
115 _mix_buffers(new BufferSet()),
116 _mmc_port (default_mmc_port),
117 _mtc_port (default_mtc_port),
118 _midi_port (default_midi_port),
119 _session_dir (new SessionDirectory(fullpath)),
120 pending_events (2048),
121 //midi_requests (128), // the size of this should match the midi request pool size
122 _send_smpte_update (false),
123 diskstreams (new DiskstreamList),
124 routes (new RouteList),
125 auditioner ((Auditioner*) 0),
128 _automation_interval (0)
130 if (!eng.connected()) {
131 throw failed_constructor();
134 n_physical_outputs = _engine.n_physical_outputs();
135 n_physical_inputs = _engine.n_physical_inputs();
137 first_stage_init (fullpath, snapshot_name);
139 initialize_start_and_end_locations(0, compute_initial_length ());
142 // try and create a new session directory
145 if(!_session_dir->create()) {
146 // an existing session.
147 // throw a_more_meaningful_exception()
149 throw failed_constructor ();
152 catch(sys::filesystem_error& ex)
155 throw failed_constructor ();
158 if(!create_session_file_from_template (*mix_template)) {
160 throw failed_constructor ();
163 cerr << "Creating session " << fullpath
164 <<" using template" << *mix_template
167 // must be an existing session
170 // ensure the necessary session subdirectories exist
171 // in case the directory structure has changed etc.
172 _session_dir->create();
174 catch(sys::filesystem_error& ex)
177 throw failed_constructor ();
180 cerr << "Loading session " << fullpath
181 << " using snapshot " << snapshot_name << " (1)"
185 if (second_stage_init (false)) {
187 throw failed_constructor ();
190 store_recent_sessions(_name, _path);
192 bool was_dirty = dirty();
194 _state_of_the_state = StateOfTheState (_state_of_the_state & ~Dirty);
196 Config->ParameterChanged.connect (mem_fun (*this, &Session::config_changed));
199 DirtyChanged (); /* EMIT SIGNAL */
203 Session::Session (AudioEngine &eng,
205 string snapshot_name,
206 AutoConnectOption input_ac,
207 AutoConnectOption output_ac,
208 uint32_t control_out_channels,
209 uint32_t master_out_channels,
210 uint32_t requested_physical_in,
211 uint32_t requested_physical_out,
212 nframes_t initial_length)
215 _scratch_buffers(new BufferSet()),
216 _silent_buffers(new BufferSet()),
217 _mix_buffers(new BufferSet()),
218 _mmc_port (default_mmc_port),
219 _mtc_port (default_mtc_port),
220 _midi_port (default_midi_port),
221 _session_dir ( new SessionDirectory(fullpath)),
222 pending_events (2048),
223 //midi_requests (16),
224 _send_smpte_update (false),
225 diskstreams (new DiskstreamList),
226 routes (new RouteList),
228 _automation_interval (0)
231 if (!eng.connected()) {
232 throw failed_constructor();
235 cerr << "Loading session " << fullpath << " using snapshot " << snapshot_name << " (2)" << endl;
237 n_physical_outputs = _engine.n_physical_outputs();
238 n_physical_inputs = _engine.n_physical_inputs();
240 if (n_physical_inputs) {
241 n_physical_inputs = max (requested_physical_in, n_physical_inputs);
244 if (n_physical_outputs) {
245 n_physical_outputs = max (requested_physical_out, n_physical_outputs);
248 first_stage_init (fullpath, snapshot_name);
250 initialize_start_and_end_locations(0, initial_length);
252 if (!_session_dir->create () || !create_session_file ()) {
254 throw failed_constructor ();
258 /* set up Master Out and Control Out if necessary */
263 if (control_out_channels) {
264 shared_ptr<Route> r (new Route (*this, _("monitor"), -1, control_out_channels, -1, control_out_channels, Route::ControlOut));
265 r->set_remote_control_id (control_id++);
270 if (master_out_channels) {
271 shared_ptr<Route> r (new Route (*this, _("master"), -1, master_out_channels, -1, master_out_channels, Route::MasterOut));
272 r->set_remote_control_id (control_id);
276 /* prohibit auto-connect to master, because there isn't one */
277 output_ac = AutoConnectOption (output_ac & ~AutoConnectMaster);
286 Config->set_input_auto_connect (input_ac);
287 Config->set_output_auto_connect (output_ac);
289 if (second_stage_init (true)) {
291 throw failed_constructor ();
294 store_recent_sessions(_name, _path);
296 bool was_dirty = dirty ();
298 _state_of_the_state = StateOfTheState (_state_of_the_state & ~Dirty);
300 Config->ParameterChanged.connect (mem_fun (*this, &Session::config_changed));
303 DirtyChanged (); /* EMIT SIGNAL */
315 /* if we got to here, leaving pending capture state around
319 remove_pending_capture_state ();
321 _state_of_the_state = StateOfTheState (CannotSave|Deletion);
322 _engine.remove_session ();
324 GoingAway (); /* EMIT SIGNAL */
330 /* clear history so that no references to objects are held any more */
334 /* clear state tree so that no references to objects are held any more */
340 terminate_butler_thread ();
341 //terminate_midi_thread ();
343 if (click_data && click_data != default_click) {
344 delete [] click_data;
347 if (click_emphasis_data && click_emphasis_data != default_click_emphasis) {
348 delete [] click_emphasis_data;
353 delete _scratch_buffers;
354 delete _silent_buffers;
357 AudioDiskstream::free_working_buffers();
359 #undef TRACK_DESTRUCTION
360 #ifdef TRACK_DESTRUCTION
361 cerr << "delete named selections\n";
362 #endif /* TRACK_DESTRUCTION */
363 for (NamedSelectionList::iterator i = named_selections.begin(); i != named_selections.end(); ) {
364 NamedSelectionList::iterator tmp;
373 #ifdef TRACK_DESTRUCTION
374 cerr << "delete playlists\n";
375 #endif /* TRACK_DESTRUCTION */
376 for (PlaylistList::iterator i = playlists.begin(); i != playlists.end(); ) {
377 PlaylistList::iterator tmp;
382 (*i)->drop_references ();
387 for (PlaylistList::iterator i = unused_playlists.begin(); i != unused_playlists.end(); ) {
388 PlaylistList::iterator tmp;
393 (*i)->drop_references ();
399 unused_playlists.clear ();
401 #ifdef TRACK_DESTRUCTION
402 cerr << "delete regions\n";
403 #endif /* TRACK_DESTRUCTION */
405 for (RegionList::iterator i = regions.begin(); i != regions.end(); ) {
406 RegionList::iterator tmp;
411 i->second->drop_references ();
418 #ifdef TRACK_DESTRUCTION
419 cerr << "delete routes\n";
420 #endif /* TRACK_DESTRUCTION */
422 RCUWriter<RouteList> writer (routes);
423 boost::shared_ptr<RouteList> r = writer.get_copy ();
424 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
425 (*i)->drop_references ();
428 /* writer goes out of scope and updates master */
433 #ifdef TRACK_DESTRUCTION
434 cerr << "delete diskstreams\n";
435 #endif /* TRACK_DESTRUCTION */
437 RCUWriter<DiskstreamList> dwriter (diskstreams);
438 boost::shared_ptr<DiskstreamList> dsl = dwriter.get_copy();
439 for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
440 (*i)->drop_references ();
444 diskstreams.flush ();
446 #ifdef TRACK_DESTRUCTION
447 cerr << "delete audio sources\n";
448 #endif /* TRACK_DESTRUCTION */
449 for (SourceMap::iterator i = sources.begin(); i != sources.end(); ) {
450 SourceMap::iterator tmp;
455 i->second->drop_references ();
462 #ifdef TRACK_DESTRUCTION
463 cerr << "delete mix groups\n";
464 #endif /* TRACK_DESTRUCTION */
465 for (list<RouteGroup *>::iterator i = mix_groups.begin(); i != mix_groups.end(); ) {
466 list<RouteGroup*>::iterator tmp;
476 #ifdef TRACK_DESTRUCTION
477 cerr << "delete edit groups\n";
478 #endif /* TRACK_DESTRUCTION */
479 for (list<RouteGroup *>::iterator i = edit_groups.begin(); i != edit_groups.end(); ) {
480 list<RouteGroup*>::iterator tmp;
490 #ifdef TRACK_DESTRUCTION
491 cerr << "delete bundles\n";
492 #endif /* TRACK_DESTRUCTION */
493 for (BundleList::iterator i = _bundles.begin(); i != _bundles.end(); ) {
494 BundleList::iterator tmp;
504 if (butler_mixdown_buffer) {
505 delete [] butler_mixdown_buffer;
508 if (butler_gain_buffer) {
509 delete [] butler_gain_buffer;
512 Crossfade::set_buffer_size (0);
520 Session::set_worst_io_latencies ()
522 _worst_output_latency = 0;
523 _worst_input_latency = 0;
525 if (!_engine.connected()) {
529 boost::shared_ptr<RouteList> r = routes.reader ();
531 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
532 _worst_output_latency = max (_worst_output_latency, (*i)->output_latency());
533 _worst_input_latency = max (_worst_input_latency, (*i)->input_latency());
538 Session::when_engine_running ()
540 string first_physical_output;
542 /* we don't want to run execute this again */
544 set_block_size (_engine.frames_per_cycle());
545 set_frame_rate (_engine.frame_rate());
547 Config->map_parameters (mem_fun (*this, &Session::config_changed));
549 /* every time we reconnect, recompute worst case output latencies */
551 _engine.Running.connect (mem_fun (*this, &Session::set_worst_io_latencies));
553 if (synced_to_jack()) {
554 _engine.transport_stop ();
557 if (Config->get_jack_time_master()) {
558 _engine.transport_locate (_transport_frame);
566 _click_io.reset (new ClickIO (*this, "click", 0, 0, -1, -1));
568 if (state_tree && (child = find_named_node (*state_tree->root(), "Click")) != 0) {
570 /* existing state for Click */
572 if (_click_io->set_state (*child->children().front()) == 0) {
574 _clicking = Config->get_clicking ();
578 error << _("could not setup Click I/O") << endmsg;
584 /* default state for Click */
586 first_physical_output = _engine.get_nth_physical_output (DataType::AUDIO, 0);
588 if (first_physical_output.length()) {
589 if (_click_io->add_output_port (first_physical_output, this)) {
590 // relax, even though its an error
592 _clicking = Config->get_clicking ();
598 catch (failed_constructor& err) {
599 error << _("cannot setup Click I/O") << endmsg;
602 set_worst_io_latencies ();
605 // XXX HOW TO ALERT UI TO THIS ? DO WE NEED TO?
608 /* Create a set of Bundle objects that map
609 to the physical outputs currently available
614 for (uint32_t np = 0; np < n_physical_outputs; ++np) {
616 snprintf (buf, sizeof (buf), _("out %" PRIu32), np+1);
618 Bundle* c = new OutputBundle (buf, true);
619 c->set_nchannels (1);
620 c->add_port_to_channel (0, _engine.get_nth_physical_output (DataType::AUDIO, np));
625 for (uint32_t np = 0; np < n_physical_inputs; ++np) {
627 snprintf (buf, sizeof (buf), _("in %" PRIu32), np+1);
629 Bundle* c = new InputBundle (buf, true);
630 c->set_nchannels (1);
631 c->add_port_to_channel (0, _engine.get_nth_physical_input (DataType::AUDIO, np));
638 for (uint32_t np = 0; np < n_physical_outputs; np +=2) {
640 snprintf (buf, sizeof (buf), _("out %" PRIu32 "+%" PRIu32), np+1, np+2);
642 Bundle* c = new OutputBundle (buf, true);
643 c->set_nchannels (2);
644 c->add_port_to_channel (0, _engine.get_nth_physical_output (DataType::AUDIO, np));
645 c->add_port_to_channel (1, _engine.get_nth_physical_output (DataType::AUDIO, np+1));
650 for (uint32_t np = 0; np < n_physical_inputs; np +=2) {
652 snprintf (buf, sizeof (buf), _("in %" PRIu32 "+%" PRIu32), np+1, np+2);
654 Bundle* c = new InputBundle (buf, true);
655 c->set_nchannels (2);
656 c->add_port_to_channel (0, _engine.get_nth_physical_input (DataType::AUDIO, np));
657 c->add_port_to_channel (1, _engine.get_nth_physical_input (DataType::AUDIO, np+1));
666 /* create master/control ports */
671 /* force the master to ignore any later call to this */
673 if (_master_out->pending_state_node) {
674 _master_out->ports_became_legal();
677 /* no panner resets till we are through */
679 _master_out->defer_pan_reset ();
681 while (_master_out->n_inputs().n_audio()
682 < _master_out->input_maximum().n_audio()) {
683 if (_master_out->add_input_port ("", this, DataType::AUDIO)) {
684 error << _("cannot setup master inputs")
690 while (_master_out->n_outputs().n_audio()
691 < _master_out->output_maximum().n_audio()) {
692 if (_master_out->add_output_port (_engine.get_nth_physical_output (DataType::AUDIO, n), this, DataType::AUDIO)) {
693 error << _("cannot setup master outputs")
700 _master_out->allow_pan_reset ();
704 Bundle* c = new OutputBundle (_("Master Out"), true);
706 c->set_nchannels (_master_out->n_inputs().n_total());
707 for (uint32_t n = 0; n < _master_out->n_inputs ().n_total(); ++n) {
708 c->add_port_to_channel ((int) n, _master_out->input(n)->name());
715 /* catch up on send+insert cnts */
719 for (list<PortInsert*>::iterator i = _port_inserts.begin(); i != _port_inserts.end(); ++i) {
722 if (sscanf ((*i)->name().c_str(), "%*s %u", &id) == 1) {
723 if (id > insert_cnt) {
731 for (list<Send*>::iterator i = _sends.begin(); i != _sends.end(); ++i) {
734 if (sscanf ((*i)->name().c_str(), "%*s %u", &id) == 1) {
742 _state_of_the_state = StateOfTheState (_state_of_the_state & ~(CannotSave|Dirty));
744 /* hook us up to the engine */
746 _engine.set_session (this);
751 osc->set_session (*this);
754 _state_of_the_state = Clean;
756 DirtyChanged (); /* EMIT SIGNAL */
760 Session::hookup_io ()
762 /* stop graph reordering notifications from
763 causing resorts, etc.
766 _state_of_the_state = StateOfTheState (_state_of_the_state | InitialConnecting);
768 if (auditioner == 0) {
770 /* we delay creating the auditioner till now because
771 it makes its own connections to ports.
772 the engine has to be running for this to work.
776 auditioner.reset (new Auditioner (*this));
779 catch (failed_constructor& err) {
780 warning << _("cannot create Auditioner: no auditioning of regions possible") << endmsg;
784 /* Tell all IO objects to create their ports */
790 vector<string> cports;
792 while (_control_out->n_inputs().n_audio() < _control_out->input_maximum().n_audio()) {
793 if (_control_out->add_input_port ("", this)) {
794 error << _("cannot setup control inputs")
800 while (_control_out->n_outputs().n_audio() < _control_out->output_maximum().n_audio()) {
801 if (_control_out->add_output_port (_engine.get_nth_physical_output (DataType::AUDIO, n), this)) {
802 error << _("cannot set up master outputs")
810 uint32_t ni = _control_out->n_inputs().get (DataType::AUDIO);
812 for (n = 0; n < ni; ++n) {
813 cports.push_back (_control_out->input(n)->name());
816 boost::shared_ptr<RouteList> r = routes.reader ();
818 for (RouteList::iterator x = r->begin(); x != r->end(); ++x) {
819 (*x)->set_control_outs (cports);
823 /* Tell all IO objects to connect themselves together */
825 IO::enable_connecting ();
827 /* Now reset all panners */
829 IO::reset_panners ();
831 /* Anyone who cares about input state, wake up and do something */
833 IOConnectionsComplete (); /* EMIT SIGNAL */
835 _state_of_the_state = StateOfTheState (_state_of_the_state & ~InitialConnecting);
837 /* now handle the whole enchilada as if it was one
843 /* update mixer solo state */
849 Session::playlist_length_changed ()
851 /* we can't just increase end_location->end() if pl->get_maximum_extent()
852 if larger. if the playlist used to be the longest playlist,
853 and its now shorter, we have to decrease end_location->end(). hence,
854 we have to iterate over all diskstreams and check the
855 playlists currently in use.
861 Session::diskstream_playlist_changed (boost::shared_ptr<Diskstream> dstream)
863 boost::shared_ptr<Playlist> playlist;
865 if ((playlist = dstream->playlist()) != 0) {
866 playlist->LengthChanged.connect (mem_fun (this, &Session::playlist_length_changed));
869 /* see comment in playlist_length_changed () */
874 Session::record_enabling_legal () const
876 /* this used to be in here, but survey says.... we don't need to restrict it */
877 // if (record_status() == Recording) {
881 if (Config->get_all_safe()) {
888 Session::reset_input_monitor_state ()
890 if (transport_rolling()) {
892 boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
894 for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
895 if ((*i)->record_enabled ()) {
896 //cerr << "switching to input = " << !auto_input << __FILE__ << __LINE__ << endl << endl;
897 (*i)->monitor_input (Config->get_monitoring_model() == HardwareMonitoring && !Config->get_auto_input());
901 boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
903 for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
904 if ((*i)->record_enabled ()) {
905 //cerr << "switching to input = " << !Config->get_auto_input() << __FILE__ << __LINE__ << endl << endl;
906 (*i)->monitor_input (Config->get_monitoring_model() == HardwareMonitoring);
913 Session::auto_punch_start_changed (Location* location)
915 replace_event (Event::PunchIn, location->start());
917 if (get_record_enabled() && Config->get_punch_in()) {
918 /* capture start has been changed, so save new pending state */
919 save_state ("", true);
924 Session::auto_punch_end_changed (Location* location)
926 nframes_t when_to_stop = location->end();
927 // when_to_stop += _worst_output_latency + _worst_input_latency;
928 replace_event (Event::PunchOut, when_to_stop);
932 Session::auto_punch_changed (Location* location)
934 nframes_t when_to_stop = location->end();
936 replace_event (Event::PunchIn, location->start());
937 //when_to_stop += _worst_output_latency + _worst_input_latency;
938 replace_event (Event::PunchOut, when_to_stop);
942 Session::auto_loop_changed (Location* location)
944 replace_event (Event::AutoLoop, location->end(), location->start());
946 if (transport_rolling() && play_loop) {
948 //if (_transport_frame < location->start() || _transport_frame > location->end()) {
950 if (_transport_frame > location->end()) {
951 // relocate to beginning of loop
952 clear_events (Event::LocateRoll);
954 request_locate (location->start(), true);
957 else if (Config->get_seamless_loop() && !loop_changing) {
959 // schedule a locate-roll to refill the diskstreams at the
961 loop_changing = true;
963 if (location->end() > last_loopend) {
964 clear_events (Event::LocateRoll);
965 Event *ev = new Event (Event::LocateRoll, Event::Add, last_loopend, last_loopend, 0, true);
972 last_loopend = location->end();
977 Session::set_auto_punch_location (Location* location)
981 if ((existing = _locations.auto_punch_location()) != 0 && existing != location) {
982 auto_punch_start_changed_connection.disconnect();
983 auto_punch_end_changed_connection.disconnect();
984 auto_punch_changed_connection.disconnect();
985 existing->set_auto_punch (false, this);
986 remove_event (existing->start(), Event::PunchIn);
987 clear_events (Event::PunchOut);
988 auto_punch_location_changed (0);
997 if (location->end() <= location->start()) {
998 error << _("Session: you can't use that location for auto punch (start <= end)") << endmsg;
1002 auto_punch_start_changed_connection.disconnect();
1003 auto_punch_end_changed_connection.disconnect();
1004 auto_punch_changed_connection.disconnect();
1006 auto_punch_start_changed_connection = location->start_changed.connect (mem_fun (this, &Session::auto_punch_start_changed));
1007 auto_punch_end_changed_connection = location->end_changed.connect (mem_fun (this, &Session::auto_punch_end_changed));
1008 auto_punch_changed_connection = location->changed.connect (mem_fun (this, &Session::auto_punch_changed));
1010 location->set_auto_punch (true, this);
1011 auto_punch_location_changed (location);
1015 Session::set_auto_loop_location (Location* location)
1019 if ((existing = _locations.auto_loop_location()) != 0 && existing != location) {
1020 auto_loop_start_changed_connection.disconnect();
1021 auto_loop_end_changed_connection.disconnect();
1022 auto_loop_changed_connection.disconnect();
1023 existing->set_auto_loop (false, this);
1024 remove_event (existing->end(), Event::AutoLoop);
1025 auto_loop_location_changed (0);
1030 if (location == 0) {
1034 if (location->end() <= location->start()) {
1035 error << _("Session: you can't use a mark for auto loop") << endmsg;
1039 last_loopend = location->end();
1041 auto_loop_start_changed_connection.disconnect();
1042 auto_loop_end_changed_connection.disconnect();
1043 auto_loop_changed_connection.disconnect();
1045 auto_loop_start_changed_connection = location->start_changed.connect (mem_fun (this, &Session::auto_loop_changed));
1046 auto_loop_end_changed_connection = location->end_changed.connect (mem_fun (this, &Session::auto_loop_changed));
1047 auto_loop_changed_connection = location->changed.connect (mem_fun (this, &Session::auto_loop_changed));
1049 location->set_auto_loop (true, this);
1050 auto_loop_location_changed (location);
1054 Session::locations_added (Location* ignored)
1060 Session::locations_changed ()
1062 _locations.apply (*this, &Session::handle_locations_changed);
1066 Session::handle_locations_changed (Locations::LocationList& locations)
1068 Locations::LocationList::iterator i;
1070 bool set_loop = false;
1071 bool set_punch = false;
1073 for (i = locations.begin(); i != locations.end(); ++i) {
1077 if (location->is_auto_punch()) {
1078 set_auto_punch_location (location);
1081 if (location->is_auto_loop()) {
1082 set_auto_loop_location (location);
1089 set_auto_loop_location (0);
1092 set_auto_punch_location (0);
1099 Session::enable_record ()
1101 /* XXX really atomic compare+swap here */
1102 if (g_atomic_int_get (&_record_status) != Recording) {
1103 g_atomic_int_set (&_record_status, Recording);
1104 _last_record_location = _transport_frame;
1105 deliver_mmc(MIDI::MachineControl::cmdRecordStrobe, _last_record_location);
1107 if (Config->get_monitoring_model() == HardwareMonitoring && Config->get_auto_input()) {
1108 boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
1109 for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
1110 if ((*i)->record_enabled ()) {
1111 (*i)->monitor_input (true);
1116 RecordStateChanged ();
1121 Session::disable_record (bool rt_context, bool force)
1125 if ((rs = (RecordState) g_atomic_int_get (&_record_status)) != Disabled) {
1127 if ((!Config->get_latched_record_enable () && !play_loop) || force) {
1128 g_atomic_int_set (&_record_status, Disabled);
1130 if (rs == Recording) {
1131 g_atomic_int_set (&_record_status, Enabled);
1135 // FIXME: timestamp correct? [DR]
1136 // FIXME FIXME FIXME: rt_context? this must be called in the process thread.
1137 // does this /need/ to be sent in all cases?
1139 deliver_mmc (MIDI::MachineControl::cmdRecordExit, _transport_frame);
1141 if (Config->get_monitoring_model() == HardwareMonitoring && Config->get_auto_input()) {
1142 boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
1144 for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
1145 if ((*i)->record_enabled ()) {
1146 (*i)->monitor_input (false);
1151 RecordStateChanged (); /* emit signal */
1154 remove_pending_capture_state ();
1160 Session::step_back_from_record ()
1162 /* XXX really atomic compare+swap here */
1163 if (g_atomic_int_get (&_record_status) == Recording) {
1164 g_atomic_int_set (&_record_status, Enabled);
1166 if (Config->get_monitoring_model() == HardwareMonitoring) {
1167 boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
1169 for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
1170 if (Config->get_auto_input() && (*i)->record_enabled ()) {
1171 //cerr << "switching from input" << __FILE__ << __LINE__ << endl << endl;
1172 (*i)->monitor_input (false);
1180 Session::maybe_enable_record ()
1182 g_atomic_int_set (&_record_status, Enabled);
1184 /* this function is currently called from somewhere other than an RT thread.
1185 this save_state() call therefore doesn't impact anything.
1188 save_state ("", true);
1190 if (_transport_speed) {
1191 if (!Config->get_punch_in()) {
1195 deliver_mmc (MIDI::MachineControl::cmdRecordPause, _transport_frame);
1196 RecordStateChanged (); /* EMIT SIGNAL */
1203 Session::audible_frame () const
1209 /* the first of these two possible settings for "offset"
1210 mean that the audible frame is stationary until
1211 audio emerges from the latency compensation
1214 the second means that the audible frame is stationary
1215 until audio would emerge from a physical port
1216 in the absence of any plugin latency compensation
1219 offset = _worst_output_latency;
1221 if (offset > current_block_size) {
1222 offset -= current_block_size;
1224 /* XXX is this correct? if we have no external
1225 physical connections and everything is internal
1226 then surely this is zero? still, how
1227 likely is that anyway?
1229 offset = current_block_size;
1232 if (synced_to_jack()) {
1233 tf = _engine.transport_frame();
1235 tf = _transport_frame;
1238 if (_transport_speed == 0) {
1248 if (!non_realtime_work_pending()) {
1252 /* take latency into account */
1261 Session::set_frame_rate (nframes_t frames_per_second)
1263 /** \fn void Session::set_frame_size(nframes_t)
1264 the AudioEngine object that calls this guarantees
1265 that it will not be called while we are also in
1266 ::process(). Its fine to do things that block
1270 _base_frame_rate = frames_per_second;
1274 _automation_interval = ((nframes_t) ceil ((double) frames_per_second * 0.25));
1276 // XXX we need some equivalent to this, somehow
1277 // SndFileSource::setup_standard_crossfades (frames_per_second);
1281 /* XXX need to reset/reinstantiate all LADSPA plugins */
1285 Session::set_block_size (nframes_t nframes)
1287 /* the AudioEngine guarantees
1288 that it will not be called while we are also in
1289 ::process(). It is therefore fine to do things that block
1295 current_block_size = nframes;
1297 ensure_buffers(_scratch_buffers->available());
1299 if (_gain_automation_buffer) {
1300 delete [] _gain_automation_buffer;
1302 _gain_automation_buffer = new gain_t[nframes];
1304 allocate_pan_automation_buffers (nframes, _npan_buffers, true);
1306 boost::shared_ptr<RouteList> r = routes.reader ();
1308 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
1309 (*i)->set_block_size (nframes);
1312 boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
1313 for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
1314 (*i)->set_block_size (nframes);
1317 set_worst_io_latencies ();
1322 Session::set_default_fade (float steepness, float fade_msecs)
1325 nframes_t fade_frames;
1327 /* Don't allow fade of less 1 frame */
1329 if (fade_msecs < (1000.0 * (1.0/_current_frame_rate))) {
1336 fade_frames = (nframes_t) floor (fade_msecs * _current_frame_rate * 0.001);
1340 default_fade_msecs = fade_msecs;
1341 default_fade_steepness = steepness;
1344 // jlc, WTF is this!
1345 Glib::RWLock::ReaderLock lm (route_lock);
1346 AudioRegion::set_default_fade (steepness, fade_frames);
1351 /* XXX have to do this at some point */
1352 /* foreach region using default fade, reset, then
1353 refill_all_diskstream_buffers ();
1358 struct RouteSorter {
1359 bool operator() (boost::shared_ptr<Route> r1, boost::shared_ptr<Route> r2) {
1360 if (r1->fed_by.find (r2) != r1->fed_by.end()) {
1362 } else if (r2->fed_by.find (r1) != r2->fed_by.end()) {
1365 if (r1->fed_by.empty()) {
1366 if (r2->fed_by.empty()) {
1367 /* no ardour-based connections inbound to either route. just use signal order */
1368 return r1->order_key(N_("signal")) < r2->order_key(N_("signal"));
1370 /* r2 has connections, r1 does not; run r1 early */
1374 return r1->order_key(N_("signal")) < r2->order_key(N_("signal"));
1381 trace_terminal (shared_ptr<Route> r1, shared_ptr<Route> rbase)
1383 shared_ptr<Route> r2;
1385 if ((r1->fed_by.find (rbase) != r1->fed_by.end()) && (rbase->fed_by.find (r1) != rbase->fed_by.end())) {
1386 info << string_compose(_("feedback loop setup between %1 and %2"), r1->name(), rbase->name()) << endmsg;
1390 /* make a copy of the existing list of routes that feed r1 */
1392 set<shared_ptr<Route> > existing = r1->fed_by;
1394 /* for each route that feeds r1, recurse, marking it as feeding
1398 for (set<shared_ptr<Route> >::iterator i = existing.begin(); i != existing.end(); ++i) {
1401 /* r2 is a route that feeds r1 which somehow feeds base. mark
1402 base as being fed by r2
1405 rbase->fed_by.insert (r2);
1409 /* 2nd level feedback loop detection. if r1 feeds or is fed by r2,
1413 if ((r1->fed_by.find (r2) != r1->fed_by.end()) && (r2->fed_by.find (r1) != r2->fed_by.end())) {
1417 /* now recurse, so that we can mark base as being fed by
1418 all routes that feed r2
1421 trace_terminal (r2, rbase);
1428 Session::resort_routes ()
1430 /* don't do anything here with signals emitted
1431 by Routes while we are being destroyed.
1434 if (_state_of_the_state & Deletion) {
1441 RCUWriter<RouteList> writer (routes);
1442 shared_ptr<RouteList> r = writer.get_copy ();
1443 resort_routes_using (r);
1444 /* writer goes out of scope and forces update */
1449 Session::resort_routes_using (shared_ptr<RouteList> r)
1451 RouteList::iterator i, j;
1453 for (i = r->begin(); i != r->end(); ++i) {
1455 (*i)->fed_by.clear ();
1457 for (j = r->begin(); j != r->end(); ++j) {
1459 /* although routes can feed themselves, it will
1460 cause an endless recursive descent if we
1461 detect it. so don't bother checking for
1469 if ((*j)->feeds (*i)) {
1470 (*i)->fed_by.insert (*j);
1475 for (i = r->begin(); i != r->end(); ++i) {
1476 trace_terminal (*i, *i);
1483 cerr << "finished route resort\n";
1485 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
1486 cerr << " " << (*i)->name() << " signal order = " << (*i)->order_key ("signal") << endl;
1493 list<boost::shared_ptr<MidiTrack> >
1494 Session::new_midi_track (TrackMode mode, uint32_t how_many)
1496 char track_name[32];
1497 uint32_t track_id = 0;
1499 uint32_t channels_used = 0;
1501 RouteList new_routes;
1502 list<boost::shared_ptr<MidiTrack> > ret;
1504 /* count existing midi tracks */
1507 shared_ptr<RouteList> r = routes.reader ();
1509 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
1510 if (dynamic_cast<MidiTrack*>((*i).get()) != 0) {
1511 if (!(*i)->is_hidden()) {
1513 channels_used += (*i)->n_inputs().n_midi();
1521 /* check for duplicate route names, since we might have pre-existing
1522 routes with this name (e.g. create Midi1, Midi2, delete Midi1,
1523 save, close,restart,add new route - first named route is now
1531 snprintf (track_name, sizeof(track_name), "Midi %" PRIu32, track_id);
1533 if (route_by_name (track_name) == 0) {
1537 } while (track_id < (UINT_MAX-1));
1540 shared_ptr<MidiTrack> track (new MidiTrack (*this, track_name, Route::Flag (0), mode));
1542 if (track->ensure_io (ChanCount(DataType::MIDI, 1), ChanCount(DataType::MIDI, 1), false, this)) {
1543 error << "cannot configure 1 in/1 out configuration for new midi track" << endmsg;
1546 channels_used += track->n_inputs ().n_midi();
1548 track->DiskstreamChanged.connect (mem_fun (this, &Session::resort_routes));
1549 track->set_remote_control_id (ntracks());
1551 new_routes.push_back (track);
1552 ret.push_back (track);
1555 catch (failed_constructor &err) {
1556 error << _("Session: could not create new midi track.") << endmsg;
1557 // XXX should we delete the tracks already created?
1565 if (!new_routes.empty()) {
1566 add_routes (new_routes, false);
1567 save_state (_current_snapshot_name);
1573 list<boost::shared_ptr<AudioTrack> >
1574 Session::new_audio_track (int input_channels, int output_channels, TrackMode mode, uint32_t how_many)
1576 char track_name[32];
1577 uint32_t track_id = 0;
1579 uint32_t channels_used = 0;
1581 RouteList new_routes;
1582 list<boost::shared_ptr<AudioTrack> > ret;
1583 uint32_t control_id;
1585 /* count existing audio tracks */
1588 shared_ptr<RouteList> r = routes.reader ();
1590 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
1591 if (dynamic_cast<AudioTrack*>((*i).get()) != 0) {
1592 if (!(*i)->is_hidden()) {
1594 channels_used += (*i)->n_inputs().n_audio();
1600 vector<string> physinputs;
1601 vector<string> physoutputs;
1602 uint32_t nphysical_in;
1603 uint32_t nphysical_out;
1605 _engine.get_physical_outputs (physoutputs);
1606 _engine.get_physical_inputs (physinputs);
1607 control_id = ntracks() + nbusses() + 1;
1611 /* check for duplicate route names, since we might have pre-existing
1612 routes with this name (e.g. create Audio1, Audio2, delete Audio1,
1613 save, close,restart,add new route - first named route is now
1621 snprintf (track_name, sizeof(track_name), "Audio %" PRIu32, track_id);
1623 if (route_by_name (track_name) == 0) {
1627 } while (track_id < (UINT_MAX-1));
1629 if (Config->get_input_auto_connect() & AutoConnectPhysical) {
1630 nphysical_in = min (n_physical_inputs, (uint32_t) physinputs.size());
1635 if (Config->get_output_auto_connect() & AutoConnectPhysical) {
1636 nphysical_out = min (n_physical_outputs, (uint32_t) physinputs.size());
1641 shared_ptr<AudioTrack> track;
1644 track = boost::shared_ptr<AudioTrack>((new AudioTrack (*this, track_name, Route::Flag (0), mode)));
1646 if (track->ensure_io (ChanCount(DataType::AUDIO, input_channels), ChanCount(DataType::AUDIO, output_channels), false, this)) {
1647 error << string_compose (_("cannot configure %1 in/%2 out configuration for new audio track"),
1648 input_channels, output_channels)
1654 for (uint32_t x = 0; x < track->n_inputs().n_audio() && x < nphysical_in; ++x) {
1658 if (Config->get_input_auto_connect() & AutoConnectPhysical) {
1659 port = physinputs[(channels_used+x)%nphysical_in];
1662 if (port.length() && track->connect_input (track->input (x), port, this)) {
1668 for (uint32_t x = 0; x < track->n_outputs().n_midi(); ++x) {
1672 if (nphysical_out && (Config->get_output_auto_connect() & AutoConnectPhysical)) {
1673 port = physoutputs[(channels_used+x)%nphysical_out];
1674 } else if (Config->get_output_auto_connect() & AutoConnectMaster) {
1676 port = _master_out->input (x%_master_out->n_inputs().n_audio())->name();
1680 if (port.length() && track->connect_output (track->output (x), port, this)) {
1685 channels_used += track->n_inputs ().n_audio();
1687 track->audio_diskstream()->non_realtime_input_change();
1689 track->DiskstreamChanged.connect (mem_fun (this, &Session::resort_routes));
1690 track->set_remote_control_id (control_id);
1693 new_routes.push_back (track);
1694 ret.push_back (track);
1697 catch (failed_constructor &err) {
1698 error << _("Session: could not create new audio track.") << endmsg;
1701 /* we need to get rid of this, since the track failed to be created */
1702 /* XXX arguably, AudioTrack::AudioTrack should not do the Session::add_diskstream() */
1705 RCUWriter<DiskstreamList> writer (diskstreams);
1706 boost::shared_ptr<DiskstreamList> ds = writer.get_copy();
1707 ds->remove (track->audio_diskstream());
1714 catch (AudioEngine::PortRegistrationFailure& pfe) {
1716 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;
1719 /* we need to get rid of this, since the track failed to be created */
1720 /* XXX arguably, AudioTrack::AudioTrack should not do the Session::add_diskstream() */
1723 RCUWriter<DiskstreamList> writer (diskstreams);
1724 boost::shared_ptr<DiskstreamList> ds = writer.get_copy();
1725 ds->remove (track->audio_diskstream());
1736 if (!new_routes.empty()) {
1737 add_routes (new_routes, false);
1738 save_state (_current_snapshot_name);
1745 Session::set_remote_control_ids ()
1747 RemoteModel m = Config->get_remote_model();
1749 shared_ptr<RouteList> r = routes.reader ();
1751 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
1752 if ( MixerOrdered == m) {
1753 long order = (*i)->order_key(N_("signal"));
1754 (*i)->set_remote_control_id( order+1 );
1755 } else if ( EditorOrdered == m) {
1756 long order = (*i)->order_key(N_("editor"));
1757 (*i)->set_remote_control_id( order+1 );
1758 } else if ( UserOrdered == m) {
1759 //do nothing ... only changes to remote id's are initiated by user
1766 Session::new_audio_route (int input_channels, int output_channels, uint32_t how_many)
1769 uint32_t bus_id = 1;
1773 uint32_t control_id;
1775 /* count existing audio busses */
1778 shared_ptr<RouteList> r = routes.reader ();
1780 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
1781 if (dynamic_cast<AudioTrack*>((*i).get()) == 0) {
1782 if (!(*i)->is_hidden() && (*i)->name() != _("master")) {
1789 vector<string> physinputs;
1790 vector<string> physoutputs;
1792 _engine.get_physical_outputs (physoutputs);
1793 _engine.get_physical_inputs (physinputs);
1794 control_id = ntracks() + nbusses() + 1;
1799 snprintf (bus_name, sizeof(bus_name), "Bus %" PRIu32, bus_id);
1803 if (route_by_name (bus_name) == 0) {
1807 } while (bus_id < (UINT_MAX-1));
1810 shared_ptr<Route> bus (new Route (*this, bus_name, -1, -1, -1, -1, Route::Flag(0), DataType::AUDIO));
1812 if (bus->ensure_io (ChanCount(DataType::AUDIO, input_channels), ChanCount(DataType::AUDIO, output_channels), false, this)) {
1813 error << string_compose (_("cannot configure %1 in/%2 out configuration for new audio track"),
1814 input_channels, output_channels)
1819 for (uint32_t x = 0; n_physical_inputs && x < bus->n_inputs().n_audio(); ++x) {
1823 if (Config->get_input_auto_connect() & AutoConnectPhysical) {
1824 port = physinputs[((n+x)%n_physical_inputs)];
1827 if (port.length() && bus->connect_input (bus->input (x), port, this)) {
1832 for (uint32_t x = 0; n_physical_outputs && x < bus->n_outputs().n_audio(); ++x) {
1836 if (Config->get_output_auto_connect() & AutoConnectPhysical) {
1837 port = physoutputs[((n+x)%n_physical_outputs)];
1838 } else if (Config->get_output_auto_connect() & AutoConnectMaster) {
1840 port = _master_out->input (x%_master_out->n_inputs().n_audio())->name();
1844 if (port.length() && bus->connect_output (bus->output (x), port, this)) {
1849 bus->set_remote_control_id (control_id);
1852 ret.push_back (bus);
1856 catch (failed_constructor &err) {
1857 error << _("Session: could not create new audio route.") << endmsg;
1861 catch (AudioEngine::PortRegistrationFailure& pfe) {
1862 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;
1872 add_routes (ret, false);
1873 save_state (_current_snapshot_name);
1881 Session::add_routes (RouteList& new_routes, bool save)
1884 RCUWriter<RouteList> writer (routes);
1885 shared_ptr<RouteList> r = writer.get_copy ();
1886 r->insert (r->end(), new_routes.begin(), new_routes.end());
1887 resort_routes_using (r);
1890 for (RouteList::iterator x = new_routes.begin(); x != new_routes.end(); ++x) {
1892 boost::weak_ptr<Route> wpr (*x);
1894 (*x)->solo_changed.connect (sigc::bind (mem_fun (*this, &Session::route_solo_changed), wpr));
1895 (*x)->mute_changed.connect (mem_fun (*this, &Session::route_mute_changed));
1896 (*x)->output_changed.connect (mem_fun (*this, &Session::set_worst_io_latencies_x));
1897 (*x)->processors_changed.connect (bind (mem_fun (*this, &Session::update_latency_compensation), false, false));
1899 if ((*x)->is_master()) {
1903 if ((*x)->is_control()) {
1904 _control_out = (*x);
1908 if (_control_out && IO::connecting_legal) {
1910 vector<string> cports;
1911 uint32_t ni = _control_out->n_inputs().n_audio();
1913 for (uint32_t n = 0; n < ni; ++n) {
1914 cports.push_back (_control_out->input(n)->name());
1917 for (RouteList::iterator x = new_routes.begin(); x != new_routes.end(); ++x) {
1918 (*x)->set_control_outs (cports);
1925 save_state (_current_snapshot_name);
1928 RouteAdded (new_routes); /* EMIT SIGNAL */
1932 Session::add_diskstream (boost::shared_ptr<Diskstream> dstream)
1934 /* need to do this in case we're rolling at the time, to prevent false underruns */
1935 dstream->do_refill_with_alloc ();
1937 dstream->set_block_size (current_block_size);
1940 RCUWriter<DiskstreamList> writer (diskstreams);
1941 boost::shared_ptr<DiskstreamList> ds = writer.get_copy();
1942 ds->push_back (dstream);
1943 /* writer goes out of scope, copies ds back to main */
1946 dstream->PlaylistChanged.connect (sigc::bind (mem_fun (*this, &Session::diskstream_playlist_changed), dstream));
1947 /* this will connect to future changes, and check the current length */
1948 diskstream_playlist_changed (dstream);
1950 dstream->prepare ();
1955 Session::remove_route (shared_ptr<Route> route)
1958 RCUWriter<RouteList> writer (routes);
1959 shared_ptr<RouteList> rs = writer.get_copy ();
1963 /* deleting the master out seems like a dumb
1964 idea, but its more of a UI policy issue
1968 if (route == _master_out) {
1969 _master_out = shared_ptr<Route> ();
1972 if (route == _control_out) {
1973 _control_out = shared_ptr<Route> ();
1975 /* cancel control outs for all routes */
1977 vector<string> empty;
1979 for (RouteList::iterator r = rs->begin(); r != rs->end(); ++r) {
1980 (*r)->set_control_outs (empty);
1984 update_route_solo_state ();
1986 /* writer goes out of scope, forces route list update */
1990 boost::shared_ptr<Diskstream> ds;
1992 if ((t = dynamic_cast<Track*>(route.get())) != 0) {
1993 ds = t->diskstream();
1999 RCUWriter<DiskstreamList> dsl (diskstreams);
2000 boost::shared_ptr<DiskstreamList> d = dsl.get_copy();
2005 find_current_end ();
2007 update_latency_compensation (false, false);
2010 // We need to disconnect the routes inputs and outputs
2011 route->disconnect_inputs(NULL);
2012 route->disconnect_outputs(NULL);
2014 /* get rid of it from the dead wood collection in the route list manager */
2016 /* XXX i think this is unsafe as it currently stands, but i am not sure. (pd, october 2nd, 2006) */
2020 /* try to cause everyone to drop their references */
2022 route->drop_references ();
2024 /* save the new state of the world */
2026 if (save_state (_current_snapshot_name)) {
2027 save_history (_current_snapshot_name);
2032 Session::route_mute_changed (void* src)
2038 Session::route_solo_changed (void* src, boost::weak_ptr<Route> wpr)
2040 if (solo_update_disabled) {
2046 boost::shared_ptr<Route> route = wpr.lock ();
2049 /* should not happen */
2050 error << string_compose (_("programming error: %1"), X_("invalid route weak ptr passed to route_solo_changed")) << endmsg;
2054 is_track = (boost::dynamic_pointer_cast<AudioTrack>(route) != 0);
2056 shared_ptr<RouteList> r = routes.reader ();
2058 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2060 /* soloing a track mutes all other tracks, soloing a bus mutes all other busses */
2064 /* don't mess with busses */
2066 if (dynamic_cast<Track*>((*i).get()) == 0) {
2072 /* don't mess with tracks */
2074 if (dynamic_cast<Track*>((*i).get()) != 0) {
2079 if ((*i) != route &&
2080 ((*i)->mix_group () == 0 ||
2081 (*i)->mix_group () != route->mix_group () ||
2082 !route->mix_group ()->is_active())) {
2084 if ((*i)->soloed()) {
2086 /* if its already soloed, and solo latching is enabled,
2087 then leave it as it is.
2090 if (Config->get_solo_latched()) {
2097 solo_update_disabled = true;
2098 (*i)->set_solo (false, src);
2099 solo_update_disabled = false;
2103 bool something_soloed = false;
2104 bool same_thing_soloed = false;
2105 bool signal = false;
2107 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2108 if ((*i)->soloed()) {
2109 something_soloed = true;
2110 if (dynamic_cast<Track*>((*i).get())) {
2112 same_thing_soloed = true;
2117 same_thing_soloed = true;
2125 if (something_soloed != currently_soloing) {
2127 currently_soloing = something_soloed;
2130 modify_solo_mute (is_track, same_thing_soloed);
2133 SoloActive (currently_soloing); /* EMIT SIGNAL */
2136 SoloChanged (); /* EMIT SIGNAL */
2142 Session::update_route_solo_state ()
2145 bool is_track = false;
2146 bool signal = false;
2148 /* caller must hold RouteLock */
2150 /* this is where we actually implement solo by changing
2151 the solo mute setting of each track.
2154 shared_ptr<RouteList> r = routes.reader ();
2156 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2157 if ((*i)->soloed()) {
2159 if (dynamic_cast<Track*>((*i).get())) {
2166 if (mute != currently_soloing) {
2168 currently_soloing = mute;
2171 if (!is_track && !mute) {
2173 /* nothing is soloed */
2175 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2176 (*i)->set_solo_mute (false);
2186 modify_solo_mute (is_track, mute);
2189 SoloActive (currently_soloing);
2194 Session::modify_solo_mute (bool is_track, bool mute)
2196 shared_ptr<RouteList> r = routes.reader ();
2198 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2202 /* only alter track solo mute */
2204 if (dynamic_cast<Track*>((*i).get())) {
2205 if ((*i)->soloed()) {
2206 (*i)->set_solo_mute (!mute);
2208 (*i)->set_solo_mute (mute);
2214 /* only alter bus solo mute */
2216 if (!dynamic_cast<Track*>((*i).get())) {
2218 if ((*i)->soloed()) {
2220 (*i)->set_solo_mute (false);
2224 /* don't mute master or control outs
2225 in response to another bus solo
2228 if ((*i) != _master_out &&
2229 (*i) != _control_out) {
2230 (*i)->set_solo_mute (mute);
2241 Session::catch_up_on_solo ()
2243 /* this is called after set_state() to catch the full solo
2244 state, which can't be correctly determined on a per-route
2245 basis, but needs the global overview that only the session
2248 update_route_solo_state();
2252 Session::route_by_name (string name)
2254 shared_ptr<RouteList> r = routes.reader ();
2256 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2257 if ((*i)->name() == name) {
2262 return shared_ptr<Route> ((Route*) 0);
2266 Session::route_by_id (PBD::ID id)
2268 shared_ptr<RouteList> r = routes.reader ();
2270 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2271 if ((*i)->id() == id) {
2276 return shared_ptr<Route> ((Route*) 0);
2280 Session::route_by_remote_id (uint32_t id)
2282 shared_ptr<RouteList> r = routes.reader ();
2284 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2285 if ((*i)->remote_control_id() == id) {
2290 return shared_ptr<Route> ((Route*) 0);
2294 Session::find_current_end ()
2296 if (_state_of_the_state & Loading) {
2300 nframes_t max = get_maximum_extent ();
2302 if (max > end_location->end()) {
2303 end_location->set_end (max);
2305 DurationChanged(); /* EMIT SIGNAL */
2310 Session::get_maximum_extent () const
2315 boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
2317 for (DiskstreamList::const_iterator i = dsl->begin(); i != dsl->end(); ++i) {
2318 boost::shared_ptr<Playlist> pl = (*i)->playlist();
2319 if ((me = pl->get_maximum_extent()) > max) {
2327 boost::shared_ptr<Diskstream>
2328 Session::diskstream_by_name (string name)
2330 boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
2332 for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
2333 if ((*i)->name() == name) {
2338 return boost::shared_ptr<Diskstream>((Diskstream*) 0);
2341 boost::shared_ptr<Diskstream>
2342 Session::diskstream_by_id (const PBD::ID& id)
2344 boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
2346 for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
2347 if ((*i)->id() == id) {
2352 return boost::shared_ptr<Diskstream>((Diskstream*) 0);
2355 /* Region management */
2358 Session::new_region_name (string old)
2360 string::size_type last_period;
2362 string::size_type len = old.length() + 64;
2365 if ((last_period = old.find_last_of ('.')) == string::npos) {
2367 /* no period present - add one explicitly */
2370 last_period = old.length() - 1;
2375 number = atoi (old.substr (last_period+1).c_str());
2379 while (number < (UINT_MAX-1)) {
2381 RegionList::const_iterator i;
2386 snprintf (buf, len, "%s%" PRIu32, old.substr (0, last_period + 1).c_str(), number);
2389 for (i = regions.begin(); i != regions.end(); ++i) {
2390 if (i->second->name() == sbuf) {
2395 if (i == regions.end()) {
2400 if (number != (UINT_MAX-1)) {
2404 error << string_compose (_("cannot create new name for region \"%1\""), old) << endmsg;
2409 Session::region_name (string& result, string base, bool newlevel) const
2414 assert(base.find("/") == string::npos);
2418 Glib::Mutex::Lock lm (region_lock);
2420 snprintf (buf, sizeof (buf), "%d", (int)regions.size() + 1);
2428 /* XXX this is going to be slow. optimize me later */
2433 string::size_type pos;
2435 pos = base.find_last_of ('.');
2437 /* pos may be npos, but then we just use entire base */
2439 subbase = base.substr (0, pos);
2443 bool name_taken = true;
2446 Glib::Mutex::Lock lm (region_lock);
2448 for (int n = 1; n < 5000; ++n) {
2451 snprintf (buf, sizeof (buf), ".%d", n);
2456 for (RegionList::const_iterator i = regions.begin(); i != regions.end(); ++i) {
2457 if (i->second->name() == result) {
2470 fatal << string_compose(_("too many regions with names like %1"), base) << endmsg;
2478 Session::add_region (boost::shared_ptr<Region> region)
2480 boost::shared_ptr<Region> other;
2484 Glib::Mutex::Lock lm (region_lock);
2486 RegionList::iterator x;
2488 for (x = regions.begin(); x != regions.end(); ++x) {
2492 if (region->region_list_equivalent (other)) {
2497 if (x == regions.end()) {
2499 pair<RegionList::key_type,RegionList::mapped_type> entry;
2501 entry.first = region->id();
2502 entry.second = region;
2504 pair<RegionList::iterator,bool> x = regions.insert (entry);
2516 /* mark dirty because something has changed even if we didn't
2517 add the region to the region list.
2523 region->GoingAway.connect (sigc::bind (mem_fun (*this, &Session::remove_region), boost::weak_ptr<Region>(region)));
2524 region->StateChanged.connect (sigc::bind (mem_fun (*this, &Session::region_changed), boost::weak_ptr<Region>(region)));
2525 RegionAdded (region); /* EMIT SIGNAL */
2530 Session::region_changed (Change what_changed, boost::weak_ptr<Region> weak_region)
2532 boost::shared_ptr<Region> region (weak_region.lock ());
2538 if (what_changed & Region::HiddenChanged) {
2539 /* relay hidden changes */
2540 RegionHiddenChange (region);
2545 Session::remove_region (boost::weak_ptr<Region> weak_region)
2547 RegionList::iterator i;
2548 boost::shared_ptr<Region> region (weak_region.lock ());
2554 bool removed = false;
2557 Glib::Mutex::Lock lm (region_lock);
2559 if ((i = regions.find (region->id())) != regions.end()) {
2565 /* mark dirty because something has changed even if we didn't
2566 remove the region from the region list.
2572 RegionRemoved(region); /* EMIT SIGNAL */
2576 boost::shared_ptr<Region>
2577 Session::find_whole_file_parent (boost::shared_ptr<Region const> child)
2579 RegionList::iterator i;
2580 boost::shared_ptr<Region> region;
2582 Glib::Mutex::Lock lm (region_lock);
2584 for (i = regions.begin(); i != regions.end(); ++i) {
2588 if (region->whole_file()) {
2590 if (child->source_equivalent (region)) {
2596 return boost::shared_ptr<Region> ();
2600 Session::find_equivalent_playlist_regions (boost::shared_ptr<Region> region, vector<boost::shared_ptr<Region> >& result)
2602 for (PlaylistList::iterator i = playlists.begin(); i != playlists.end(); ++i)
2603 (*i)->get_region_list_equivalent_regions (region, result);
2607 Session::destroy_region (boost::shared_ptr<Region> region)
2609 vector<boost::shared_ptr<Source> > srcs;
2612 boost::shared_ptr<AudioRegion> aregion;
2614 if ((aregion = boost::dynamic_pointer_cast<AudioRegion> (region)) == 0) {
2618 if (aregion->playlist()) {
2619 aregion->playlist()->destroy_region (region);
2622 for (uint32_t n = 0; n < aregion->n_channels(); ++n) {
2623 srcs.push_back (aregion->source (n));
2627 region->drop_references ();
2629 for (vector<boost::shared_ptr<Source> >::iterator i = srcs.begin(); i != srcs.end(); ++i) {
2631 if (!(*i)->used()) {
2632 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*i);
2635 (afs)->mark_for_remove ();
2638 (*i)->drop_references ();
2640 cerr << "source was not used by any playlist\n";
2648 Session::destroy_regions (list<boost::shared_ptr<Region> > regions)
2650 for (list<boost::shared_ptr<Region> >::iterator i = regions.begin(); i != regions.end(); ++i) {
2651 destroy_region (*i);
2657 Session::remove_last_capture ()
2659 list<boost::shared_ptr<Region> > r;
2661 boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
2663 for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
2664 list<boost::shared_ptr<Region> >& l = (*i)->last_capture_regions();
2667 r.insert (r.end(), l.begin(), l.end());
2672 destroy_regions (r);
2674 save_state (_current_snapshot_name);
2680 Session::remove_region_from_region_list (boost::shared_ptr<Region> r)
2686 /* Source Management */
2688 Session::add_source (boost::shared_ptr<Source> source)
2690 pair<SourceMap::key_type, SourceMap::mapped_type> entry;
2691 pair<SourceMap::iterator,bool> result;
2693 entry.first = source->id();
2694 entry.second = source;
2697 Glib::Mutex::Lock lm (source_lock);
2698 result = sources.insert (entry);
2701 if (result.second) {
2702 source->GoingAway.connect (sigc::bind (mem_fun (this, &Session::remove_source), boost::weak_ptr<Source> (source)));
2708 Session::remove_source (boost::weak_ptr<Source> src)
2710 SourceMap::iterator i;
2711 boost::shared_ptr<Source> source = src.lock();
2718 Glib::Mutex::Lock lm (source_lock);
2720 if ((i = sources.find (source->id())) != sources.end()) {
2725 if (!_state_of_the_state & InCleanup) {
2727 /* save state so we don't end up with a session file
2728 referring to non-existent sources.
2731 save_state (_current_snapshot_name);
2735 boost::shared_ptr<Source>
2736 Session::source_by_id (const PBD::ID& id)
2738 Glib::Mutex::Lock lm (source_lock);
2739 SourceMap::iterator i;
2740 boost::shared_ptr<Source> source;
2742 if ((i = sources.find (id)) != sources.end()) {
2746 /* XXX search MIDI or other searches here */
2752 boost::shared_ptr<Source>
2753 Session::source_by_path_and_channel (const Glib::ustring& path, uint16_t chn)
2755 Glib::Mutex::Lock lm (source_lock);
2757 for (SourceMap::iterator i = sources.begin(); i != sources.end(); ++i) {
2758 cerr << "comparing " << path << " with " << i->second->name() << endl;
2759 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(i->second);
2761 if (afs && afs->path() == path && chn == afs->channel()) {
2766 return boost::shared_ptr<Source>();
2770 Session::peak_path_from_audio_path (string audio_path) const
2772 sys::path peakfile_path(_session_dir->peak_path());
2774 peakfile_path /= basename_nosuffix (audio_path) + peakfile_suffix;
2776 return peakfile_path.to_string();
2780 Session::change_audio_path_by_name (string path, string oldname, string newname, bool destructive)
2783 string old_basename = PBD::basename_nosuffix (oldname);
2784 string new_legalized = legalize_for_path (newname);
2786 /* note: we know (or assume) the old path is already valid */
2790 /* destructive file sources have a name of the form:
2792 /path/to/Tnnnn-NAME(%[LR])?.wav
2794 the task here is to replace NAME with the new name.
2797 /* find last slash */
2801 string::size_type slash;
2802 string::size_type dash;
2804 if ((slash = path.find_last_of ('/')) == string::npos) {
2808 dir = path.substr (0, slash+1);
2810 /* '-' is not a legal character for the NAME part of the path */
2812 if ((dash = path.find_last_of ('-')) == string::npos) {
2816 prefix = path.substr (slash+1, dash-(slash+1));
2821 path += new_legalized;
2822 path += ".wav"; /* XXX gag me with a spoon */
2826 /* non-destructive file sources have a name of the form:
2828 /path/to/NAME-nnnnn(%[LR])?.wav
2830 the task here is to replace NAME with the new name.
2835 string::size_type slash;
2836 string::size_type dash;
2837 string::size_type postfix;
2839 /* find last slash */
2841 if ((slash = path.find_last_of ('/')) == string::npos) {
2845 dir = path.substr (0, slash+1);
2847 /* '-' is not a legal character for the NAME part of the path */
2849 if ((dash = path.find_last_of ('-')) == string::npos) {
2853 suffix = path.substr (dash+1);
2855 // Suffix is now everything after the dash. Now we need to eliminate
2856 // the nnnnn part, which is done by either finding a '%' or a '.'
2858 postfix = suffix.find_last_of ("%");
2859 if (postfix == string::npos) {
2860 postfix = suffix.find_last_of ('.');
2863 if (postfix != string::npos) {
2864 suffix = suffix.substr (postfix);
2866 error << "Logic error in Session::change_audio_path_by_name(), please report to the developers" << endl;
2870 const uint32_t limit = 10000;
2871 char buf[PATH_MAX+1];
2873 for (uint32_t cnt = 1; cnt <= limit; ++cnt) {
2875 snprintf (buf, sizeof(buf), "%s%s-%u%s", dir.c_str(), newname.c_str(), cnt, suffix.c_str());
2877 if (access (buf, F_OK) != 0) {
2885 error << "FATAL ERROR! Could not find a " << endl;
2894 Session::audio_path_from_name (string name, uint32_t nchan, uint32_t chan, bool destructive)
2898 char buf[PATH_MAX+1];
2899 const uint32_t limit = 10000;
2903 legalized = legalize_for_path (name);
2905 /* find a "version" of the file name that doesn't exist in
2906 any of the possible directories.
2909 for (cnt = (destructive ? ++destructive_index : 1); cnt <= limit; ++cnt) {
2911 vector<space_and_path>::iterator i;
2912 uint32_t existing = 0;
2914 for (i = session_dirs.begin(); i != session_dirs.end(); ++i) {
2916 SessionDirectory sdir((*i).path);
2918 spath = sdir.sound_path().to_string();
2922 snprintf (buf, sizeof(buf), "%s/T%04d-%s.wav", spath.c_str(), cnt, legalized.c_str());
2923 } else if (nchan == 2) {
2925 snprintf (buf, sizeof(buf), "%s/T%04d-%s%%L.wav", spath.c_str(), cnt, legalized.c_str());
2927 snprintf (buf, sizeof(buf), "%s/T%04d-%s%%R.wav", spath.c_str(), cnt, legalized.c_str());
2929 } else if (nchan < 26) {
2930 snprintf (buf, sizeof(buf), "%s/T%04d-%s%%%c.wav", spath.c_str(), cnt, legalized.c_str(), 'a' + chan);
2932 snprintf (buf, sizeof(buf), "%s/T%04d-%s.wav", spath.c_str(), cnt, legalized.c_str());
2941 snprintf (buf, sizeof(buf), "%s-%u.wav", spath.c_str(), cnt);
2942 } else if (nchan == 2) {
2944 snprintf (buf, sizeof(buf), "%s-%u%%L.wav", spath.c_str(), cnt);
2946 snprintf (buf, sizeof(buf), "%s-%u%%R.wav", spath.c_str(), cnt);
2948 } else if (nchan < 26) {
2949 snprintf (buf, sizeof(buf), "%s-%u%%%c.wav", spath.c_str(), cnt, 'a' + chan);
2951 snprintf (buf, sizeof(buf), "%s-%u.wav", spath.c_str(), cnt);
2955 if (sys::exists(buf)) {
2961 if (existing == 0) {
2966 error << string_compose(_("There are already %1 recordings for %2, which I consider too many."), limit, name) << endmsg;
2968 throw failed_constructor();
2972 /* we now have a unique name for the file, but figure out where to
2978 SessionDirectory sdir(get_best_session_directory_for_new_source ());
2980 spath = sdir.sound_path().to_string();
2983 string::size_type pos = foo.find_last_of ('/');
2985 if (pos == string::npos) {
2988 spath += foo.substr (pos + 1);
2994 boost::shared_ptr<AudioFileSource>
2995 Session::create_audio_source_for_session (AudioDiskstream& ds, uint32_t chan, bool destructive)
2997 string spath = audio_path_from_name (ds.name(), ds.n_channels().n_audio(), chan, destructive);
2998 return boost::dynamic_pointer_cast<AudioFileSource> (
2999 SourceFactory::createWritable (DataType::AUDIO, *this, spath, destructive, frame_rate()));
3002 // FIXME: _terrible_ code duplication
3004 Session::change_midi_path_by_name (string path, string oldname, string newname, bool destructive)
3007 string old_basename = PBD::basename_nosuffix (oldname);
3008 string new_legalized = legalize_for_path (newname);
3010 /* note: we know (or assume) the old path is already valid */
3014 /* destructive file sources have a name of the form:
3016 /path/to/Tnnnn-NAME(%[LR])?.wav
3018 the task here is to replace NAME with the new name.
3021 /* find last slash */
3025 string::size_type slash;
3026 string::size_type dash;
3028 if ((slash = path.find_last_of ('/')) == string::npos) {
3032 dir = path.substr (0, slash+1);
3034 /* '-' is not a legal character for the NAME part of the path */
3036 if ((dash = path.find_last_of ('-')) == string::npos) {
3040 prefix = path.substr (slash+1, dash-(slash+1));
3045 path += new_legalized;
3046 path += ".mid"; /* XXX gag me with a spoon */
3050 /* non-destructive file sources have a name of the form:
3052 /path/to/NAME-nnnnn(%[LR])?.wav
3054 the task here is to replace NAME with the new name.
3059 string::size_type slash;
3060 string::size_type dash;
3061 string::size_type postfix;
3063 /* find last slash */
3065 if ((slash = path.find_last_of ('/')) == string::npos) {
3069 dir = path.substr (0, slash+1);
3071 /* '-' is not a legal character for the NAME part of the path */
3073 if ((dash = path.find_last_of ('-')) == string::npos) {
3077 suffix = path.substr (dash+1);
3079 // Suffix is now everything after the dash. Now we need to eliminate
3080 // the nnnnn part, which is done by either finding a '%' or a '.'
3082 postfix = suffix.find_last_of ("%");
3083 if (postfix == string::npos) {
3084 postfix = suffix.find_last_of ('.');
3087 if (postfix != string::npos) {
3088 suffix = suffix.substr (postfix);
3090 error << "Logic error in Session::change_midi_path_by_name(), please report to the developers" << endl;
3094 const uint32_t limit = 10000;
3095 char buf[PATH_MAX+1];
3097 for (uint32_t cnt = 1; cnt <= limit; ++cnt) {
3099 snprintf (buf, sizeof(buf), "%s%s-%u%s", dir.c_str(), newname.c_str(), cnt, suffix.c_str());
3101 if (access (buf, F_OK) != 0) {
3109 error << "FATAL ERROR! Could not find a " << endl;
3118 Session::midi_path_from_name (string name)
3122 char buf[PATH_MAX+1];
3123 const uint32_t limit = 10000;
3127 legalized = legalize_for_path (name);
3129 /* find a "version" of the file name that doesn't exist in
3130 any of the possible directories.
3133 for (cnt = 1; cnt <= limit; ++cnt) {
3135 vector<space_and_path>::iterator i;
3136 uint32_t existing = 0;
3138 for (i = session_dirs.begin(); i != session_dirs.end(); ++i) {
3140 SessionDirectory sdir((*i).path);
3142 sys::path p = sdir.midi_path();
3146 spath = p.to_string();
3148 snprintf (buf, sizeof(buf), "%s-%u.mid", spath.c_str(), cnt);
3150 if (sys::exists (buf)) {
3155 if (existing == 0) {
3160 error << string_compose(_("There are already %1 recordings for %2, which I consider too many."), limit, name) << endmsg;
3161 throw failed_constructor();
3165 /* we now have a unique name for the file, but figure out where to
3171 SessionDirectory sdir(get_best_session_directory_for_new_source ());
3173 spath = sdir.midi_path().to_string();
3176 string::size_type pos = foo.find_last_of ('/');
3178 if (pos == string::npos) {
3181 spath += foo.substr (pos + 1);
3187 boost::shared_ptr<MidiSource>
3188 Session::create_midi_source_for_session (MidiDiskstream& ds)
3190 string mpath = midi_path_from_name (ds.name());
3192 return boost::dynamic_pointer_cast<SMFSource> (SourceFactory::createWritable (DataType::MIDI, *this, mpath, false, frame_rate()));
3196 /* Playlist management */
3198 boost::shared_ptr<Playlist>
3199 Session::playlist_by_name (string name)
3201 Glib::Mutex::Lock lm (playlist_lock);
3202 for (PlaylistList::iterator i = playlists.begin(); i != playlists.end(); ++i) {
3203 if ((*i)->name() == name) {
3207 for (PlaylistList::iterator i = unused_playlists.begin(); i != unused_playlists.end(); ++i) {
3208 if ((*i)->name() == name) {
3213 return boost::shared_ptr<Playlist>();
3217 Session::add_playlist (boost::shared_ptr<Playlist> playlist)
3219 if (playlist->hidden()) {
3224 Glib::Mutex::Lock lm (playlist_lock);
3225 if (find (playlists.begin(), playlists.end(), playlist) == playlists.end()) {
3226 playlists.insert (playlists.begin(), playlist);
3227 playlist->InUse.connect (sigc::bind (mem_fun (*this, &Session::track_playlist), boost::weak_ptr<Playlist>(playlist)));
3228 playlist->GoingAway.connect (sigc::bind (mem_fun (*this, &Session::remove_playlist), boost::weak_ptr<Playlist>(playlist)));
3234 PlaylistAdded (playlist); /* EMIT SIGNAL */
3238 Session::get_playlists (vector<boost::shared_ptr<Playlist> >& s)
3241 Glib::Mutex::Lock lm (playlist_lock);
3242 for (PlaylistList::iterator i = playlists.begin(); i != playlists.end(); ++i) {
3245 for (PlaylistList::iterator i = unused_playlists.begin(); i != unused_playlists.end(); ++i) {
3252 Session::track_playlist (bool inuse, boost::weak_ptr<Playlist> wpl)
3254 boost::shared_ptr<Playlist> pl(wpl.lock());
3260 PlaylistList::iterator x;
3263 /* its not supposed to be visible */
3268 Glib::Mutex::Lock lm (playlist_lock);
3272 unused_playlists.insert (pl);
3274 if ((x = playlists.find (pl)) != playlists.end()) {
3275 playlists.erase (x);
3281 playlists.insert (pl);
3283 if ((x = unused_playlists.find (pl)) != unused_playlists.end()) {
3284 unused_playlists.erase (x);
3291 Session::remove_playlist (boost::weak_ptr<Playlist> weak_playlist)
3293 if (_state_of_the_state & Deletion) {
3297 boost::shared_ptr<Playlist> playlist (weak_playlist.lock());
3304 Glib::Mutex::Lock lm (playlist_lock);
3306 PlaylistList::iterator i;
3308 i = find (playlists.begin(), playlists.end(), playlist);
3309 if (i != playlists.end()) {
3310 playlists.erase (i);
3313 i = find (unused_playlists.begin(), unused_playlists.end(), playlist);
3314 if (i != unused_playlists.end()) {
3315 unused_playlists.erase (i);
3322 PlaylistRemoved (playlist); /* EMIT SIGNAL */
3326 Session::set_audition (boost::shared_ptr<Region> r)
3328 pending_audition_region = r;
3329 post_transport_work = PostTransportWork (post_transport_work | PostTransportAudition);
3330 schedule_butler_transport_work ();
3334 Session::audition_playlist ()
3336 Event* ev = new Event (Event::Audition, Event::Add, Event::Immediate, 0, 0.0);
3337 ev->region.reset ();
3342 Session::non_realtime_set_audition ()
3344 if (!pending_audition_region) {
3345 auditioner->audition_current_playlist ();
3347 auditioner->audition_region (pending_audition_region);
3348 pending_audition_region.reset ();
3350 AuditionActive (true); /* EMIT SIGNAL */
3354 Session::audition_region (boost::shared_ptr<Region> r)
3356 Event* ev = new Event (Event::Audition, Event::Add, Event::Immediate, 0, 0.0);
3362 Session::cancel_audition ()
3364 if (auditioner->active()) {
3365 auditioner->cancel_audition ();
3366 AuditionActive (false); /* EMIT SIGNAL */
3371 Session::RoutePublicOrderSorter::operator() (boost::shared_ptr<Route> a, boost::shared_ptr<Route> b)
3373 return a->order_key(N_("signal")) < b->order_key(N_("signal"));
3377 Session::remove_empty_sounds ()
3379 vector<string> audio_filenames;
3381 get_files_in_directory (_session_dir->sound_path(), audio_filenames);
3383 Glib::Mutex::Lock lm (source_lock);
3385 TapeFileMatcher tape_file_matcher;
3387 remove_if (audio_filenames.begin(), audio_filenames.end(),
3388 sigc::mem_fun (tape_file_matcher, &TapeFileMatcher::matches));
3390 for (vector<string>::iterator i = audio_filenames.begin(); i != audio_filenames.end(); ++i) {
3392 sys::path audio_file_path (_session_dir->sound_path());
3394 audio_file_path /= *i;
3396 if (AudioFileSource::is_empty (*this, audio_file_path.to_string())) {
3400 sys::remove (audio_file_path);
3401 const string peak_path = peak_path_from_audio_path (audio_file_path.to_string());
3402 sys::remove (peak_path);
3404 catch (const sys::filesystem_error& err)
3406 error << err.what() << endmsg;
3413 Session::is_auditioning () const
3415 /* can be called before we have an auditioner object */
3417 return auditioner->active();
3424 Session::set_all_solo (bool yn)
3426 shared_ptr<RouteList> r = routes.reader ();
3428 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3429 if (!(*i)->is_hidden()) {
3430 (*i)->set_solo (yn, this);
3438 Session::set_all_mute (bool yn)
3440 shared_ptr<RouteList> r = routes.reader ();
3442 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3443 if (!(*i)->is_hidden()) {
3444 (*i)->set_mute (yn, this);
3452 Session::n_diskstreams () const
3456 boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
3458 for (DiskstreamList::const_iterator i = dsl->begin(); i != dsl->end(); ++i) {
3459 if (!(*i)->hidden()) {
3467 Session::graph_reordered ()
3469 /* don't do this stuff if we are setting up connections
3470 from a set_state() call or creating new tracks.
3473 if (_state_of_the_state & InitialConnecting) {
3477 /* every track/bus asked for this to be handled but it was deferred because
3478 we were connecting. do it now.
3481 request_input_change_handling ();
3485 /* force all diskstreams to update their capture offset values to
3486 reflect any changes in latencies within the graph.
3489 boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
3491 for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
3492 (*i)->set_capture_offset ();
3497 Session::record_disenable_all ()
3499 record_enable_change_all (false);
3503 Session::record_enable_all ()
3505 record_enable_change_all (true);
3509 Session::record_enable_change_all (bool yn)
3511 shared_ptr<RouteList> r = routes.reader ();
3513 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3516 if ((at = dynamic_cast<Track*>((*i).get())) != 0) {
3517 at->set_record_enable (yn, this);
3521 /* since we don't keep rec-enable state, don't mark session dirty */
3525 Session::add_processor (Processor* processor)
3528 PortInsert* port_insert;
3529 PluginInsert* plugin_insert;
3531 if ((port_insert = dynamic_cast<PortInsert *> (processor)) != 0) {
3532 _port_inserts.insert (_port_inserts.begin(), port_insert);
3533 } else if ((plugin_insert = dynamic_cast<PluginInsert *> (processor)) != 0) {
3534 _plugin_inserts.insert (_plugin_inserts.begin(), plugin_insert);
3535 } else if ((send = dynamic_cast<Send *> (processor)) != 0) {
3536 _sends.insert (_sends.begin(), send);
3538 fatal << _("programming error: unknown type of Insert created!") << endmsg;
3542 processor->GoingAway.connect (sigc::bind (mem_fun (*this, &Session::remove_processor), processor));
3548 Session::remove_processor (Processor* processor)
3551 PortInsert* port_insert;
3552 PluginInsert* plugin_insert;
3554 if ((port_insert = dynamic_cast<PortInsert *> (processor)) != 0) {
3555 list<PortInsert*>::iterator x = find (_port_inserts.begin(), _port_inserts.end(), port_insert);
3556 if (x != _port_inserts.end()) {
3557 insert_bitset[port_insert->bit_slot()] = false;
3558 _port_inserts.erase (x);
3560 } else if ((plugin_insert = dynamic_cast<PluginInsert *> (processor)) != 0) {
3561 _plugin_inserts.remove (plugin_insert);
3562 } else if ((send = dynamic_cast<Send *> (processor)) != 0) {
3563 list<Send*>::iterator x = find (_sends.begin(), _sends.end(), send);
3564 if (x != _sends.end()) {
3565 send_bitset[send->bit_slot()] = false;
3569 fatal << _("programming error: unknown type of Insert deleted!") << endmsg;
3577 Session::available_capture_duration ()
3579 float sample_bytes_on_disk = 4.0; // keep gcc happy
3581 switch (Config->get_native_file_data_format()) {
3583 sample_bytes_on_disk = 4.0;
3587 sample_bytes_on_disk = 3.0;
3591 sample_bytes_on_disk = 2.0;
3595 /* impossible, but keep some gcc versions happy */
3596 fatal << string_compose (_("programming error: %1"),
3597 X_("illegal native file data format"))
3602 double scale = 4096.0 / sample_bytes_on_disk;
3604 if (_total_free_4k_blocks * scale > (double) max_frames) {
3608 return (nframes_t) floor (_total_free_4k_blocks * scale);
3612 Session::add_bundle (ARDOUR::Bundle* bundle)
3615 Glib::Mutex::Lock guard (bundle_lock);
3616 _bundles.push_back (bundle);
3619 BundleAdded (bundle); /* EMIT SIGNAL */
3625 Session::remove_bundle (ARDOUR::Bundle* bundle)
3627 bool removed = false;
3630 Glib::Mutex::Lock guard (bundle_lock);
3631 BundleList::iterator i = find (_bundles.begin(), _bundles.end(), bundle);
3633 if (i != _bundles.end()) {
3640 BundleRemoved (bundle); /* EMIT SIGNAL */
3647 Session::bundle_by_name (string name) const
3649 Glib::Mutex::Lock lm (bundle_lock);
3651 for (BundleList::const_iterator i = _bundles.begin(); i != _bundles.end(); ++i) {
3652 if ((*i)->name() == name) {
3661 Session::tempo_map_changed (Change ignored)
3667 /** Ensures that all buffers (scratch, send, silent, etc) are allocated for
3668 * the given count with the current block size.
3671 Session::ensure_buffers (ChanCount howmany)
3673 if (current_block_size == 0)
3674 return; // too early? (is this ok?)
3676 // We need at least 2 MIDI scratch buffers to mix/merge
3677 if (howmany.n_midi() < 2)
3678 howmany.set_midi(2);
3680 // FIXME: JACK needs to tell us maximum MIDI buffer size
3681 // Using nasty assumption (max # events == nframes) for now
3682 _scratch_buffers->ensure_buffers(howmany, current_block_size);
3683 _mix_buffers->ensure_buffers(howmany, current_block_size);
3684 _silent_buffers->ensure_buffers(howmany, current_block_size);
3686 allocate_pan_automation_buffers (current_block_size, howmany.n_audio(), false);
3690 Session::next_insert_id ()
3692 /* this doesn't really loop forever. just think about it */
3695 for (boost::dynamic_bitset<uint32_t>::size_type n = 0; n < insert_bitset.size(); ++n) {
3696 if (!insert_bitset[n]) {
3697 insert_bitset[n] = true;
3703 /* none available, so resize and try again */
3705 insert_bitset.resize (insert_bitset.size() + 16, false);
3710 Session::next_send_id ()
3712 /* this doesn't really loop forever. just think about it */
3715 for (boost::dynamic_bitset<uint32_t>::size_type n = 0; n < send_bitset.size(); ++n) {
3716 if (!send_bitset[n]) {
3717 send_bitset[n] = true;
3723 /* none available, so resize and try again */
3725 send_bitset.resize (send_bitset.size() + 16, false);
3730 Session::mark_send_id (uint32_t id)
3732 if (id >= send_bitset.size()) {
3733 send_bitset.resize (id+16, false);
3735 if (send_bitset[id]) {
3736 warning << string_compose (_("send ID %1 appears to be in use already"), id) << endmsg;
3738 send_bitset[id] = true;
3742 Session::mark_insert_id (uint32_t id)
3744 if (id >= insert_bitset.size()) {
3745 insert_bitset.resize (id+16, false);
3747 if (insert_bitset[id]) {
3748 warning << string_compose (_("insert ID %1 appears to be in use already"), id) << endmsg;
3750 insert_bitset[id] = true;
3753 /* Named Selection management */
3756 Session::named_selection_by_name (string name)
3758 Glib::Mutex::Lock lm (named_selection_lock);
3759 for (NamedSelectionList::iterator i = named_selections.begin(); i != named_selections.end(); ++i) {
3760 if ((*i)->name == name) {
3768 Session::add_named_selection (NamedSelection* named_selection)
3771 Glib::Mutex::Lock lm (named_selection_lock);
3772 named_selections.insert (named_selections.begin(), named_selection);
3775 for (list<boost::shared_ptr<Playlist> >::iterator i = named_selection->playlists.begin(); i != named_selection->playlists.end(); ++i) {
3781 NamedSelectionAdded (); /* EMIT SIGNAL */
3785 Session::remove_named_selection (NamedSelection* named_selection)
3787 bool removed = false;
3790 Glib::Mutex::Lock lm (named_selection_lock);
3792 NamedSelectionList::iterator i = find (named_selections.begin(), named_selections.end(), named_selection);
3794 if (i != named_selections.end()) {
3796 named_selections.erase (i);
3803 NamedSelectionRemoved (); /* EMIT SIGNAL */
3808 Session::reset_native_file_format ()
3810 boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
3812 for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
3813 (*i)->reset_write_sources (false);
3818 Session::route_name_unique (string n) const
3820 shared_ptr<RouteList> r = routes.reader ();
3822 for (RouteList::const_iterator i = r->begin(); i != r->end(); ++i) {
3823 if ((*i)->name() == n) {
3832 Session::n_playlists () const
3834 Glib::Mutex::Lock lm (playlist_lock);
3835 return playlists.size();
3839 Session::allocate_pan_automation_buffers (nframes_t nframes, uint32_t howmany, bool force)
3841 if (!force && howmany <= _npan_buffers) {
3845 if (_pan_automation_buffer) {
3847 for (uint32_t i = 0; i < _npan_buffers; ++i) {
3848 delete [] _pan_automation_buffer[i];
3851 delete [] _pan_automation_buffer;
3854 _pan_automation_buffer = new pan_t*[howmany];
3856 for (uint32_t i = 0; i < howmany; ++i) {
3857 _pan_automation_buffer[i] = new pan_t[nframes];
3860 _npan_buffers = howmany;
3864 Session::freeze (InterThreadInfo& itt)
3866 shared_ptr<RouteList> r = routes.reader ();
3868 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3872 if ((at = dynamic_cast<Track*>((*i).get())) != 0) {
3873 /* XXX this is wrong because itt.progress will keep returning to zero at the start
3884 Session::write_one_audio_track (AudioTrack& track, nframes_t start, nframes_t len,
3885 bool overwrite, vector<boost::shared_ptr<Source> >& srcs, InterThreadInfo& itt)
3888 boost::shared_ptr<Playlist> playlist;
3889 boost::shared_ptr<AudioFileSource> fsource;
3891 char buf[PATH_MAX+1];
3892 ChanCount nchans(track.audio_diskstream()->n_channels());
3894 nframes_t this_chunk;
3897 SessionDirectory sdir(get_best_session_directory_for_new_source ());
3898 const string sound_dir = sdir.sound_path().to_string();
3900 // any bigger than this seems to cause stack overflows in called functions
3901 const nframes_t chunk_size = (128 * 1024)/4;
3903 g_atomic_int_set (&processing_prohibited, 1);
3905 /* call tree *MUST* hold route_lock */
3907 if ((playlist = track.diskstream()->playlist()) == 0) {
3911 /* external redirects will be a problem */
3913 if (track.has_external_redirects()) {
3917 for (uint32_t chan_n=0; chan_n < nchans.n_audio(); ++chan_n) {
3919 for (x = 0; x < 99999; ++x) {
3920 snprintf (buf, sizeof(buf), "%s/%s-%d-bounce-%" PRIu32 ".wav", sound_dir.c_str(), playlist->name().c_str(), chan_n, x+1);
3921 if (access (buf, F_OK) != 0) {
3927 error << string_compose (_("too many bounced versions of playlist \"%1\""), playlist->name()) << endmsg;
3932 fsource = boost::dynamic_pointer_cast<AudioFileSource> (
3933 SourceFactory::createWritable (DataType::AUDIO, *this, buf, false, frame_rate()));
3936 catch (failed_constructor& err) {
3937 error << string_compose (_("cannot create new audio file \"%1\" for %2"), buf, track.name()) << endmsg;
3941 srcs.push_back (fsource);
3944 /* XXX need to flush all redirects */
3949 /* create a set of reasonably-sized buffers */
3950 buffers.ensure_buffers(nchans, chunk_size);
3951 buffers.set_count(nchans);
3953 for (vector<boost::shared_ptr<Source> >::iterator src=srcs.begin(); src != srcs.end(); ++src) {
3954 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
3956 afs->prepare_for_peakfile_writes ();
3959 while (to_do && !itt.cancel) {
3961 this_chunk = min (to_do, chunk_size);
3963 if (track.export_stuff (buffers, start, this_chunk)) {
3968 for (vector<boost::shared_ptr<Source> >::iterator src=srcs.begin(); src != srcs.end(); ++src, ++n) {
3969 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
3972 if (afs->write (buffers.get_audio(n).data(), this_chunk) != this_chunk) {
3978 start += this_chunk;
3979 to_do -= this_chunk;
3981 itt.progress = (float) (1.0 - ((double) to_do / len));
3990 xnow = localtime (&now);
3992 for (vector<boost::shared_ptr<Source> >::iterator src=srcs.begin(); src != srcs.end(); ++src) {
3993 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
3996 afs->update_header (position, *xnow, now);
3997 afs->flush_header ();
4001 /* construct a region to represent the bounced material */
4003 boost::shared_ptr<Region> aregion = RegionFactory::create (srcs, 0, srcs.front()->length(),
4004 region_name_from_path (srcs.front()->name(), true));
4011 for (vector<boost::shared_ptr<Source> >::iterator src = srcs.begin(); src != srcs.end(); ++src) {
4012 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
4015 afs->mark_for_remove ();
4018 (*src)->drop_references ();
4022 for (vector<boost::shared_ptr<Source> >::iterator src = srcs.begin(); src != srcs.end(); ++src) {
4023 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
4026 afs->done_with_peakfile_writes ();
4030 g_atomic_int_set (&processing_prohibited, 0);
4036 Session::get_silent_buffers (ChanCount count)
4038 assert(_silent_buffers->available() >= count);
4039 _silent_buffers->set_count(count);
4041 for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
4042 for (size_t i=0; i < count.get(*t); ++i) {
4043 _silent_buffers->get(*t, i).clear();
4047 return *_silent_buffers;
4051 Session::get_scratch_buffers (ChanCount count)
4053 assert(_scratch_buffers->available() >= count);
4054 _scratch_buffers->set_count(count);
4055 return *_scratch_buffers;
4059 Session::get_mix_buffers (ChanCount count)
4061 assert(_mix_buffers->available() >= count);
4062 _mix_buffers->set_count(count);
4063 return *_mix_buffers;
4067 Session::ntracks () const
4070 shared_ptr<RouteList> r = routes.reader ();
4072 for (RouteList::const_iterator i = r->begin(); i != r->end(); ++i) {
4073 if (dynamic_cast<Track*> ((*i).get())) {
4082 Session::nbusses () const
4085 shared_ptr<RouteList> r = routes.reader ();
4087 for (RouteList::const_iterator i = r->begin(); i != r->end(); ++i) {
4088 if (dynamic_cast<Track*> ((*i).get()) == 0) {
4097 Session::add_automation_list(AutomationList *al)
4099 automation_lists[al->id()] = al;
4103 Session::compute_initial_length ()
4105 return _engine.frame_rate() * 60 * 5;