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