latched rec-enable
[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   $Id$
19 */
20
21 #include <algorithm>
22 #include <fstream>
23 #include <string>
24 #include <cerrno>
25
26 #include <sigc++/bind.h>
27
28 #include <cstdio> /* snprintf(3) ... grrr */
29 #include <cmath>
30 #include <unistd.h>
31 #include <sys/stat.h>
32 #include <climits>
33 #include <fcntl.h>
34 #include <poll.h>
35 #include <signal.h>
36 #include <sys/mman.h>
37 #include <sys/time.h>
38 #include <dirent.h>
39
40 #ifdef HAVE_SYS_VFS_H
41 #include <sys/vfs.h>
42 #else
43 #include <sys/mount.h>
44 #include <sys/param.h>
45 #endif
46
47 #include <midi++/mmc.h>
48 #include <midi++/port.h>
49 #include <pbd/error.h>
50 #include <pbd/dirname.h>
51 #include <pbd/lockmonitor.h>
52 #include <pbd/pathscanner.h>
53 #include <pbd/pthread_utils.h>
54 #include <pbd/basename.h>
55 #include <pbd/strsplit.h>
56
57 #include <ardour/audioengine.h>
58 #include <ardour/configuration.h>
59 #include <ardour/session.h>
60 #include <ardour/diskstream.h>
61 #include <ardour/utils.h>
62 #include <ardour/audioplaylist.h>
63 #include <ardour/source.h>
64 #include <ardour/filesource.h>
65 #include <ardour/sndfilesource.h>
66 #include <ardour/sndfile_helpers.h>
67 #include <ardour/auditioner.h>
68 #include <ardour/export.h>
69 #include <ardour/redirect.h>
70 #include <ardour/send.h>
71 #include <ardour/insert.h>
72 #include <ardour/connection.h>
73 #include <ardour/slave.h>
74 #include <ardour/tempo.h>
75 #include <ardour/audio_track.h>
76 #include <ardour/cycle_timer.h>
77 #include <ardour/utils.h>
78 #include <ardour/named_selection.h>
79 #include <ardour/version.h>
80 #include <ardour/location.h>
81 #include <ardour/audioregion.h>
82 #include <ardour/crossfade.h>
83
84 #include "i18n.h"
85 #include <locale.h>
86
87 using namespace std;
88 using namespace ARDOUR;
89
90 void
91 Session::first_stage_init (string fullpath, string snapshot_name)
92 {
93         if (fullpath.length() == 0) {
94                 throw failed_constructor();
95         }
96
97         char buf[PATH_MAX+1];
98         if (!realpath(fullpath.c_str(), buf) && (errno != ENOENT)) {
99                 error << string_compose(_("Could not use path %1 (%s)"), buf, strerror(errno)) << endmsg;
100                 throw failed_constructor();
101         }
102         _path = string(buf);
103
104         if (_path[_path.length()-1] != '/') {
105                 _path += '/';
106         }
107
108         /* these two are just provisional settings. set_state()
109            will likely override them.
110         */
111
112         _name = _current_snapshot_name = snapshot_name;
113         setup_raid_path (_path);
114
115         _current_frame_rate = _engine.frame_rate ();
116         _tempo_map = new TempoMap (_current_frame_rate);
117         _tempo_map->StateChanged.connect (mem_fun (*this, &Session::tempo_map_changed));
118
119         atomic_set (&processing_prohibited, 0);
120         send_cnt = 0;
121         insert_cnt = 0;
122         _transport_speed = 0;
123         _last_transport_speed = 0;
124         transport_sub_state = 0;
125         _transport_frame = 0;
126         last_stop_frame = 0;
127         end_location = new Location (0, 0, _("end"), Location::Flags ((Location::IsMark|Location::IsEnd)));
128         _end_location_is_free = true;
129         atomic_set (&_record_status, Disabled);
130         auto_play = false;
131         punch_in = false;
132         punch_out = false;
133         auto_loop = false;
134         seamless_loop = false;
135         loop_changing = false;
136         auto_input = true;
137         crossfades_active = false;
138         all_safe = false;
139         auto_return = false;
140         _last_roll_location = 0;
141         _last_record_location = 0;
142         pending_locate_frame = 0;
143         pending_locate_roll = false;
144         pending_locate_flush = false;
145         dstream_buffer_size = 0;
146         state_tree = 0;
147         state_was_pending = false;
148         set_next_event ();
149         outbound_mtc_smpte_frame = 0;
150         next_quarter_frame_to_send = -1;
151         current_block_size = 0;
152         _solo_latched = true;
153         _solo_model = InverseMute;
154         solo_update_disabled = false;
155         currently_soloing = false;
156         _worst_output_latency = 0;
157         _worst_input_latency = 0;
158         _worst_track_latency = 0;
159         _state_of_the_state = StateOfTheState(CannotSave|InitialConnecting|Loading);
160         _slave = 0;
161         _slave_type = None;
162         butler_mixdown_buffer = 0;
163         butler_gain_buffer = 0;
164         auditioner = 0;
165         mmc_control = false;
166         midi_feedback = false;
167         midi_control = true;
168         mmc = 0;
169         post_transport_work = PostTransportWork (0);
170         atomic_set (&butler_should_do_transport_work, 0);
171         atomic_set (&butler_active, 0);
172         atomic_set (&_playback_load, 100);
173         atomic_set (&_capture_load, 100);
174         atomic_set (&_playback_load_min, 100);
175         atomic_set (&_capture_load_min, 100);
176         pending_audition_region = 0;
177         _edit_mode = Slide;
178         pending_edit_mode = _edit_mode;
179         _play_range = false;
180         _control_out = 0;
181         _master_out = 0;
182         input_auto_connect = AutoConnectOption (0);
183         output_auto_connect = AutoConnectOption (0);
184         _have_captured = false;
185         waiting_to_start = false;
186         _exporting = false;
187         _gain_automation_buffer = 0;
188         _pan_automation_buffer = 0;
189         _npan_buffers = 0;
190         pending_abort = false;
191         layer_model = MoveAddHigher;
192         xfade_model = ShortCrossfade;
193         
194         /* default short fade = 15ms */
195
196         Crossfade::set_short_xfade_length ((jack_nframes_t) floor ((15.0 * frame_rate()) / 1000.0));
197
198         last_mmc_step.tv_sec = 0;
199         last_mmc_step.tv_usec = 0;
200         step_speed = 0.0;
201
202         preroll.type = AnyTime::Frames;
203         preroll.frames = 0;
204         postroll.type = AnyTime::Frames;
205         postroll.frames = 0;
206
207         /* click sounds are unset by default, which causes us to internal
208            waveforms for clicks.
209         */
210         
211         _click_io = 0;
212         _clicking = false;
213         click_requested = false;
214         click_data = 0;
215         click_emphasis_data = 0;
216         click_length = 0;
217         click_emphasis_length = 0;
218
219         process_function = &Session::process_with_events;
220
221         last_smpte_when = 0;
222         _smpte_offset = 0;
223         _smpte_offset_negative = true;
224         last_smpte_valid = false;
225
226         last_rr_session_dir = session_dirs.begin();
227         refresh_disk_space ();
228
229         // set_default_fade (0.2, 5.0); /* steepness, millisecs */
230
231         /* default configuration */
232
233         do_not_record_plugins = false;
234         over_length_short = 2;
235         over_length_long = 10;
236         send_midi_timecode = false;
237         send_midi_machine_control = false;
238         shuttle_speed_factor = 1.0;
239         shuttle_speed_threshold = 5;
240         rf_speed = 2.0;
241         _meter_hold = 100; // XXX unknown units: number of calls to meter::set()
242         _meter_falloff = 1.5f; // XXX unknown units: refresh_rate
243         max_level = 0;
244         min_level = 0;
245
246         /* slave stuff */
247
248         average_slave_delta = 1800;
249         have_first_delta_accumulator = false;
250         delta_accumulator_cnt = 0;
251         slave_state = Stopped;
252
253         /* default SMPTE type is 30 FPS, non-drop */
254
255         set_smpte_type (30.0, false);
256
257         _engine.GraphReordered.connect (mem_fun (*this, &Session::graph_reordered));
258
259         /* These are all static "per-class" signals */
260
261         Region::CheckNewRegion.connect (mem_fun (*this, &Session::add_region));
262         Source::SourceCreated.connect (mem_fun (*this, &Session::add_source));
263         Playlist::PlaylistCreated.connect (mem_fun (*this, &Session::add_playlist));
264         Redirect::RedirectCreated.connect (mem_fun (*this, &Session::add_redirect));
265         DiskStream::DiskStreamCreated.connect (mem_fun (*this, &Session::add_diskstream));
266         NamedSelection::NamedSelectionCreated.connect (mem_fun (*this, &Session::add_named_selection));
267
268         IO::MoreOutputs.connect (mem_fun (*this, &Session::ensure_passthru_buffers));
269
270         /* stop IO objects from doing stuff until we're ready for them */
271
272         IO::disable_panners ();
273         IO::disable_ports ();
274         IO::disable_connecting ();
275 }
276
277 int
278 Session::second_stage_init (bool new_session)
279 {
280         SndFileSource::set_peak_dir (peak_dir());
281
282         if (!new_session) {
283                 if (load_state (_current_snapshot_name)) {
284                         return -1;
285                 }
286                 remove_empty_sounds ();
287         }
288
289         if (start_butler_thread()) {
290                 return -1;
291         }
292
293         if (start_midi_thread ()) {
294                 return -1;
295         }
296
297         if (init_feedback ()) {
298                 return -1;
299         }
300
301         if (state_tree) {
302                 if (set_state (*state_tree->root())) {
303                         return -1;
304                 }
305         }
306
307         /* we can't save till after ::when_engine_running() is called,
308            because otherwise we save state with no connections made.
309            therefore, we reset _state_of_the_state because ::set_state()
310            will have cleared it.
311
312            we also have to include Loading so that any events that get
313            generated between here and the end of ::when_engine_running()
314            will be processed directly rather than queued.
315         */
316
317         _state_of_the_state = StateOfTheState (_state_of_the_state|CannotSave|Loading);
318
319         // set_auto_input (true);
320         _locations.changed.connect (mem_fun (this, &Session::locations_changed));
321         _locations.added.connect (mem_fun (this, &Session::locations_added));
322         setup_click_sounds (0);
323         setup_midi_control ();
324
325         /* Pay attention ... */
326
327         _engine.Halted.connect (mem_fun (*this, &Session::engine_halted));
328         _engine.Xrun.connect (mem_fun (*this, &Session::xrun_recovery));
329
330         if (_engine.running()) {
331                 when_engine_running();
332         } else {
333                 first_time_running = _engine.Running.connect (mem_fun (*this, &Session::when_engine_running));
334         }
335
336         send_full_time_code ();
337         _engine.transport_locate (0);
338         deliver_mmc (MIDI::MachineControl::cmdMmcReset, 0);
339         deliver_mmc (MIDI::MachineControl::cmdLocate, 0);
340         send_all_midi_feedback();
341
342         if (new_session) {
343                 _end_location_is_free = true;
344         } else {
345                 _end_location_is_free = false;
346         }
347         
348         return 0;
349 }
350
351 string
352 Session::raid_path () const
353 {
354         string path;
355
356         for (vector<space_and_path>::const_iterator i = session_dirs.begin(); i != session_dirs.end(); ++i) {
357                 path += (*i).path;
358                 path += ':';
359         }
360         
361         return path.substr (0, path.length() - 1); // drop final colon
362 }
363
364 void
365 Session::set_raid_path (string path)
366 {
367         /* public-access to setup_raid_path() */
368
369         setup_raid_path (path);
370 }
371
372 void
373 Session::setup_raid_path (string path)
374 {
375         string::size_type colon;
376         string remaining;
377         space_and_path sp;
378         string fspath;
379         string::size_type len = path.length();
380         int colons;
381
382         colons = 0;
383
384         if (path.length() == 0) {
385                 return;
386         }
387
388         session_dirs.clear ();
389
390         for (string::size_type n = 0; n < len; ++n) {
391                 if (path[n] == ':') {
392                         colons++;
393                 }
394         }
395
396         if (colons == 0) {
397
398                 /* no multiple search path, just one directory (common case) */
399
400                 sp.path = path;
401                 sp.blocks = 0;
402                 session_dirs.push_back (sp);
403                 
404                 FileSource::set_search_path (path + sound_dir_name);
405
406                 return;
407         }
408
409         remaining = path;
410
411         while ((colon = remaining.find_first_of (':')) != string::npos) {
412                 
413                 sp.blocks = 0;
414                 sp.path = remaining.substr (0, colon);
415
416                 fspath += sp.path;
417                 if (fspath[fspath.length()-1] != '/') {
418                         fspath += '/';
419                 }
420                 fspath += sound_dir_name;
421                 fspath += ':';
422
423                 session_dirs.push_back (sp);
424
425                 remaining = remaining.substr (colon+1);
426         }
427
428         if (remaining.length()) {
429
430                 sp.blocks = 0;
431                 sp.path = remaining;
432
433                 fspath += sp.path;
434                 if (fspath[fspath.length()-1] != '/') {
435                         fspath += '/';
436                 }
437                 fspath += sound_dir_name;
438
439                 session_dirs.push_back (sp);
440         }
441
442         /* set the FileSource search path */
443
444         FileSource::set_search_path (fspath);
445
446         /* reset the round-robin soundfile path thingie */
447
448         last_rr_session_dir = session_dirs.begin();
449 }
450
451 int
452 Session::create (bool& new_session, string* mix_template, jack_nframes_t initial_length)
453 {
454         string dir;
455         
456         if (mkdir (_path.c_str(), 0755) < 0) {
457                 if (errno == EEXIST) {
458                         new_session = false;
459                 } else {
460                         error << string_compose(_("Session: cannot create session dir \"%1\" (%2)"), _path, strerror (errno)) << endmsg;
461                         return -1;
462                 }
463         } else {
464                 new_session = true;
465         }
466
467         dir = peak_dir ();
468
469         if (mkdir (dir.c_str(), 0755) < 0) {
470                 if (errno != EEXIST) {
471                         error << string_compose(_("Session: cannot create session peakfile dir \"%1\" (%2)"), dir, strerror (errno)) << endmsg;
472                         return -1;
473                 }
474         }
475
476         dir = sound_dir ();
477
478         if (mkdir (dir.c_str(), 0755) < 0) {
479                 if (errno != EEXIST) {
480                         error << string_compose(_("Session: cannot create session sounds dir \"%1\" (%2)"), dir, strerror (errno)) << endmsg;
481                         return -1;
482                 }
483         }
484
485         dir = dead_sound_dir ();
486
487         if (mkdir (dir.c_str(), 0755) < 0) {
488                 if (errno != EEXIST) {
489                         error << string_compose(_("Session: cannot create session dead sounds dir \"%1\" (%2)"), dir, strerror (errno)) << endmsg;
490                         return -1;
491                 }
492         }
493
494         dir = automation_dir ();
495
496         if (mkdir (dir.c_str(), 0755) < 0) {
497                 if (errno != EEXIST) {
498                         error << string_compose(_("Session: cannot create session automation dir \"%1\" (%2)"), dir, strerror (errno)) << endmsg;
499                         return -1;
500                 }
501         }
502
503         
504         /* check new_session so we don't overwrite an existing one */
505         
506         if (mix_template) {
507                 if (new_session){
508
509                         string lookfor = "^";
510                         lookfor += *mix_template;
511                         lookfor += _template_suffix;
512                         lookfor += '$';
513
514                         PathScanner scanner;
515                         string tpath = template_path();
516                         string in_path;
517                         string out_path;
518
519                         vector<string*>* result= scanner (tpath, lookfor, false, true);
520
521                         if (result == 0) {
522                                 error << string_compose (_("Could not find a template called %1 in %2"), *mix_template, tpath)
523                                       << endmsg;
524                                 *mix_template = "";
525                         }
526
527                         if (result->size() == 0) {
528                                 delete result;
529                                 error << string_compose (_("Could not find a template called %1 in %2"), *mix_template, tpath)
530                                       << endmsg;
531                                 *mix_template = "";
532                         }
533
534                         in_path = *(result->front());
535
536                         ifstream in(in_path.c_str());
537                         
538                         if (in){
539                                 string out_path = _path;
540                                 out_path += _name;
541                                 out_path += _statefile_suffix;
542                                 
543                                 ofstream out(out_path.c_str());
544
545                                 if (out){
546                                         out << in.rdbuf();
547                                         
548                                         // okay, session is set up.  Treat like normal saved
549                                         // session from now on.
550                                         
551                                         new_session = false;
552                                         return 0;
553                                         
554                                 } else {
555                                         error << string_compose (_("Could not open %1 for writing mix template"), out_path) 
556                                               << endmsg;
557                                         return -1;
558                                 }
559                                 
560                         } else {
561                                 error << string_compose (_("Could not open mix template %1 for reading"), in_path) 
562                                       << endmsg;
563                                 return -1;
564                         }
565                         
566                         
567                 } else {
568                         warning << _("Session already exists.  Not overwriting") << endmsg;
569                         return -1;
570                 }
571         }
572
573         if (new_session) {
574
575                 /* set an initial end point */
576
577                 end_location->set_end (initial_length);
578                 _locations.add (end_location);
579
580                 _state_of_the_state = Clean;
581
582                 if (save_state (_current_snapshot_name)) {
583                         return -1;
584                 }
585         }
586
587         return 0;
588 }
589
590 int
591 Session::load_diskstreams (const XMLNode& node)
592 {
593         XMLNodeList          clist;
594         XMLNodeConstIterator citer;
595         
596         clist = node.children();
597
598         for (citer = clist.begin(); citer != clist.end(); ++citer) {
599                 
600                 DiskStream* dstream;
601
602                 try {
603                         dstream = new DiskStream (*this, **citer);
604                         /* added automatically by DiskStreamCreated handler */
605                 } 
606                 
607                 catch (failed_constructor& err) {
608                         error << _("Session: could not load diskstream via XML state")                        << endmsg;
609                         return -1;
610                 }
611         }
612
613         return 0;
614 }
615
616 void
617 Session::remove_pending_capture_state ()
618 {
619         string xml_path;
620
621         xml_path = _path;
622         xml_path += _current_snapshot_name;
623         xml_path += _pending_suffix;
624
625         unlink (xml_path.c_str());
626 }
627
628 int
629 Session::save_state (string snapshot_name, bool pending)
630 {
631         XMLTree tree;
632         string xml_path;
633         string bak_path;
634
635         if (_state_of_the_state & CannotSave) {
636                 return 1;
637         }
638
639         tree.set_root (&get_state());
640
641         if (snapshot_name.empty()) {
642                 snapshot_name = _current_snapshot_name;
643         }
644
645         if (!pending) {
646
647                 xml_path = _path;
648                 xml_path += snapshot_name;
649                 xml_path += _statefile_suffix;
650                 bak_path = xml_path;
651                 bak_path += ".bak";
652                 
653                 // Make backup of state file
654                 
655                 if ((access (xml_path.c_str(), F_OK) == 0) &&
656                     (rename(xml_path.c_str(), bak_path.c_str()))) {
657                         error << _("could not backup old state file, current state not saved.") << endmsg;
658                         return -1;
659                 }
660
661         } else {
662
663                 xml_path = _path;
664                 xml_path += snapshot_name;
665                 xml_path += _pending_suffix;
666
667         }
668
669         if (!tree.write (xml_path)) {
670                 error << string_compose (_("state could not be saved to %1"), xml_path) << endmsg;
671
672                 /* don't leave a corrupt file lying around if it is
673                    possible to fix.
674                 */
675
676                 if (unlink (xml_path.c_str())) {
677                         error << string_compose (_("could not remove corrupt state file %1"), xml_path) << endmsg;
678                 } else {
679                         if (!pending) {
680                                 if (rename (bak_path.c_str(), xml_path.c_str())) {
681                                         error << string_compose (_("could not restore state file from backup %1"), bak_path) << endmsg;
682                                 }
683                         }
684                 }
685
686                 return -1;
687         }
688
689         if (!pending) {
690
691                 bool was_dirty = dirty();
692                 
693                 _state_of_the_state = StateOfTheState (_state_of_the_state & ~Dirty);
694                 
695                 if (was_dirty) {
696                         DirtyChanged (); /* EMIT SIGNAL */
697                 }
698                 
699                 StateSaved (snapshot_name); /* EMIT SIGNAL */
700         }
701
702         return 0;
703 }
704
705 int
706 Session::restore_state (string snapshot_name)
707 {
708         if (load_state (snapshot_name) == 0) {
709                 set_state (*state_tree->root());
710         }
711         
712         return 0;
713 }
714
715 int
716 Session::load_state (string snapshot_name)
717 {
718         if (state_tree) {
719                 delete state_tree;
720                 state_tree = 0;
721         }
722
723         string xmlpath;
724         
725         state_was_pending = false;
726
727         /* check for leftover pending state from a crashed capture attempt */
728
729         xmlpath = _path;
730         xmlpath += snapshot_name;
731         xmlpath += _pending_suffix;
732
733         if (!access (xmlpath.c_str(), F_OK)) {
734
735                 /* there is pending state from a crashed capture attempt */
736
737                 if (AskAboutPendingState()) {
738                         state_was_pending = true;
739                 } 
740         } 
741
742         if (!state_was_pending) {
743
744                 xmlpath = _path;
745                 xmlpath += snapshot_name;
746                 xmlpath += _statefile_suffix;
747         }
748
749         if (access (xmlpath.c_str(), F_OK)) {
750                 error << string_compose(_("%1: session state information file \"%2\" doesn't exist!"), _name, xmlpath) << endmsg;
751                 return 1;
752         }
753
754         state_tree = new XMLTree;
755
756         set_dirty();
757
758         if (state_tree->read (xmlpath)) {
759                 return 0;
760         } else {
761                 error << string_compose(_("Could not understand ardour file %1"), xmlpath) << endmsg;
762         }
763
764         delete state_tree;
765         state_tree = 0;
766         return -1;
767 }
768
769 int
770 Session::load_options (const XMLNode& node)
771 {
772         XMLNode* child;
773         XMLProperty* prop;
774         bool have_fade_msecs = false;
775         bool have_fade_steepness = false;
776         float fade_msecs = 0;
777         float fade_steepness = 0;
778         SlaveSource slave_src = None;
779         int x;
780         LocaleGuard lg (X_("POSIX"));
781         
782         if ((child = find_named_node (node, "input-auto-connect")) != 0) {
783                 if ((prop = child->property ("val")) != 0) {
784                         sscanf (prop->value().c_str(), "%x", &x);
785                         input_auto_connect = AutoConnectOption (x);
786                 }
787         }
788
789         if ((child = find_named_node (node, "output-auto-connect")) != 0) {
790                 if ((prop = child->property ("val")) != 0) {
791                         sscanf (prop->value().c_str(), "%x", &x);
792                         output_auto_connect = AutoConnectOption (x);
793                 }
794         }
795                                 
796         if ((child = find_named_node (node, "slave")) != 0) {
797                 if ((prop = child->property ("type")) != 0) {
798                         if (prop->value() == "none") {
799                                 slave_src = None;
800                         } else if (prop->value() == "mtc") {
801                                 slave_src = MTC;
802                         } else if (prop->value() == "jack") {
803                                 slave_src = JACK;
804                         }
805                         set_slave_source (slave_src, 0);
806                 }
807         }
808
809         /* we cannot set edit mode if we are loading a session,
810            because it might destroy the playlist's positioning
811         */
812
813         if ((child = find_named_node (node, "edit-mode")) != 0) {
814                 if ((prop = child->property ("val")) != 0) {
815                         if (prop->value() == "slide") {
816                                 pending_edit_mode = Slide;
817                         } else if (prop->value() == "splice") {
818                                 pending_edit_mode = Splice;
819                         } 
820                 }
821         }
822                                 
823         if ((child = find_named_node (node, "send-midi-timecode")) != 0) {
824                 if ((prop = child->property ("val")) != 0) {
825                         bool x = (prop->value() == "yes");
826                         send_mtc = !x; /* force change in value */
827                         set_send_mtc (x);
828                 }
829         }
830         if ((child = find_named_node (node, "send-midi-machine-control")) != 0) {
831                 if ((prop = child->property ("val")) != 0) {
832                         bool x = (prop->value() == "yes");
833                         send_mmc = !x; /* force change in value */
834                         set_send_mmc (prop->value() == "yes");
835                 }
836         }
837         if ((child = find_named_node (node, "max-level")) != 0) {
838                 if ((prop = child->property ("val")) != 0) {
839                         max_level = atoi (prop->value().c_str());
840                 }
841         }
842         if ((child = find_named_node (node, "min-level")) != 0) {
843                 if ((prop = child->property ("val")) != 0) {
844                         min_level = atoi (prop->value().c_str());
845                 }
846         }
847         if ((child = find_named_node (node, "meter-hold")) != 0) {
848                 if ((prop = child->property ("val")) != 0) {
849                         _meter_hold = atof (prop->value().c_str());
850                 }
851         }
852         if ((child = find_named_node (node, "meter-falloff")) != 0) {
853                 if ((prop = child->property ("val")) != 0) {
854                         _meter_falloff = atof (prop->value().c_str());
855                 }
856         }
857         if ((child = find_named_node (node, "long-over-length")) != 0) {
858                 if ((prop = child->property ("val")) != 0) {
859                         over_length_long = atoi (prop->value().c_str());
860                 }
861         }
862         if ((child = find_named_node (node, "short-over-length")) != 0) {
863                 if ((prop = child->property ("val")) != 0) {
864                         over_length_short = atoi (prop->value().c_str());
865                 }
866         }
867         if ((child = find_named_node (node, "shuttle-speed-factor")) != 0) {
868                 if ((prop = child->property ("val")) != 0) {
869                         shuttle_speed_factor = atof (prop->value().c_str());
870                 }
871         }
872         if ((child = find_named_node (node, "shuttle-speed-threshold")) != 0) {
873                 if ((prop = child->property ("val")) != 0) {
874                         shuttle_speed_threshold = atof (prop->value().c_str());
875                 }
876         }
877         if ((child = find_named_node (node, "rf-speed")) != 0) {
878                 if ((prop = child->property ("val")) != 0) {
879                         rf_speed = atof (prop->value().c_str());
880                 }
881         }
882         if ((child = find_named_node (node, "smpte-frames-per-second")) != 0) {
883                 if ((prop = child->property ("val")) != 0) {
884                         set_smpte_type( atof (prop->value().c_str()), smpte_drop_frames );
885                 }
886         }
887         if ((child = find_named_node (node, "smpte-drop-frames")) != 0) {
888                 if ((prop = child->property ("val")) != 0) {
889                         set_smpte_type( smpte_frames_per_second, (prop->value() == "yes") );
890                 }
891         }
892         if ((child = find_named_node (node, "smpte-offset")) != 0) {
893                 if ((prop = child->property ("val")) != 0) {
894                         set_smpte_offset( atoi (prop->value().c_str()) );
895                 }
896         }
897         if ((child = find_named_node (node, "smpte-offset-negative")) != 0) {
898                 if ((prop = child->property ("val")) != 0) {
899                         set_smpte_offset_negative( (prop->value() == "yes") );
900                 }
901         }
902         if ((child = find_named_node (node, "click-sound")) != 0) {
903                 if ((prop = child->property ("val")) != 0) {
904                         click_sound = prop->value();
905                 }
906         }
907         if ((child = find_named_node (node, "click-emphasis-sound")) != 0) {
908                 if ((prop = child->property ("val")) != 0) {
909                         click_emphasis_sound = prop->value();
910                 }
911         }
912
913         if ((child = find_named_node (node, "solo-model")) != 0) {
914                 if ((prop = child->property ("val")) != 0) {
915                         if (prop->value() == "SoloBus")
916                                 _solo_model = SoloBus;
917                         else
918                                 _solo_model = InverseMute;
919                 }
920         }
921
922         /* BOOLEAN OPTIONS */
923
924         if ((child = find_named_node (node, "auto-play")) != 0) {
925                 if ((prop = child->property ("val")) != 0) {
926                         set_auto_play (prop->value() == "yes");
927                 }
928         }
929         if ((child = find_named_node (node, "auto-input")) != 0) {
930                 if ((prop = child->property ("val")) != 0) {
931                         set_auto_input (prop->value() == "yes");
932                 }
933         }
934         if ((child = find_named_node (node, "seamless-loop")) != 0) {
935                 if ((prop = child->property ("val")) != 0) {
936                         set_seamless_loop (prop->value() == "yes");
937                 }
938         }
939         if ((child = find_named_node (node, "punch-in")) != 0) {
940                 if ((prop = child->property ("val")) != 0) {
941                         set_punch_in (prop->value() == "yes");
942                 }
943         }
944         if ((child = find_named_node (node, "punch-out")) != 0) {
945                 if ((prop = child->property ("val")) != 0) {
946                         set_punch_out (prop->value() == "yes");
947                 }
948         }
949         if ((child = find_named_node (node, "auto-return")) != 0) {
950                 if ((prop = child->property ("val")) != 0) {
951                         set_auto_return (prop->value() == "yes");
952                 }
953         }
954         if ((child = find_named_node (node, "send-mtc")) != 0) {
955                 if ((prop = child->property ("val")) != 0) {
956                         set_send_mtc (prop->value() == "yes");
957                 }
958         }
959         if ((child = find_named_node (node, "mmc-control")) != 0) {
960                 if ((prop = child->property ("val")) != 0) {
961                         set_mmc_control (prop->value() == "yes");
962                 }
963         }
964         if ((child = find_named_node (node, "midi-control")) != 0) {
965                 if ((prop = child->property ("val")) != 0) {
966                         set_midi_control (prop->value() == "yes");
967                 }
968         }
969         if ((child = find_named_node (node, "midi-feedback")) != 0) {
970                 if ((prop = child->property ("val")) != 0) {
971                         set_midi_feedback (prop->value() == "yes");
972                 }
973         }
974         // Legacy support for <recording-plugins>
975         if ((child = find_named_node (node, "recording-plugins")) != 0) {
976                 if ((prop = child->property ("val")) != 0) {
977                         set_do_not_record_plugins (prop->value() == "no");
978                 }
979         }
980         if ((child = find_named_node (node, "do-not-record-plugins")) != 0) {
981                 if ((prop = child->property ("val")) != 0) {
982                         set_do_not_record_plugins (prop->value() == "yes");
983                 }
984         }
985         if ((child = find_named_node (node, "crossfades-active")) != 0) {
986                 if ((prop = child->property ("val")) != 0) {
987                         set_crossfades_active (prop->value() == "yes");
988                 }
989         }
990         if ((child = find_named_node (node, "audible-click")) != 0) {
991                 if ((prop = child->property ("val")) != 0) {
992                         set_clicking (prop->value() == "yes");
993                 }
994         }
995
996         if ((child = find_named_node (node, "layer-model")) != 0) {
997                 if ((prop = child->property ("val")) != 0) {
998                         if (prop->value() == X_("LaterHigher")) {
999                                 set_layer_model (LaterHigher);
1000                         } else if (prop->value() == X_("AddHigher")) {
1001                                 set_layer_model (AddHigher);
1002                         } else {
1003                                 set_layer_model (MoveAddHigher);
1004                         }
1005                 }
1006         }
1007
1008         if ((child = find_named_node (node, "xfade-model")) != 0) {
1009                 if ((prop = child->property ("val")) != 0) {
1010                         if (prop->value() == X_("Short")) {
1011                                 set_xfade_model (ShortCrossfade);
1012                         } else {
1013                                 set_xfade_model (FullCrossfade);
1014                         }
1015                 }
1016         }
1017
1018         if ((child = find_named_node (node, "short-xfade-length")) != 0) {
1019                 if ((prop = child->property ("val")) != 0) {
1020                         /* value is stored as a fractional seconds */
1021                         float secs = atof (prop->value().c_str());
1022                         Crossfade::set_short_xfade_length ((jack_nframes_t) floor (secs * frame_rate()));
1023                 } 
1024         }
1025
1026         if ((child = find_named_node (node, "full-xfades-unmuted")) != 0) {
1027                 if ((prop = child->property ("val")) != 0) {
1028                         crossfades_active = (prop->value() == "yes");
1029                 }
1030         } 
1031
1032         /* TIED OPTIONS */
1033
1034         if ((child = find_named_node (node, "default-fade-steepness")) != 0) {
1035                 if ((prop = child->property ("val")) != 0) {
1036                         fade_steepness = atof (prop->value().c_str());
1037                         have_fade_steepness = true;
1038                 }
1039         }
1040         if ((child = find_named_node (node, "default-fade-msec")) != 0) {
1041                 if ((prop = child->property ("val")) != 0) {
1042                         fade_msecs = atof (prop->value().c_str());
1043                         have_fade_msecs = true;
1044                 }
1045         }
1046
1047         if (have_fade_steepness || have_fade_msecs) {
1048                 // set_default_fade (fade_steepness, fade_msecs);
1049         }
1050
1051         return 0;
1052 }
1053
1054 XMLNode&
1055 Session::get_options () const
1056 {
1057         XMLNode* opthead;
1058         XMLNode* child;
1059         char buf[32];
1060         LocaleGuard lg (X_("POSIX"));
1061
1062         opthead = new XMLNode ("Options");
1063
1064         SlaveSource src = slave_source ();
1065         string src_string;
1066         switch (src) {
1067         case None:
1068                 src_string = "none";
1069                 break;
1070         case MTC:
1071                 src_string = "mtc";
1072                 break;
1073         case JACK:
1074                 src_string = "jack";
1075                 break;
1076         }
1077         child = opthead->add_child ("slave");
1078         child->add_property ("type", src_string);
1079         
1080         child = opthead->add_child ("send-midi-timecode");
1081         child->add_property ("val", send_midi_timecode?"yes":"no");
1082
1083         child = opthead->add_child ("send-midi-machine-control");
1084         child->add_property ("val", send_midi_machine_control?"yes":"no");
1085
1086         snprintf (buf, sizeof(buf)-1, "%x", (int) input_auto_connect);
1087         child = opthead->add_child ("input-auto-connect");
1088         child->add_property ("val", buf);
1089
1090         snprintf (buf, sizeof(buf)-1, "%x", (int) output_auto_connect);
1091         child = opthead->add_child ("output-auto-connect");
1092         child->add_property ("val", buf);
1093
1094         snprintf (buf, sizeof(buf)-1, "%d", max_level);
1095         child = opthead->add_child ("max-level");
1096         child->add_property ("val", buf);
1097
1098         snprintf (buf, sizeof(buf)-1, "%d", min_level);
1099         child = opthead->add_child ("min-level");
1100         child->add_property ("val", buf);
1101
1102         snprintf (buf, sizeof(buf)-1, "%f", _meter_hold);
1103         child = opthead->add_child ("meter-hold");
1104         child->add_property ("val", buf);
1105
1106         snprintf (buf, sizeof(buf)-1, "%f", _meter_falloff);
1107         child = opthead->add_child ("meter-falloff");
1108         child->add_property ("val", buf);
1109         
1110         snprintf (buf, sizeof(buf)-1, "%u", over_length_long);
1111         child = opthead->add_child ("long-over-length");
1112         child->add_property ("val", buf);
1113
1114         snprintf (buf, sizeof(buf)-1, "%u", over_length_short);
1115         child = opthead->add_child ("short-over-length");
1116         child->add_property ("val", buf);
1117
1118         snprintf (buf, sizeof(buf)-1, "%f", shuttle_speed_factor);
1119         child = opthead->add_child ("shuttle-speed-factor");
1120         child->add_property ("val", buf);
1121
1122         snprintf (buf, sizeof(buf)-1, "%f", shuttle_speed_threshold);
1123         child = opthead->add_child ("shuttle-speed-threshold");
1124         child->add_property ("val", buf);
1125
1126         snprintf (buf, sizeof(buf)-1, "%f", rf_speed);
1127         child = opthead->add_child ("rf-speed");
1128         child->add_property ("val", buf);
1129
1130         snprintf (buf, sizeof(buf)-1, "%.2f", smpte_frames_per_second);
1131         child = opthead->add_child ("smpte-frames-per-second");
1132         child->add_property ("val", buf);
1133         
1134         child = opthead->add_child ("smpte-drop-frames");
1135         child->add_property ("val", smpte_drop_frames ? "yes" : "no");
1136         
1137         snprintf (buf, sizeof(buf)-1, "%u", smpte_offset ());
1138         child = opthead->add_child ("smpte-offset");
1139         child->add_property ("val", buf);
1140         
1141         child = opthead->add_child ("smpte-offset-negative");
1142         child->add_property ("val", smpte_offset_negative () ? "yes" : "no");
1143         
1144         child = opthead->add_child ("edit-mode");
1145         switch (_edit_mode) {
1146         case Splice:
1147                 child->add_property ("val", "splice");
1148                 break;
1149
1150         case Slide:
1151                 child->add_property ("val", "slide");
1152                 break;
1153         }
1154
1155         child = opthead->add_child ("auto-play");
1156         child->add_property ("val", get_auto_play () ? "yes" : "no");
1157         child = opthead->add_child ("auto-input");
1158         child->add_property ("val", get_auto_input () ? "yes" : "no");
1159         child = opthead->add_child ("seamless-loop");
1160         child->add_property ("val", get_seamless_loop () ? "yes" : "no");
1161         child = opthead->add_child ("punch-in");
1162         child->add_property ("val", get_punch_in () ? "yes" : "no");
1163         child = opthead->add_child ("punch-out");
1164         child->add_property ("val", get_punch_out () ? "yes" : "no");
1165         child = opthead->add_child ("all-safe");
1166         child->add_property ("val", get_all_safe () ? "yes" : "no");
1167         child = opthead->add_child ("auto-return");
1168         child->add_property ("val", get_auto_return () ? "yes" : "no");
1169         child = opthead->add_child ("mmc-control");
1170         child->add_property ("val", get_mmc_control () ? "yes" : "no");
1171         child = opthead->add_child ("midi-control");
1172         child->add_property ("val", get_midi_control () ? "yes" : "no");
1173         child = opthead->add_child ("midi-feedback");
1174         child->add_property ("val", get_midi_feedback () ? "yes" : "no");
1175         child = opthead->add_child ("do-not-record-plugins");
1176         child->add_property ("val", get_do_not_record_plugins () ? "yes" : "no");
1177         child = opthead->add_child ("auto-crossfade");
1178         child->add_property ("val", get_crossfades_active () ? "yes" : "no");
1179         child = opthead->add_child ("audible-click");
1180         child->add_property ("val", get_clicking () ? "yes" : "no");
1181
1182         if (click_sound.length()) {
1183                 child = opthead->add_child ("click-sound");
1184                 child->add_property ("val", click_sound);
1185         }
1186
1187         if (click_emphasis_sound.length()) {
1188                 child = opthead->add_child ("click-emphasis-sound");
1189                 child->add_property ("val", click_emphasis_sound);
1190         }
1191
1192         child = opthead->add_child ("solo-model");
1193         child->add_property ("val", _solo_model == SoloBus ? "SoloBus" : "InverseMute");
1194
1195         child = opthead->add_child ("layer-model");
1196         switch (layer_model) {
1197         case LaterHigher:
1198                 child->add_property ("val", X_("LaterHigher"));
1199                 break;
1200         case MoveAddHigher:
1201                 child->add_property ("val", X_("MoveAddHigher"));
1202                 break;
1203         case AddHigher:
1204                 child->add_property ("val", X_("AddHigher"));
1205                 break;
1206         }
1207
1208         child = opthead->add_child ("xfade-model");
1209         switch (xfade_model) {
1210         case FullCrossfade:
1211                 child->add_property ("val", X_("Full"));
1212                 break;
1213         case ShortCrossfade:
1214                 child->add_property ("val", X_("Short"));
1215         }
1216
1217         child = opthead->add_child ("short-xfade-length");
1218         /* store as fractions of a second */
1219         snprintf (buf, sizeof(buf)-1, "%f", 
1220                   (float) Crossfade::short_xfade_length() / frame_rate());
1221         child->add_property ("val", buf);
1222
1223         child = opthead->add_child ("full-xfades-unmuted");
1224         child->add_property ("val", crossfades_active ? "yes" : "no");
1225
1226         return *opthead;
1227 }
1228
1229 XMLNode&
1230 Session::get_state()
1231 {
1232         return state(true);
1233 }
1234
1235 XMLNode&
1236 Session::get_template()
1237 {
1238         /* if we don't disable rec-enable, diskstreams
1239            will believe they need to store their capture
1240            sources in their state node. 
1241         */
1242         
1243         disable_record ();
1244
1245         return state(false);
1246 }
1247
1248 XMLNode&
1249 Session::state(bool full_state)
1250 {
1251         XMLNode* node = new XMLNode("Session");
1252         XMLNode* child;
1253
1254         // store libardour version, just in case
1255         char buf[16];
1256         snprintf(buf, sizeof(buf)-1, "%d.%d.%d", 
1257                  libardour_major_version, libardour_minor_version, libardour_micro_version);
1258         node->add_property("version", string(buf));
1259                 
1260         /* store configuration settings */
1261
1262         if (full_state) {
1263         
1264                 /* store the name */
1265                 node->add_property ("name", _name);
1266
1267                 if (session_dirs.size() > 1) {
1268
1269                         string p;
1270
1271                         vector<space_and_path>::iterator i = session_dirs.begin();
1272                         vector<space_and_path>::iterator next;
1273
1274                         ++i; /* skip the first one */
1275                         next = i;
1276                         ++next;
1277
1278                         while (i != session_dirs.end()) {
1279
1280                                 p += (*i).path;
1281
1282                                 if (next != session_dirs.end()) {
1283                                         p += ':';
1284                                 } else {
1285                                         break;
1286                                 }
1287
1288                                 ++next;
1289                                 ++i;
1290                         }
1291                         
1292                         child = node->add_child ("Path");
1293                         child->add_content (p);
1294                 }
1295         }
1296
1297         node->add_child_nocopy (get_options());
1298
1299         child = node->add_child ("Sources");
1300
1301         if (full_state) {
1302                 LockMonitor sl (source_lock, __LINE__, __FILE__);
1303
1304                 for (SourceList::iterator siter = sources.begin(); siter != sources.end(); ++siter) {
1305                         
1306                         /* Don't save information about FileSources that are empty */
1307                         
1308                         FileSource* fs;
1309                         
1310                         if ((fs = dynamic_cast<FileSource*> ((*siter).second)) != 0) {
1311                                 if (fs->length() == 0) {
1312                                         continue;
1313                                 }
1314                         }
1315                         
1316                         child->add_child_nocopy ((*siter).second->get_state());
1317                 }
1318         }
1319
1320         child = node->add_child ("Regions");
1321
1322         if (full_state) { 
1323                 LockMonitor rl (region_lock, __LINE__, __FILE__);
1324
1325                 for (AudioRegionList::const_iterator i = audio_regions.begin(); i != audio_regions.end(); ++i) {
1326                         
1327                         /* only store regions not attached to playlists */
1328
1329                         if ((*i).second->playlist() == 0) {
1330                                 child->add_child_nocopy (i->second->state (true));
1331                         }
1332                 }
1333         }
1334
1335         child = node->add_child ("DiskStreams");
1336
1337         { 
1338                 RWLockMonitor dl (diskstream_lock, false, __LINE__, __FILE__);
1339                 for (DiskStreamList::iterator i = diskstreams.begin(); i != diskstreams.end(); ++i) {
1340                         if (!(*i)->hidden()) {
1341                                 child->add_child_nocopy ((*i)->get_state());
1342                         }
1343                 }
1344         }
1345
1346         node->add_child_nocopy (_locations.get_state());
1347         
1348         child = node->add_child ("Connections");
1349         {
1350                 LockMonitor lm (connection_lock, __LINE__, __FILE__);
1351                 for (ConnectionList::iterator i = _connections.begin(); i != _connections.end(); ++i) {
1352                         if (!(*i)->system_dependent()) {
1353                                 child->add_child_nocopy ((*i)->get_state());
1354                         }
1355                 }
1356         }
1357
1358         child = node->add_child ("Routes");
1359         {
1360                 RWLockMonitor lm (route_lock, false, __LINE__, __FILE__);
1361                 
1362                 RoutePublicOrderSorter cmp;
1363                 RouteList public_order(routes);
1364                 public_order.sort (cmp);
1365                 
1366                 for (RouteList::iterator i = public_order.begin(); i != public_order.end(); ++i) {
1367                         if (!(*i)->hidden()) {
1368                                 if (full_state) {
1369                                         child->add_child_nocopy ((*i)->get_state());
1370                                 } else {
1371                                         child->add_child_nocopy ((*i)->get_template());
1372                                 }
1373                         }
1374                 }
1375         }
1376
1377         
1378         child = node->add_child ("EditGroups");
1379         for (list<RouteGroup *>::iterator i = edit_groups.begin(); i != edit_groups.end(); ++i) {
1380                 child->add_child_nocopy ((*i)->get_state());
1381         }
1382
1383         child = node->add_child ("MixGroups");
1384         for (list<RouteGroup *>::iterator i = mix_groups.begin(); i != mix_groups.end(); ++i) {
1385                 child->add_child_nocopy ((*i)->get_state());
1386         }
1387
1388         child = node->add_child ("Playlists");
1389         for (PlaylistList::iterator i = playlists.begin(); i != playlists.end(); ++i) {
1390                 if (!(*i)->hidden()) {
1391                         if (!(*i)->empty()) {
1392                                 if (full_state) {
1393                                         child->add_child_nocopy ((*i)->get_state());
1394                                 } else {
1395                                         child->add_child_nocopy ((*i)->get_template());
1396                                 }
1397                         }
1398                 }
1399         }
1400
1401         child = node->add_child ("UnusedPlaylists");
1402         for (PlaylistList::iterator i = unused_playlists.begin(); i != unused_playlists.end(); ++i) {
1403                 if (!(*i)->hidden()) {
1404                         if (!(*i)->empty()) {
1405                                 if (full_state) {
1406                                         child->add_child_nocopy ((*i)->get_state());
1407                                 } else {
1408                                         child->add_child_nocopy ((*i)->get_template());
1409                                 }
1410                         }
1411                 }
1412         }
1413         
1414         
1415         if (_click_io) {
1416                 child = node->add_child ("Click");
1417                 child->add_child_nocopy (_click_io->state (full_state));
1418         }
1419
1420         if (full_state) {
1421                 child = node->add_child ("NamedSelections");
1422                 for (NamedSelectionList::iterator i = named_selections.begin(); i != named_selections.end(); ++i) {
1423                         if (full_state) {
1424                                 child->add_child_nocopy ((*i)->get_state());
1425                         } 
1426                 }
1427         }
1428
1429         node->add_child_nocopy (_tempo_map->get_state());
1430
1431         if (_extra_xml) {
1432                 node->add_child_copy (*_extra_xml);
1433         }
1434
1435         return *node;
1436 }
1437
1438 int
1439 Session::set_state (const XMLNode& node)
1440 {
1441         XMLNodeList nlist;
1442         XMLNode* child;
1443         const XMLProperty* prop;
1444         int ret = -1;
1445
1446         _state_of_the_state = StateOfTheState (_state_of_the_state|CannotSave);
1447         
1448         if (node.name() != "Session"){
1449                 fatal << _("programming error: Session: incorrect XML node sent to set_state()") << endmsg;
1450                 return -1;
1451         }
1452
1453         StateManager::prohibit_save ();
1454
1455         if ((prop = node.property ("name")) != 0) {
1456                 _name = prop->value ();
1457         }
1458         
1459         IO::disable_ports ();
1460         IO::disable_connecting ();
1461
1462         /* Object loading order:
1463
1464         MIDI
1465         Path
1466         extra
1467         Options
1468         Sources
1469         AudioRegions
1470         DiskStreams
1471         Connections
1472         Locations
1473         Routes
1474         EditGroups
1475         MixGroups
1476         Click
1477         */
1478
1479         if (use_config_midi_ports ()) {
1480         }
1481
1482         if ((child = find_named_node (node, "Path")) != 0) {
1483                 /* XXX this XML content stuff horrible API design */
1484                 string raid_path = _path + ':' + child->children().front()->content();
1485                 setup_raid_path (raid_path);
1486         } else {
1487                 /* the path is already set */
1488         }
1489
1490         if ((child = find_named_node (node, "extra")) != 0) {
1491                 _extra_xml = new XMLNode (*child);
1492         }
1493
1494         if ((child = find_named_node (node, "Options")) == 0) {
1495                 error << _("Session: XML state has no options section") << endmsg;
1496         } else if (load_options (*child)) {
1497         }
1498
1499         if ((child = find_named_node (node, "Sources")) == 0) {
1500                 error << _("Session: XML state has no sources section") << endmsg;
1501                 goto out;
1502         } else if (load_sources (*child)) {
1503                 goto out;
1504         }
1505
1506         if ((child = find_named_node (node, "Regions")) == 0) {
1507                 error << _("Session: XML state has no Regions section") << endmsg;
1508                 goto out;
1509         } else if (load_regions (*child)) {
1510                 goto out;
1511         }
1512
1513         if ((child = find_named_node (node, "Playlists")) == 0) {
1514                 error << _("Session: XML state has no playlists section") << endmsg;
1515                 goto out;
1516         } else if (load_playlists (*child)) {
1517                 goto out;
1518         }
1519
1520         if ((child = find_named_node (node, "UnusedPlaylists")) == 0) {
1521                 // this is OK
1522         } else if (load_unused_playlists (*child)) {
1523                 goto out;
1524         }
1525         
1526         if ((child = find_named_node (node, "NamedSelections")) != 0) {
1527                 if (load_named_selections (*child)) {
1528                         goto out;
1529                 }
1530         }
1531
1532         if ((child = find_named_node (node, "DiskStreams")) == 0) {
1533                 error << _("Session: XML state has no diskstreams section") << endmsg;
1534                 goto out;
1535         } else if (load_diskstreams (*child)) {
1536                 goto out;
1537         }
1538
1539         if ((child = find_named_node (node, "Connections")) == 0) {
1540                 error << _("Session: XML state has no connections section") << endmsg;
1541                 goto out;
1542         } else if (load_connections (*child)) {
1543                 goto out;
1544         }
1545
1546         if ((child = find_named_node (node, "Locations")) == 0) {
1547                 error << _("Session: XML state has no locations section") << endmsg;
1548                 goto out;
1549         } else if (_locations.set_state (*child)) {
1550                 goto out;
1551         }
1552
1553         Location* location;
1554
1555         if ((location = _locations.auto_loop_location()) != 0) {
1556                 set_auto_loop_location (location);
1557         }
1558
1559         if ((location = _locations.auto_punch_location()) != 0) {
1560                 set_auto_punch_location (location);
1561         }
1562
1563         if ((location = _locations.end_location()) == 0) {
1564                 _locations.add (end_location);
1565         } else {
1566                 end_location = location;
1567         }
1568
1569         _locations.save_state (_("initial state"));
1570
1571         if ((child = find_named_node (node, "EditGroups")) == 0) {
1572                 error << _("Session: XML state has no edit groups section") << endmsg;
1573                 goto out;
1574         } else if (load_edit_groups (*child)) {
1575                 goto out;
1576         }
1577
1578         if ((child = find_named_node (node, "MixGroups")) == 0) {
1579                 error << _("Session: XML state has no mix groups section") << endmsg;
1580                 goto out;
1581         } else if (load_mix_groups (*child)) {
1582                 goto out;
1583         }
1584
1585         if ((child = find_named_node (node, "TempoMap")) == 0) {
1586                 error << _("Session: XML state has no Tempo Map section") << endmsg;
1587                 goto out;
1588         } else if (_tempo_map->set_state (*child)) {
1589                 goto out;
1590         }
1591
1592         if ((child = find_named_node (node, "Routes")) == 0) {
1593                 error << _("Session: XML state has no routes section") << endmsg;
1594                 goto out;
1595         } else if (load_routes (*child)) {
1596                 goto out;
1597         }
1598
1599         if ((child = find_named_node (node, "Click")) == 0) {
1600                 warning << _("Session: XML state has no click section") << endmsg;
1601         } else if (_click_io) {
1602                 _click_io->set_state (*child);
1603         }
1604         
1605         /* OK, now we can set edit mode */
1606
1607         set_edit_mode (pending_edit_mode);
1608
1609         /* here beginneth the second phase ... */
1610
1611         StateReady (); /* EMIT SIGNAL */
1612
1613         _state_of_the_state = Clean;
1614
1615         StateManager::allow_save (_("initial state"), true);
1616
1617         if (state_was_pending) {
1618                 save_state (_current_snapshot_name);
1619                 remove_pending_capture_state ();
1620                 state_was_pending = false;
1621         }
1622
1623         return 0;
1624
1625   out:
1626         /* we failed, re-enable state saving but don't actually save internal state */
1627         StateManager::allow_save (X_("ignored"), false);
1628         return ret;
1629 }
1630
1631 int
1632 Session::load_routes (const XMLNode& node)
1633 {
1634         XMLNodeList nlist;
1635         XMLNodeConstIterator niter;
1636         Route *route;
1637
1638         nlist = node.children();
1639
1640         set_dirty();
1641
1642         for (niter = nlist.begin(); niter != nlist.end(); ++niter) {
1643
1644                 if ((route = XMLRouteFactory (**niter)) == 0) {
1645                         error << _("Session: cannot create Route from XML description.")                              << endmsg;
1646                         return -1;
1647                 }
1648
1649                 add_route (route);
1650         }
1651
1652         return 0;
1653 }
1654
1655 Route *
1656 Session::XMLRouteFactory (const XMLNode& node)
1657 {
1658         if (node.name() != "Route") {
1659                 return 0;
1660         }
1661
1662         if (node.property ("diskstream") != 0 || node.property ("diskstream-id") != 0) {
1663                 return new AudioTrack (*this, node);
1664         } else {
1665                 return new Route (*this, node);
1666         }
1667 }
1668
1669 int
1670 Session::load_regions (const XMLNode& node)
1671 {
1672         XMLNodeList nlist;
1673         XMLNodeConstIterator niter;
1674         AudioRegion* region;
1675
1676         nlist = node.children();
1677
1678         set_dirty();
1679
1680         for (niter = nlist.begin(); niter != nlist.end(); ++niter) {
1681
1682                 if ((region = XMLRegionFactory (**niter, false)) == 0) {
1683                         error << _("Session: cannot create Region from XML description.") << endmsg;
1684                 }
1685         }
1686
1687         return 0;
1688 }
1689
1690 AudioRegion *
1691 Session::XMLRegionFactory (const XMLNode& node, bool full)
1692 {
1693         const XMLProperty* prop;
1694         id_t s_id;
1695         Source* source;
1696         AudioRegion::SourceList sources;
1697         uint32_t nchans = 1;
1698         char buf[128];
1699         
1700         if (node.name() != X_("Region")) {
1701                 return 0;
1702         }
1703
1704         if ((prop = node.property (X_("channels"))) != 0) {
1705                 nchans = atoi (prop->value().c_str());
1706         }
1707
1708         
1709         if ((prop = node.property (X_("source-0"))) == 0) {
1710                 if ((prop = node.property ("source")) == 0) {
1711                         error << _("Session: XMLNode describing a AudioRegion is incomplete (no source)") << endmsg;
1712                         return 0;
1713                 }
1714         }
1715
1716         sscanf (prop->value().c_str(), "%" PRIu64, &s_id);
1717
1718         if ((source = get_source (s_id)) == 0) {
1719                 error << string_compose(_("Session: XMLNode describing a AudioRegion references an unknown source id =%1"), s_id) << endmsg;
1720                 return 0;
1721         }
1722
1723         sources.push_back(source);
1724
1725         /* pickup other channels */
1726
1727         for (uint32_t n=1; n < nchans; ++n) {
1728                 snprintf (buf, sizeof(buf), X_("source-%d"), n);
1729                 if ((prop = node.property (buf)) != 0) {
1730                         sscanf (prop->value().c_str(), "%" PRIu64, &s_id);
1731                         
1732                         if ((source = get_source (s_id)) == 0) {
1733                                 error << string_compose(_("Session: XMLNode describing a AudioRegion references an unknown source id =%1"), s_id) << endmsg;
1734                                 return 0;
1735                         }
1736                         sources.push_back(source);
1737                 }
1738         }
1739         
1740         
1741         try {
1742                 return new AudioRegion (sources, node);
1743         }
1744
1745         catch (failed_constructor& err) {
1746                 return 0;
1747         }
1748 }
1749
1750 XMLNode&
1751 Session::get_sources_as_xml ()
1752
1753 {
1754         XMLNode* node = new XMLNode (X_("Sources"));
1755         LockMonitor lm (source_lock, __LINE__, __FILE__);
1756
1757         for (SourceList::iterator i = sources.begin(); i != sources.end(); ++i) {
1758                 node->add_child_nocopy ((*i).second->get_state());
1759         }
1760
1761         return *node;
1762 }
1763
1764 string
1765 Session::path_from_region_name (string name, string identifier)
1766 {
1767         char buf[PATH_MAX+1];
1768         uint32_t n;
1769         string dir = discover_best_sound_dir ();
1770
1771         for (n = 0; n < 999999; ++n) {
1772                 if (identifier.length()) {
1773                         snprintf (buf, sizeof(buf), "%s/%s%s%" PRIu32 ".wav", dir.c_str(), name.c_str(), 
1774                                   identifier.c_str(), n);
1775                 } else {
1776                         snprintf (buf, sizeof(buf), "%s/%s-%" PRIu32 ".wav", dir.c_str(), name.c_str(), n);
1777                 }
1778                 if (access (buf, F_OK) != 0) {
1779                         return buf;
1780                 }
1781         }
1782
1783         return "";
1784 }
1785         
1786
1787 int
1788 Session::load_sources (const XMLNode& node)
1789 {
1790         XMLNodeList nlist;
1791         XMLNodeConstIterator niter;
1792         Source* source;
1793
1794         nlist = node.children();
1795
1796         set_dirty();
1797
1798         for (niter = nlist.begin(); niter != nlist.end(); ++niter) {
1799
1800                 if ((source = XMLSourceFactory (**niter)) == 0) {
1801                         error << _("Session: cannot create Source from XML description.") << endmsg;
1802                 }
1803         }
1804
1805         return 0;
1806 }
1807
1808 Source *
1809 Session::XMLSourceFactory (const XMLNode& node)
1810 {
1811         Source *src = 0;
1812
1813         if (node.name() != "Source") {
1814                 return 0;
1815         }
1816
1817         try {
1818                 src = new FileSource (node, frame_rate());
1819         }
1820         
1821         catch (failed_constructor& err) {
1822
1823                 try {
1824                         src = new SndFileSource (node);
1825                 }
1826
1827                 catch (failed_constructor& err) {
1828                         error << _("Found a sound file that cannot be used by Ardour. See the progammers.") << endmsg;
1829                         return 0;
1830                 } 
1831         }
1832
1833         return src;
1834 }
1835
1836 int
1837 Session::save_template (string template_name)
1838 {
1839         XMLTree tree;
1840         string xml_path, bak_path, template_path;
1841
1842         if (_state_of_the_state & CannotSave) {
1843                 return -1;
1844         }
1845
1846         DIR* dp;
1847         string dir = template_dir();
1848
1849         if ((dp = opendir (dir.c_str()))) {
1850                 closedir (dp);
1851         } else {
1852                 if (mkdir (dir.c_str(), S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH)<0) {
1853                         error << string_compose(_("Could not create mix templates directory \"%1\" (%2)"), dir, strerror (errno)) << endmsg;
1854                         return -1;
1855                 }
1856         }
1857
1858         tree.set_root (&get_template());
1859
1860         xml_path = dir;
1861         xml_path += template_name;
1862         xml_path += _template_suffix;
1863
1864         ifstream in(xml_path.c_str());
1865         
1866         if (in) {
1867                 warning << string_compose(_("Template \"%1\" already exists - new version not created"), template_name) << endmsg;
1868                 return -1;
1869         } else {
1870                 in.close();
1871         }
1872
1873         if (!tree.write (xml_path)) {
1874                 error << _("mix template not saved") << endmsg;
1875                 return -1;
1876         }
1877
1878         return 0;
1879 }
1880
1881 int
1882 Session::rename_template (string old_name, string new_name) 
1883 {
1884         string old_path = template_dir() + old_name + _template_suffix;
1885         string new_path = template_dir() + new_name + _template_suffix;
1886
1887         return rename (old_path.c_str(), new_path.c_str());
1888 }
1889
1890 int
1891 Session::delete_template (string name) 
1892 {
1893         string template_path = template_dir();
1894         template_path += name;
1895         template_path += _template_suffix;
1896
1897         return remove (template_path.c_str());
1898 }
1899
1900 void
1901 Session::refresh_disk_space ()
1902 {
1903 #if HAVE_SYS_VFS_H
1904         struct statfs statfsbuf;
1905         vector<space_and_path>::iterator i;
1906         LockMonitor lm (space_lock, __LINE__, __FILE__);
1907         double scale;
1908
1909         /* get freespace on every FS that is part of the session path */
1910
1911         _total_free_4k_blocks = 0;
1912         
1913         for (i = session_dirs.begin(); i != session_dirs.end(); ++i) {
1914                 statfs ((*i).path.c_str(), &statfsbuf);
1915
1916                 scale = statfsbuf.f_bsize/4096.0;
1917
1918                 (*i).blocks = (uint32_t) floor (statfsbuf.f_bavail * scale);
1919                 _total_free_4k_blocks += (*i).blocks;
1920         }
1921 #endif
1922 }
1923
1924 int
1925 Session::ensure_sound_dir (string path, string& result)
1926 {
1927         string dead;
1928         string peak;
1929
1930         /* Ensure that the parent directory exists */
1931         
1932         if (mkdir (path.c_str(), 0775)) {
1933                 if (errno != EEXIST) {
1934                         error << string_compose(_("cannot create session directory \"%1\"; ignored"), path) << endmsg;
1935                         return -1;
1936                 }
1937         }
1938         
1939         /* Ensure that the sounds directory exists */
1940         
1941         result = path;
1942         result += '/';
1943         result += sound_dir_name;
1944         
1945         if (mkdir (result.c_str(), 0775)) {
1946                 if (errno != EEXIST) {
1947                         error << string_compose(_("cannot create sounds directory \"%1\"; ignored"), result) << endmsg;
1948                         return -1;
1949                 }
1950         }
1951
1952         dead = path;
1953         dead += '/';
1954         dead += dead_sound_dir_name;
1955         
1956         if (mkdir (dead.c_str(), 0775)) {
1957                 if (errno != EEXIST) {
1958                         error << string_compose(_("cannot create dead sounds directory \"%1\"; ignored"), dead) << endmsg;
1959                         return -1;
1960                 }
1961         }
1962
1963         peak = path;
1964         peak += '/';
1965         peak += peak_dir_name;
1966         
1967         if (mkdir (peak.c_str(), 0775)) {
1968                 if (errno != EEXIST) {
1969                         error << string_compose(_("cannot create peak file directory \"%1\"; ignored"), peak) << endmsg;
1970                         return -1;
1971                 }
1972         }
1973         
1974         /* callers expect this to be terminated ... */
1975                         
1976         result += '/';
1977         return 0;
1978 }       
1979
1980 string
1981 Session::discover_best_sound_dir ()
1982 {
1983         vector<space_and_path>::iterator i;
1984         string result;
1985
1986         /* handle common case without system calls */
1987
1988         if (session_dirs.size() == 1) {
1989                 return sound_dir();
1990         }
1991
1992         /* OK, here's the algorithm we're following here:
1993
1994         We want to select which directory to use for 
1995         the next file source to be created. Ideally,
1996         we'd like to use a round-robin process so as to
1997         get maximum performance benefits from splitting
1998         the files across multiple disks.
1999
2000         However, in situations without much diskspace, an
2001         RR approach may end up filling up a filesystem
2002         with new files while others still have space.
2003         Its therefore important to pay some attention to
2004         the freespace in the filesystem holding each
2005         directory as well. However, if we did that by
2006         itself, we'd keep creating new files in the file
2007         system with the most space until it was as full
2008         as all others, thus negating any performance
2009         benefits of this RAID-1 like approach.
2010
2011         So, we use a user-configurable space threshold. If
2012         there are at least 2 filesystems with more than this
2013         much space available, we use RR selection between them. 
2014         If not, then we pick the filesystem with the most space.
2015
2016         This gets a good balance between the two
2017         approaches.  
2018         */
2019         
2020         refresh_disk_space ();
2021         
2022         int free_enough = 0;
2023
2024         for (i = session_dirs.begin(); i != session_dirs.end(); ++i) {
2025                 if ((*i).blocks * 4096 >= Config->get_disk_choice_space_threshold()) {
2026                         free_enough++;
2027                 }
2028         }
2029
2030         if (free_enough >= 2) {
2031
2032                 bool found_it = false;
2033
2034                 /* use RR selection process, ensuring that the one
2035                    picked works OK.
2036                 */
2037
2038                 i = last_rr_session_dir;
2039
2040                 do {
2041                         if (++i == session_dirs.end()) {
2042                                 i = session_dirs.begin();
2043                         }
2044
2045                         if ((*i).blocks * 4096 >= Config->get_disk_choice_space_threshold()) {
2046                                 if (ensure_sound_dir ((*i).path, result) == 0) {
2047                                         last_rr_session_dir = i;
2048                                         found_it = true;
2049                                         break;
2050                                 }
2051                         }
2052
2053                 } while (i != last_rr_session_dir);
2054
2055                 if (!found_it) {
2056                         result = sound_dir();
2057                 }
2058
2059         } else {
2060
2061                 /* pick FS with the most freespace (and that
2062                    seems to actually work ...)
2063                 */
2064                 
2065                 vector<space_and_path> sorted;
2066                 space_and_path_ascending_cmp cmp;
2067
2068                 sorted = session_dirs;
2069                 sort (sorted.begin(), sorted.end(), cmp);
2070                 
2071                 for (i = sorted.begin(); i != sorted.end(); ++i) {
2072                         if (ensure_sound_dir ((*i).path, result) == 0) {
2073                                 last_rr_session_dir = i;
2074                                 break;
2075                         }
2076                 }
2077                 
2078                 /* if the above fails, fall back to the most simplistic solution */
2079                 
2080                 if (i == sorted.end()) {
2081                         return sound_dir();
2082                 } 
2083         }
2084
2085         return result;
2086 }
2087
2088 int
2089 Session::load_playlists (const XMLNode& node)
2090 {
2091         XMLNodeList nlist;
2092         XMLNodeConstIterator niter;
2093         Playlist *playlist;
2094
2095         nlist = node.children();
2096
2097         set_dirty();
2098
2099         for (niter = nlist.begin(); niter != nlist.end(); ++niter) {
2100                 
2101                 if ((playlist = XMLPlaylistFactory (**niter)) == 0) {
2102                         error << _("Session: cannot create Playlist from XML description.") << endmsg;
2103                 }
2104         }
2105
2106         return 0;
2107 }
2108
2109 int
2110 Session::load_unused_playlists (const XMLNode& node)
2111 {
2112         XMLNodeList nlist;
2113         XMLNodeConstIterator niter;
2114         Playlist *playlist;
2115
2116         nlist = node.children();
2117
2118         set_dirty();
2119
2120         for (niter = nlist.begin(); niter != nlist.end(); ++niter) {
2121                 
2122                 if ((playlist = XMLPlaylistFactory (**niter)) == 0) {
2123                         error << _("Session: cannot create Playlist from XML description.") << endmsg;
2124                         continue;
2125                 }
2126
2127                 // now manually untrack it
2128
2129                 track_playlist (playlist, false);
2130         }
2131
2132         return 0;
2133 }
2134
2135
2136 Playlist *
2137 Session::XMLPlaylistFactory (const XMLNode& node)
2138 {
2139         try {
2140                 return new AudioPlaylist (*this, node);
2141         }
2142
2143         catch (failed_constructor& err) {
2144                 return 0;
2145         }
2146 }
2147
2148 int
2149 Session::load_named_selections (const XMLNode& node)
2150 {
2151         XMLNodeList nlist;
2152         XMLNodeConstIterator niter;
2153         NamedSelection *ns;
2154
2155         nlist = node.children();
2156
2157         set_dirty();
2158
2159         for (niter = nlist.begin(); niter != nlist.end(); ++niter) {
2160                 
2161                 if ((ns = XMLNamedSelectionFactory (**niter)) == 0) {
2162                         error << _("Session: cannot create Named Selection from XML description.") << endmsg;
2163                 }
2164         }
2165
2166         return 0;
2167 }
2168
2169 NamedSelection *
2170 Session::XMLNamedSelectionFactory (const XMLNode& node)
2171 {
2172         try {
2173                 return new NamedSelection (*this, node);
2174         }
2175
2176         catch (failed_constructor& err) {
2177                 return 0;
2178         }
2179 }
2180
2181 string
2182 Session::dead_sound_dir () const
2183 {
2184         string res = _path;
2185         res += dead_sound_dir_name;
2186         res += '/';
2187         return res;
2188 }
2189
2190 string
2191 Session::sound_dir () const
2192 {
2193         string res = _path;
2194         res += sound_dir_name;
2195         res += '/';
2196         return res;
2197 }
2198
2199 string
2200 Session::peak_dir () const
2201 {
2202         string res = _path;
2203         res += peak_dir_name;
2204         res += '/';
2205         return res;
2206 }
2207         
2208 string
2209 Session::automation_dir () const
2210 {
2211         string res = _path;
2212         res += "automation/";
2213         return res;
2214 }
2215
2216 string
2217 Session::template_dir ()
2218 {
2219         string path = Config->get_user_ardour_path();
2220         path += "templates/";
2221
2222         return path;
2223 }
2224
2225 string
2226 Session::template_path ()
2227 {
2228         string path;
2229
2230         path += Config->get_user_ardour_path();
2231         if (path[path.length()-1] != ':') {
2232                 path += ':';
2233         }
2234         path += Config->get_system_ardour_path();
2235
2236         vector<string> split_path;
2237         
2238         split (path, split_path, ':');
2239         path = "";
2240
2241         for (vector<string>::iterator i = split_path.begin(); i != split_path.end(); ++i) {
2242                 path += *i;
2243                 path += "templates/";
2244                 
2245                 if (distance (i, split_path.end()) != 1) {
2246                         path += ':';
2247                 }
2248         }
2249                 
2250         return path;
2251 }
2252
2253 int
2254 Session::load_connections (const XMLNode& node)
2255 {
2256         XMLNodeList nlist = node.children();
2257         XMLNodeConstIterator niter;
2258
2259         set_dirty();
2260
2261         for (niter = nlist.begin(); niter != nlist.end(); ++niter) {
2262                 if ((*niter)->name() == "InputConnection") {
2263                         add_connection (new ARDOUR::InputConnection (**niter));
2264                 } else if ((*niter)->name() == "OutputConnection") {
2265                         add_connection (new ARDOUR::OutputConnection (**niter));
2266                 } else {
2267                         error << string_compose(_("Unknown node \"%1\" found in Connections list from state file"), (*niter)->name()) << endmsg;
2268                         return -1;
2269                 }
2270         }
2271
2272         return 0;
2273 }                               
2274
2275 int
2276 Session::load_edit_groups (const XMLNode& node)
2277 {
2278         return load_route_groups (node, true);
2279 }
2280
2281 int
2282 Session::load_mix_groups (const XMLNode& node)
2283 {
2284         return load_route_groups (node, false);
2285 }
2286
2287 int
2288 Session::load_route_groups (const XMLNode& node, bool edit)
2289 {
2290         XMLNodeList nlist = node.children();
2291         XMLNodeConstIterator niter;
2292         RouteGroup* route;
2293
2294         set_dirty();
2295
2296         for (niter = nlist.begin(); niter != nlist.end(); ++niter) {
2297                 if ((*niter)->name() == "RouteGroup") {
2298                         if (edit) {
2299                                 route = add_edit_group ("");
2300                                 route->set_state (**niter);
2301                         } else {
2302                                 route = add_mix_group ("");
2303                                 route->set_state (**niter);
2304                         }
2305                 }
2306         }
2307         
2308         return 0;
2309 }                               
2310
2311 void
2312 Session::swap_configuration(Configuration** new_config)
2313 {
2314         RWLockMonitor lm (route_lock, true, __LINE__, __FILE__); // jlc - WHY?
2315         Configuration* tmp = *new_config;
2316         *new_config = Config;
2317         Config = tmp;
2318         set_dirty();
2319 }
2320
2321 void
2322 Session::copy_configuration(Configuration* new_config)
2323 {
2324         RWLockMonitor lm (route_lock, true, __LINE__, __FILE__);
2325         new_config = new Configuration(*Config);
2326 }
2327
2328 static bool
2329 state_file_filter (const string &str, void *arg)
2330 {
2331         return (str.length() > strlen(Session::statefile_suffix()) &&
2332                 str.find (Session::statefile_suffix()) == (str.length() - strlen (Session::statefile_suffix())));
2333 }
2334
2335 struct string_cmp {
2336         bool operator()(const string* a, const string* b) {
2337                 return *a < *b;
2338         }
2339 };
2340
2341 static string*
2342 remove_end(string* state)
2343 {
2344         string statename(*state);
2345         
2346         string::size_type start,end;
2347         if ((start = statename.find_last_of ('/')) != string::npos) {
2348                 statename = statename.substr (start+1);
2349         }
2350                 
2351         if ((end = statename.rfind(".ardour")) < 0) {
2352                 end = statename.length();
2353         }
2354
2355         return new string(statename.substr (0, end));
2356 }
2357
2358 vector<string *> *
2359 Session::possible_states (string path) 
2360 {
2361         PathScanner scanner;
2362         vector<string*>* states = scanner (path, state_file_filter, 0, false, false);
2363         
2364         transform(states->begin(), states->end(), states->begin(), remove_end);
2365         
2366         string_cmp cmp;
2367         sort (states->begin(), states->end(), cmp);
2368         
2369         return states;
2370 }
2371
2372 vector<string *> *
2373 Session::possible_states () const
2374 {
2375         return possible_states(_path);
2376 }
2377
2378 void
2379 Session::auto_save()
2380 {
2381         save_state (_current_snapshot_name);
2382 }
2383
2384 RouteGroup *
2385 Session::add_edit_group (string name)
2386 {
2387         RouteGroup* rg = new RouteGroup (name);
2388         edit_groups.push_back (rg);
2389         edit_group_added (rg); /* EMIT SIGNAL */
2390         set_dirty();
2391         return rg;
2392 }
2393
2394 RouteGroup *
2395 Session::add_mix_group (string name)
2396 {
2397         RouteGroup* rg = new RouteGroup (name, RouteGroup::Relative);
2398         mix_groups.push_back (rg);
2399         mix_group_added (rg); /* EMIT SIGNAL */
2400         set_dirty();
2401         return rg;
2402 }
2403
2404 RouteGroup *
2405 Session::mix_group_by_name (string name)
2406 {
2407         list<RouteGroup *>::iterator i;
2408
2409         for (i = mix_groups.begin(); i != mix_groups.end(); ++i) {
2410                 if ((*i)->name() == name) {
2411                         return* i;
2412                 }
2413         }
2414         return 0;
2415 }
2416
2417 RouteGroup *
2418 Session::edit_group_by_name (string name)
2419 {
2420         list<RouteGroup *>::iterator i;
2421
2422         for (i = edit_groups.begin(); i != edit_groups.end(); ++i) {
2423                 if ((*i)->name() == name) {
2424                         return* i;
2425                 }
2426         }
2427         return 0;
2428 }
2429
2430 void
2431 Session::set_meter_hold (float val)
2432 {
2433         _meter_hold = val;
2434         MeterHoldChanged(); // emit
2435 }
2436
2437 void
2438 Session::set_meter_falloff (float val)
2439 {
2440         _meter_falloff = val;
2441         MeterFalloffChanged(); // emit
2442 }
2443
2444
2445 void
2446 Session::begin_reversible_command (string name, UndoAction* private_undo)
2447 {
2448         current_cmd.clear ();
2449         current_cmd.set_name (name);
2450
2451         if (private_undo) {
2452                 current_cmd.add_undo (*private_undo);
2453         }
2454 }
2455
2456 void
2457 Session::commit_reversible_command (UndoAction* private_redo)
2458 {
2459         struct timeval now;
2460
2461         if (private_redo) {
2462                 current_cmd.add_redo_no_execute (*private_redo);
2463         }
2464
2465         gettimeofday (&now, 0);
2466         current_cmd.set_timestamp (now);
2467
2468         history.add (current_cmd);
2469 }
2470
2471 Session::GlobalRouteBooleanState 
2472 Session::get_global_route_boolean (bool (Route::*method)(void) const)
2473 {
2474         GlobalRouteBooleanState s;
2475         RWLockMonitor lm (route_lock, false, __LINE__, __FILE__);
2476
2477         for (RouteList::iterator i = routes.begin(); i != routes.end(); ++i) {
2478                 if (!(*i)->hidden()) {
2479                         RouteBooleanState v;
2480                         
2481                         v.first =* i;
2482                         v.second = ((*i)->*method)();
2483                         
2484                         s.push_back (v);
2485                 }
2486         }
2487
2488         return s;
2489 }
2490
2491 Session::GlobalRouteMeterState
2492 Session::get_global_route_metering ()
2493 {
2494         GlobalRouteMeterState s;
2495         RWLockMonitor lm (route_lock, false, __LINE__, __FILE__);
2496
2497         for (RouteList::iterator i = routes.begin(); i != routes.end(); ++i) {
2498                 if (!(*i)->hidden()) {
2499                         RouteMeterState v;
2500                         
2501                         v.first =* i;
2502                         v.second = (*i)->meter_point();
2503                         
2504                         s.push_back (v);
2505                 }
2506         }
2507
2508         return s;
2509 }
2510
2511 void
2512 Session::set_global_route_metering (GlobalRouteMeterState s, void* arg) 
2513 {
2514         for (GlobalRouteMeterState::iterator i = s.begin(); i != s.end(); ++i) {
2515                 i->first->set_meter_point (i->second, arg);
2516         }
2517 }
2518
2519 void
2520 Session::set_global_route_boolean (GlobalRouteBooleanState s, void (Route::*method)(bool, void*), void* arg)
2521 {
2522         for (GlobalRouteBooleanState::iterator i = s.begin(); i != s.end(); ++i) {
2523                 (i->first->*method) (i->second, arg);
2524         }
2525 }
2526
2527 void
2528 Session::set_global_mute (GlobalRouteBooleanState s, void* src)
2529 {
2530         set_global_route_boolean (s, &Route::set_mute, src);
2531 }
2532
2533 void
2534 Session::set_global_solo (GlobalRouteBooleanState s, void* src)
2535 {
2536         set_global_route_boolean (s, &Route::set_solo, src);
2537 }
2538
2539 void
2540 Session::set_global_record_enable (GlobalRouteBooleanState s, void* src)
2541 {
2542         set_global_route_boolean (s, &Route::set_record_enable, src);
2543 }
2544
2545 UndoAction
2546 Session::global_mute_memento (void* src)
2547 {
2548         return sigc::bind (mem_fun (*this, &Session::set_global_mute), get_global_route_boolean (&Route::muted), src);
2549 }
2550
2551 UndoAction
2552 Session::global_metering_memento (void* src)
2553 {
2554         return sigc::bind (mem_fun (*this, &Session::set_global_route_metering), get_global_route_metering (), src);
2555 }
2556
2557 UndoAction
2558 Session::global_solo_memento (void* src)
2559 {
2560         return sigc::bind (mem_fun (*this, &Session::set_global_solo), get_global_route_boolean (&Route::soloed), src);
2561 }
2562
2563 UndoAction
2564 Session::global_record_enable_memento (void* src)
2565 {
2566         return sigc::bind (mem_fun (*this, &Session::set_global_record_enable), get_global_route_boolean (&Route::record_enabled), src);
2567 }
2568
2569 static bool
2570 template_filter (const string &str, void *arg)
2571 {
2572         return (str.length() > strlen(Session::template_suffix()) &&
2573                 str.find (Session::template_suffix()) == (str.length() - strlen (Session::template_suffix())));
2574 }
2575
2576 void
2577 Session::get_template_list (list<string> &template_names)
2578 {
2579         vector<string *> *templates;
2580         PathScanner scanner;
2581         string path;
2582
2583         path = template_path ();
2584
2585         templates = scanner (path, template_filter, 0, false, true);
2586         
2587         vector<string*>::iterator i;
2588         for (i = templates->begin(); i != templates->end(); ++i) {
2589                 string fullpath = *(*i);
2590                 int start, end;
2591
2592                 start = fullpath.find_last_of ('/') + 1;
2593                 if ((end = fullpath.find_last_of ('.')) <0) {
2594                         end = fullpath.length();
2595                 }
2596                 
2597                 template_names.push_back(fullpath.substr(start, (end-start)));
2598         }
2599 }
2600
2601 int
2602 Session::read_favorite_dirs (FavoriteDirs & favs)
2603 {
2604         string path = Config->get_user_ardour_path();
2605         path += "/favorite_dirs";
2606
2607         ifstream fav (path.c_str());
2608
2609         favs.clear();
2610         
2611         if (!fav) {
2612                 if (errno != ENOENT) {
2613                         //error << string_compose (_("cannot open favorite file %1 (%2)"), path, strerror (errno)) << endmsg;
2614                         return -1;
2615                 } else {
2616                         return 1;
2617                 }
2618         }
2619
2620         while (true) {
2621
2622                 string newfav;
2623
2624                 getline(fav, newfav);
2625
2626                 if (!fav.good()) {
2627                         break;
2628                 }
2629
2630                 favs.push_back (newfav);
2631         }
2632
2633         return 0;
2634 }
2635
2636 int
2637 Session::write_favorite_dirs (FavoriteDirs & favs)
2638 {
2639         string path = Config->get_user_ardour_path();
2640         path += "/favorite_dirs";
2641
2642         ofstream fav (path.c_str());
2643
2644         if (!fav) {
2645                 return -1;
2646         }
2647
2648         for (FavoriteDirs::iterator i = favs.begin(); i != favs.end(); ++i) {
2649                 fav << (*i) << endl;
2650         }
2651         
2652         return 0;
2653 }
2654
2655 static bool
2656 accept_all_non_peak_files (const string& path, void *arg)
2657 {
2658         return (path.length() > 5 && path.find (".peak") != (path.length() - 5));
2659 }
2660
2661 static bool
2662 accept_all_state_files (const string& path, void *arg)
2663 {
2664         return (path.length() > 7 && path.find (".ardour") == (path.length() - 7));
2665 }
2666
2667 int 
2668 Session::find_all_sources (string path, set<string>& result)
2669 {
2670         XMLTree tree;
2671         XMLNode* node;
2672
2673         if (!tree.read (path)) {
2674                 return -1;
2675         }
2676
2677         if ((node = find_named_node (*tree.root(), "Sources")) == 0) {
2678                 return -2;
2679         }
2680
2681         XMLNodeList nlist;
2682         XMLNodeConstIterator niter;
2683
2684         nlist = node->children();
2685
2686         set_dirty();
2687
2688         for (niter = nlist.begin(); niter != nlist.end(); ++niter) {
2689                 
2690                 XMLProperty* prop;
2691
2692                 if ((prop = (*niter)->property (X_("name"))) == 0) {
2693                         continue;
2694                 }
2695
2696                 if (prop->value()[0] == '/') {
2697                         /* external file, ignore */
2698                         continue;
2699                 }
2700
2701                 string path = _path; /* /-terminated */
2702                 path += sound_dir_name;
2703                 path += '/';
2704                 path += prop->value();
2705
2706                 result.insert (path);
2707         }
2708
2709         return 0;
2710 }
2711
2712 int
2713 Session::find_all_sources_across_snapshots (set<string>& result, bool exclude_this_snapshot)
2714 {
2715         PathScanner scanner;
2716         vector<string*>* state_files;
2717         string ripped;
2718         string this_snapshot_path;
2719
2720         result.clear ();
2721
2722         ripped = _path;
2723
2724         if (ripped[ripped.length()-1] == '/') {
2725                 ripped = ripped.substr (0, ripped.length() - 1);
2726         }
2727
2728         state_files = scanner (ripped, accept_all_state_files, (void *) 0, false, true);
2729         
2730         if (state_files == 0) {
2731                 /* impossible! */
2732                 return 0;
2733         }
2734
2735         this_snapshot_path = _path;
2736         this_snapshot_path += _current_snapshot_name;
2737         this_snapshot_path += _statefile_suffix;
2738
2739         for (vector<string*>::iterator i = state_files->begin(); i != state_files->end(); ++i) {
2740
2741                 if (exclude_this_snapshot && **i == this_snapshot_path) {
2742                         continue;
2743                 }
2744
2745                 if (find_all_sources (**i, result) < 0) {
2746                         return -1;
2747                 }
2748         }
2749
2750         return 0;
2751 }
2752
2753 int
2754 Session::cleanup_sources (Session::cleanup_report& rep)
2755 {
2756         vector<Source*> dead_sources;
2757         vector<Playlist*> playlists_tbd;
2758         PathScanner scanner;
2759         string sound_path;
2760         vector<space_and_path>::iterator i;
2761         vector<space_and_path>::iterator nexti;
2762         vector<string*>* soundfiles;
2763         vector<string> unused;
2764         set<string> all_sources;
2765         bool used;
2766         string spath;
2767         int ret = -1;
2768                 
2769         _state_of_the_state = (StateOfTheState) (_state_of_the_state | InCleanup);
2770         
2771         /* step 1: consider deleting all unused playlists */
2772
2773         for (PlaylistList::iterator x = unused_playlists.begin(); x != unused_playlists.end(); ++x) {
2774                 int status;
2775
2776                 status = AskAboutPlaylistDeletion (*x);
2777
2778                 switch (status) {
2779                 case -1:
2780                         ret = 0;
2781                         goto out;
2782                         break;
2783
2784                 case 0:
2785                         playlists_tbd.push_back (*x);
2786                         break;
2787
2788                 default:
2789                         /* leave it alone */
2790                         break;
2791                 }
2792         }
2793
2794         /* now delete any that were marked for deletion */
2795
2796         for (vector<Playlist*>::iterator x = playlists_tbd.begin(); x != playlists_tbd.end(); ++x) {
2797                 PlaylistList::iterator foo;
2798
2799                 if ((foo = unused_playlists.find (*x)) != unused_playlists.end()) {
2800                         unused_playlists.erase (foo);
2801                 }
2802                 delete *x;
2803         }
2804
2805         /* step 2: clear the undo/redo history for all playlists */
2806
2807         for (PlaylistList::iterator x = playlists.begin(); x != playlists.end(); ++x) {
2808                 (*x)->drop_all_states ();
2809         }
2810
2811         /* step 3: find all un-referenced sources */
2812
2813         rep.paths.clear ();
2814         rep.space = 0;
2815
2816         for (SourceList::iterator i = sources.begin(); i != sources.end(); ) {
2817
2818                 SourceList::iterator tmp;
2819
2820                 tmp = i;
2821                 ++tmp;
2822
2823                 /* only remove files that are not in use and have some size
2824                    to them. otherwise we remove the current "nascent"
2825                    capture files.
2826                 */
2827
2828                 if ((*i).second->use_cnt() == 0 && (*i).second->length() > 0) {
2829                         dead_sources.push_back (i->second);
2830
2831                         /* remove this source from our own list to avoid us
2832                            adding it to the list of all sources below
2833                         */
2834
2835                         sources.erase (i);
2836                 }
2837
2838                 i = tmp;
2839         }
2840
2841         /* Step 4: get rid of all regions in the region list that use any dead sources
2842            in case the sources themselves don't go away (they might be referenced in
2843            other snapshots).
2844         */
2845                 
2846         for (vector<Source*>::iterator i = dead_sources.begin(); i != dead_sources.end();++i) {
2847
2848                 for (AudioRegionList::iterator r = audio_regions.begin(); r != audio_regions.end(); ) {
2849                         AudioRegionList::iterator tmp;
2850                         AudioRegion* ar;
2851
2852                         tmp = r;
2853                         ++tmp;
2854                         
2855                         ar = (*r).second;
2856
2857                         for (uint32_t n = 0; n < ar->n_channels(); ++n) {
2858                                 if (&ar->source (n) == (*i)) {
2859                                         /* this region is dead */
2860                                         remove_region (ar);
2861                                 }
2862                         }
2863                         
2864                         r = tmp;
2865                 }
2866         }
2867
2868         /* build a list of all the possible sound directories for the session */
2869
2870         for (i = session_dirs.begin(); i != session_dirs.end(); ) {
2871
2872                 nexti = i;
2873                 ++nexti;
2874
2875                 sound_path += (*i).path;
2876                 sound_path += sound_dir_name;
2877
2878                 if (nexti != session_dirs.end()) {
2879                         sound_path += ':';
2880                 }
2881
2882                 i = nexti;
2883         }
2884         
2885         /* now do the same thing for the files that ended up in the sounds dir(s) 
2886            but are not referenced as sources in any snapshot.
2887         */
2888
2889         soundfiles = scanner (sound_path, accept_all_non_peak_files, (void *) 0, false, true);
2890
2891         if (soundfiles == 0) {
2892                 return 0;
2893         }
2894
2895         /* find all sources, but don't use this snapshot because the
2896            state file on disk still references sources we may have already
2897            dropped.
2898         */
2899
2900         find_all_sources_across_snapshots (all_sources, true);
2901
2902         /* add our current source list
2903          */
2904
2905         for (SourceList::iterator i = sources.begin(); i != sources.end(); ++i) {
2906                 FileSource* fs;
2907                 SndFileSource* sfs;
2908                 
2909                 if ((fs = dynamic_cast<FileSource*> ((*i).second)) != 0) {
2910                         all_sources.insert (fs->path());
2911                 } else if ((sfs = dynamic_cast<SndFileSource*> ((*i).second)) != 0) {
2912                         all_sources.insert (sfs->path());
2913                 } 
2914         }
2915
2916         for (vector<string*>::iterator x = soundfiles->begin(); x != soundfiles->end(); ++x) {
2917
2918                 used = false;
2919                 spath = **x;
2920
2921                 for (set<string>::iterator i = all_sources.begin(); i != all_sources.end(); ++i) {
2922
2923                         if (spath == *i) {
2924                                 used = true;
2925                                 break;
2926                         }
2927
2928                 }
2929
2930                 if (!used) {
2931                         unused.push_back (spath);
2932                 }
2933         }
2934
2935         /* now try to move all unused files into the "dead_sounds" directory(ies) */
2936
2937         for (vector<string>::iterator x = unused.begin(); x != unused.end(); ++x) {
2938                 struct stat statbuf;
2939
2940                 rep.paths.push_back (*x);
2941                 if (stat ((*x).c_str(), &statbuf) == 0) {
2942                         rep.space += statbuf.st_size;
2943                 }
2944
2945                 string newpath;
2946                 
2947                 /* don't move the file across filesystems, just
2948                    stick it in the `dead_sound_dir_name' directory
2949                    on whichever filesystem it was already on.
2950                 */
2951
2952                 newpath = PBD::dirname (*x);
2953                 newpath = PBD::dirname (newpath);
2954
2955                 newpath += '/';
2956                 newpath += dead_sound_dir_name;
2957                 newpath += '/';
2958                 newpath += PBD::basename ((*x));
2959                 
2960                 if (access (newpath.c_str(), F_OK) == 0) {
2961                         
2962                         /* the new path already exists, try versioning */
2963                         
2964                         char buf[PATH_MAX+1];
2965                         int version = 1;
2966                         string newpath_v;
2967                         
2968                         snprintf (buf, sizeof (buf), "%s.%d", newpath.c_str(), version);
2969                         newpath_v = buf;
2970
2971                         while (access (newpath_v.c_str(), F_OK) == 0 && version < 999) {
2972                                 snprintf (buf, sizeof (buf), "%s.%d", newpath.c_str(), ++version);
2973                                 newpath_v = buf;
2974                         }
2975                         
2976                         if (version == 999) {
2977                                 error << string_compose (_("there are already 1000 files with names like %1; versioning discontinued"),
2978                                                   newpath)
2979                                       << endmsg;
2980                         } else {
2981                                 newpath = newpath_v;
2982                         }
2983                         
2984                 } else {
2985                         
2986                         /* it doesn't exist, or we can't read it or something */
2987                         
2988                 }
2989
2990                 if (::rename ((*x).c_str(), newpath.c_str()) != 0) {
2991                         error << string_compose (_("cannot rename audio file source from %1 to %2 (%3)"),
2992                                           (*x), newpath, strerror (errno))
2993                               << endmsg;
2994                         goto out;
2995                 }
2996                 
2997
2998                 /* see if there an easy to find peakfile for this file, and remove it.
2999                  */
3000
3001                 string peakpath = (*x).substr (0, (*x).find_last_of ('.'));
3002                 peakpath += ".peak";
3003
3004                 if (access (peakpath.c_str(), W_OK) == 0) {
3005                         if (::unlink (peakpath.c_str()) != 0) {
3006                                 error << string_compose (_("cannot remove peakfile %1 for %2 (%3)"),
3007                                                   peakpath, _path, strerror (errno))
3008                                       << endmsg;
3009                                 /* try to back out */
3010                                 rename (newpath.c_str(), _path.c_str());
3011                                 goto out;
3012                         }
3013                 }
3014
3015         }
3016
3017         ret = 0;
3018
3019         /* dump the history list */
3020
3021         history.clear ();
3022
3023         /* save state so we don't end up a session file
3024            referring to non-existent sources.
3025         */
3026         
3027         save_state ("");
3028
3029   out:
3030         _state_of_the_state = (StateOfTheState) (_state_of_the_state & ~InCleanup);
3031         return ret;
3032 }
3033
3034 int
3035 Session::cleanup_trash_sources (Session::cleanup_report& rep)
3036 {
3037         vector<space_and_path>::iterator i;
3038         string dead_sound_dir;
3039         struct dirent* dentry;
3040         struct stat statbuf;
3041         DIR* dead;
3042
3043         rep.paths.clear ();
3044         rep.space = 0;
3045
3046         for (i = session_dirs.begin(); i != session_dirs.end(); ++i) {
3047                 
3048                 dead_sound_dir = (*i).path;
3049                 dead_sound_dir += dead_sound_dir_name;
3050
3051                 if ((dead = opendir (dead_sound_dir.c_str())) == 0) {
3052                         continue;
3053                 }
3054
3055                 while ((dentry = readdir (dead)) != 0) {
3056
3057                         /* avoid '.' and '..' */
3058                         
3059                         if ((dentry->d_name[0] == '.' && dentry->d_name[1] == '\0') || 
3060                             (dentry->d_name[2] == '\0' && dentry->d_name[0] == '.' && dentry->d_name[1] == '.')) {
3061                                 continue;
3062                         }
3063
3064                         string fullpath;
3065
3066                         fullpath = dead_sound_dir;
3067                         fullpath += '/';
3068                         fullpath += dentry->d_name;
3069
3070                         if (stat (fullpath.c_str(), &statbuf)) {
3071                                 continue;
3072                         }
3073
3074                         if (!S_ISREG (statbuf.st_mode)) {
3075                                 continue;
3076                         }
3077
3078                         if (unlink (fullpath.c_str())) {
3079                                 error << string_compose (_("cannot remove dead sound file %1 (%2)"),
3080                                                   fullpath, strerror (errno))
3081                                       << endmsg;
3082                         }
3083
3084                         rep.paths.push_back (dentry->d_name);
3085                         rep.space += statbuf.st_size;
3086                 }
3087
3088                 closedir (dead);
3089                 
3090         }
3091
3092         return 0;
3093 }
3094
3095 void
3096 Session::set_dirty ()
3097 {
3098         bool was_dirty = dirty();
3099         
3100         _state_of_the_state = StateOfTheState (_state_of_the_state | Dirty);
3101
3102         if (!was_dirty) {
3103                 DirtyChanged(); /* EMIT SIGNAL */
3104         }
3105 }
3106
3107
3108 void
3109 Session::set_clean ()
3110 {
3111         bool was_dirty = dirty();
3112         
3113         _state_of_the_state = Clean;
3114
3115         if (was_dirty) {
3116                 DirtyChanged(); /* EMIT SIGNAL */
3117         }
3118 }
3119