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