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