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