Clean up MMC transmission a bit, and make sure that it is all done from one thread.
[ardour.git] / libs / ardour / session_state.cc
1 /*
2   Copyright (C) 1999-2002 Paul Davis
3
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.
8
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.
13
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.
17
18 */
19
20
21 #ifdef WAF_BUILD
22 #include "libardour-config.h"
23 #endif
24
25 #define __STDC_FORMAT_MACROS 1
26 #include <stdint.h>
27
28 #include <algorithm>
29 #include <fstream>
30 #include <string>
31 #include <cerrno>
32
33
34 #include <cstdio> /* snprintf(3) ... grrr */
35 #include <cmath>
36 #include <unistd.h>
37 #include <sys/stat.h>
38 #include <climits>
39 #include <fcntl.h>
40 #include <poll.h>
41 #include <signal.h>
42 #include <sys/mman.h>
43 #include <sys/time.h>
44 #include <dirent.h>
45
46 #ifdef HAVE_SYS_VFS_H
47 #include <sys/vfs.h>
48 #else
49 #include <sys/param.h>
50 #include <sys/mount.h>
51 #endif
52
53 #include <glibmm.h>
54 #include <glibmm/thread.h>
55
56 #include "midi++/mmc.h"
57 #include "midi++/port.h"
58
59 #include "pbd/boost_debug.h"
60 #include "pbd/controllable_descriptor.h"
61 #include "pbd/enumwriter.h"
62 #include "pbd/error.h"
63 #include "pbd/pathscanner.h"
64 #include "pbd/pthread_utils.h"
65 #include "pbd/search_path.h"
66 #include "pbd/stacktrace.h"
67 #include "pbd/convert.h"
68
69 #include "ardour/amp.h"
70 #include "ardour/audio_diskstream.h"
71 #include "ardour/audio_track.h"
72 #include "ardour/audioengine.h"
73 #include "ardour/audiofilesource.h"
74 #include "ardour/audioplaylist.h"
75 #include "ardour/audioregion.h"
76 #include "ardour/auditioner.h"
77 #include "ardour/buffer.h"
78 #include "ardour/butler.h"
79 #include "ardour/configuration.h"
80 #include "ardour/control_protocol_manager.h"
81 #include "ardour/crossfade.h"
82 #include "ardour/cycle_timer.h"
83 #include "ardour/directory_names.h"
84 #include "ardour/filename_extensions.h"
85 #include "ardour/io_processor.h"
86 #include "ardour/location.h"
87 #include "ardour/midi_diskstream.h"
88 #include "ardour/midi_patch_manager.h"
89 #include "ardour/midi_playlist.h"
90 #include "ardour/midi_region.h"
91 #include "ardour/midi_source.h"
92 #include "ardour/midi_track.h"
93 #include "ardour/named_selection.h"
94 #include "ardour/processor.h"
95 #include "ardour/port.h"
96 #include "ardour/region_factory.h"
97 #include "ardour/route_group.h"
98 #include "ardour/send.h"
99 #include "ardour/session.h"
100 #include "ardour/session_directory.h"
101 #include "ardour/session_metadata.h"
102 #include "ardour/session_state_utils.h"
103 #include "ardour/session_playlists.h"
104 #include "ardour/session_utils.h"
105 #include "ardour/silentfilesource.h"
106 #include "ardour/slave.h"
107 #include "ardour/smf_source.h"
108 #include "ardour/sndfile_helpers.h"
109 #include "ardour/sndfilesource.h"
110 #include "ardour/source_factory.h"
111 #include "ardour/template_utils.h"
112 #include "ardour/tempo.h"
113 #include "ardour/ticker.h"
114 #include "ardour/user_bundle.h"
115 #include "ardour/utils.h"
116 #include "ardour/utils.h"
117 #include "ardour/version.h"
118 #include "ardour/playlist_factory.h"
119
120 #include "control_protocol/control_protocol.h"
121
122 #include "i18n.h"
123 #include <locale.h>
124
125 using namespace std;
126 using namespace ARDOUR;
127 using namespace PBD;
128
129 void
130 Session::first_stage_init (string fullpath, string snapshot_name)
131 {
132         if (fullpath.length() == 0) {
133                 destroy ();
134                 throw failed_constructor();
135         }
136
137         char buf[PATH_MAX+1];
138         if (!realpath (fullpath.c_str(), buf) && (errno != ENOENT)) {
139                 error << string_compose(_("Could not use path %1 (%s)"), buf, strerror(errno)) << endmsg;
140                 destroy ();
141                 throw failed_constructor();
142         }
143
144         _path = string(buf);
145
146         if (_path[_path.length()-1] != '/') {
147                 _path += '/';
148         }
149
150         if (Glib::file_test (_path, Glib::FILE_TEST_EXISTS) && ::access (_path.c_str(), W_OK)) {
151                 _writable = false;
152         } else {
153                 _writable = true;
154         }
155
156         /* these two are just provisional settings. set_state()
157            will likely override them.
158         */
159
160         _name = _current_snapshot_name = snapshot_name;
161
162         set_history_depth (Config->get_history_depth());
163
164         _current_frame_rate = _engine.frame_rate ();
165         _nominal_frame_rate = _current_frame_rate;
166         _base_frame_rate = _current_frame_rate;
167
168         _tempo_map = new TempoMap (_current_frame_rate);
169         _tempo_map->PropertyChanged.connect_same_thread (*this, boost::bind (&Session::tempo_map_changed, this, _1));
170
171
172         _non_soloed_outs_muted = false;
173         _listen_cnt = 0;
174         _solo_isolated_cnt = 0;
175         g_atomic_int_set (&processing_prohibited, 0);
176         _transport_speed = 0;
177         _last_transport_speed = 0;
178         _target_transport_speed = 0;
179         auto_play_legal = false;
180         transport_sub_state = 0;
181         _transport_frame = 0;
182         _requested_return_frame = -1;
183         _session_range_location = 0;
184         g_atomic_int_set (&_record_status, Disabled);
185         loop_changing = false;
186         play_loop = false;
187         have_looped = false;
188         _last_roll_location = 0;
189         _last_roll_or_reversal_location = 0;
190         _last_record_location = 0;
191         pending_locate_frame = 0;
192         pending_locate_roll = false;
193         pending_locate_flush = false;
194         state_was_pending = false;
195         set_next_event ();
196         outbound_mtc_timecode_frame = 0;
197         next_quarter_frame_to_send = -1;
198         current_block_size = 0;
199         solo_update_disabled = false;
200         _have_captured = false;
201         _worst_output_latency = 0;
202         _worst_input_latency = 0;
203         _worst_track_latency = 0;
204         _state_of_the_state = StateOfTheState(CannotSave|InitialConnecting|Loading);
205         _was_seamless = Config->get_seamless_loop ();
206         _slave = 0;
207         session_send_mtc = false;
208         g_atomic_int_set (&_playback_load, 100);
209         g_atomic_int_set (&_capture_load, 100);
210         _play_range = false;
211         _exporting = false;
212         pending_abort = false;
213         destructive_index = 0;
214         first_file_data_format_reset = true;
215         first_file_header_format_reset = true;
216         post_export_sync = false;
217         midi_control_ui = 0;
218
219         AudioDiskstream::allocate_working_buffers();
220
221         /* default short fade = 15ms */
222
223         Crossfade::set_short_xfade_length ((nframes_t) floor (config.get_short_xfade_seconds() * frame_rate()));
224         SndFileSource::setup_standard_crossfades (*this, frame_rate());
225
226         last_mmc_step.tv_sec = 0;
227         last_mmc_step.tv_usec = 0;
228         step_speed = 0.0;
229
230         /* click sounds are unset by default, which causes us to internal
231            waveforms for clicks.
232         */
233
234         click_length = 0;
235         click_emphasis_length = 0;
236         _clicking = false;
237
238         process_function = &Session::process_with_events;
239
240         if (config.get_use_video_sync()) {
241                 waiting_for_sync_offset = true;
242         } else {
243                 waiting_for_sync_offset = false;
244         }
245
246         last_timecode_when = 0;
247         _timecode_offset = 0;
248         _timecode_offset_negative = true;
249         last_timecode_valid = false;
250
251         sync_time_vars ();
252
253         last_rr_session_dir = session_dirs.begin();
254         refresh_disk_space ();
255
256         // set_default_fade (0.2, 5.0); /* steepness, millisecs */
257
258         /* slave stuff */
259
260         average_slave_delta = 1800; // !!! why 1800 ????
261         have_first_delta_accumulator = false;
262         delta_accumulator_cnt = 0;
263         _slave_state = Stopped;
264
265         _engine.GraphReordered.connect_same_thread (*this, boost::bind (&Session::graph_reordered, this));
266
267         /* These are all static "per-class" signals */
268
269         SourceFactory::SourceCreated.connect_same_thread (*this, boost::bind (&Session::add_source, this, _1));
270         PlaylistFactory::PlaylistCreated.connect_same_thread (*this, boost::bind (&Session::add_playlist, this, _1, _2));
271         AutomationList::AutomationListCreated.connect_same_thread (*this, boost::bind (&Session::add_automation_list, this, _1));
272         Controllable::Destroyed.connect_same_thread (*this, boost::bind (&Session::remove_controllable, this, _1));
273         IO::PortCountChanged.connect_same_thread (*this, boost::bind (&Session::ensure_buffers, this, _1));
274
275         /* stop IO objects from doing stuff until we're ready for them */
276
277         Delivery::disable_panners ();
278         IO::disable_connecting ();
279 }
280
281 int
282 Session::second_stage_init ()
283 {
284         AudioFileSource::set_peak_dir (_session_dir->peak_path().to_string());
285
286         if (!_is_new) {
287                 if (load_state (_current_snapshot_name)) {
288                         return -1;
289                 }
290                 remove_empty_sounds ();
291         }
292
293         if (_butler->start_thread()) {
294                 return -1;
295         }
296
297         if (start_midi_thread ()) {
298                 return -1;
299         }
300
301         setup_midi_machine_control ();
302
303         // set_state() will call setup_raid_path(), but if it's a new session we need
304         // to call setup_raid_path() here.
305
306         if (state_tree) {
307                 if (set_state (*state_tree->root(), Stateful::loading_state_version)) {
308                         return -1;
309                 }
310         } else {
311                 setup_raid_path(_path);
312         }
313
314         /* we can't save till after ::when_engine_running() is called,
315            because otherwise we save state with no connections made.
316            therefore, we reset _state_of_the_state because ::set_state()
317            will have cleared it.
318
319            we also have to include Loading so that any events that get
320            generated between here and the end of ::when_engine_running()
321            will be processed directly rather than queued.
322         */
323
324         _state_of_the_state = StateOfTheState (_state_of_the_state|CannotSave|Loading);
325
326         _locations.changed.connect_same_thread (*this, boost::bind (&Session::locations_changed, this));
327         _locations.added.connect_same_thread (*this, boost::bind (&Session::locations_added, this, _1));
328         setup_click_sounds (0);
329         setup_midi_control ();
330
331         /* Pay attention ... */
332
333         _engine.Halted.connect_same_thread (*this, boost::bind (&Session::engine_halted, this));
334         _engine.Xrun.connect_same_thread (*this, boost::bind (&Session::xrun_recovery, this));
335
336         try {
337                 when_engine_running ();
338         }
339
340         /* handle this one in a different way than all others, so that its clear what happened */
341
342         catch (AudioEngine::PortRegistrationFailure& err) {
343                 error << err.what() << endmsg;
344                 return -1;
345         }
346
347         catch (...) {
348                 return -1;
349         }
350
351         BootMessage (_("Reset Remote Controls"));
352
353         send_full_time_code (0);
354         _engine.transport_locate (0);
355         _mmc->send (MIDI::MachineControlCommand (MIDI::MachineControl::cmdMmcReset));
356         _mmc->send (MIDI::MachineControlCommand (Timecode::Time ()));
357
358         MidiClockTicker::instance().set_session (this);
359         MIDI::Name::MidiPatchManager::instance().set_session (this);
360
361         /* initial program change will be delivered later; see ::config_changed() */
362
363         BootMessage (_("Reset Control Protocols"));
364
365         ControlProtocolManager::instance().set_session (this);
366
367         _state_of_the_state = Clean;
368
369         Port::set_connecting_blocked (false);
370
371         DirtyChanged (); /* EMIT SIGNAL */
372
373         if (state_was_pending) {
374                 save_state (_current_snapshot_name);
375                 remove_pending_capture_state ();
376                 state_was_pending = false;
377         }
378
379         BootMessage (_("Session loading complete"));
380
381         return 0;
382 }
383
384 string
385 Session::raid_path () const
386 {
387         SearchPath raid_search_path;
388
389         for (vector<space_and_path>::const_iterator i = session_dirs.begin(); i != session_dirs.end(); ++i) {
390                 raid_search_path += sys::path((*i).path);
391         }
392
393         return raid_search_path.to_string ();
394 }
395
396 void
397 Session::setup_raid_path (string path)
398 {
399         if (path.empty()) {
400                 return;
401         }
402
403         space_and_path sp;
404         string fspath;
405
406         session_dirs.clear ();
407
408         SearchPath search_path(path);
409         SearchPath sound_search_path;
410         SearchPath midi_search_path;
411
412         for (SearchPath::const_iterator i = search_path.begin(); i != search_path.end(); ++i) {
413                 sp.path = (*i).to_string ();
414                 sp.blocks = 0; // not needed
415                 session_dirs.push_back (sp);
416
417                 SessionDirectory sdir(sp.path);
418
419                 sound_search_path += sdir.sound_path ();
420                 midi_search_path += sdir.midi_path ();
421         }
422
423         // set the search path for each data type
424         FileSource::set_search_path (DataType::AUDIO, sound_search_path.to_string ());
425         SMFSource::set_search_path (DataType::MIDI, midi_search_path.to_string ());
426
427         // reset the round-robin soundfile path thingie
428         last_rr_session_dir = session_dirs.begin();
429 }
430
431 bool
432 Session::path_is_within_session (const std::string& path)
433 {
434         for (vector<space_and_path>::const_iterator i = session_dirs.begin(); i != session_dirs.end(); ++i) {
435                 if (path.find ((*i).path) == 0) {
436                         return true;
437                 }
438         }
439         return false;
440 }
441
442 int
443 Session::ensure_subdirs ()
444 {
445         string dir;
446
447         dir = session_directory().peak_path().to_string();
448
449         if (g_mkdir_with_parents (dir.c_str(), 0755) < 0) {
450                 error << string_compose(_("Session: cannot create session peakfile folder \"%1\" (%2)"), dir, strerror (errno)) << endmsg;
451                 return -1;
452         }
453
454         dir = session_directory().sound_path().to_string();
455
456         if (g_mkdir_with_parents (dir.c_str(), 0755) < 0) {
457                 error << string_compose(_("Session: cannot create session sounds dir \"%1\" (%2)"), dir, strerror (errno)) << endmsg;
458                 return -1;
459         }
460
461         dir = session_directory().midi_path().to_string();
462
463         if (g_mkdir_with_parents (dir.c_str(), 0755) < 0) {
464                 error << string_compose(_("Session: cannot create session midi dir \"%1\" (%2)"), dir, strerror (errno)) << endmsg;
465                 return -1;
466         }
467
468         dir = session_directory().dead_sound_path().to_string();
469
470         if (g_mkdir_with_parents (dir.c_str(), 0755) < 0) {
471                 error << string_compose(_("Session: cannot create session dead sounds folder \"%1\" (%2)"), dir, strerror (errno)) << endmsg;
472                 return -1;
473         }
474
475         dir = session_directory().export_path().to_string();
476
477         if (g_mkdir_with_parents (dir.c_str(), 0755) < 0) {
478                 error << string_compose(_("Session: cannot create session export folder \"%1\" (%2)"), dir, strerror (errno)) << endmsg;
479                 return -1;
480         }
481
482         dir = analysis_dir ();
483
484         if (g_mkdir_with_parents (dir.c_str(), 0755) < 0) {
485                 error << string_compose(_("Session: cannot create session analysis folder \"%1\" (%2)"), dir, strerror (errno)) << endmsg;
486                 return -1;
487         }
488
489         return 0;
490 }
491
492 int
493 Session::create (const string& mix_template, BusProfile* bus_profile)
494 {
495
496         if (g_mkdir_with_parents (_path.c_str(), 0755) < 0) {
497                 error << string_compose(_("Session: cannot create session folder \"%1\" (%2)"), _path, strerror (errno)) << endmsg;
498                 return -1;
499         }
500
501         if (ensure_subdirs ()) {
502                 return -1;
503         }
504
505         if (!mix_template.empty()) {
506                 std::string in_path = mix_template;
507
508                 ifstream in(in_path.c_str());
509
510                 if (in){
511                         string out_path = _path;
512                         out_path += _name;
513                         out_path += statefile_suffix;
514
515                         ofstream out(out_path.c_str());
516
517                         if (out){
518                                 out << in.rdbuf();
519                                 _is_new = false;
520                                 return 0;
521
522                         } else {
523                                 error << string_compose (_("Could not open %1 for writing mix template"), out_path)
524                                         << endmsg;
525                                 return -1;
526                         }
527
528                 } else {
529                         error << string_compose (_("Could not open mix template %1 for reading"), in_path)
530                                 << endmsg;
531                         return -1;
532                 }
533
534         }
535
536         /* Instantiate metadata */
537
538         _metadata = new SessionMetadata ();
539
540         /* set initial start + end point */
541
542         _state_of_the_state = Clean;
543         
544         /* set up Master Out and Control Out if necessary */
545
546         if (bus_profile) {
547
548                 RouteList rl;
549                 int control_id = 1;
550                 ChanCount count(DataType::AUDIO, bus_profile->master_out_channels);
551
552                 if (bus_profile->master_out_channels) {
553                         Route* rt = new Route (*this, _("master"), Route::MasterOut, DataType::AUDIO);
554                         if (rt->init ()) {
555                                 delete rt;
556                                 return -1;
557                         }
558                         boost_debug_shared_ptr_mark_interesting (rt, "Route");
559                         boost::shared_ptr<Route> r (rt);
560                         r->input()->ensure_io (count, false, this);
561                         r->output()->ensure_io (count, false, this);
562                         r->set_remote_control_id (control_id++);
563
564                         rl.push_back (r);
565
566                         if (Config->get_use_monitor_bus()) {
567                                 Route* rt = new Route (*this, _("monitor"), Route::MonitorOut, DataType::AUDIO);
568                                 if (rt->init ()) {
569                                         delete rt;
570                                         return -1;
571                                 }
572                                 boost_debug_shared_ptr_mark_interesting (rt, "Route");
573                                 boost::shared_ptr<Route> r (rt);
574                                 r->input()->ensure_io (count, false, this);
575                                 r->output()->ensure_io (count, false, this);
576                                 r->set_remote_control_id (control_id);
577                                 
578                                 rl.push_back (r);
579                         }
580
581                 } else {
582                         /* prohibit auto-connect to master, because there isn't one */
583                         bus_profile->output_ac = AutoConnectOption (bus_profile->output_ac & ~AutoConnectMaster);
584                 }
585
586                 if (!rl.empty()) {
587                         add_routes (rl, false);
588                 }
589
590                 /* this allows the user to override settings with an environment variable.
591                  */
592
593                 if (no_auto_connect()) {
594                         bus_profile->input_ac = AutoConnectOption (0);
595                         bus_profile->output_ac = AutoConnectOption (0);
596                 }
597                 
598                 Config->set_input_auto_connect (bus_profile->input_ac);
599                 Config->set_output_auto_connect (bus_profile->output_ac);
600         }
601
602         save_state ("");
603
604         return 0;
605 }
606
607 void
608 Session::maybe_write_autosave()
609 {
610         if (dirty() && record_status() != Recording) {
611                 save_state("", true);
612         }
613 }
614
615 void
616 Session::remove_pending_capture_state ()
617 {
618         sys::path pending_state_file_path(_session_dir->root_path());
619
620         pending_state_file_path /= legalize_for_path (_current_snapshot_name) + pending_suffix;
621
622         try
623         {
624                 sys::remove (pending_state_file_path);
625         }
626         catch(sys::filesystem_error& ex)
627         {
628                 error << string_compose(_("Could remove pending capture state at path \"%1\" (%2)"),
629                                 pending_state_file_path.to_string(), ex.what()) << endmsg;
630         }
631 }
632
633 /** Rename a state file.
634  * @param snapshot_name Snapshot name.
635  */
636 void
637 Session::rename_state (string old_name, string new_name)
638 {
639         if (old_name == _current_snapshot_name || old_name == _name) {
640                 /* refuse to rename the current snapshot or the "main" one */
641                 return;
642         }
643
644         const string old_xml_filename = legalize_for_path (old_name) + statefile_suffix;
645         const string new_xml_filename = legalize_for_path (new_name) + statefile_suffix;
646
647         const sys::path old_xml_path = _session_dir->root_path() / old_xml_filename;
648         const sys::path new_xml_path = _session_dir->root_path() / new_xml_filename;
649
650         try
651         {
652                 sys::rename (old_xml_path, new_xml_path);
653         }
654         catch (const sys::filesystem_error& err)
655         {
656                 error << string_compose(_("could not rename snapshot %1 to %2 (%3)"),
657                                 old_name, new_name, err.what()) << endmsg;
658         }
659 }
660
661 /** Remove a state file.
662  * @param snapshot_name Snapshot name.
663  */
664 void
665 Session::remove_state (string snapshot_name)
666 {
667         if (snapshot_name == _current_snapshot_name || snapshot_name == _name) {
668                 // refuse to remove the current snapshot or the "main" one
669                 return;
670         }
671
672         sys::path xml_path(_session_dir->root_path());
673
674         xml_path /= legalize_for_path (snapshot_name) + statefile_suffix;
675
676         if (!create_backup_file (xml_path)) {
677                 // don't remove it if a backup can't be made
678                 // create_backup_file will log the error.
679                 return;
680         }
681
682         // and delete it
683         sys::remove (xml_path);
684 }
685
686 #ifdef HAVE_JACK_SESSION
687 void
688 Session::jack_session_event (jack_session_event_t * event)
689 {
690         char timebuf[128];
691         time_t n;
692         struct tm local_time;
693
694         time (&n);
695         localtime_r (&n, &local_time);
696         strftime (timebuf, sizeof(timebuf), "JS_%FT%T", &local_time);
697
698         if (event->type == JackSessionSaveTemplate)
699         {
700                 if (save_template( timebuf )) {
701                         event->flags = JackSessionSaveError; 
702                 } else {
703                         string cmd ("ardour3 -P -U ");
704                         cmd += event->client_uuid;
705                         cmd += " -T ";
706                         cmd += timebuf;
707
708                         event->command_line = strdup (cmd.c_str());
709                 }
710         }
711         else
712         {
713                 if (save_state (timebuf)) {
714                         event->flags = JackSessionSaveError; 
715                 } else {
716                         sys::path xml_path (_session_dir->root_path());
717                         xml_path /= legalize_for_path (timebuf) + statefile_suffix;
718
719                         string cmd ("ardour3 -P -U ");
720                         cmd += event->client_uuid;
721                         cmd += " \"";
722                         cmd += xml_path.to_string();
723                         cmd += '\"';
724
725                         event->command_line = strdup (cmd.c_str());
726                 }
727         }
728
729         jack_session_reply (_engine.jack(), event);
730
731         if (event->type == JackSessionSaveAndQuit) {
732                 // TODO: make ardour quit.
733         }
734
735         jack_session_event_free( event );
736 }
737 #endif
738
739 int
740 Session::save_state (string snapshot_name, bool pending, bool switch_to_snapshot)
741 {
742         XMLTree tree;
743         sys::path xml_path(_session_dir->root_path());
744
745         if (!_writable || (_state_of_the_state & CannotSave)) {
746                 return 1;
747         }
748
749         if (!_engine.connected ()) {
750                 error << string_compose (_("the %1 audio engine is not connected and state saving would lose all I/O connections. Session not saved"),
751                                          PROGRAM_NAME)
752                       << endmsg;
753                 return 1;
754         }
755
756         /* tell sources we're saving first, in case they write out to a new file
757          * which should be saved with the state rather than the old one */
758         for (SourceMap::const_iterator i = sources.begin(); i != sources.end(); ++i) {
759                 i->second->session_saved();
760         }
761
762         tree.set_root (&get_state());
763
764         if (snapshot_name.empty()) {
765                 snapshot_name = _current_snapshot_name;
766         } else if (switch_to_snapshot) {
767                 _current_snapshot_name = snapshot_name;
768         }
769
770         if (!pending) {
771
772                 /* proper save: use statefile_suffix (.ardour in English) */
773
774                 xml_path /= legalize_for_path (snapshot_name) + statefile_suffix;
775
776                 /* make a backup copy of the old file */
777
778                 if (sys::exists(xml_path) && !create_backup_file (xml_path)) {
779                         // create_backup_file will log the error
780                         return -1;
781                 }
782
783         } else {
784
785                 /* pending save: use pending_suffix (.pending in English) */
786                 xml_path /= legalize_for_path (snapshot_name) + pending_suffix;
787         }
788
789         sys::path tmp_path(_session_dir->root_path());
790
791         tmp_path /= legalize_for_path (snapshot_name) + temp_suffix;
792
793         // cerr << "actually writing state to " << xml_path.to_string() << endl;
794
795         if (!tree.write (tmp_path.to_string())) {
796                 error << string_compose (_("state could not be saved to %1"), tmp_path.to_string()) << endmsg;
797                 sys::remove (tmp_path);
798                 return -1;
799
800         } else {
801
802                 if (rename (tmp_path.to_string().c_str(), xml_path.to_string().c_str()) != 0) {
803                         error << string_compose (_("could not rename temporary session file %1 to %2"),
804                                         tmp_path.to_string(), xml_path.to_string()) << endmsg;
805                         sys::remove (tmp_path);
806                         return -1;
807                 }
808         }
809
810         if (!pending) {
811
812                 save_history (snapshot_name);
813
814                 bool was_dirty = dirty();
815
816                 _state_of_the_state = StateOfTheState (_state_of_the_state & ~Dirty);
817
818                 if (was_dirty) {
819                         DirtyChanged (); /* EMIT SIGNAL */
820                 }
821
822                 StateSaved (snapshot_name); /* EMIT SIGNAL */
823         }
824
825         return 0;
826 }
827
828 int
829 Session::restore_state (string snapshot_name)
830 {
831         if (load_state (snapshot_name) == 0) {
832                 set_state (*state_tree->root(), Stateful::loading_state_version);
833         }
834
835         return 0;
836 }
837
838 int
839 Session::load_state (string snapshot_name)
840 {
841         delete state_tree;
842         state_tree = 0;
843
844         state_was_pending = false;
845
846         /* check for leftover pending state from a crashed capture attempt */
847
848         sys::path xmlpath(_session_dir->root_path());
849         xmlpath /= legalize_for_path (snapshot_name) + pending_suffix;
850
851         if (sys::exists (xmlpath)) {
852
853                 /* there is pending state from a crashed capture attempt */
854
855                 boost::optional<int> r = AskAboutPendingState();
856                 if (r.get_value_or (1)) {
857                         state_was_pending = true;
858                 }
859         }
860
861         if (!state_was_pending) {
862                 xmlpath = _session_dir->root_path();
863                 xmlpath /= snapshot_name;
864         }
865
866         if (!sys::exists (xmlpath)) {
867                 xmlpath = _session_dir->root_path();
868                 xmlpath /= legalize_for_path (snapshot_name) + statefile_suffix;
869                 if (!sys::exists (xmlpath)) {
870                         error << string_compose(_("%1: session state information file \"%2\" doesn't exist!"), _name, xmlpath.to_string()) << endmsg;
871                         return 1;
872                 }
873         }
874
875         state_tree = new XMLTree;
876
877         set_dirty();
878
879         /* writable() really reflects the whole folder, but if for any
880            reason the session state file can't be written to, still
881            make us unwritable.
882         */
883
884         if (::access (xmlpath.to_string().c_str(), W_OK) != 0) {
885                 _writable = false;
886         }
887
888         if (!state_tree->read (xmlpath.to_string())) {
889                 error << string_compose(_("Could not understand ardour file %1"), xmlpath.to_string()) << endmsg;
890                 delete state_tree;
891                 state_tree = 0;
892                 return -1;
893         }
894
895         XMLNode& root (*state_tree->root());
896
897         if (root.name() != X_("Session")) {
898                 error << string_compose (_("Session file %1 is not a session"), xmlpath.to_string()) << endmsg;
899                 delete state_tree;
900                 state_tree = 0;
901                 return -1;
902         }
903
904         const XMLProperty* prop;
905
906         if ((prop = root.property ("version")) == 0) {
907                 /* no version implies very old version of Ardour */
908                 Stateful::loading_state_version = 1000;
909         } else {
910                 int major;
911                 int minor;
912                 int micro;
913
914                 sscanf (prop->value().c_str(), "%d.%d.%d", &major, &minor, &micro);
915                 Stateful::loading_state_version = (major * 1000) + minor;
916         }
917                 
918         if (Stateful::loading_state_version < CURRENT_SESSION_FILE_VERSION) {
919
920                 sys::path backup_path(_session_dir->root_path());
921
922                 backup_path /= legalize_for_path (snapshot_name) + "-1" + statefile_suffix;
923
924                 // only create a backup once
925                 if (sys::exists (backup_path)) {
926                         return 0;
927                 }
928
929                 info << string_compose (_("Copying old session file %1 to %2\nUse %2 with %3 versions before 2.0 from now on"),
930                                         xmlpath.to_string(), backup_path.to_string(), PROGRAM_NAME)
931                      << endmsg;
932
933                 try
934                 {
935                         sys::copy_file (xmlpath, backup_path);
936                 }
937                 catch(sys::filesystem_error& ex)
938                 {
939                         error << string_compose (_("Unable to make backup of state file %1 (%2)"),
940                                         xmlpath.to_string(), ex.what())
941                                 << endmsg;
942                         return -1;
943                 }
944         }
945
946         return 0;
947 }
948
949 int
950 Session::load_options (const XMLNode& node)
951 {
952         LocaleGuard lg (X_("POSIX"));
953         config.set_variables (node);
954         return 0;
955 }
956
957 XMLNode&
958 Session::get_state()
959 {
960         return state(true);
961 }
962
963 XMLNode&
964 Session::get_template()
965 {
966         /* if we don't disable rec-enable, diskstreams
967            will believe they need to store their capture
968            sources in their state node.
969         */
970
971         disable_record (false);
972
973         return state(false);
974 }
975
976 XMLNode&
977 Session::state(bool full_state)
978 {
979         XMLNode* node = new XMLNode("Session");
980         XMLNode* child;
981
982         // store libardour version, just in case
983         char buf[16];
984         snprintf(buf, sizeof(buf), "%d.%d.%d", libardour3_major_version, libardour3_minor_version, libardour3_micro_version);
985         node->add_property("version", string(buf));
986
987         /* store configuration settings */
988
989         if (full_state) {
990
991                 node->add_property ("name", _name);
992                 snprintf (buf, sizeof (buf), "%" PRId32, _nominal_frame_rate);
993                 node->add_property ("sample-rate", buf);
994
995                 if (session_dirs.size() > 1) {
996
997                         string p;
998
999                         vector<space_and_path>::iterator i = session_dirs.begin();
1000                         vector<space_and_path>::iterator next;
1001
1002                         ++i; /* skip the first one */
1003                         next = i;
1004                         ++next;
1005
1006                         while (i != session_dirs.end()) {
1007
1008                                 p += (*i).path;
1009
1010                                 if (next != session_dirs.end()) {
1011                                         p += ':';
1012                                 } else {
1013                                         break;
1014                                 }
1015
1016                                 ++next;
1017                                 ++i;
1018                         }
1019
1020                         child = node->add_child ("Path");
1021                         child->add_content (p);
1022                 }
1023         }
1024
1025         /* save the ID counter */
1026
1027         snprintf (buf, sizeof (buf), "%" PRIu64, ID::counter());
1028         node->add_property ("id-counter", buf);
1029
1030         /* various options */
1031
1032         node->add_child_nocopy (config.get_variables ());
1033
1034         node->add_child_nocopy (_metadata->get_state());
1035
1036         child = node->add_child ("Sources");
1037
1038         if (full_state) {
1039                 Glib::Mutex::Lock sl (source_lock);
1040
1041                 for (SourceMap::iterator siter = sources.begin(); siter != sources.end(); ++siter) {
1042
1043                         /* Don't save information about non-destructive file sources that are empty
1044                            and unused by any regions.
1045                         */
1046
1047                         boost::shared_ptr<FileSource> fs;
1048                         if ((fs = boost::dynamic_pointer_cast<FileSource> (siter->second)) != 0) {
1049                                 if (!fs->destructive()) {
1050                                         if (fs->empty() && !fs->used()) {
1051                                                 continue;
1052                                         }
1053                                 }
1054                         }
1055
1056                         child->add_child_nocopy (siter->second->get_state());
1057                 }
1058         }
1059
1060         child = node->add_child ("Regions");
1061
1062         if (full_state) {
1063                 Glib::Mutex::Lock rl (region_lock);
1064                 const RegionFactory::RegionMap& region_map (RegionFactory::all_regions());
1065                 for (RegionFactory::RegionMap::const_iterator i = region_map.begin(); i != region_map.end(); ++i) {
1066                         boost::shared_ptr<Region> r = i->second;
1067                         /* only store regions not attached to playlists */
1068                         if (r->playlist() == 0) {
1069                                 child->add_child_nocopy (r->state (true));
1070                         }
1071                 }
1072         }
1073
1074         if (full_state) {
1075                 node->add_child_nocopy (_locations.get_state());
1076         } else {
1077                 // for a template, just create a new Locations, populate it
1078                 // with the default start and end, and get the state for that.
1079                 Locations loc;
1080                 Location* range = new Location (0, 0, _("session"), Location::IsSessionRange);
1081                 range->set (max_frames, 0);
1082                 loc.add (range);
1083                 node->add_child_nocopy (loc.get_state());
1084         }
1085
1086         child = node->add_child ("Bundles");
1087         {
1088                 boost::shared_ptr<BundleList> bundles = _bundles.reader ();
1089                 for (BundleList::iterator i = bundles->begin(); i != bundles->end(); ++i) {
1090                         boost::shared_ptr<UserBundle> b = boost::dynamic_pointer_cast<UserBundle> (*i);
1091                         if (b) {
1092                                 child->add_child_nocopy (b->get_state());
1093                         }
1094                 }
1095         }
1096
1097         child = node->add_child ("Routes");
1098         {
1099                 boost::shared_ptr<RouteList> r = routes.reader ();
1100
1101                 RoutePublicOrderSorter cmp;
1102                 RouteList public_order (*r);
1103                 public_order.sort (cmp);
1104
1105                 /* the sort should have put control outs first */
1106
1107                 if (_monitor_out) {
1108                         assert (_monitor_out == public_order.front());
1109                 }
1110
1111                 for (RouteList::iterator i = public_order.begin(); i != public_order.end(); ++i) {
1112                         if (!(*i)->is_hidden()) {
1113                                 if (full_state) {
1114                                         child->add_child_nocopy ((*i)->get_state());
1115                                 } else {
1116                                         child->add_child_nocopy ((*i)->get_template());
1117                                 }
1118                         }
1119                 }
1120         }
1121
1122         playlists->add_state (node, full_state);
1123
1124         child = node->add_child ("RouteGroups");
1125         for (list<RouteGroup *>::iterator i = _route_groups.begin(); i != _route_groups.end(); ++i) {
1126                 child->add_child_nocopy ((*i)->get_state());
1127         }
1128
1129         if (_click_io) {
1130                 child = node->add_child ("Click");
1131                 child->add_child_nocopy (_click_io->state (full_state));
1132         }
1133
1134         if (full_state) {
1135                 child = node->add_child ("NamedSelections");
1136                 for (NamedSelectionList::iterator i = named_selections.begin(); i != named_selections.end(); ++i) {
1137                         if (full_state) {
1138                                 child->add_child_nocopy ((*i)->get_state());
1139                         }
1140                 }
1141         }
1142
1143         node->add_child_nocopy (_tempo_map->get_state());
1144
1145         node->add_child_nocopy (get_control_protocol_state());
1146
1147         if (_extra_xml) {
1148                 node->add_child_copy (*_extra_xml);
1149         }
1150
1151         return *node;
1152 }
1153
1154 XMLNode&
1155 Session::get_control_protocol_state ()
1156 {
1157         ControlProtocolManager& cpm (ControlProtocolManager::instance());
1158         return cpm.get_state();
1159 }
1160
1161 int
1162 Session::set_state (const XMLNode& node, int version)
1163 {
1164         XMLNodeList nlist;
1165         XMLNode* child;
1166         const XMLProperty* prop;
1167         int ret = -1;
1168
1169         _state_of_the_state = StateOfTheState (_state_of_the_state|CannotSave);
1170
1171         if (node.name() != X_("Session")){
1172                 fatal << _("programming error: Session: incorrect XML node sent to set_state()") << endmsg;
1173                 return -1;
1174         }
1175
1176         if ((prop = node.property ("version")) != 0) {
1177                 version = atoi (prop->value ()) * 1000;
1178         }
1179
1180         if ((prop = node.property ("name")) != 0) {
1181                 _name = prop->value ();
1182         }
1183
1184         if ((prop = node.property (X_("sample-rate"))) != 0) {
1185
1186                 _nominal_frame_rate = atoi (prop->value());
1187
1188                 if (_nominal_frame_rate != _current_frame_rate) {
1189                         boost::optional<int> r = AskAboutSampleRateMismatch (_nominal_frame_rate, _current_frame_rate);
1190                         if (r.get_value_or (0)) {
1191                                 return -1;
1192                         }
1193                 }
1194         }
1195
1196         setup_raid_path(_session_dir->root_path().to_string());
1197
1198         if ((prop = node.property (X_("id-counter"))) != 0) {
1199                 uint64_t x;
1200                 sscanf (prop->value().c_str(), "%" PRIu64, &x);
1201                 ID::init_counter (x);
1202         } else {
1203                 /* old sessions used a timebased counter, so fake
1204                    the startup ID counter based on a standard
1205                    timestamp.
1206                 */
1207                 time_t now;
1208                 time (&now);
1209                 ID::init_counter (now);
1210         }
1211
1212
1213         IO::disable_connecting ();
1214
1215         /* Object loading order:
1216
1217         Path
1218         Extra
1219         Options/Config
1220         MIDI Control // relies on data from Options/Config
1221         Metadata
1222         Locations
1223         Sources
1224         AudioRegions
1225         Connections
1226         Routes
1227         RouteGroups
1228         MixGroups
1229         Click
1230         ControlProtocols
1231         */
1232
1233         if ((child = find_named_node (node, "Extra")) != 0) {
1234                 _extra_xml = new XMLNode (*child);
1235         }
1236
1237         if (((child = find_named_node (node, "Options")) != 0)) { /* old style */
1238                 load_options (*child);
1239         } else if ((child = find_named_node (node, "Config")) != 0) { /* new style */
1240                 load_options (*child);
1241         } else {
1242                 error << _("Session: XML state has no options section") << endmsg;
1243         }
1244
1245         setup_midi_machine_control ();
1246         
1247         if (use_config_midi_ports ()) {
1248         }
1249
1250         if (version >= 3000) {
1251                 if ((child = find_named_node (node, "Metadata")) == 0) {
1252                         warning << _("Session: XML state has no metadata section") << endmsg;
1253                 } else if (_metadata->set_state (*child, version)) {
1254                         goto out;
1255                 }
1256         }
1257
1258         if ((child = find_named_node (node, "Locations")) == 0) {
1259                 error << _("Session: XML state has no locations section") << endmsg;
1260                 goto out;
1261         } else if (_locations.set_state (*child, version)) {
1262                 goto out;
1263         }
1264
1265         Location* location;
1266
1267         if ((location = _locations.auto_loop_location()) != 0) {
1268                 set_auto_loop_location (location);
1269         }
1270
1271         if ((location = _locations.auto_punch_location()) != 0) {
1272                 set_auto_punch_location (location);
1273         }
1274
1275         if ((location = _locations.session_range_location()) != 0) {
1276                 delete _session_range_location;
1277                 _session_range_location = location;
1278         }
1279
1280         if (_session_range_location) {
1281                 AudioFileSource::set_header_position_offset (_session_range_location->start());
1282         }
1283
1284         if ((child = find_named_node (node, "Sources")) == 0) {
1285                 error << _("Session: XML state has no sources section") << endmsg;
1286                 goto out;
1287         } else if (load_sources (*child)) {
1288                 goto out;
1289         }
1290
1291         if ((child = find_named_node (node, "Regions")) == 0) {
1292                 error << _("Session: XML state has no Regions section") << endmsg;
1293                 goto out;
1294         } else if (load_regions (*child)) {
1295                 goto out;
1296         }
1297
1298         if ((child = find_named_node (node, "Playlists")) == 0) {
1299                 error << _("Session: XML state has no playlists section") << endmsg;
1300                 goto out;
1301         } else if (playlists->load (*this, *child)) {
1302                 goto out;
1303         }
1304
1305         if ((child = find_named_node (node, "UnusedPlaylists")) == 0) {
1306                 // this is OK
1307         } else if (playlists->load_unused (*this, *child)) {
1308                 goto out;
1309         }
1310         
1311         if ((child = find_named_node (node, "NamedSelections")) != 0) {
1312                 if (load_named_selections (*child)) {
1313                         goto out;
1314                 }
1315         }
1316
1317         if (version >= 3000) {
1318                 if ((child = find_named_node (node, "Bundles")) == 0) {
1319                         warning << _("Session: XML state has no bundles section") << endmsg;
1320                         //goto out;
1321                 } else {
1322                         /* We can't load Bundles yet as they need to be able
1323                            to convert from port names to Port objects, which can't happen until
1324                            later */
1325                         _bundle_xml_node = new XMLNode (*child);
1326                 }
1327         }
1328         
1329         if ((child = find_named_node (node, "TempoMap")) == 0) {
1330                 error << _("Session: XML state has no Tempo Map section") << endmsg;
1331                 goto out;
1332         } else if (_tempo_map->set_state (*child, version)) {
1333                 goto out;
1334         }
1335
1336         if (version < 3000) {
1337                 if ((child = find_named_node (node, X_("DiskStreams"))) == 0) {
1338                         error << _("Session: XML state has no diskstreams section") << endmsg;
1339                         goto out;
1340                 } else if (load_diskstreams_2X (*child, version)) {
1341                         goto out;
1342                 }
1343         }
1344
1345         if ((child = find_named_node (node, "Routes")) == 0) {
1346                 error << _("Session: XML state has no routes section") << endmsg;
1347                 goto out;
1348         } else if (load_routes (*child, version)) {
1349                 goto out;
1350         }
1351
1352         /* our diskstreams list is no longer needed as they are now all owned by their Route */
1353         _diskstreams_2X.clear ();
1354
1355         if (version >= 3000) {
1356                 
1357                 if ((child = find_named_node (node, "RouteGroups")) == 0) {
1358                         error << _("Session: XML state has no route groups section") << endmsg;
1359                         goto out;
1360                 } else if (load_route_groups (*child, version)) {
1361                         goto out;
1362                 }
1363                 
1364         } else if (version < 3000) {
1365                 
1366                 if ((child = find_named_node (node, "EditGroups")) == 0) {
1367                         error << _("Session: XML state has no edit groups section") << endmsg;
1368                         goto out;
1369                 } else if (load_route_groups (*child, version)) {
1370                         goto out;
1371                 }
1372
1373                 if ((child = find_named_node (node, "MixGroups")) == 0) {
1374                         error << _("Session: XML state has no mix groups section") << endmsg;
1375                         goto out;
1376                 } else if (load_route_groups (*child, version)) {
1377                         goto out;
1378                 }
1379         }
1380
1381         if ((child = find_named_node (node, "Click")) == 0) {
1382                 warning << _("Session: XML state has no click section") << endmsg;
1383         } else if (_click_io) {
1384                 _click_io->set_state (*child, version);
1385         }
1386
1387         if ((child = find_named_node (node, "ControlProtocols")) != 0) {
1388                 ControlProtocolManager::instance().set_protocol_states (*child);
1389         }
1390
1391         /* here beginneth the second phase ... */
1392
1393         StateReady (); /* EMIT SIGNAL */
1394
1395         return 0;
1396
1397   out:
1398         return ret;
1399 }
1400
1401 int
1402 Session::load_routes (const XMLNode& node, int version)
1403 {
1404         XMLNodeList nlist;
1405         XMLNodeConstIterator niter;
1406         RouteList new_routes;
1407
1408         nlist = node.children();
1409
1410         set_dirty();
1411
1412         for (niter = nlist.begin(); niter != nlist.end(); ++niter) {
1413
1414                 boost::shared_ptr<Route> route;
1415                 if (version < 3000) {
1416                         route = XMLRouteFactory_2X (**niter, version);
1417                 } else {
1418                         route = XMLRouteFactory (**niter, version);
1419                 }
1420                 
1421                 if (route == 0) {
1422                         error << _("Session: cannot create Route from XML description.") << endmsg;
1423                         return -1;
1424                 }
1425
1426                 BootMessage (string_compose (_("Loaded track/bus %1"), route->name()));
1427
1428                 new_routes.push_back (route);
1429         }
1430
1431         add_routes (new_routes, false);
1432
1433         return 0;
1434 }
1435
1436 boost::shared_ptr<Route>
1437 Session::XMLRouteFactory (const XMLNode& node, int version)
1438 {
1439         boost::shared_ptr<Route> ret;
1440
1441         if (node.name() != "Route") {
1442                 return ret;
1443         }
1444
1445         XMLNode* ds_child = find_named_node (node, X_("Diskstream"));
1446
1447         DataType type = DataType::AUDIO;
1448         const XMLProperty* prop = node.property("default-type");
1449
1450         if (prop) {
1451                 type = DataType (prop->value());
1452         }
1453
1454         assert (type != DataType::NIL);
1455
1456         if (ds_child) {
1457
1458                 Track* track;
1459                 
1460                 if (type == DataType::AUDIO) {
1461                         track = new AudioTrack (*this, X_("toBeResetFroXML"));
1462                         
1463                 } else {
1464                         track = new MidiTrack (*this, X_("toBeResetFroXML"));
1465                 }
1466                 
1467                 if (track->init()) {
1468                         delete track;
1469                         return ret;
1470                 }
1471                 
1472                 if (track->set_state (node, version)) {
1473                         delete track;
1474                         return ret;
1475                 }
1476                 
1477                 boost_debug_shared_ptr_mark_interesting (track, "Track");
1478                 ret.reset (track);
1479                 
1480         } else {
1481                 Route* rt = new Route (*this, X_("toBeResetFroXML"));
1482
1483                 if (rt->init () == 0 && rt->set_state (node, version) == 0) {
1484                         boost_debug_shared_ptr_mark_interesting (rt, "Route");
1485                         ret.reset (rt);
1486                 } else {
1487                         delete rt;
1488                 }
1489         }
1490
1491         return ret;
1492 }
1493
1494 boost::shared_ptr<Route>
1495 Session::XMLRouteFactory_2X (const XMLNode& node, int version)
1496 {
1497         boost::shared_ptr<Route> ret;
1498
1499         if (node.name() != "Route") {
1500                 return ret;
1501         }
1502
1503         XMLProperty const * ds_prop = node.property (X_("diskstream-id"));
1504         if (!ds_prop) {
1505                 ds_prop = node.property (X_("diskstream"));
1506         }
1507
1508         DataType type = DataType::AUDIO;
1509         const XMLProperty* prop = node.property("default-type");
1510
1511         if (prop) {
1512                 type = DataType (prop->value());
1513         }
1514
1515         assert (type != DataType::NIL);
1516
1517         if (ds_prop) {
1518
1519                 list<boost::shared_ptr<Diskstream> >::iterator i = _diskstreams_2X.begin ();
1520                 while (i != _diskstreams_2X.end() && (*i)->id() != ds_prop->value()) {
1521                         ++i;
1522                 }
1523
1524                 if (i == _diskstreams_2X.end()) {
1525                         error << _("Could not find diskstream for route") << endmsg;
1526                         return boost::shared_ptr<Route> ();
1527                 }
1528
1529                 Track* track;
1530                 
1531                 if (type == DataType::AUDIO) {
1532                         track = new AudioTrack (*this, X_("toBeResetFroXML"));
1533                         
1534                 } else {
1535                         track = new MidiTrack (*this, X_("toBeResetFroXML"));
1536                 }
1537                 
1538                 if (track->init()) {
1539                         delete track;
1540                         return ret;
1541                 }
1542                 
1543                 if (track->set_state (node, version)) {
1544                         delete track;
1545                         return ret;
1546                 }
1547
1548                 track->set_diskstream (*i);
1549                 
1550                 boost_debug_shared_ptr_mark_interesting (track, "Track");
1551                 ret.reset (track);
1552                 
1553         } else {
1554                 Route* rt = new Route (*this, X_("toBeResetFroXML"));
1555
1556                 if (rt->init () == 0 && rt->set_state (node, version) == 0) {
1557                         boost_debug_shared_ptr_mark_interesting (rt, "Route");
1558                         ret.reset (rt);
1559                 } else {
1560                         delete rt;
1561                 }
1562         }
1563
1564         return ret;
1565 }
1566
1567 int
1568 Session::load_regions (const XMLNode& node)
1569 {
1570         XMLNodeList nlist;
1571         XMLNodeConstIterator niter;
1572         boost::shared_ptr<Region> region;
1573
1574         nlist = node.children();
1575
1576         set_dirty();
1577
1578         for (niter = nlist.begin(); niter != nlist.end(); ++niter) {
1579                 if ((region = XMLRegionFactory (**niter, false)) == 0) {
1580                         error << _("Session: cannot create Region from XML description.");
1581                         const XMLProperty *name = (**niter).property("name");
1582
1583                         if (name) {
1584                                 error << " " << string_compose (_("Can not load state for region '%1'"), name->value());
1585                         }
1586
1587                         error << endmsg;
1588                 }
1589         }
1590
1591         return 0;
1592 }
1593
1594 boost::shared_ptr<Region>
1595 Session::XMLRegionFactory (const XMLNode& node, bool full)
1596 {
1597         const XMLProperty* type = node.property("type");
1598
1599         try {
1600
1601         if ( !type || type->value() == "audio" ) {
1602
1603                 return boost::shared_ptr<Region>(XMLAudioRegionFactory (node, full));
1604
1605         } else if (type->value() == "midi") {
1606
1607                 return boost::shared_ptr<Region>(XMLMidiRegionFactory (node, full));
1608
1609         }
1610
1611         } catch (failed_constructor& err) {
1612                 return boost::shared_ptr<Region> ();
1613         }
1614
1615         return boost::shared_ptr<Region> ();
1616 }
1617
1618 boost::shared_ptr<AudioRegion>
1619 Session::XMLAudioRegionFactory (const XMLNode& node, bool /*full*/)
1620 {
1621         const XMLProperty* prop;
1622         boost::shared_ptr<Source> source;
1623         boost::shared_ptr<AudioSource> as;
1624         SourceList sources;
1625         SourceList master_sources;
1626         uint32_t nchans = 1;
1627         char buf[128];
1628
1629         if (node.name() != X_("Region")) {
1630                 return boost::shared_ptr<AudioRegion>();
1631         }
1632
1633         if ((prop = node.property (X_("channels"))) != 0) {
1634                 nchans = atoi (prop->value().c_str());
1635         }
1636
1637         if ((prop = node.property ("name")) == 0) {
1638                 cerr << "no name for this region\n";
1639                 abort ();
1640         }
1641
1642         if ((prop = node.property (X_("source-0"))) == 0) {
1643                 if ((prop = node.property ("source")) == 0) {
1644                         error << _("Session: XMLNode describing a AudioRegion is incomplete (no source)") << endmsg;
1645                         return boost::shared_ptr<AudioRegion>();
1646                 }
1647         }
1648
1649         PBD::ID s_id (prop->value());
1650
1651         if ((source = source_by_id (s_id)) == 0) {
1652                 error << string_compose(_("Session: XMLNode describing a AudioRegion references an unknown source id =%1"), s_id) << endmsg;
1653                 return boost::shared_ptr<AudioRegion>();
1654         }
1655
1656         as = boost::dynamic_pointer_cast<AudioSource>(source);
1657         if (!as) {
1658                 error << string_compose(_("Session: XMLNode describing a AudioRegion references a non-audio source id =%1"), s_id) << endmsg;
1659                 return boost::shared_ptr<AudioRegion>();
1660         }
1661
1662         sources.push_back (as);
1663
1664         /* pickup other channels */
1665
1666         for (uint32_t n=1; n < nchans; ++n) {
1667                 snprintf (buf, sizeof(buf), X_("source-%d"), n);
1668                 if ((prop = node.property (buf)) != 0) {
1669
1670                         PBD::ID id2 (prop->value());
1671
1672                         if ((source = source_by_id (id2)) == 0) {
1673                                 error << string_compose(_("Session: XMLNode describing a AudioRegion references an unknown source id =%1"), id2) << endmsg;
1674                                 return boost::shared_ptr<AudioRegion>();
1675                         }
1676
1677                         as = boost::dynamic_pointer_cast<AudioSource>(source);
1678                         if (!as) {
1679                                 error << string_compose(_("Session: XMLNode describing a AudioRegion references a non-audio source id =%1"), id2) << endmsg;
1680                                 return boost::shared_ptr<AudioRegion>();
1681                         }
1682                         sources.push_back (as);
1683                 }
1684         }
1685
1686         for (uint32_t n = 0; n < nchans; ++n) {
1687                 snprintf (buf, sizeof(buf), X_("master-source-%d"), n);
1688                 if ((prop = node.property (buf)) != 0) {
1689
1690                         PBD::ID id2 (prop->value());
1691
1692                         if ((source = source_by_id (id2)) == 0) {
1693                                 error << string_compose(_("Session: XMLNode describing a AudioRegion references an unknown source id =%1"), id2) << endmsg;
1694                                 return boost::shared_ptr<AudioRegion>();
1695                         }
1696
1697                         as = boost::dynamic_pointer_cast<AudioSource>(source);
1698                         if (!as) {
1699                                 error << string_compose(_("Session: XMLNode describing a AudioRegion references a non-audio source id =%1"), id2) << endmsg;
1700                                 return boost::shared_ptr<AudioRegion>();
1701                         }
1702                         master_sources.push_back (as);
1703                 }
1704         }
1705
1706         try {
1707                 boost::shared_ptr<AudioRegion> region (boost::dynamic_pointer_cast<AudioRegion> (RegionFactory::create (sources, node)));
1708
1709                 /* a final detail: this is the one and only place that we know how long missing files are */
1710
1711                 if (region->whole_file()) {
1712                         for (SourceList::iterator sx = sources.begin(); sx != sources.end(); ++sx) {
1713                                 boost::shared_ptr<SilentFileSource> sfp = boost::dynamic_pointer_cast<SilentFileSource> (*sx);
1714                                 if (sfp) {
1715                                         sfp->set_length (region->length());
1716                                 }
1717                         }
1718                 }
1719
1720                 if (!master_sources.empty()) {
1721                         if (master_sources.size() != nchans) {
1722                                 error << _("Session: XMLNode describing an AudioRegion is missing some master sources; ignored") << endmsg;
1723                         } else {
1724                                 region->set_master_sources (master_sources);
1725                         }
1726                 }
1727
1728                 return region;
1729
1730         }
1731
1732         catch (failed_constructor& err) {
1733                 return boost::shared_ptr<AudioRegion>();
1734         }
1735 }
1736
1737 boost::shared_ptr<MidiRegion>
1738 Session::XMLMidiRegionFactory (const XMLNode& node, bool /*full*/)
1739 {
1740         const XMLProperty* prop;
1741         boost::shared_ptr<Source> source;
1742         boost::shared_ptr<MidiSource> ms;
1743         SourceList sources;
1744         uint32_t nchans = 1;
1745
1746         if (node.name() != X_("Region")) {
1747                 return boost::shared_ptr<MidiRegion>();
1748         }
1749
1750         if ((prop = node.property (X_("channels"))) != 0) {
1751                 nchans = atoi (prop->value().c_str());
1752         }
1753
1754         if ((prop = node.property ("name")) == 0) {
1755                 cerr << "no name for this region\n";
1756                 abort ();
1757         }
1758
1759         // Multiple midi channels?  that's just crazy talk
1760         assert(nchans == 1);
1761
1762         if ((prop = node.property (X_("source-0"))) == 0) {
1763                 if ((prop = node.property ("source")) == 0) {
1764                         error << _("Session: XMLNode describing a MidiRegion is incomplete (no source)") << endmsg;
1765                         return boost::shared_ptr<MidiRegion>();
1766                 }
1767         }
1768
1769         PBD::ID s_id (prop->value());
1770
1771         if ((source = source_by_id (s_id)) == 0) {
1772                 error << string_compose(_("Session: XMLNode describing a MidiRegion references an unknown source id =%1"), s_id) << endmsg;
1773                 return boost::shared_ptr<MidiRegion>();
1774         }
1775
1776         ms = boost::dynamic_pointer_cast<MidiSource>(source);
1777         if (!ms) {
1778                 error << string_compose(_("Session: XMLNode describing a MidiRegion references a non-midi source id =%1"), s_id) << endmsg;
1779                 return boost::shared_ptr<MidiRegion>();
1780         }
1781
1782         sources.push_back (ms);
1783
1784         try {
1785                 boost::shared_ptr<MidiRegion> region (boost::dynamic_pointer_cast<MidiRegion> (RegionFactory::create (sources, node)));
1786                 /* a final detail: this is the one and only place that we know how long missing files are */
1787
1788                 if (region->whole_file()) {
1789                         for (SourceList::iterator sx = sources.begin(); sx != sources.end(); ++sx) {
1790                                 boost::shared_ptr<SilentFileSource> sfp = boost::dynamic_pointer_cast<SilentFileSource> (*sx);
1791                                 if (sfp) {
1792                                         sfp->set_length (region->length());
1793                                 }
1794                         }
1795                 }
1796
1797                 return region;
1798         }
1799
1800         catch (failed_constructor& err) {
1801                 return boost::shared_ptr<MidiRegion>();
1802         }
1803 }
1804
1805 XMLNode&
1806 Session::get_sources_as_xml ()
1807
1808 {
1809         XMLNode* node = new XMLNode (X_("Sources"));
1810         Glib::Mutex::Lock lm (source_lock);
1811
1812         for (SourceMap::iterator i = sources.begin(); i != sources.end(); ++i) {
1813                 node->add_child_nocopy (i->second->get_state());
1814         }
1815
1816         return *node;
1817 }
1818
1819 string
1820 Session::path_from_region_name (DataType type, string name, string identifier)
1821 {
1822         char buf[PATH_MAX+1];
1823         uint32_t n;
1824         SessionDirectory sdir(get_best_session_directory_for_new_source());
1825         sys::path source_dir = ((type == DataType::AUDIO)
1826                 ? sdir.sound_path() : sdir.midi_path());
1827
1828         string ext = ((type == DataType::AUDIO) ? ".wav" : ".mid");
1829
1830         for (n = 0; n < 999999; ++n) {
1831                 if (identifier.length()) {
1832                         snprintf (buf, sizeof(buf), "%s%s%" PRIu32 "%s", name.c_str(),
1833                                   identifier.c_str(), n, ext.c_str());
1834                 } else {
1835                         snprintf (buf, sizeof(buf), "%s-%" PRIu32 "%s", name.c_str(),
1836                                         n, ext.c_str());
1837                 }
1838
1839                 sys::path source_path = source_dir / buf;
1840
1841                 if (!sys::exists (source_path)) {
1842                         return source_path.to_string();
1843                 }
1844         }
1845
1846         error << string_compose (_("cannot create new file from region name \"%1\" with ident = \"%2\": too many existing files with similar names"),
1847                                  name, identifier)
1848               << endmsg;
1849
1850         return "";
1851 }
1852
1853
1854 int
1855 Session::load_sources (const XMLNode& node)
1856 {
1857         XMLNodeList nlist;
1858         XMLNodeConstIterator niter;
1859         boost::shared_ptr<Source> source;
1860
1861         nlist = node.children();
1862
1863         set_dirty();
1864
1865         for (niter = nlist.begin(); niter != nlist.end(); ++niter) {
1866                 try {
1867                         if ((source = XMLSourceFactory (**niter)) == 0) {
1868                                 error << _("Session: cannot create Source from XML description.") << endmsg;
1869                         }
1870                 } catch (MissingSource& err) {
1871                         warning << _("A sound file is missing. It will be replaced by silence.") << endmsg;
1872                         source = SourceFactory::createSilent (*this, **niter, max_frames, _current_frame_rate);
1873                 }
1874         }
1875
1876         return 0;
1877 }
1878
1879 boost::shared_ptr<Source>
1880 Session::XMLSourceFactory (const XMLNode& node)
1881 {
1882         if (node.name() != "Source") {
1883                 return boost::shared_ptr<Source>();
1884         }
1885
1886         try {
1887                 /* note: do peak building in another thread when loading session state */
1888                 return SourceFactory::create (*this, node, true);
1889         }
1890
1891         catch (failed_constructor& err) {
1892                 error << string_compose (_("Found a sound file that cannot be used by %1. Talk to the progammers."), PROGRAM_NAME) << endmsg;
1893                 return boost::shared_ptr<Source>();
1894         }
1895 }
1896
1897 int
1898 Session::save_template (string template_name)
1899 {
1900         XMLTree tree;
1901
1902         if (_state_of_the_state & CannotSave) {
1903                 return -1;
1904         }
1905
1906         sys::path user_template_dir(user_template_directory());
1907
1908         try
1909         {
1910                 sys::create_directories (user_template_dir);
1911         }
1912         catch(sys::filesystem_error& ex)
1913         {
1914                 error << string_compose(_("Could not create mix templates directory \"%1\" (%2)"),
1915                                 user_template_dir.to_string(), ex.what()) << endmsg;
1916                 return -1;
1917         }
1918
1919         tree.set_root (&get_template());
1920
1921         sys::path template_file_path(user_template_dir);
1922         template_file_path /= template_name + template_suffix;
1923
1924         if (sys::exists (template_file_path))
1925         {
1926                 warning << string_compose(_("Template \"%1\" already exists - new version not created"),
1927                                 template_file_path.to_string()) << endmsg;
1928                 return -1;
1929         }
1930
1931         if (!tree.write (template_file_path.to_string())) {
1932                 error << _("mix template not saved") << endmsg;
1933                 return -1;
1934         }
1935
1936         return 0;
1937 }
1938
1939 int
1940 Session::rename_template (string old_name, string new_name)
1941 {
1942         sys::path old_path (user_template_directory());
1943         old_path /= old_name + template_suffix;
1944
1945         sys::path new_path(user_template_directory());
1946         new_path /= new_name + template_suffix;
1947
1948         if (sys::exists (new_path)) {
1949                 warning << string_compose(_("Template \"%1\" already exists - template not renamed"),
1950                                           new_path.to_string()) << endmsg;
1951                 return -1;
1952         }
1953
1954         try {
1955                 sys::rename (old_path, new_path);
1956                 return 0;
1957         } catch (...) {
1958                 return -1;
1959         }
1960 }
1961
1962 int
1963 Session::delete_template (string name)
1964 {
1965         sys::path path = user_template_directory();
1966         path /= name + template_suffix;
1967
1968         try {
1969                 sys::remove (path);
1970                 return 0;
1971         } catch (...) {
1972                 return -1;
1973         }
1974 }
1975
1976 void
1977 Session::refresh_disk_space ()
1978 {
1979 #if HAVE_SYS_VFS_H
1980         struct statfs statfsbuf;
1981         vector<space_and_path>::iterator i;
1982         Glib::Mutex::Lock lm (space_lock);
1983         double scale;
1984
1985         /* get freespace on every FS that is part of the session path */
1986
1987         _total_free_4k_blocks = 0;
1988
1989         for (i = session_dirs.begin(); i != session_dirs.end(); ++i) {
1990                 statfs ((*i).path.c_str(), &statfsbuf);
1991
1992                 scale = statfsbuf.f_bsize/4096.0;
1993
1994                 (*i).blocks = (uint32_t) floor (statfsbuf.f_bavail * scale);
1995                 _total_free_4k_blocks += (*i).blocks;
1996         }
1997 #endif
1998 }
1999
2000 string
2001 Session::get_best_session_directory_for_new_source ()
2002 {
2003         vector<space_and_path>::iterator i;
2004         string result = _session_dir->root_path().to_string();
2005
2006         /* handle common case without system calls */
2007
2008         if (session_dirs.size() == 1) {
2009                 return result;
2010         }
2011
2012         /* OK, here's the algorithm we're following here:
2013
2014         We want to select which directory to use for
2015         the next file source to be created. Ideally,
2016         we'd like to use a round-robin process so as to
2017         get maximum performance benefits from splitting
2018         the files across multiple disks.
2019
2020         However, in situations without much diskspace, an
2021         RR approach may end up filling up a filesystem
2022         with new files while others still have space.
2023         Its therefore important to pay some attention to
2024         the freespace in the filesystem holding each
2025         directory as well. However, if we did that by
2026         itself, we'd keep creating new files in the file
2027         system with the most space until it was as full
2028         as all others, thus negating any performance
2029         benefits of this RAID-1 like approach.
2030
2031         So, we use a user-configurable space threshold. If
2032         there are at least 2 filesystems with more than this
2033         much space available, we use RR selection between them.
2034         If not, then we pick the filesystem with the most space.
2035
2036         This gets a good balance between the two
2037         approaches.
2038         */
2039
2040         refresh_disk_space ();
2041
2042         int free_enough = 0;
2043
2044         for (i = session_dirs.begin(); i != session_dirs.end(); ++i) {
2045                 if ((*i).blocks * 4096 >= Config->get_disk_choice_space_threshold()) {
2046                         free_enough++;
2047                 }
2048         }
2049
2050         if (free_enough >= 2) {
2051                 /* use RR selection process, ensuring that the one
2052                    picked works OK.
2053                 */
2054
2055                 i = last_rr_session_dir;
2056
2057                 do {
2058                         if (++i == session_dirs.end()) {
2059                                 i = session_dirs.begin();
2060                         }
2061
2062                         if ((*i).blocks * 4096 >= Config->get_disk_choice_space_threshold()) {
2063                                 if (create_session_directory ((*i).path)) {
2064                                         result = (*i).path;
2065                                         last_rr_session_dir = i;
2066                                         return result;
2067                                 }
2068                         }
2069
2070                 } while (i != last_rr_session_dir);
2071
2072         } else {
2073
2074                 /* pick FS with the most freespace (and that
2075                    seems to actually work ...)
2076                 */
2077
2078                 vector<space_and_path> sorted;
2079                 space_and_path_ascending_cmp cmp;
2080
2081                 sorted = session_dirs;
2082                 sort (sorted.begin(), sorted.end(), cmp);
2083
2084                 for (i = sorted.begin(); i != sorted.end(); ++i) {
2085                         if (create_session_directory ((*i).path)) {
2086                                 result = (*i).path;
2087                                 last_rr_session_dir = i;
2088                                 return result;
2089                         }
2090                 }
2091         }
2092
2093         return result;
2094 }
2095
2096 int
2097 Session::load_named_selections (const XMLNode& node)
2098 {
2099         XMLNodeList nlist;
2100         XMLNodeConstIterator niter;
2101         NamedSelection *ns;
2102
2103         nlist = node.children();
2104
2105         set_dirty();
2106
2107         for (niter = nlist.begin(); niter != nlist.end(); ++niter) {
2108
2109                 if ((ns = XMLNamedSelectionFactory (**niter)) == 0) {
2110                         error << _("Session: cannot create Named Selection from XML description.") << endmsg;
2111                 }
2112         }
2113
2114         return 0;
2115 }
2116
2117 NamedSelection *
2118 Session::XMLNamedSelectionFactory (const XMLNode& node)
2119 {
2120         try {
2121                 return new NamedSelection (*this, node);
2122         }
2123
2124         catch (failed_constructor& err) {
2125                 return 0;
2126         }
2127 }
2128
2129 string
2130 Session::automation_dir () const
2131 {
2132         return Glib::build_filename (_path, "automation");
2133 }
2134
2135 string
2136 Session::analysis_dir () const
2137 {
2138         return Glib::build_filename (_path, "analysis");
2139 }
2140
2141 int
2142 Session::load_bundles (XMLNode const & node)
2143 {
2144         XMLNodeList nlist = node.children();
2145         XMLNodeConstIterator niter;
2146
2147         set_dirty();
2148
2149         for (niter = nlist.begin(); niter != nlist.end(); ++niter) {
2150                 if ((*niter)->name() == "InputBundle") {
2151                         add_bundle (boost::shared_ptr<UserBundle> (new UserBundle (**niter, true)));
2152                 } else if ((*niter)->name() == "OutputBundle") {
2153                         add_bundle (boost::shared_ptr<UserBundle> (new UserBundle (**niter, false)));
2154                 } else {
2155                         error << string_compose(_("Unknown node \"%1\" found in Bundles list from state file"), (*niter)->name()) << endmsg;
2156                         return -1;
2157                 }
2158         }
2159
2160         return 0;
2161 }
2162
2163 int
2164 Session::load_route_groups (const XMLNode& node, int version)
2165 {
2166         XMLNodeList nlist = node.children();
2167         XMLNodeConstIterator niter;
2168
2169         set_dirty ();
2170
2171         if (version >= 3000) {
2172                 
2173                 for (niter = nlist.begin(); niter != nlist.end(); ++niter) {
2174                         if ((*niter)->name() == "RouteGroup") {
2175                                 RouteGroup* rg = new RouteGroup (*this, "");
2176                                 add_route_group (rg);
2177                                 rg->set_state (**niter, version);
2178                         }
2179                 }
2180
2181         } else if (version < 3000) {
2182
2183                 for (niter = nlist.begin(); niter != nlist.end(); ++niter) {
2184                         if ((*niter)->name() == "EditGroup" || (*niter)->name() == "MixGroup") {
2185                                 RouteGroup* rg = new RouteGroup (*this, "");
2186                                 add_route_group (rg);
2187                                 rg->set_state (**niter, version);
2188                         }
2189                 }
2190         }
2191
2192         return 0;
2193 }
2194
2195 void
2196 Session::auto_save()
2197 {
2198         save_state (_current_snapshot_name);
2199 }
2200
2201 static bool
2202 state_file_filter (const string &str, void */*arg*/)
2203 {
2204         return (str.length() > strlen(statefile_suffix) &&
2205                 str.find (statefile_suffix) == (str.length() - strlen (statefile_suffix)));
2206 }
2207
2208 struct string_cmp {
2209         bool operator()(const string* a, const string* b) {
2210                 return *a < *b;
2211         }
2212 };
2213
2214 static string*
2215 remove_end(string* state)
2216 {
2217         string statename(*state);
2218
2219         string::size_type start,end;
2220         if ((start = statename.find_last_of ('/')) != string::npos) {
2221                 statename = statename.substr (start+1);
2222         }
2223
2224         if ((end = statename.rfind(".ardour")) == string::npos) {
2225                 end = statename.length();
2226         }
2227
2228         return new string(statename.substr (0, end));
2229 }
2230
2231 vector<string *> *
2232 Session::possible_states (string path)
2233 {
2234         PathScanner scanner;
2235         vector<string*>* states = scanner (path, state_file_filter, 0, false, false);
2236
2237         transform(states->begin(), states->end(), states->begin(), remove_end);
2238
2239         string_cmp cmp;
2240         sort (states->begin(), states->end(), cmp);
2241
2242         return states;
2243 }
2244
2245 vector<string *> *
2246 Session::possible_states () const
2247 {
2248         return possible_states(_path);
2249 }
2250
2251 void
2252 Session::add_route_group (RouteGroup* g)
2253 {
2254         _route_groups.push_back (g);
2255         route_group_added (g); /* EMIT SIGNAL */
2256         set_dirty ();
2257 }
2258
2259 void
2260 Session::remove_route_group (RouteGroup& rg)
2261 {
2262         list<RouteGroup*>::iterator i;
2263
2264         if ((i = find (_route_groups.begin(), _route_groups.end(), &rg)) != _route_groups.end()) {
2265                 _route_groups.erase (i);
2266                 delete &rg;
2267
2268                 route_group_removed (); /* EMIT SIGNAL */
2269         }
2270
2271 }
2272
2273 RouteGroup *
2274 Session::route_group_by_name (string name)
2275 {
2276         list<RouteGroup *>::iterator i;
2277
2278         for (i = _route_groups.begin(); i != _route_groups.end(); ++i) {
2279                 if ((*i)->name() == name) {
2280                         return* i;
2281                 }
2282         }
2283         return 0;
2284 }
2285
2286 UndoTransaction*
2287 Session::start_reversible_command (const string& name)
2288 {
2289         UndoTransaction* trans = new UndoTransaction();
2290         trans->set_name(name);
2291         return trans;
2292 }
2293
2294 void
2295 Session::finish_reversible_command (UndoTransaction& ut)
2296 {
2297         struct timeval now;
2298         gettimeofday(&now, 0);
2299         ut.set_timestamp(now);
2300         _history.add (&ut);
2301 }
2302
2303 void
2304 Session::begin_reversible_command(const string& name)
2305 {
2306         UndoTransaction* trans = new UndoTransaction();
2307         trans->set_name(name);
2308
2309         if (!_current_trans.empty()) {
2310                 _current_trans.top()->add_command (trans);
2311         } else {
2312                 _current_trans.push(trans);
2313         }
2314 }
2315
2316 void
2317 Session::commit_reversible_command(Command *cmd)
2318 {
2319         assert(!_current_trans.empty());
2320         struct timeval now;
2321
2322         if (cmd) {
2323                 _current_trans.top()->add_command(cmd);
2324         }
2325
2326         if (_current_trans.top()->empty()) {
2327                 _current_trans.pop();
2328                 return;
2329         }
2330
2331         gettimeofday(&now, 0);
2332         _current_trans.top()->set_timestamp(now);
2333
2334         _history.add(_current_trans.top());
2335         _current_trans.pop();
2336 }
2337
2338 static bool
2339 accept_all_non_peak_files (const string& path, void */*arg*/)
2340 {
2341         return (path.length() > 5 && path.find (peakfile_suffix) != (path.length() - 5));
2342 }
2343
2344 static bool
2345 accept_all_state_files (const string& path, void */*arg*/)
2346 {
2347         return (path.length() > 7 && path.find (".ardour") == (path.length() - 7));
2348 }
2349
2350 int
2351 Session::find_all_sources (string path, set<string>& result)
2352 {
2353         XMLTree tree;
2354         XMLNode* node;
2355
2356         if (!tree.read (path)) {
2357                 return -1;
2358         }
2359
2360         if ((node = find_named_node (*tree.root(), "Sources")) == 0) {
2361                 return -2;
2362         }
2363
2364         XMLNodeList nlist;
2365         XMLNodeConstIterator niter;
2366
2367         nlist = node->children();
2368
2369         set_dirty();
2370
2371         for (niter = nlist.begin(); niter != nlist.end(); ++niter) {
2372
2373                 XMLProperty* prop;
2374
2375                 if ((prop = (*niter)->property (X_("type"))) == 0) {
2376                         continue;
2377                 }
2378
2379                 DataType type (prop->value());
2380
2381                 if ((prop = (*niter)->property (X_("name"))) == 0) {
2382                         continue;
2383                 }
2384
2385                 if (prop->value()[0] == '/') {
2386                         /* external file, ignore */
2387                         continue;
2388                 }
2389
2390                 Glib::ustring found_path;
2391                 bool is_new;
2392                 uint16_t chan;
2393
2394                 if (FileSource::find (type, prop->value(), true, is_new, chan, found_path)) {
2395                         result.insert (found_path);
2396                 }
2397         }
2398
2399         return 0;
2400 }
2401
2402 int
2403 Session::find_all_sources_across_snapshots (set<string>& result, bool exclude_this_snapshot)
2404 {
2405         PathScanner scanner;
2406         vector<string*>* state_files;
2407         string ripped;
2408         string this_snapshot_path;
2409
2410         result.clear ();
2411
2412         ripped = _path;
2413
2414         if (ripped[ripped.length()-1] == '/') {
2415                 ripped = ripped.substr (0, ripped.length() - 1);
2416         }
2417
2418         state_files = scanner (ripped, accept_all_state_files, (void *) 0, false, true);
2419
2420         if (state_files == 0) {
2421                 /* impossible! */
2422                 return 0;
2423         }
2424
2425         this_snapshot_path = _path;
2426         this_snapshot_path += legalize_for_path (_current_snapshot_name);
2427         this_snapshot_path += statefile_suffix;
2428
2429         for (vector<string*>::iterator i = state_files->begin(); i != state_files->end(); ++i) {
2430
2431                 if (exclude_this_snapshot && **i == this_snapshot_path) {
2432                         continue;
2433                 }
2434
2435                 if (find_all_sources (**i, result) < 0) {
2436                         return -1;
2437                 }
2438         }
2439
2440         return 0;
2441 }
2442
2443 struct RegionCounter {
2444     typedef std::map<PBD::ID,boost::shared_ptr<AudioSource> > AudioSourceList;
2445     AudioSourceList::iterator iter;
2446     boost::shared_ptr<Region> region;
2447     uint32_t count;
2448
2449     RegionCounter() : count (0) {}
2450 };
2451
2452 int
2453 Session::ask_about_playlist_deletion (boost::shared_ptr<Playlist> p)
2454 {
2455         boost::optional<int> r = AskAboutPlaylistDeletion (p);
2456         return r.get_value_or (1);
2457 }
2458
2459 int
2460 Session::cleanup_sources (CleanupReport& rep)
2461 {
2462         // FIXME: needs adaptation to midi
2463
2464         vector<boost::shared_ptr<Source> > dead_sources;
2465         PathScanner scanner;
2466         string sound_path;
2467         vector<space_and_path>::iterator i;
2468         vector<space_and_path>::iterator nexti;
2469         vector<string*>* soundfiles;
2470         vector<string> unused;
2471         set<string> all_sources;
2472         bool used;
2473         string spath;
2474         int ret = -1;
2475
2476         _state_of_the_state = (StateOfTheState) (_state_of_the_state | InCleanup);
2477
2478         /* step 1: consider deleting all unused playlists */
2479         
2480         if (playlists->maybe_delete_unused (boost::bind (Session::ask_about_playlist_deletion, _1))) {
2481                 ret = 0;
2482                 goto out;
2483         }
2484
2485         /* step 2: find all un-used sources */
2486
2487         rep.paths.clear ();
2488         rep.space = 0;
2489
2490         for (SourceMap::iterator i = sources.begin(); i != sources.end(); ) {
2491
2492                 SourceMap::iterator tmp;
2493
2494                 tmp = i;
2495                 ++tmp;
2496
2497                 /* do not bother with files that are zero size, otherwise we remove the current "nascent"
2498                    capture files.
2499                 */
2500
2501                 if (!i->second->used() && (i->second->length(i->second->timeline_position() > 0))) {
2502                         dead_sources.push_back (i->second);
2503                         i->second->drop_references ();
2504                 }
2505
2506                 i = tmp;
2507         }
2508
2509         /* build a list of all the possible sound directories for the session */
2510
2511         for (i = session_dirs.begin(); i != session_dirs.end(); ) {
2512
2513                 nexti = i;
2514                 ++nexti;
2515
2516                 SessionDirectory sdir ((*i).path);
2517                 sound_path += sdir.sound_path().to_string();
2518
2519                 if (nexti != session_dirs.end()) {
2520                         sound_path += ':';
2521                 }
2522
2523                 i = nexti;
2524         }
2525
2526         /* now do the same thing for the files that ended up in the sounds dir(s)
2527            but are not referenced as sources in any snapshot.
2528         */
2529
2530         soundfiles = scanner (sound_path, accept_all_non_peak_files, (void *) 0, false, true);
2531
2532         if (soundfiles == 0) {
2533                 return 0;
2534         }
2535
2536         /* find all sources, but don't use this snapshot because the
2537            state file on disk still references sources we may have already
2538            dropped.
2539         */
2540
2541         find_all_sources_across_snapshots (all_sources, true);
2542
2543         /*  add our current source list
2544          */
2545
2546         for (SourceMap::iterator i = sources.begin(); i != sources.end(); ++i) {
2547                 boost::shared_ptr<FileSource> fs;
2548
2549                 if ((fs = boost::dynamic_pointer_cast<FileSource> (i->second)) != 0) {
2550                         all_sources.insert (fs->path());
2551                 }
2552         }
2553
2554         char tmppath1[PATH_MAX+1];
2555         char tmppath2[PATH_MAX+1];
2556
2557         for (vector<string*>::iterator x = soundfiles->begin(); x != soundfiles->end(); ++x) {
2558
2559                 used = false;
2560                 spath = **x;
2561
2562                 for (set<string>::iterator i = all_sources.begin(); i != all_sources.end(); ++i) {
2563
2564                         realpath(spath.c_str(), tmppath1);
2565                         realpath((*i).c_str(),  tmppath2);
2566
2567                         if (strcmp(tmppath1, tmppath2) == 0) {
2568                                 used = true;
2569                                 break;
2570                         }
2571                 }
2572
2573                 if (!used) {
2574                         unused.push_back (spath);
2575                 }
2576         }
2577
2578         /* now try to move all unused files into the "dead_sounds" directory(ies) */
2579
2580         for (vector<string>::iterator x = unused.begin(); x != unused.end(); ++x) {
2581                 struct stat statbuf;
2582
2583                 rep.paths.push_back (*x);
2584                 if (stat ((*x).c_str(), &statbuf) == 0) {
2585                         rep.space += statbuf.st_size;
2586                 }
2587
2588                 string newpath;
2589
2590                 /* don't move the file across filesystems, just
2591                    stick it in the `dead_sound_dir_name' directory
2592                    on whichever filesystem it was already on.
2593                 */
2594
2595                 if ((*x).find ("/sounds/") != string::npos) {
2596
2597                         /* old school, go up 1 level */
2598
2599                         newpath = Glib::path_get_dirname (*x);      // "sounds"
2600                         newpath = Glib::path_get_dirname (newpath); // "session-name"
2601
2602                 } else {
2603
2604                         /* new school, go up 4 levels */
2605
2606                         newpath = Glib::path_get_dirname (*x);      // "audiofiles"
2607                         newpath = Glib::path_get_dirname (newpath); // "session-name"
2608                         newpath = Glib::path_get_dirname (newpath); // "interchange"
2609                         newpath = Glib::path_get_dirname (newpath); // "session-dir"
2610                 }
2611
2612                 newpath += '/';
2613                 newpath += dead_sound_dir_name;
2614
2615                 if (g_mkdir_with_parents (newpath.c_str(), 0755) < 0) {
2616                         error << string_compose(_("Session: cannot create session peakfile folder \"%1\" (%2)"), newpath, strerror (errno)) << endmsg;
2617                         return -1;
2618                 }
2619
2620                 newpath += '/';
2621                 newpath += Glib::path_get_basename ((*x));
2622
2623                 if (access (newpath.c_str(), F_OK) == 0) {
2624
2625                         /* the new path already exists, try versioning */
2626
2627                         char buf[PATH_MAX+1];
2628                         int version = 1;
2629                         string newpath_v;
2630
2631                         snprintf (buf, sizeof (buf), "%s.%d", newpath.c_str(), version);
2632                         newpath_v = buf;
2633
2634                         while (access (newpath_v.c_str(), F_OK) == 0 && version < 999) {
2635                                 snprintf (buf, sizeof (buf), "%s.%d", newpath.c_str(), ++version);
2636                                 newpath_v = buf;
2637                         }
2638
2639                         if (version == 999) {
2640                                 error << string_compose (_("there are already 1000 files with names like %1; versioning discontinued"),
2641                                                   newpath)
2642                                       << endmsg;
2643                         } else {
2644                                 newpath = newpath_v;
2645                         }
2646
2647                 } else {
2648
2649                         /* it doesn't exist, or we can't read it or something */
2650
2651                 }
2652
2653                 if (::rename ((*x).c_str(), newpath.c_str()) != 0) {
2654                         error << string_compose (_("cannot rename audio file source from %1 to %2 (%3)"),
2655                                           (*x), newpath, strerror (errno))
2656                               << endmsg;
2657                         goto out;
2658                 }
2659
2660                 /* see if there an easy to find peakfile for this file, and remove it.
2661                  */
2662
2663                 string peakpath = (*x).substr (0, (*x).find_last_of ('.'));
2664                 peakpath += peakfile_suffix;
2665
2666                 if (access (peakpath.c_str(), W_OK) == 0) {
2667                         if (::unlink (peakpath.c_str()) != 0) {
2668                                 error << string_compose (_("cannot remove peakfile %1 for %2 (%3)"),
2669                                                   peakpath, _path, strerror (errno))
2670                                       << endmsg;
2671                                 /* try to back out */
2672                                 rename (newpath.c_str(), _path.c_str());
2673                                 goto out;
2674                         }
2675                 }
2676         }
2677
2678         ret = 0;
2679
2680         /* dump the history list */
2681
2682         _history.clear ();
2683
2684         /* save state so we don't end up a session file
2685            referring to non-existent sources.
2686         */
2687
2688         save_state ("");
2689
2690   out:
2691         _state_of_the_state = (StateOfTheState) (_state_of_the_state & ~InCleanup);
2692
2693         return ret;
2694 }
2695
2696 int
2697 Session::cleanup_trash_sources (CleanupReport& rep)
2698 {
2699         // FIXME: needs adaptation for MIDI
2700
2701         vector<space_and_path>::iterator i;
2702         string dead_sound_dir;
2703         struct dirent* dentry;
2704         struct stat statbuf;
2705         DIR* dead;
2706
2707         rep.paths.clear ();
2708         rep.space = 0;
2709
2710         for (i = session_dirs.begin(); i != session_dirs.end(); ++i) {
2711
2712                 dead_sound_dir = (*i).path;
2713                 dead_sound_dir += dead_sound_dir_name;
2714
2715                 if ((dead = opendir (dead_sound_dir.c_str())) == 0) {
2716                         continue;
2717                 }
2718
2719                 while ((dentry = readdir (dead)) != 0) {
2720
2721                         /* avoid '.' and '..' */
2722
2723                         if ((dentry->d_name[0] == '.' && dentry->d_name[1] == '\0') ||
2724                             (dentry->d_name[2] == '\0' && dentry->d_name[0] == '.' && dentry->d_name[1] == '.')) {
2725                                 continue;
2726                         }
2727
2728                         string fullpath;
2729
2730                         fullpath = dead_sound_dir;
2731                         fullpath += '/';
2732                         fullpath += dentry->d_name;
2733
2734                         if (stat (fullpath.c_str(), &statbuf)) {
2735                                 continue;
2736                         }
2737
2738                         if (!S_ISREG (statbuf.st_mode)) {
2739                                 continue;
2740                         }
2741
2742                         if (unlink (fullpath.c_str())) {
2743                                 error << string_compose (_("cannot remove dead sound file %1 (%2)"),
2744                                                   fullpath, strerror (errno))
2745                                       << endmsg;
2746                         }
2747
2748                         rep.paths.push_back (dentry->d_name);
2749                         rep.space += statbuf.st_size;
2750                 }
2751
2752                 closedir (dead);
2753
2754         }
2755
2756         return 0;
2757 }
2758
2759 void
2760 Session::set_dirty ()
2761 {
2762         bool was_dirty = dirty();
2763
2764         _state_of_the_state = StateOfTheState (_state_of_the_state | Dirty);
2765
2766
2767         if (!was_dirty) {
2768                 DirtyChanged(); /* EMIT SIGNAL */
2769         }
2770 }
2771
2772
2773 void
2774 Session::set_clean ()
2775 {
2776         bool was_dirty = dirty();
2777
2778         _state_of_the_state = Clean;
2779
2780
2781         if (was_dirty) {
2782                 DirtyChanged(); /* EMIT SIGNAL */
2783         }
2784 }
2785
2786 void
2787 Session::set_deletion_in_progress ()
2788 {
2789         _state_of_the_state = StateOfTheState (_state_of_the_state | Deletion);
2790 }
2791
2792 void
2793 Session::clear_deletion_in_progress ()
2794 {
2795         _state_of_the_state = StateOfTheState (_state_of_the_state & (~Deletion));
2796 }
2797
2798 void
2799 Session::add_controllable (boost::shared_ptr<Controllable> c)
2800 {
2801         /* this adds a controllable to the list managed by the Session.
2802            this is a subset of those managed by the Controllable class
2803            itself, and represents the only ones whose state will be saved
2804            as part of the session.
2805         */
2806
2807         Glib::Mutex::Lock lm (controllables_lock);
2808         controllables.insert (c);
2809 }
2810
2811 struct null_deleter { void operator()(void const *) const {} };
2812
2813 void
2814 Session::remove_controllable (Controllable* c)
2815 {
2816         if (_state_of_the_state | Deletion) {
2817                 return;
2818         }
2819
2820         Glib::Mutex::Lock lm (controllables_lock);
2821
2822         Controllables::iterator x = controllables.find (boost::shared_ptr<Controllable>(c, null_deleter()));
2823
2824         if (x != controllables.end()) {
2825                 controllables.erase (x);
2826         }
2827 }
2828
2829 boost::shared_ptr<Controllable>
2830 Session::controllable_by_id (const PBD::ID& id)
2831 {
2832         Glib::Mutex::Lock lm (controllables_lock);
2833
2834         for (Controllables::iterator i = controllables.begin(); i != controllables.end(); ++i) {
2835                 if ((*i)->id() == id) {
2836                         return *i;
2837                 }
2838         }
2839
2840         return boost::shared_ptr<Controllable>();
2841 }
2842
2843 boost::shared_ptr<Controllable>
2844 Session::controllable_by_descriptor (const ControllableDescriptor& desc)
2845 {
2846         boost::shared_ptr<Controllable> c;
2847         boost::shared_ptr<Route> r;
2848
2849         switch (desc.top_level_type()) {
2850         case ControllableDescriptor::NamedRoute:
2851         {
2852                 std::string str = desc.top_level_name();
2853                 if (str == "master") {
2854                         r = _master_out;
2855                 } else if (str == "control" || str == "listen") {
2856                         r = _monitor_out;
2857                 } else {
2858                         r = route_by_name (desc.top_level_name());
2859                 }
2860                 break;
2861         }
2862
2863         case ControllableDescriptor::RemoteControlID:
2864                 r = route_by_remote_id (desc.rid());
2865                 break;
2866         }
2867         
2868         if (!r) {
2869                 return c;
2870         }
2871
2872         switch (desc.subtype()) {
2873         case ControllableDescriptor::Gain:
2874                 c = r->gain_control ();
2875                 break;
2876
2877         case ControllableDescriptor::Solo:
2878                 c = r->solo_control();
2879                 break;
2880
2881         case ControllableDescriptor::Mute:
2882                 c = r->mute_control();
2883                 break;
2884
2885         case ControllableDescriptor::Recenable:
2886         {
2887                 boost::shared_ptr<Track> t = boost::dynamic_pointer_cast<Track>(r);
2888                 
2889                 if (t) {
2890                         c = t->rec_enable_control ();
2891                 }
2892                 break;
2893         }
2894
2895         case ControllableDescriptor::Pan:
2896                 /* XXX pan control */
2897                 break;
2898
2899         case ControllableDescriptor::Balance:
2900                 /* XXX simple pan control */
2901                 break;
2902
2903         case ControllableDescriptor::PluginParameter:
2904         {
2905                 uint32_t plugin = desc.target (0);
2906                 uint32_t parameter_index = desc.target (1);
2907
2908                 /* revert to zero based counting */
2909                 
2910                 if (plugin > 0) {
2911                         --plugin;
2912                 }
2913                 
2914                 if (parameter_index > 0) {
2915                         --parameter_index;
2916                 }
2917
2918                 boost::shared_ptr<Processor> p = r->nth_plugin (plugin);
2919                 
2920                 if (p) {
2921                         c = boost::dynamic_pointer_cast<ARDOUR::AutomationControl>(
2922                                 p->control(Evoral::Parameter(PluginAutomation, 0, parameter_index)));
2923                 }
2924                 break;
2925         }
2926
2927         case ControllableDescriptor::SendGain: 
2928         {
2929                 uint32_t send = desc.target (0);
2930
2931                 /* revert to zero-based counting */
2932                 
2933                 if (send > 0) {
2934                         --send;
2935                 }
2936                 
2937                 boost::shared_ptr<Processor> p = r->nth_send (send);
2938                 
2939                 if (p) {
2940                         boost::shared_ptr<Send> s = boost::dynamic_pointer_cast<Send>(p);
2941                         boost::shared_ptr<Amp> a = s->amp();
2942
2943                         if (a) {
2944                                 c = s->amp()->gain_control();
2945                         }
2946                 }
2947                 break;
2948         }
2949
2950         default:
2951                 /* relax and return a null pointer */
2952                 break;
2953         }
2954
2955         return c;
2956 }
2957
2958 void
2959 Session::add_instant_xml (XMLNode& node, bool write_to_config)
2960 {
2961         if (_writable) {
2962                 Stateful::add_instant_xml (node, _path);
2963         }
2964
2965         if (write_to_config) {
2966                 Config->add_instant_xml (node);
2967         }
2968 }
2969
2970 XMLNode*
2971 Session::instant_xml (const string& node_name)
2972 {
2973         return Stateful::instant_xml (node_name, _path);
2974 }
2975
2976 int
2977 Session::save_history (string snapshot_name)
2978 {
2979         XMLTree tree;
2980
2981         if (!_writable) {
2982                 return 0;
2983         }
2984
2985         if (snapshot_name.empty()) {
2986                 snapshot_name = _current_snapshot_name;
2987         }
2988
2989         const string history_filename = legalize_for_path (snapshot_name) + history_suffix;
2990         const string backup_filename = history_filename + backup_suffix;
2991         const sys::path xml_path = _session_dir->root_path() / history_filename;
2992         const sys::path backup_path = _session_dir->root_path() / backup_filename;
2993
2994         if (sys::exists (xml_path)) {
2995                 try
2996                 {
2997                         sys::rename (xml_path, backup_path);
2998                 }
2999                 catch (const sys::filesystem_error& err)
3000                 {
3001                         error << _("could not backup old history file, current history not saved") << endmsg;
3002                         return -1;
3003                 }
3004         }
3005
3006         if (!Config->get_save_history() || Config->get_saved_history_depth() < 0) {
3007                 return 0;
3008         }
3009
3010         tree.set_root (&_history.get_state (Config->get_saved_history_depth()));
3011
3012         if (!tree.write (xml_path.to_string()))
3013         {
3014                 error << string_compose (_("history could not be saved to %1"), xml_path.to_string()) << endmsg;
3015
3016                 try
3017                 {
3018                         sys::remove (xml_path);
3019                         sys::rename (backup_path, xml_path);
3020                 }
3021                 catch (const sys::filesystem_error& err)
3022                 {
3023                         error << string_compose (_("could not restore history file from backup %1 (%2)"),
3024                                         backup_path.to_string(), err.what()) << endmsg;
3025                 }
3026
3027                 return -1;
3028         }
3029
3030         return 0;
3031 }
3032
3033 int
3034 Session::restore_history (string snapshot_name)
3035 {
3036         XMLTree tree;
3037
3038         if (snapshot_name.empty()) {
3039                 snapshot_name = _current_snapshot_name;
3040         }
3041
3042         const string xml_filename = legalize_for_path (snapshot_name) + history_suffix;
3043         const sys::path xml_path = _session_dir->root_path() / xml_filename;
3044
3045         info << "Loading history from " << xml_path.to_string() << endmsg;
3046
3047         if (!sys::exists (xml_path)) {
3048                 info << string_compose (_("%1: no history file \"%2\" for this session."),
3049                                 _name, xml_path.to_string()) << endmsg;
3050                 return 1;
3051         }
3052
3053         if (!tree.read (xml_path.to_string())) {
3054                 error << string_compose (_("Could not understand session history file \"%1\""),
3055                                 xml_path.to_string()) << endmsg;
3056                 return -1;
3057         }
3058
3059         // replace history
3060         _history.clear();
3061
3062         for (XMLNodeConstIterator it  = tree.root()->children().begin(); it != tree.root()->children().end(); it++) {
3063
3064                 XMLNode *t = *it;
3065                 UndoTransaction* ut = new UndoTransaction ();
3066                 struct timeval tv;
3067
3068                 ut->set_name(t->property("name")->value());
3069                 stringstream ss(t->property("tv-sec")->value());
3070                 ss >> tv.tv_sec;
3071                 ss.str(t->property("tv-usec")->value());
3072                 ss >> tv.tv_usec;
3073                 ut->set_timestamp(tv);
3074
3075                 for (XMLNodeConstIterator child_it  = t->children().begin();
3076                                 child_it != t->children().end(); child_it++)
3077                 {
3078                         XMLNode *n = *child_it;
3079                         Command *c;
3080
3081                         if (n->name() == "MementoCommand" ||
3082                                         n->name() == "MementoUndoCommand" ||
3083                                         n->name() == "MementoRedoCommand") {
3084
3085                                 if ((c = memento_command_factory(n))) {
3086                                         ut->add_command(c);
3087                                 }
3088
3089                         } else if (n->name() == "DiffCommand") {
3090                                 PBD::ID  id(n->property("midi-source")->value());
3091                                 boost::shared_ptr<MidiSource> midi_source =
3092                                         boost::dynamic_pointer_cast<MidiSource, Source>(source_by_id(id));
3093                                 if (midi_source) {
3094                                         ut->add_command(new MidiModel::DiffCommand(midi_source->model(), *n));
3095                                 } else {
3096                                         error << _("Failed to downcast MidiSource for DiffCommand") << endmsg;
3097                                 }
3098
3099                         } else if (n->name() == "StatefulDiffCommand") {
3100                                 if ((c = stateful_diff_command_factory (n))) {
3101                                         ut->add_command (c);
3102                                 }
3103                         } else {
3104                                 error << string_compose(_("Couldn't figure out how to make a Command out of a %1 XMLNode."), n->name()) << endmsg;
3105                         }
3106                 }
3107
3108                 _history.add (ut);
3109         }
3110
3111         return 0;
3112 }
3113
3114 void
3115 Session::config_changed (std::string p, bool ours)
3116 {
3117         if (ours) {
3118                 set_dirty ();
3119         }
3120
3121         if (p == "seamless-loop") {
3122
3123         } else if (p == "rf-speed") {
3124
3125         } else if (p == "auto-loop") {
3126
3127         } else if (p == "auto-input") {
3128
3129                 if (Config->get_monitoring_model() == HardwareMonitoring && transport_rolling()) {
3130                         /* auto-input only makes a difference if we're rolling */
3131
3132                         boost::shared_ptr<RouteList> rl = routes.reader ();
3133                         for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
3134                                 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
3135                                 if (tr && tr->record_enabled ()) {
3136                                         tr->monitor_input (!config.get_auto_input());
3137                                 }
3138                         }
3139                 }
3140
3141         } else if (p == "punch-in") {
3142
3143                 Location* location;
3144
3145                 if ((location = _locations.auto_punch_location()) != 0) {
3146
3147                         if (config.get_punch_in ()) {
3148                                 replace_event (SessionEvent::PunchIn, location->start());
3149                         } else {
3150                                 remove_event (location->start(), SessionEvent::PunchIn);
3151                         }
3152                 }
3153
3154         } else if (p == "punch-out") {
3155
3156                 Location* location;
3157
3158                 if ((location = _locations.auto_punch_location()) != 0) {
3159
3160                         if (config.get_punch_out()) {
3161                                 replace_event (SessionEvent::PunchOut, location->end());
3162                         } else {
3163                                 clear_events (SessionEvent::PunchOut);
3164                         }
3165                 }
3166
3167         } else if (p == "edit-mode") {
3168
3169                 Glib::Mutex::Lock lm (playlists->lock);
3170
3171                 for (SessionPlaylists::List::iterator i = playlists->playlists.begin(); i != playlists->playlists.end(); ++i) {
3172                         (*i)->set_edit_mode (Config->get_edit_mode ());
3173                 }
3174
3175         } else if (p == "use-video-sync") {
3176
3177                 waiting_for_sync_offset = config.get_use_video_sync();
3178
3179         } else if (p == "mmc-control") {
3180
3181                 //poke_midi_thread ();
3182
3183         } else if (p == "mmc-device-id" || p == "mmc-receive-id") {
3184
3185                 _mmc->set_receive_device_id (Config->get_mmc_receive_device_id());
3186
3187         } else if (p == "mmc-send-id") {
3188
3189                 _mmc->set_send_device_id (Config->get_mmc_send_device_id());
3190
3191         } else if (p == "midi-control") {
3192
3193                 //poke_midi_thread ();
3194
3195         } else if (p == "raid-path") {
3196
3197                 setup_raid_path (config.get_raid_path());
3198
3199         } else if (p == "timecode-format") {
3200
3201                 sync_time_vars ();
3202
3203         } else if (p == "video-pullup") {
3204
3205                 sync_time_vars ();
3206
3207         } else if (p == "seamless-loop") {
3208
3209                 if (play_loop && transport_rolling()) {
3210                         // to reset diskstreams etc
3211                         request_play_loop (true);
3212                 }
3213
3214         } else if (p == "rf-speed") {
3215
3216                 cumulative_rf_motion = 0;
3217                 reset_rf_scale (0);
3218
3219         } else if (p == "click-sound") {
3220
3221                 setup_click_sounds (1);
3222
3223         } else if (p == "click-emphasis-sound") {
3224
3225                 setup_click_sounds (-1);
3226
3227         } else if (p == "clicking") {
3228
3229                 if (Config->get_clicking()) {
3230                         if (_click_io && click_data) { // don't require emphasis data
3231                                 _clicking = true;
3232                         }
3233                 } else {
3234                         _clicking = false;
3235                 }
3236
3237         } else if (p == "send-mtc") {
3238
3239                 /* only set the internal flag if we have
3240                    a port.
3241                 */
3242
3243                 if (_mtc_port != 0) {
3244                         session_send_mtc = Config->get_send_mtc();
3245                         if (session_send_mtc) {
3246                                 /* mark us ready to send */
3247                                 next_quarter_frame_to_send = 0;
3248                         }
3249                 } else {
3250                         session_send_mtc = false;
3251                 }
3252
3253         } else if (p == "send-mmc") {
3254
3255                 _mmc->enable_send (Config->get_send_mmc ());
3256
3257         } else if (p == "midi-feedback") {
3258
3259                 /* only set the internal flag if we have
3260                    a port.
3261                 */
3262
3263                 if (_mtc_port != 0) {
3264                         session_midi_feedback = Config->get_midi_feedback();
3265                 }
3266
3267         } else if (p == "jack-time-master") {
3268
3269                 engine().reset_timebase ();
3270
3271         } else if (p == "native-file-header-format") {
3272
3273                 if (!first_file_header_format_reset) {
3274                         reset_native_file_format ();
3275                 }
3276
3277                 first_file_header_format_reset = false;
3278
3279         } else if (p == "native-file-data-format") {
3280
3281                 if (!first_file_data_format_reset) {
3282                         reset_native_file_format ();
3283                 }
3284
3285                 first_file_data_format_reset = false;
3286
3287         } else if (p == "external-sync") {
3288                 if (!config.get_external_sync()) {
3289                         drop_sync_source ();
3290                 } else {
3291                         switch_to_sync_source (config.get_sync_source());
3292                 }
3293         } else if (p == "remote-model") {
3294                 set_remote_control_ids ();
3295         }  else if (p == "denormal-model") {
3296                 setup_fpu ();
3297         } else if (p == "history-depth") {
3298                 set_history_depth (Config->get_history_depth());
3299         } else if (p == "sync-all-route-ordering") {
3300                 sync_order_keys ("session");
3301         } else if (p == "initial-program-change") {
3302
3303                 if (_mmc->port() && Config->get_initial_program_change() >= 0) {
3304                         MIDI::byte buf[2];
3305
3306                         buf[0] = MIDI::program; // channel zero by default
3307                         buf[1] = (Config->get_initial_program_change() & 0x7f);
3308
3309                         _mmc->port()->midimsg (buf, sizeof (buf), 0);
3310                 }
3311         } else if (p == "initial-program-change") {
3312
3313                 if (_mmc->port() && Config->get_initial_program_change() >= 0) {
3314                         MIDI::byte* buf = new MIDI::byte[2];
3315
3316                         buf[0] = MIDI::program; // channel zero by default
3317                         buf[1] = (Config->get_initial_program_change() & 0x7f);
3318                         // deliver_midi (_mmc_port, buf, 2);
3319                 }
3320         } else if (p == "solo-mute-override") {
3321                 // catch_up_on_solo_mute_override ();
3322         } else if (p == "listen-position") {
3323                 listen_position_changed ();
3324         } else if (p == "solo-control-is-listen-control") {
3325                 solo_control_mode_changed ();
3326         }
3327
3328
3329         set_dirty ();
3330 }
3331
3332 void
3333 Session::set_history_depth (uint32_t d)
3334 {
3335         _history.set_depth (d);
3336 }
3337
3338 int
3339 Session::load_diskstreams_2X (XMLNode const & node, int)
3340 {
3341         XMLNodeList          clist;
3342         XMLNodeConstIterator citer;
3343
3344         clist = node.children();
3345
3346         for (citer = clist.begin(); citer != clist.end(); ++citer) {
3347
3348                 try {
3349                         /* diskstreams added automatically by DiskstreamCreated handler */
3350                         if ((*citer)->name() == "AudioDiskstream" || (*citer)->name() == "DiskStream") {
3351                                 boost::shared_ptr<AudioDiskstream> dsp (new AudioDiskstream (*this, **citer));
3352                                 _diskstreams_2X.push_back (dsp);
3353                         } else {
3354                                 error << _("Session: unknown diskstream type in XML") << endmsg;
3355                         }
3356                 }
3357
3358                 catch (failed_constructor& err) {
3359                         error << _("Session: could not load diskstream via XML state") << endmsg;
3360                         return -1;
3361                 }
3362         }
3363
3364         return 0;
3365 }
3366
3367 /** Create our MachineControl object and connect things to it */
3368 void
3369 Session::setup_midi_machine_control ()
3370 {
3371         _mmc = new MIDI::MachineControl;
3372         _mmc->set_port (default_mmc_port);
3373
3374         _mmc->Play.connect_same_thread (*this, boost::bind (&Session::mmc_deferred_play, this, _1));
3375         _mmc->DeferredPlay.connect_same_thread (*this, boost::bind (&Session::mmc_deferred_play, this, _1));
3376         _mmc->Stop.connect_same_thread (*this, boost::bind (&Session::mmc_stop, this, _1));
3377         _mmc->FastForward.connect_same_thread (*this, boost::bind (&Session::mmc_fast_forward, this, _1));
3378         _mmc->Rewind.connect_same_thread (*this, boost::bind (&Session::mmc_rewind, this, _1));
3379         _mmc->Pause.connect_same_thread (*this, boost::bind (&Session::mmc_pause, this, _1));
3380         _mmc->RecordPause.connect_same_thread (*this, boost::bind (&Session::mmc_record_pause, this, _1));
3381         _mmc->RecordStrobe.connect_same_thread (*this, boost::bind (&Session::mmc_record_strobe, this, _1));
3382         _mmc->RecordExit.connect_same_thread (*this, boost::bind (&Session::mmc_record_exit, this, _1));
3383         _mmc->Locate.connect_same_thread (*this, boost::bind (&Session::mmc_locate, this, _1, _2));
3384         _mmc->Step.connect_same_thread (*this, boost::bind (&Session::mmc_step, this, _1, _2));
3385         _mmc->Shuttle.connect_same_thread (*this, boost::bind (&Session::mmc_shuttle, this, _1, _2, _3));
3386         _mmc->TrackRecordStatusChange.connect_same_thread (*this, boost::bind (&Session::mmc_record_enable, this, _1, _2, _3));
3387
3388         /* also handle MIDI SPP because its so common */
3389
3390         _mmc->port()->input()->start.connect_same_thread (*this, boost::bind (&Session::spp_start, this, _1, _2));
3391         _mmc->port()->input()->contineu.connect_same_thread (*this, boost::bind (&Session::spp_continue, this, _1, _2));
3392         _mmc->port()->input()->stop.connect_same_thread (*this, boost::bind (&Session::spp_stop, this, _1, _2));
3393 }