Move some sync-related options to being session variables.
[ardour.git] / libs / ardour / session_state.cc
index eaaa723a0c107bd1b8139f070b944e915b9f9d03..4d07a6c6e26db883651860a941ef68e0e61456e4 100644 (file)
   along with this program; if not, write to the Free Software
   Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
     
-  $Id$
 */
 
+#define __STDC_FORMAT_MACROS 1
+#include <stdint.h>
+
 #include <algorithm>
 #include <fstream>
 #include <string>
 #ifdef HAVE_SYS_VFS_H
 #include <sys/vfs.h>
 #else
-#include <sys/mount.h>
 #include <sys/param.h>
+#include <sys/mount.h>
 #endif
 
 #include <glibmm.h>
-
-#include <midi++/mmc.h>
-#include <midi++/port.h>
-#include <pbd/error.h>
-
 #include <glibmm/thread.h>
-#include <pbd/pathscanner.h>
-#include <pbd/pthread_utils.h>
-#include <pbd/strsplit.h>
-
-#include <ardour/audioengine.h>
-#include <ardour/configuration.h>
-#include <ardour/session.h>
-#include <ardour/buffer.h>
-#include <ardour/audio_diskstream.h>
-#include <ardour/midi_diskstream.h>
-#include <ardour/utils.h>
-#include <ardour/audioplaylist.h>
-#include <ardour/midi_playlist.h>
-#include <ardour/smf_source.h>
-#include <ardour/audiofilesource.h>
-#include <ardour/destructive_filesource.h>
-#include <ardour/midi_source.h>
-#include <ardour/sndfile_helpers.h>
-#include <ardour/auditioner.h>
-#include <ardour/export.h>
-#include <ardour/redirect.h>
-#include <ardour/send.h>
-#include <ardour/insert.h>
-#include <ardour/connection.h>
-#include <ardour/slave.h>
-#include <ardour/tempo.h>
-#include <ardour/audio_track.h>
-#include <ardour/midi_track.h>
-#include <ardour/cycle_timer.h>
-#include <ardour/utils.h>
-#include <ardour/named_selection.h>
-#include <ardour/version.h>
-#include <ardour/location.h>
-#include <ardour/audioregion.h>
-#include <ardour/midi_region.h>
-#include <ardour/crossfade.h>
-#include <ardour/control_protocol_manager.h>
-#include <ardour/region_factory.h>
-#include <ardour/source_factory.h>
+
+#include "midi++/mmc.h"
+#include "midi++/port.h"
+
+#include "pbd/error.h"
+#include "pbd/pathscanner.h"
+#include "pbd/pthread_utils.h"
+#include "pbd/search_path.h"
+#include "pbd/stacktrace.h"
+
+#include "ardour/audioengine.h"
+#include "ardour/configuration.h"
+#include "ardour/session.h"
+#include "ardour/session_directory.h"
+#include "ardour/session_utils.h"
+#include "ardour/session_state_utils.h"
+#include "ardour/session_metadata.h"
+#include "ardour/buffer.h"
+#include "ardour/audio_diskstream.h"
+#include "ardour/midi_diskstream.h"
+#include "ardour/utils.h"
+#include "ardour/audioplaylist.h"
+#include "ardour/midi_playlist.h"
+#include "ardour/smf_source.h"
+#include "ardour/audiofilesource.h"
+#include "ardour/silentfilesource.h"
+#include "ardour/sndfilesource.h"
+#include "ardour/midi_source.h"
+#include "ardour/sndfile_helpers.h"
+#include "ardour/auditioner.h"
+#include "ardour/io_processor.h"
+#include "ardour/send.h"
+#include "ardour/processor.h"
+#include "ardour/user_bundle.h"
+#include "ardour/slave.h"
+#include "ardour/tempo.h"
+#include "ardour/audio_track.h"
+#include "ardour/midi_track.h"
+#include "ardour/midi_patch_manager.h"
+#include "ardour/cycle_timer.h"
+#include "ardour/utils.h"
+#include "ardour/named_selection.h"
+#include "ardour/version.h"
+#include "ardour/location.h"
+#include "ardour/audioregion.h"
+#include "ardour/midi_region.h"
+#include "ardour/crossfade.h"
+#include "ardour/control_protocol_manager.h"
+#include "ardour/region_factory.h"
+#include "ardour/source_factory.h"
+#include "ardour/playlist_factory.h"
+#include "ardour/filename_extensions.h"
+#include "ardour/directory_names.h"
+#include "ardour/template_utils.h"
+#include "ardour/ticker.h"
+#include "ardour/route_group.h"
+
+#include "control_protocol/control_protocol.h"
 
 #include "i18n.h"
 #include <locale.h>
@@ -102,14 +118,17 @@ void
 Session::first_stage_init (string fullpath, string snapshot_name)
 {
        if (fullpath.length() == 0) {
+               destroy ();
                throw failed_constructor();
        }
 
        char buf[PATH_MAX+1];
-       if (!realpath(fullpath.c_str(), buf) && (errno != ENOENT)) {
+       if (!realpath (fullpath.c_str(), buf) && (errno != ENOENT)) {
                error << string_compose(_("Could not use path %1 (%s)"), buf, strerror(errno)) << endmsg;
+               destroy ();
                throw failed_constructor();
        }
+
        _path = string(buf);
 
        if (_path[_path.length()-1] != '/') {
@@ -121,48 +140,45 @@ Session::first_stage_init (string fullpath, string snapshot_name)
        */
 
        _name = _current_snapshot_name = snapshot_name;
-       setup_raid_path (_path);
+
+       set_history_depth (Config->get_history_depth());
 
        _current_frame_rate = _engine.frame_rate ();
+       _nominal_frame_rate = _current_frame_rate;
+       _base_frame_rate = _current_frame_rate;
+
        _tempo_map = new TempoMap (_current_frame_rate);
        _tempo_map->StateChanged.connect (mem_fun (*this, &Session::tempo_map_changed));
 
+
+
        g_atomic_int_set (&processing_prohibited, 0);
-       send_cnt = 0;
        insert_cnt = 0;
        _transport_speed = 0;
        _last_transport_speed = 0;
+       phi = (uint64_t) (0x1000000);
+       target_phi = phi;
+       auto_play_legal = false;
        transport_sub_state = 0;
        _transport_frame = 0;
-       last_stop_frame = 0;
        end_location = new Location (0, 0, _("end"), Location::Flags ((Location::IsMark|Location::IsEnd)));
        start_location = new Location (0, 0, _("start"), Location::Flags ((Location::IsMark|Location::IsStart)));
-       _end_location_is_free = true;
        g_atomic_int_set (&_record_status, Disabled);
-       auto_play = false;
-       punch_in = false;
-       punch_out = false;
-       auto_loop = false;
-       seamless_loop = false;
        loop_changing = false;
-       auto_input = true;
-       crossfades_active = false;
-       all_safe = false;
-       auto_return = false;
+       play_loop = false;
+       have_looped = false;
        _last_roll_location = 0;
        _last_record_location = 0;
        pending_locate_frame = 0;
        pending_locate_roll = false;
        pending_locate_flush = false;
-       dstream_buffer_size = 0;
-       state_tree = 0;
+       audio_dstream_buffer_size = 0;
+       midi_dstream_buffer_size = 0;
        state_was_pending = false;
        set_next_event ();
        outbound_mtc_smpte_frame = 0;
        next_quarter_frame_to_send = -1;
        current_block_size = 0;
-       _solo_latched = true;
-       _solo_model = InverseMute;
        solo_update_disabled = false;
        currently_soloing = false;
        _have_captured = false;
@@ -170,130 +186,89 @@ Session::first_stage_init (string fullpath, string snapshot_name)
        _worst_input_latency = 0;
        _worst_track_latency = 0;
        _state_of_the_state = StateOfTheState(CannotSave|InitialConnecting|Loading);
+
        _slave = 0;
-       _slave_type = None;
-       butler_mixdown_buffer = 0;
-       butler_gain_buffer = 0;
-       mmc_control = false;
-       midi_control = true;
-       mmc = 0;
+       session_send_mmc = false;
+       session_send_mtc = false;
        post_transport_work = PostTransportWork (0);
        g_atomic_int_set (&butler_should_do_transport_work, 0);
-       g_atomic_int_set (&butler_active, 0);
        g_atomic_int_set (&_playback_load, 100);
        g_atomic_int_set (&_capture_load, 100);
        g_atomic_int_set (&_playback_load_min, 100);
        g_atomic_int_set (&_capture_load_min, 100);
-       _edit_mode = Slide;
-       pending_edit_mode = _edit_mode;
        _play_range = false;
-       input_auto_connect = AutoConnectOption (0);
-       output_auto_connect = AutoConnectOption (0);
-       waiting_to_start = false;
        _exporting = false;
+       _exporting_realtime = false;
        _gain_automation_buffer = 0;
        _pan_automation_buffer = 0;
        _npan_buffers = 0;
        pending_abort = false;
-       layer_model = MoveAddHigher;
-       xfade_model = ShortCrossfade;
        destructive_index = 0;
-       current_trans = 0;
+       first_file_data_format_reset = true;
+       first_file_header_format_reset = true;
+       butler_thread = (pthread_t) 0;
+       //midi_thread = (pthread_t) 0;
 
        AudioDiskstream::allocate_working_buffers();
 
        /* default short fade = 15ms */
 
-       Crossfade::set_short_xfade_length ((jack_nframes_t) floor ((15.0 * frame_rate()) / 1000.0));
-       DestructiveFileSource::setup_standard_crossfades (frame_rate());
+       Crossfade::set_short_xfade_length ((nframes_t) floor (config.get_short_xfade_seconds() * frame_rate()));
+       SndFileSource::setup_standard_crossfades (*this, frame_rate());
 
        last_mmc_step.tv_sec = 0;
        last_mmc_step.tv_usec = 0;
        step_speed = 0.0;
 
-       preroll.type = AnyTime::Frames;
-       preroll.frames = 0;
-       postroll.type = AnyTime::Frames;
-       postroll.frames = 0;
-
        /* click sounds are unset by default, which causes us to internal
           waveforms for clicks.
        */
        
-       _clicking = false;
-       click_requested = false;
-       click_data = 0;
-       click_emphasis_data = 0;
        click_length = 0;
        click_emphasis_length = 0;
+       _clicking = false;
 
        process_function = &Session::process_with_events;
 
-       if (Config->get_use_video_sync()) {
+       if (config.get_use_video_sync()) {
                waiting_for_sync_offset = true;
        } else {
                waiting_for_sync_offset = false;
        }
 
-       _current_frame_rate = 48000;
-       _base_frame_rate = 48000;
-
-       smpte_frames_per_second = 30;
-       video_pullup = 0.0;
-       smpte_drop_frames = false;
        last_smpte_when = 0;
        _smpte_offset = 0;
        _smpte_offset_negative = true;
        last_smpte_valid = false;
 
+       sync_time_vars ();
+
        last_rr_session_dir = session_dirs.begin();
        refresh_disk_space ();
 
        // set_default_fade (0.2, 5.0); /* steepness, millisecs */
 
-       /* default configuration */
-
-       do_not_record_plugins = false;
-       over_length_short = 2;
-       over_length_long = 10;
-       send_midi_timecode = false;
-       send_midi_machine_control = false;
-       shuttle_speed_factor = 1.0;
-       shuttle_speed_threshold = 5;
-       rf_speed = 2.0;
-       _meter_hold = 100; // XXX unknown units: number of calls to meter::set()
-       _meter_falloff = 0.375f; // XXX unknown units: refresh_rate
-       max_level = 0;
-       min_level = 0;
-
        /* slave stuff */
 
-       average_slave_delta = 1800;
+       average_slave_delta = 1800; // !!! why 1800 ????
        have_first_delta_accumulator = false;
        delta_accumulator_cnt = 0;
        slave_state = Stopped;
 
-       /* default SMPTE type is 30 FPS, non-drop */
-
-       set_smpte_type (30.0, false);
-       set_video_pullup (0.0);
-
        _engine.GraphReordered.connect (mem_fun (*this, &Session::graph_reordered));
 
        /* These are all static "per-class" signals */
 
        RegionFactory::CheckNewRegion.connect (mem_fun (*this, &Session::add_region));
        SourceFactory::SourceCreated.connect (mem_fun (*this, &Session::add_source));
-       Playlist::PlaylistCreated.connect (mem_fun (*this, &Session::add_playlist));
-       Redirect::RedirectCreated.connect (mem_fun (*this, &Session::add_redirect));
+       PlaylistFactory::PlaylistCreated.connect (mem_fun (*this, &Session::add_playlist));
+       Processor::ProcessorCreated.connect (mem_fun (*this, &Session::add_processor));
        NamedSelection::NamedSelectionCreated.connect (mem_fun (*this, &Session::add_named_selection));
-       Curve::CurveCreated.connect (mem_fun (*this, &Session::add_curve));
        AutomationList::AutomationListCreated.connect (mem_fun (*this, &Session::add_automation_list));
 
-       Controllable::Created.connect (mem_fun (*this, &Session::add_controllable));
-       Controllable::GoingAway.connect (mem_fun (*this, &Session::remove_controllable));
+       Controllable::Destroyed.connect (mem_fun (*this, &Session::remove_controllable));
 
-       IO::MoreChannels.connect (mem_fun (*this, &Session::ensure_buffers));
+       IO::PortCountChanged.connect (mem_fun (*this, &Session::ensure_buffers));
 
        /* stop IO objects from doing stuff until we're ready for them */
 
@@ -305,11 +280,10 @@ Session::first_stage_init (string fullpath, string snapshot_name)
 int
 Session::second_stage_init (bool new_session)
 {
-       AudioFileSource::set_peak_dir (peak_dir());
+       AudioFileSource::set_peak_dir (_session_dir->peak_path().to_string());
 
        if (!new_session) {
                if (load_state (_current_snapshot_name)) {
-                       cerr << "load state failed\n";
                        return -1;
                }
                remove_empty_sounds ();
@@ -319,14 +293,19 @@ Session::second_stage_init (bool new_session)
                return -1;
        }
 
-       /*if (start_midi_thread ()) {
+       if (start_midi_thread ()) {
                return -1;
-       }*/
+       }
+
+       // set_state() will call setup_raid_path(), but if it's a new session we need
+       // to call setup_raid_path() here.
 
        if (state_tree) {
                if (set_state (*state_tree->root())) {
                        return -1;
                }
+       } else {
+               setup_raid_path(_path);
        }
 
        /* we can't save till after ::when_engine_running() is called,
@@ -341,7 +320,7 @@ Session::second_stage_init (bool new_session)
 
        _state_of_the_state = StateOfTheState (_state_of_the_state|CannotSave|Loading);
 
-       // set_auto_input (true);
+
        _locations.changed.connect (mem_fun (this, &Session::locations_changed));
        _locations.added.connect (mem_fun (this, &Session::locations_added));
        setup_click_sounds (0);
@@ -352,294 +331,221 @@ Session::second_stage_init (bool new_session)
        _engine.Halted.connect (mem_fun (*this, &Session::engine_halted));
        _engine.Xrun.connect (mem_fun (*this, &Session::xrun_recovery));
 
-       if (_engine.running()) {
+       try {
                when_engine_running();
-       } else {
-               first_time_running = _engine.Running.connect (mem_fun (*this, &Session::when_engine_running));
        }
 
-       //send_full_time_code ();
+       /* handle this one in a different way than all others, so that its clear what happened */
+       
+       catch (AudioEngine::PortRegistrationFailure& err) {
+               error << err.what() << endmsg;
+               return -1;
+       }
+
+       catch (...) {
+               return -1;
+       }
+
+       BootMessage (_("Reset Remote Controls"));
+
+       send_full_time_code (0);
        _engine.transport_locate (0);
        deliver_mmc (MIDI::MachineControl::cmdMmcReset, 0);
        deliver_mmc (MIDI::MachineControl::cmdLocate, 0);
+       
+       MidiClockTicker::instance().set_session(*this);
+       MIDI::Name::MidiPatchManager::instance().set_session(*this);
+
+       /* initial program change will be delivered later; see ::config_changed() */
+
+       BootMessage (_("Reset Control Protocols"));
 
        ControlProtocolManager::instance().set_session (*this);
 
-       if (new_session) {
-               _end_location_is_free = true;
-       } else {
-               _end_location_is_free = false;
+       config.set_end_marker_is_free (new_session);
+
+       _state_of_the_state = Clean;
+       
+       DirtyChanged (); /* EMIT SIGNAL */
+
+       if (state_was_pending) {
+               save_state (_current_snapshot_name);
+               remove_pending_capture_state ();
+               state_was_pending = false;
        }
        
-        restore_history(_current_snapshot_name);
+       BootMessage (_("Session loading complete"));
+
        return 0;
 }
 
 string
 Session::raid_path () const
 {
-       string path;
+       SearchPath raid_search_path;
 
        for (vector<space_and_path>::const_iterator i = session_dirs.begin(); i != session_dirs.end(); ++i) {
-               path += (*i).path;
-               path += ':';
+               raid_search_path += sys::path((*i).path);
        }
        
-       return path.substr (0, path.length() - 1); // drop final colon
-}
-
-void
-Session::set_raid_path (string path)
-{
-       /* public-access to setup_raid_path() */
-
-       setup_raid_path (path);
+       return raid_search_path.to_string ();
 }
 
 void
 Session::setup_raid_path (string path)
 {
-       string::size_type colon;
-       string remaining;
-       space_and_path sp;
-       string fspath;
-       string::size_type len = path.length();
-       int colons;
-
-       colons = 0;
-
-       if (path.length() == 0) {
+       if (path.empty()) {
                return;
        }
+       
+       space_and_path sp;
+       string fspath;
 
        session_dirs.clear ();
 
-       for (string::size_type n = 0; n < len; ++n) {
-               if (path[n] == ':') {
-                       colons++;
-               }
-       }
-
-       if (colons == 0) {
-
-               /* no multiple search path, just one location (common case) */
+       SearchPath search_path(path);
+       SearchPath sound_search_path;
+       SearchPath midi_search_path;
 
-               sp.path = path;
-               sp.blocks = 0;
+       for (SearchPath::const_iterator i = search_path.begin(); i != search_path.end(); ++i) {
+               sp.path = (*i).to_string ();
+               sp.blocks = 0; // not needed
                session_dirs.push_back (sp);
 
-               string fspath;
+               SessionDirectory sdir(sp.path);
 
-               /* sounds dir */
-
-               fspath += sp.path;
-               if (fspath[fspath.length()-1] != '/') {
-                       fspath += '/';
-               }
-               fspath += sound_dir_name;
-               fspath += ':';
-
-               /* tape dir */
-
-               fspath += sp.path;
-               if (fspath[fspath.length()-1] != '/') {
-                       fspath += '/';
-               }
-               fspath += tape_dir_name;
-               
-               AudioFileSource::set_search_path (fspath);
-               SMFSource::set_search_path (fspath); // FIXME: should be different
-
-               return;
+               sound_search_path += sdir.sound_path ();
+               midi_search_path += sdir.midi_path ();
        }
 
-       remaining = path;
+       // set the search path for each data type
+       FileSource::set_search_path (DataType::AUDIO, sound_search_path.to_string ());
+       SMFSource::set_search_path (DataType::MIDI, midi_search_path.to_string ());
 
-       while ((colon = remaining.find_first_of (':')) != string::npos) {
-               
-               sp.blocks = 0;
-               sp.path = remaining.substr (0, colon);
-               session_dirs.push_back (sp);
+       // reset the round-robin soundfile path thingie
+       last_rr_session_dir = session_dirs.begin();
+}
 
-               /* add sounds to file search path */
+int
+Session::ensure_subdirs ()
+{
+       string dir;
 
-               fspath += sp.path;
-               if (fspath[fspath.length()-1] != '/') {
-                       fspath += '/';
-               }
-               fspath += sound_dir_name;
-               fspath += ':';
+       dir = session_directory().peak_path().to_string();
 
-               /* add tape dir to file search path */
+       if (g_mkdir_with_parents (dir.c_str(), 0755) < 0) {
+               error << string_compose(_("Session: cannot create session peakfile folder \"%1\" (%2)"), dir, strerror (errno)) << endmsg;
+               return -1;
+       }
 
-               fspath += sp.path;
-               if (fspath[fspath.length()-1] != '/') {
-                       fspath += '/';
-               }
-               fspath += tape_dir_name;
-               fspath += ':';
+       dir = session_directory().sound_path().to_string();
 
-               remaining = remaining.substr (colon+1);
+       if (g_mkdir_with_parents (dir.c_str(), 0755) < 0) {
+               error << string_compose(_("Session: cannot create session sounds dir \"%1\" (%2)"), dir, strerror (errno)) << endmsg;
+               return -1;
        }
+       
+       dir = session_directory().midi_path().to_string();
 
-       if (remaining.length()) {
+       if (g_mkdir_with_parents (dir.c_str(), 0755) < 0) {
+               error << string_compose(_("Session: cannot create session midi dir \"%1\" (%2)"), dir, strerror (errno)) << endmsg;
+               return -1;
+       }
 
-               sp.blocks = 0;
-               sp.path = remaining;
+       dir = session_directory().dead_sound_path().to_string();
 
-               fspath += ':';
-               fspath += sp.path;
-               if (fspath[fspath.length()-1] != '/') {
-                       fspath += '/';
-               }
-               fspath += sound_dir_name;
-               fspath += ':';
+       if (g_mkdir_with_parents (dir.c_str(), 0755) < 0) {
+               error << string_compose(_("Session: cannot create session dead sounds folder \"%1\" (%2)"), dir, strerror (errno)) << endmsg;
+               return -1;
+       }
 
-               fspath += sp.path;
-               if (fspath[fspath.length()-1] != '/') {
-                       fspath += '/';
-               }
-               fspath += tape_dir_name;
+       dir = session_directory().export_path().to_string();
 
-               session_dirs.push_back (sp);
+       if (g_mkdir_with_parents (dir.c_str(), 0755) < 0) {
+               error << string_compose(_("Session: cannot create session export folder \"%1\" (%2)"), dir, strerror (errno)) << endmsg;
+               return -1;
        }
 
-       /* set the AudioFileSource search path */
-
-       AudioFileSource::set_search_path (fspath);
-       SMFSource::set_search_path (fspath); // FIXME: should be different
+       dir = analysis_dir ();
 
-       /* reset the round-robin soundfile path thingie */
+       if (g_mkdir_with_parents (dir.c_str(), 0755) < 0) {
+               error << string_compose(_("Session: cannot create session analysis folder \"%1\" (%2)"), dir, strerror (errno)) << endmsg;
+               return -1;
+       }
 
-       last_rr_session_dir = session_dirs.begin();
+       return 0;
 }
 
 int
-Session::create (bool& new_session, string* mix_template, jack_nframes_t initial_length)
+Session::create (bool& new_session, const string& mix_template, nframes_t initial_length)
 {
-       string dir;
-       
-       if (mkdir (_path.c_str(), 0755) < 0) {
-               if (errno == EEXIST) {
-                       new_session = false;
-               } else {
-                       error << string_compose(_("Session: cannot create session dir \"%1\" (%2)"), _path, strerror (errno)) << endmsg;
-                       return -1;
-               }
-       } else {
-               new_session = true;
-       }
 
-       dir = peak_dir ();
-
-       if (mkdir (dir.c_str(), 0755) < 0) {
-               if (errno != EEXIST) {
-                       error << string_compose(_("Session: cannot create session peakfile dir \"%1\" (%2)"), dir, strerror (errno)) << endmsg;
-                       return -1;
-               }
+       if (g_mkdir_with_parents (_path.c_str(), 0755) < 0) {
+               error << string_compose(_("Session: cannot create session folder \"%1\" (%2)"), _path, strerror (errno)) << endmsg;
+               return -1;
        }
 
-       dir = sound_dir ();
-
-       if (mkdir (dir.c_str(), 0755) < 0) {
-               if (errno != EEXIST) {
-                       error << string_compose(_("Session: cannot create session sounds dir \"%1\" (%2)"), dir, strerror (errno)) << endmsg;
-                       return -1;
-               }
+       if (ensure_subdirs ()) {
+               return -1;
        }
 
-       dir = tape_dir ();
+       /* check new_session so we don't overwrite an existing one */
 
-       if (mkdir (dir.c_str(), 0755) < 0) {
-               if (errno != EEXIST) {
-                       error << string_compose(_("Session: cannot create session tape dir \"%1\" (%2)"), dir, strerror (errno)) << endmsg;
-                       return -1;
-               }
-       }
+       if (!mix_template.empty()) {
+               std::string in_path = mix_template;
 
-       dir = dead_sound_dir ();
+               ifstream in(in_path.c_str());
 
-       if (mkdir (dir.c_str(), 0755) < 0) {
-               if (errno != EEXIST) {
-                       error << string_compose(_("Session: cannot create session dead sounds dir \"%1\" (%2)"), dir, strerror (errno)) << endmsg;
-                       return -1;
-               }
-       }
+               if (in){
+                       string out_path = _path;
+                       out_path += _name;
+                       out_path += statefile_suffix;
 
-       dir = automation_dir ();
+                       ofstream out(out_path.c_str());
 
-       if (mkdir (dir.c_str(), 0755) < 0) {
-               if (errno != EEXIST) {
-                       error << string_compose(_("Session: cannot create session automation dir \"%1\" (%2)"), dir, strerror (errno)) << endmsg;
-                       return -1;
-               }
-       }
+                       if (out){
+                               out << in.rdbuf();
 
-       
-       /* check new_session so we don't overwrite an existing one */
-       
-       if (mix_template) {
-               if (new_session){
-                       std::string in_path = *mix_template;
+                               // okay, session is set up.  Treat like normal saved
+                               // session from now on.
+
+                               new_session = false;
+                               return 0;
 
-                       ifstream in(in_path.c_str());
-                       
-                       if (in){
-                               string out_path = _path;
-                               out_path += _name;
-                               out_path += _statefile_suffix;
-                               
-                               ofstream out(out_path.c_str());
-
-                               if (out){
-                                       out << in.rdbuf();
-                                       
-                                       // okay, session is set up.  Treat like normal saved
-                                       // session from now on.
-                                       
-                                       new_session = false;
-                                       return 0;
-                                       
-                               } else {
-                                       error << string_compose (_("Could not open %1 for writing mix template"), out_path) 
-                                             << endmsg;
-                                       return -1;
-                               }
-                               
                        } else {
-                               error << string_compose (_("Could not open mix template %1 for reading"), in_path) 
-                                     << endmsg;
+                               error << string_compose (_("Could not open %1 for writing mix template"), out_path) 
+                                       << endmsg;
                                return -1;
                        }
-                       
-                       
+
                } else {
-                       warning << _("Session already exists.  Not overwriting") << endmsg;
+                       error << string_compose (_("Could not open mix template %1 for reading"), in_path) 
+                               << endmsg;
                        return -1;
                }
+
        }
+       
+       /* Instantiate metadata */
+       
+       _metadata = new SessionMetadata ();
 
-       if (new_session) {
+       /* set initial start + end point */
 
-               /* set initial start + end point */
+       start_location->set_end (0);
+       _locations.add (start_location);
 
-               start_location->set_end (0);
-               _locations.add (start_location);
+       end_location->set_end (initial_length);
+       _locations.add (end_location);
 
-               end_location->set_end (initial_length);
-               _locations.add (end_location);
-               
-               _state_of_the_state = Clean;
+       _state_of_the_state = Clean;
 
-               if (save_state (_current_snapshot_name)) {
-                        save_history (_current_snapshot_name);
-                       return -1;
-               }
-       }
+       save_state ("");
 
        return 0;
 }
 
+
 int
 Session::load_diskstreams (const XMLNode& node)
 {
@@ -672,29 +578,106 @@ Session::load_diskstreams (const XMLNode& node)
        return 0;
 }
 
+void
+Session::maybe_write_autosave()
+{
+        if (dirty() && record_status() != Recording) {
+                save_state("", true);
+        }
+}
+
 void
 Session::remove_pending_capture_state ()
 {
-       string xml_path;
+       sys::path pending_state_file_path(_session_dir->root_path());
+       
+       pending_state_file_path /= _current_snapshot_name + pending_suffix;
 
-       xml_path = _path;
-       xml_path += _current_snapshot_name;
-       xml_path += _pending_suffix;
+       try
+       {
+               sys::remove (pending_state_file_path);
+       }
+       catch(sys::filesystem_error& ex)
+       {
+               error << string_compose(_("Could remove pending capture state at path \"%1\" (%2)"),
+                               pending_state_file_path.to_string(), ex.what()) << endmsg;
+       }
+}
 
-       unlink (xml_path.c_str());
+/** Rename a state file.
+ * @param snapshot_name Snapshot name.
+ */
+void
+Session::rename_state (string old_name, string new_name)
+{
+       if (old_name == _current_snapshot_name || old_name == _name) {
+               /* refuse to rename the current snapshot or the "main" one */
+               return;
+       }
+
+       const string old_xml_filename = old_name + statefile_suffix;
+       const string new_xml_filename = new_name + statefile_suffix;
+
+       const sys::path old_xml_path = _session_dir->root_path() / old_xml_filename;
+       const sys::path new_xml_path = _session_dir->root_path() / new_xml_filename;
+
+       try
+       {
+               sys::rename (old_xml_path, new_xml_path);
+       }
+       catch (const sys::filesystem_error& err)
+       {
+               error << string_compose(_("could not rename snapshot %1 to %2 (%3)"),
+                               old_name, new_name, err.what()) << endmsg;
+       }
+}
+
+/** Remove a state file.
+ * @param snapshot_name Snapshot name.
+ */
+void
+Session::remove_state (string snapshot_name)
+{
+       if (snapshot_name == _current_snapshot_name || snapshot_name == _name) {
+               // refuse to remove the current snapshot or the "main" one
+               return;
+       }
+
+       sys::path xml_path(_session_dir->root_path());
+
+       xml_path /= snapshot_name + statefile_suffix;
+
+       if (!create_backup_file (xml_path)) {
+               // don't remove it if a backup can't be made
+               // create_backup_file will log the error.
+               return;
+       }
+
+       // and delete it
+       sys::remove (xml_path);
 }
 
 int
 Session::save_state (string snapshot_name, bool pending)
 {
        XMLTree tree;
-       string xml_path;
-       string bak_path;
+       sys::path xml_path(_session_dir->root_path());
 
        if (_state_of_the_state & CannotSave) {
                return 1;
        }
 
+       if (!_engine.connected ()) {
+               error << _("Ardour's audio engine is not connected and state saving would lose all I/O connections. Session not saved")
+                     << endmsg;
+               return 1;
+       }
+
+       /* tell sources we're saving first, in case they write out to a new file
+        * which should be saved with the state rather than the old one */
+       for (SourceMap::const_iterator i = sources.begin(); i != sources.end(); ++i)
+               i->second->session_saved();
+
        tree.set_root (&get_state());
 
        if (snapshot_name.empty()) {
@@ -703,50 +686,47 @@ Session::save_state (string snapshot_name, bool pending)
 
        if (!pending) {
 
-               xml_path = _path;
-               xml_path += snapshot_name;
-               xml_path += _statefile_suffix;
-               bak_path = xml_path;
-               bak_path += ".bak";
-               
-               // Make backup of state file
+               /* proper save: use statefile_suffix (.ardour in English) */
                
-               if ((access (xml_path.c_str(), F_OK) == 0) &&
-                   (rename(xml_path.c_str(), bak_path.c_str()))) {
-                       error << _("could not backup old state file, current state not saved.") << endmsg;
+               xml_path /= snapshot_name + statefile_suffix;
+
+               /* make a backup copy of the old file */
+
+               if (sys::exists(xml_path) && !create_backup_file (xml_path)) {
+                       // create_backup_file will log the error
                        return -1;
                }
 
        } else {
 
-               xml_path = _path;
-               xml_path += snapshot_name;
-               xml_path += _pending_suffix;
-
+               /* pending save: use pending_suffix (.pending in English) */
+               xml_path /= snapshot_name + pending_suffix;
        }
 
-       if (!tree.write (xml_path)) {
-               error << string_compose (_("state could not be saved to %1"), xml_path) << endmsg;
+       sys::path tmp_path(_session_dir->root_path());
 
-               /* don't leave a corrupt file lying around if it is
-                  possible to fix.
-               */
+       tmp_path /= snapshot_name + temp_suffix;
 
-               if (unlink (xml_path.c_str())) {
-                       error << string_compose (_("could not remove corrupt state file %1"), xml_path) << endmsg;
-               } else {
-                       if (!pending) {
-                               if (rename (bak_path.c_str(), xml_path.c_str())) {
-                                       error << string_compose (_("could not restore state file from backup %1"), bak_path) << endmsg;
-                               }
-                       }
-               }
+       // cerr << "actually writing state to " << xml_path.to_string() << endl;
 
+       if (!tree.write (tmp_path.to_string())) {
+               error << string_compose (_("state could not be saved to %1"), tmp_path.to_string()) << endmsg;
+               sys::remove (tmp_path);
                return -1;
+
+       } else {
+
+               if (rename (tmp_path.to_string().c_str(), xml_path.to_string().c_str()) != 0) {
+                       error << string_compose (_("could not rename temporary session file %1 to %2"),
+                                       tmp_path.to_string(), xml_path.to_string()) << endmsg;
+                       sys::remove (tmp_path);
+                       return -1;
+               }
        }
 
        if (!pending) {
-                save_history(snapshot_name);
+
+               save_history (snapshot_name);
 
                bool was_dirty = dirty();
 
@@ -755,7 +735,7 @@ Session::save_state (string snapshot_name, bool pending)
                if (was_dirty) {
                        DirtyChanged (); /* EMIT SIGNAL */
                }
-               
+
                StateSaved (snapshot_name); /* EMIT SIGNAL */
        }
 
@@ -775,22 +755,17 @@ Session::restore_state (string snapshot_name)
 int
 Session::load_state (string snapshot_name)
 {
-       if (state_tree) {
-               delete state_tree;
-               state_tree = 0;
-       }
+       delete state_tree;
+       state_tree = 0;
 
-       string xmlpath;
-       
        state_was_pending = false;
 
        /* check for leftover pending state from a crashed capture attempt */
 
-       xmlpath = _path;
-       xmlpath += snapshot_name;
-       xmlpath += _pending_suffix;
+       sys::path xmlpath(_session_dir->root_path());
+       xmlpath /= snapshot_name + pending_suffix;
 
-       if (!access (xmlpath.c_str(), F_OK)) {
+       if (sys::exists (xmlpath)) {
 
                /* there is pending state from a crashed capture attempt */
 
@@ -800,14 +775,12 @@ Session::load_state (string snapshot_name)
        } 
 
        if (!state_was_pending) {
-
-               xmlpath = _path;
-               xmlpath += snapshot_name;
-               xmlpath += _statefile_suffix;
+               xmlpath = _session_dir->root_path();
+               xmlpath /= snapshot_name + statefile_suffix;
        }
-
-       if (access (xmlpath.c_str(), F_OK)) {
-               error << string_compose(_("%1: session state information file \"%2\" doesn't exist!"), _name, xmlpath) << endmsg;
+       
+       if (!sys::exists (xmlpath)) {
+               error << string_compose(_("%1: session state information file \"%2\" doesn't exist!"), _name, xmlpath.to_string()) << endmsg;
                return 1;
        }
 
@@ -815,492 +788,81 @@ Session::load_state (string snapshot_name)
 
        set_dirty();
 
-       if (state_tree->read (xmlpath)) {
-               return 0;
-       } else {
-               error << string_compose(_("Could not understand ardour file %1"), xmlpath) << endmsg;
+       if (!state_tree->read (xmlpath.to_string())) {
+               error << string_compose(_("Could not understand ardour file %1"), xmlpath.to_string()) << endmsg;
+               delete state_tree;
+               state_tree = 0;
+               return -1;
        }
 
-       delete state_tree;
-       state_tree = 0;
-       return -1;
-}
-
-int
-Session::load_options (const XMLNode& node)
-{
-       XMLNode* child;
-       XMLProperty* prop;
-       bool have_fade_msecs = false;
-       bool have_fade_steepness = false;
-       float fade_msecs = 0;
-       float fade_steepness = 0;
-       SlaveSource slave_src = None;
-       int x;
-       LocaleGuard lg (X_("POSIX"));
+       XMLNode& root (*state_tree->root());
        
-       if ((child = find_named_node (node, "input-auto-connect")) != 0) {
-               if ((prop = child->property ("val")) != 0) {
-                       sscanf (prop->value().c_str(), "%x", &x);
-                       input_auto_connect = AutoConnectOption (x);
-               }
-       }
-
-       if ((child = find_named_node (node, "output-auto-connect")) != 0) {
-               if ((prop = child->property ("val")) != 0) {
-                       sscanf (prop->value().c_str(), "%x", &x);
-                       output_auto_connect = AutoConnectOption (x);
-               }
-       }
-                               
-       if ((child = find_named_node (node, "slave")) != 0) {
-               if ((prop = child->property ("type")) != 0) {
-                       if (prop->value() == "none") {
-                               slave_src = None;
-                       } else if (prop->value() == "mtc") {
-                               slave_src = MTC;
-                       } else if (prop->value() == "jack") {
-                               slave_src = JACK;
-                       }
-                       set_slave_source (slave_src, 0);
-               }
-       }
-
-       /* we cannot set edit mode if we are loading a session,
-          because it might destroy the playlist's positioning
-       */
-
-       if ((child = find_named_node (node, "edit-mode")) != 0) {
-               if ((prop = child->property ("val")) != 0) {
-                       if (prop->value() == "slide") {
-                               pending_edit_mode = Slide;
-                       } else if (prop->value() == "splice") {
-                               pending_edit_mode = Splice;
-                       } 
-               }
-       }
-                               
-       if ((child = find_named_node (node, "send-midi-timecode")) != 0) {
-               if ((prop = child->property ("val")) != 0) {
-                       bool x = (prop->value() == "yes");
-                       send_mtc = !x; /* force change in value */
-                       set_send_mtc (x);
-               }
-       }
-       if ((child = find_named_node (node, "send-midi-machine-control")) != 0) {
-               if ((prop = child->property ("val")) != 0) {
-                       bool x = (prop->value() == "yes");
-                       send_mmc = !x; /* force change in value */
-                       set_send_mmc (prop->value() == "yes");
-               }
-       }
-       if ((child = find_named_node (node, "max-level")) != 0) {
-               if ((prop = child->property ("val")) != 0) {
-                       max_level = atoi (prop->value().c_str());
-               }
-       }
-       if ((child = find_named_node (node, "min-level")) != 0) {
-               if ((prop = child->property ("val")) != 0) {
-                       min_level = atoi (prop->value().c_str());
-               }
-       }
-       if ((child = find_named_node (node, "meter-hold")) != 0) {
-               if ((prop = child->property ("val")) != 0) {
-                       _meter_hold = atof (prop->value().c_str());
-               }
-       }
-       if ((child = find_named_node (node, "meter-falloff")) != 0) {
-               if ((prop = child->property ("val")) != 0) {
-                       _meter_falloff = atof (prop->value().c_str());
-               }
-       }
-       if ((child = find_named_node (node, "long-over-length")) != 0) {
-               if ((prop = child->property ("val")) != 0) {
-                       over_length_long = atoi (prop->value().c_str());
-               }
-       }
-       if ((child = find_named_node (node, "short-over-length")) != 0) {
-               if ((prop = child->property ("val")) != 0) {
-                       over_length_short = atoi (prop->value().c_str());
-               }
-       }
-       if ((child = find_named_node (node, "shuttle-speed-factor")) != 0) {
-               if ((prop = child->property ("val")) != 0) {
-                       shuttle_speed_factor = atof (prop->value().c_str());
-               }
-       }
-       if ((child = find_named_node (node, "shuttle-speed-threshold")) != 0) {
-               if ((prop = child->property ("val")) != 0) {
-                       shuttle_speed_threshold = atof (prop->value().c_str());
-               }
-       }
-       if ((child = find_named_node (node, "rf-speed")) != 0) {
-               if ((prop = child->property ("val")) != 0) {
-                       rf_speed = atof (prop->value().c_str());
-               }
-       }
-       if ((child = find_named_node (node, "video-pullup")) != 0) {
-               if ((prop = child->property ("val")) != 0) {
-                       set_video_pullup( atof (prop->value().c_str()) );
-               }
-       }
-       if ((child = find_named_node (node, "smpte-frames-per-second")) != 0) {
-               if ((prop = child->property ("val")) != 0) {
-                       set_smpte_type( atof (prop->value().c_str()), smpte_drop_frames );
-               }
-       }
-       if ((child = find_named_node (node, "smpte-drop-frames")) != 0) {
-               if ((prop = child->property ("val")) != 0) {
-                       set_smpte_type( smpte_frames_per_second, (prop->value() == "yes") );
-               }
-       }
-       if ((child = find_named_node (node, "smpte-offset")) != 0) {
-               if ((prop = child->property ("val")) != 0) {
-                       set_smpte_offset( atoi (prop->value().c_str()) );
-               }
-       }
-       if ((child = find_named_node (node, "smpte-offset-negative")) != 0) {
-               if ((prop = child->property ("val")) != 0) {
-                       set_smpte_offset_negative( (prop->value() == "yes") );
-               }
-       }
-       if ((child = find_named_node (node, "click-sound")) != 0) {
-               if ((prop = child->property ("val")) != 0) {
-                       click_sound = prop->value();
-               }
-       }
-       if ((child = find_named_node (node, "click-emphasis-sound")) != 0) {
-               if ((prop = child->property ("val")) != 0) {
-                       click_emphasis_sound = prop->value();
-               }
-       }
-
-       if ((child = find_named_node (node, "solo-model")) != 0) {
-               if ((prop = child->property ("val")) != 0) {
-                       if (prop->value() == "SoloBus")
-                               _solo_model = SoloBus;
-                       else
-                               _solo_model = InverseMute;
-               }
+       if (root.name() != X_("Session")) {
+               error << string_compose (_("Session file %1 is not an Ardour session"), xmlpath.to_string()) << endmsg;
+               delete state_tree;
+               state_tree = 0;
+               return -1;
        }
 
-       /* BOOLEAN OPTIONS */
-
-       if ((child = find_named_node (node, "auto-play")) != 0) {
-               if ((prop = child->property ("val")) != 0) {
-                       set_auto_play (prop->value() == "yes");
-               }
-       }
-       if ((child = find_named_node (node, "auto-input")) != 0) {
-               if ((prop = child->property ("val")) != 0) {
-                       set_auto_input (prop->value() == "yes");
-               }
-       }
-       if ((child = find_named_node (node, "seamless-loop")) != 0) {
-               if ((prop = child->property ("val")) != 0) {
-                       set_seamless_loop (prop->value() == "yes");
-               }
-       }
-       if ((child = find_named_node (node, "punch-in")) != 0) {
-               if ((prop = child->property ("val")) != 0) {
-                       set_punch_in (prop->value() == "yes");
-               }
-       }
-       if ((child = find_named_node (node, "punch-out")) != 0) {
-               if ((prop = child->property ("val")) != 0) {
-                       set_punch_out (prop->value() == "yes");
-               }
-       }
-       if ((child = find_named_node (node, "auto-return")) != 0) {
-               if ((prop = child->property ("val")) != 0) {
-                       set_auto_return (prop->value() == "yes");
-               }
-       }
-       if ((child = find_named_node (node, "send-mtc")) != 0) {
-               if ((prop = child->property ("val")) != 0) {
-                       set_send_mtc (prop->value() == "yes");
-               }
-       }
-       if ((child = find_named_node (node, "mmc-control")) != 0) {
-               if ((prop = child->property ("val")) != 0) {
-                       set_mmc_control (prop->value() == "yes");
-               }
-       }
-       if ((child = find_named_node (node, "midi-control")) != 0) {
-               if ((prop = child->property ("val")) != 0) {
-                       set_midi_control (prop->value() == "yes");
-               }
-       }
-       if ((child = find_named_node (node, "midi-feedback")) != 0) {
-               if ((prop = child->property ("val")) != 0) {
-                       set_midi_feedback (prop->value() == "yes");
-               }
-       }
-       // Legacy support for <recording-plugins>
-       if ((child = find_named_node (node, "recording-plugins")) != 0) {
-               if ((prop = child->property ("val")) != 0) {
-                       set_do_not_record_plugins (prop->value() == "no");
-               }
-       }
-       if ((child = find_named_node (node, "do-not-record-plugins")) != 0) {
-               if ((prop = child->property ("val")) != 0) {
-                       set_do_not_record_plugins (prop->value() == "yes");
-               }
-       }
-       if ((child = find_named_node (node, "crossfades-active")) != 0) {
-               if ((prop = child->property ("val")) != 0) {
-                       set_crossfades_active (prop->value() == "yes");
-               }
-       }
-       if ((child = find_named_node (node, "audible-click")) != 0) {
-               if ((prop = child->property ("val")) != 0) {
-                       set_clicking (prop->value() == "yes");
-               }
-       }
+       const XMLProperty* prop;
+       bool is_old = false; // session is _very_ old (pre-2.0)
 
-       if ((child = find_named_node (node, "end-marker-is-free")) != 0) {
-               if ((prop = child->property ("val")) != 0) {
-                       _end_location_is_free = (prop->value() == "yes");
+       if ((prop = root.property ("version")) == 0) {
+               /* no version implies very old version of Ardour */
+               is_old = true;
+       } else {
+               int major_version;
+               major_version = atoi (prop->value().c_str()); // grab just the first number before the period
+               if (major_version < 2) {
+                       is_old = true;
                }
        }
 
-       if ((child = find_named_node (node, "layer-model")) != 0) {
-               if ((prop = child->property ("val")) != 0) {
-                       if (prop->value() == X_("LaterHigher")) {
-                               set_layer_model (LaterHigher);
-                       } else if (prop->value() == X_("AddHigher")) {
-                               set_layer_model (AddHigher);
-                       } else {
-                               set_layer_model (MoveAddHigher);
-                       }
-               }
-       }
+       if (is_old) {
 
-       if ((child = find_named_node (node, "xfade-model")) != 0) {
-               if ((prop = child->property ("val")) != 0) {
-                       if (prop->value() == X_("Short")) {
-                               set_xfade_model (ShortCrossfade);
-                       } else {
-                               set_xfade_model (FullCrossfade);
-                       }
-               }
-       }
+               sys::path backup_path(_session_dir->root_path());
 
-       if ((child = find_named_node (node, "short-xfade-length")) != 0) {
-               if ((prop = child->property ("val")) != 0) {
-                       /* value is stored as a fractional seconds */
-                       float secs = atof (prop->value().c_str());
-                       Crossfade::set_short_xfade_length ((jack_nframes_t) floor (secs * frame_rate()));
-               } 
-       }
+               backup_path /= snapshot_name + "-1" + statefile_suffix;
 
-       if ((child = find_named_node (node, "full-xfades-unmuted")) != 0) {
-               if ((prop = child->property ("val")) != 0) {
-                       crossfades_active = (prop->value() == "yes");
+               // only create a backup once
+               if (sys::exists (backup_path)) {
+                       return 0;
                }
-       } 
 
-       /* TIED OPTIONS */
+               info << string_compose (_("Copying old session file %1 to %2\nUse %2 with Ardour versions before 2.0 from now on"),
+                                       xmlpath.to_string(), backup_path.to_string()) 
+                    << endmsg;
 
-       if ((child = find_named_node (node, "default-fade-steepness")) != 0) {
-               if ((prop = child->property ("val")) != 0) {
-                       fade_steepness = atof (prop->value().c_str());
-                       have_fade_steepness = true;
+               try
+               {
+                       sys::copy_file (xmlpath, backup_path);
                }
-       }
-       if ((child = find_named_node (node, "default-fade-msec")) != 0) {
-               if ((prop = child->property ("val")) != 0) {
-                       fade_msecs = atof (prop->value().c_str());
-                       have_fade_msecs = true;
+               catch(sys::filesystem_error& ex)
+               {
+                       error << string_compose (_("Unable to make backup of state file %1 (%2)"),
+                                       xmlpath.to_string(), ex.what())
+                               << endmsg;
+                       return -1;
                }
        }
 
-       if (have_fade_steepness || have_fade_msecs) {
-               // set_default_fade (fade_steepness, fade_msecs);
-       }
-
        return 0;
 }
 
-XMLNode&
-Session::get_options () const
+int
+Session::load_options (const XMLNode& node)
 {
-       XMLNode* opthead;
-       XMLNode* child;
-       char buf[32];
        LocaleGuard lg (X_("POSIX"));
 
-       opthead = new XMLNode ("Options");
-
-       SlaveSource src = slave_source ();
-       string src_string;
-       switch (src) {
-       case None:
-               src_string = "none";
-               break;
-       case MTC:
-               src_string = "mtc";
-               break;
-       case JACK:
-               src_string = "jack";
-               break;
-       }
-       child = opthead->add_child ("slave");
-       child->add_property ("type", src_string);
-       
-       child = opthead->add_child ("send-midi-timecode");
-       child->add_property ("val", send_midi_timecode?"yes":"no");
-
-       child = opthead->add_child ("send-midi-machine-control");
-       child->add_property ("val", send_midi_machine_control?"yes":"no");
-
-       snprintf (buf, sizeof(buf)-1, "%x", (int) input_auto_connect);
-       child = opthead->add_child ("input-auto-connect");
-       child->add_property ("val", buf);
-
-       snprintf (buf, sizeof(buf)-1, "%x", (int) output_auto_connect);
-       child = opthead->add_child ("output-auto-connect");
-       child->add_property ("val", buf);
-
-       snprintf (buf, sizeof(buf)-1, "%d", max_level);
-       child = opthead->add_child ("max-level");
-       child->add_property ("val", buf);
-
-       snprintf (buf, sizeof(buf)-1, "%d", min_level);
-       child = opthead->add_child ("min-level");
-       child->add_property ("val", buf);
-
-       snprintf (buf, sizeof(buf)-1, "%f", _meter_hold);
-       child = opthead->add_child ("meter-hold");
-       child->add_property ("val", buf);
-
-       snprintf (buf, sizeof(buf)-1, "%f", _meter_falloff);
-       child = opthead->add_child ("meter-falloff");
-       child->add_property ("val", buf);
-       
-       snprintf (buf, sizeof(buf)-1, "%u", over_length_long);
-       child = opthead->add_child ("long-over-length");
-       child->add_property ("val", buf);
-
-       snprintf (buf, sizeof(buf)-1, "%u", over_length_short);
-       child = opthead->add_child ("short-over-length");
-       child->add_property ("val", buf);
+       config.set_variables (node);
 
-       snprintf (buf, sizeof(buf)-1, "%f", shuttle_speed_factor);
-       child = opthead->add_child ("shuttle-speed-factor");
-       child->add_property ("val", buf);
-
-       snprintf (buf, sizeof(buf)-1, "%f", shuttle_speed_threshold);
-       child = opthead->add_child ("shuttle-speed-threshold");
-       child->add_property ("val", buf);
+       /* now reset MIDI ports because the session can have its own 
+          MIDI configuration.
+       */
 
-       snprintf (buf, sizeof(buf)-1, "%f", rf_speed);
-       child = opthead->add_child ("rf-speed");
-       child->add_property ("val", buf);
+       setup_midi ();
 
-       snprintf (buf, sizeof(buf)-1, "%.4f", video_pullup);
-       child = opthead->add_child ("video-pullup");
-       child->add_property ("val", buf);
-       
-       snprintf (buf, sizeof(buf)-1, "%.2f", smpte_frames_per_second);
-       child = opthead->add_child ("smpte-frames-per-second");
-       child->add_property ("val", buf);
-       
-       child = opthead->add_child ("smpte-drop-frames");
-       child->add_property ("val", smpte_drop_frames ? "yes" : "no");
-       
-       snprintf (buf, sizeof(buf)-1, "%u", smpte_offset ());
-       child = opthead->add_child ("smpte-offset");
-       child->add_property ("val", buf);
-       
-       child = opthead->add_child ("smpte-offset-negative");
-       child->add_property ("val", smpte_offset_negative () ? "yes" : "no");
-       
-       child = opthead->add_child ("edit-mode");
-       switch (_edit_mode) {
-       case Splice:
-               child->add_property ("val", "splice");
-               break;
-
-       case Slide:
-               child->add_property ("val", "slide");
-               break;
-       }
-
-       child = opthead->add_child ("auto-play");
-       child->add_property ("val", get_auto_play () ? "yes" : "no");
-       child = opthead->add_child ("auto-input");
-       child->add_property ("val", get_auto_input () ? "yes" : "no");
-       child = opthead->add_child ("seamless-loop");
-       child->add_property ("val", get_seamless_loop () ? "yes" : "no");
-       child = opthead->add_child ("punch-in");
-       child->add_property ("val", get_punch_in () ? "yes" : "no");
-       child = opthead->add_child ("punch-out");
-       child->add_property ("val", get_punch_out () ? "yes" : "no");
-       child = opthead->add_child ("all-safe");
-       child->add_property ("val", get_all_safe () ? "yes" : "no");
-       child = opthead->add_child ("auto-return");
-       child->add_property ("val", get_auto_return () ? "yes" : "no");
-       child = opthead->add_child ("mmc-control");
-       child->add_property ("val", get_mmc_control () ? "yes" : "no");
-       child = opthead->add_child ("midi-control");
-       child->add_property ("val", get_midi_control () ? "yes" : "no");
-       child = opthead->add_child ("midi-feedback");
-       child->add_property ("val", get_midi_feedback () ? "yes" : "no");
-       child = opthead->add_child ("do-not-record-plugins");
-       child->add_property ("val", get_do_not_record_plugins () ? "yes" : "no");
-       child = opthead->add_child ("auto-crossfade");
-       child->add_property ("val", get_crossfades_active () ? "yes" : "no");
-       child = opthead->add_child ("audible-click");
-       child->add_property ("val", get_clicking () ? "yes" : "no");
-       child = opthead->add_child ("end-marker-is-free");
-       child->add_property ("val", _end_location_is_free ? "yes" : "no");
-
-       if (click_sound.length()) {
-               child = opthead->add_child ("click-sound");
-               child->add_property ("val", click_sound);
-       }
-
-       if (click_emphasis_sound.length()) {
-               child = opthead->add_child ("click-emphasis-sound");
-               child->add_property ("val", click_emphasis_sound);
-       }
-
-       child = opthead->add_child ("solo-model");
-       child->add_property ("val", _solo_model == SoloBus ? "SoloBus" : "InverseMute");
-
-       child = opthead->add_child ("layer-model");
-       switch (layer_model) {
-       case LaterHigher:
-               child->add_property ("val", X_("LaterHigher"));
-               break;
-       case MoveAddHigher:
-               child->add_property ("val", X_("MoveAddHigher"));
-               break;
-       case AddHigher:
-               child->add_property ("val", X_("AddHigher"));
-               break;
-       }
-
-       child = opthead->add_child ("xfade-model");
-       switch (xfade_model) {
-       case FullCrossfade:
-               child->add_property ("val", X_("Full"));
-               break;
-       case ShortCrossfade:
-               child->add_property ("val", X_("Short"));
-       }
-
-       child = opthead->add_child ("short-xfade-length");
-       /* store as fractions of a second */
-       snprintf (buf, sizeof(buf)-1, "%f", 
-                 (float) Crossfade::short_xfade_length() / frame_rate());
-       child->add_property ("val", buf);
-
-       child = opthead->add_child ("full-xfades-unmuted");
-       child->add_property ("val", crossfades_active ? "yes" : "no");
-
-       return *opthead;
+       return 0;
 }
 
 XMLNode&
@@ -1330,16 +892,16 @@ Session::state(bool full_state)
 
        // store libardour version, just in case
        char buf[16];
-       snprintf(buf, sizeof(buf)-1, "%d.%d.%d", 
-                libardour_major_version, libardour_minor_version, libardour_micro_version);
+       snprintf(buf, sizeof(buf), "%d.%d.%d", libardour3_major_version, libardour3_minor_version, libardour3_micro_version);
        node->add_property("version", string(buf));
                
        /* store configuration settings */
 
        if (full_state) {
        
-               /* store the name */
                node->add_property ("name", _name);
+               snprintf (buf, sizeof (buf), "%" PRId32, _nominal_frame_rate);
+               node->add_property ("sample-rate", buf);
 
                if (session_dirs.size() > 1) {
 
@@ -1378,7 +940,9 @@ Session::state(bool full_state)
 
        /* various options */
 
-       node->add_child_nocopy (get_options());
+       node->add_child_nocopy (config.get_variables ());
+
+       node->add_child_nocopy (_metadata->get_state());
 
        child = node->add_child ("Sources");
 
@@ -1387,18 +951,15 @@ Session::state(bool full_state)
 
                for (SourceMap::iterator siter = sources.begin(); siter != sources.end(); ++siter) {
                        
-                       /* Don't save information about AudioFileSources that are empty */
+                       /* Don't save information about non-destructive file sources that are empty */
+                       /* FIXME: MIDI breaks if this is made FileSource like it should be... */
                        
                        boost::shared_ptr<AudioFileSource> fs;
-
                        if ((fs = boost::dynamic_pointer_cast<AudioFileSource> (siter->second)) != 0) {
-                               boost::shared_ptr<DestructiveFileSource> dfs = boost::dynamic_pointer_cast<DestructiveFileSource> (fs);
-
-                               /* Don't save sources that are empty, unless they're destructive (which are OK
-                                  if they are empty, because we will re-use them every time.)
-                               */
-                               if ( ! dfs && siter->second->length() == 0) {
-                                       continue;
+                               if (!fs->destructive()) {
+                                       if (fs->length(fs->timeline_position()) == 0) {
+                                               continue;
+                                       }
                                }
                        }
                        
@@ -1432,14 +993,28 @@ Session::state(bool full_state)
                }
        }
 
-       node->add_child_nocopy (_locations.get_state());
-       
-       child = node->add_child ("Connections");
+       if (full_state) {
+               node->add_child_nocopy (_locations.get_state());
+       } else {
+               // for a template, just create a new Locations, populate it
+               // with the default start and end, and get the state for that.
+               Locations loc;
+               Location* start = new Location(0, 0, _("start"), Location::Flags ((Location::IsMark|Location::IsStart)));
+               Location* end = new Location(0, 0, _("end"), Location::Flags ((Location::IsMark|Location::IsEnd)));
+               start->set_end(0);
+               loc.add (start);
+               end->set_end(compute_initial_length());
+               loc.add (end);
+               node->add_child_nocopy (loc.get_state());
+       }
+       
+       child = node->add_child ("Bundles");
        {
-               Glib::Mutex::Lock lm (connection_lock);
-               for (ConnectionList::iterator i = _connections.begin(); i != _connections.end(); ++i) {
-                       if (!(*i)->system_dependent()) {
-                               child->add_child_nocopy ((*i)->get_state());
+               boost::shared_ptr<BundleList> bundles = _bundles.reader ();
+               for (BundleList::iterator i = bundles->begin(); i != bundles->end(); ++i) {
+                       boost::shared_ptr<UserBundle> b = boost::dynamic_pointer_cast<UserBundle> (*i);
+                       if (b) {
+                               child->add_child_nocopy (b->get_state());
                        }
                }
        }
@@ -1453,7 +1028,7 @@ Session::state(bool full_state)
                public_order.sort (cmp);
                
                for (RouteList::iterator i = public_order.begin(); i != public_order.end(); ++i) {
-                       if (!(*i)->hidden()) {
+                       if (!(*i)->is_hidden()) {
                                if (full_state) {
                                        child->add_child_nocopy ((*i)->get_state());
                                } else {
@@ -1517,6 +1092,8 @@ Session::state(bool full_state)
 
        node->add_child_nocopy (_tempo_map->get_state());
 
+       node->add_child_nocopy (get_control_protocol_state());
+
        if (_extra_xml) {
                node->add_child_copy (*_extra_xml);
        }
@@ -1524,6 +1101,13 @@ Session::state(bool full_state)
        return *node;
 }
 
+XMLNode&
+Session::get_control_protocol_state ()
+{
+       ControlProtocolManager& cpm (ControlProtocolManager::instance());
+       return cpm.get_state();
+}
+
 int
 Session::set_state (const XMLNode& node)
 {
@@ -1539,12 +1123,23 @@ Session::set_state (const XMLNode& node)
                return -1;
        }
 
-       StateManager::prohibit_save ();
-
        if ((prop = node.property ("name")) != 0) {
                _name = prop->value ();
        }
 
+       if ((prop = node.property (X_("sample-rate"))) != 0) {
+
+               _nominal_frame_rate = atoi (prop->value());
+
+               if (_nominal_frame_rate != _current_frame_rate) {
+                       if (AskAboutSampleRateMismatch (_nominal_frame_rate, _current_frame_rate)) {
+                               return -1;
+                       }
+               }
+       }
+
+       setup_raid_path(_session_dir->root_path().to_string());
+
        if ((prop = node.property (X_("id-counter"))) != 0) {
                uint64_t x;
                sscanf (prop->value().c_str(), "%" PRIu64, &x);
@@ -1565,41 +1160,77 @@ Session::set_state (const XMLNode& node)
 
        /* Object loading order:
 
-       MIDI
        Path
-       extra
-       Options
+       Extra
+       Options/Config
+       MIDI Control // relies on data from Options/Config
+       Metadata
+       Locations
        Sources
        AudioRegions
        AudioDiskstreams
        Connections
-       Locations
        Routes
        EditGroups
        MixGroups
        Click
+       ControlProtocols
        */
 
-       if (use_config_midi_ports ()) {
+       if ((child = find_named_node (node, "Extra")) != 0) {
+               _extra_xml = new XMLNode (*child);
        }
 
-       if ((child = find_named_node (node, "Path")) != 0) {
-               /* XXX this XML content stuff horrible API design */
-               string raid_path = _path + ':' + child->children().front()->content();
-               setup_raid_path (raid_path);
+       if (((child = find_named_node (node, "Options")) != 0)) { /* old style */
+               load_options (*child);
+       } else if ((child = find_named_node (node, "Config")) != 0) { /* new style */
+               load_options (*child);
        } else {
-               /* the path is already set */
+               error << _("Session: XML state has no options section") << endmsg;
        }
 
-       if ((child = find_named_node (node, "extra")) != 0) {
-               _extra_xml = new XMLNode (*child);
+       if (use_config_midi_ports ()) {
        }
 
-       if ((child = find_named_node (node, "Options")) == 0) {
-               error << _("Session: XML state has no options section") << endmsg;
-       } else if (load_options (*child)) {
+       if ((child = find_named_node (node, "Metadata")) == 0) {
+               warning << _("Session: XML state has no metadata section (2.0 session?)") << endmsg;
+       } else if (_metadata->set_state (*child)) {
+               goto out;
+       }
+
+       if ((child = find_named_node (node, "Locations")) == 0) {
+               error << _("Session: XML state has no locations section") << endmsg;
+               goto out;
+       } else if (_locations.set_state (*child)) {
+               goto out;
+       }
+
+       Location* location;
+
+       if ((location = _locations.auto_loop_location()) != 0) {
+               set_auto_loop_location (location);
+       }
+
+       if ((location = _locations.auto_punch_location()) != 0) {
+               set_auto_punch_location (location);
+       }
+
+       if ((location = _locations.end_location()) == 0) {
+               _locations.add (end_location);
+       } else {
+               delete end_location;
+               end_location = location;
        }
 
+       if ((location = _locations.start_location()) == 0) {
+               _locations.add (start_location);
+       } else {
+               delete start_location;
+               start_location = location;
+       }
+
+       AudioFileSource::set_header_position_offset (start_location->start());
+
        if ((child = find_named_node (node, "Sources")) == 0) {
                error << _("Session: XML state has no sources section") << endmsg;
                goto out;
@@ -1640,46 +1271,16 @@ Session::set_state (const XMLNode& node)
                goto out;
        }
 
-       if ((child = find_named_node (node, "Connections")) == 0) {
-               error << _("Session: XML state has no connections section") << endmsg;
-               goto out;
-       } else if (load_connections (*child)) {
-               goto out;
-       }
-
-       if ((child = find_named_node (node, "Locations")) == 0) {
-               error << _("Session: XML state has no locations section") << endmsg;
-               goto out;
-       } else if (_locations.set_state (*child)) {
-               goto out;
-       }
-
-       Location* location;
-
-       if ((location = _locations.auto_loop_location()) != 0) {
-               set_auto_loop_location (location);
-       }
-
-       if ((location = _locations.auto_punch_location()) != 0) {
-               set_auto_punch_location (location);
-       }
-
-       if ((location = _locations.end_location()) == 0) {
-               _locations.add (end_location);
-       } else {
-               delete end_location;
-               end_location = location;
-       }
-
-       if ((location = _locations.start_location()) == 0) {
-               _locations.add (start_location);
+       if ((child = find_named_node (node, "Bundles")) == 0) {
+               warning << _("Session: XML state has no bundles section (2.0 session?)") << endmsg;
+               //goto out;
        } else {
-               delete start_location;
-               start_location = location;
+               /* We can't load Bundles yet as they need to be able
+                  to convert from port names to Port objects, which can't happen until
+                  later */
+               _bundle_xml_node = new XMLNode (*child);
        }
-
-       _locations.save_state (_("initial state"));
-
+       
        if ((child = find_named_node (node, "EditGroups")) == 0) {
                error << _("Session: XML state has no edit groups section") << endmsg;
                goto out;
@@ -1713,30 +1314,18 @@ Session::set_state (const XMLNode& node)
        } else if (_click_io) {
                _click_io->set_state (*child);
        }
-       
-       /* OK, now we can set edit mode */
 
-       set_edit_mode (pending_edit_mode);
+       if ((child = find_named_node (node, "ControlProtocols")) != 0) {
+               ControlProtocolManager::instance().set_protocol_states (*child);
+       }
 
        /* here beginneth the second phase ... */
 
        StateReady (); /* EMIT SIGNAL */
 
-       _state_of_the_state = Clean;
-
-       StateManager::allow_save (_("initial state"), true);
-
-       if (state_was_pending) {
-               save_state (_current_snapshot_name);
-               remove_pending_capture_state ();
-               state_was_pending = false;
-       }
-
        return 0;
 
   out:
-       /* we failed, re-enable state saving but don't actually save internal state */
-       StateManager::allow_save (X_("ignored"), false);
        return ret;
 }
 
@@ -1756,14 +1345,16 @@ Session::load_routes (const XMLNode& node)
                boost::shared_ptr<Route> route (XMLRouteFactory (**niter));
 
                if (route == 0) {
-                       error << _("Session: cannot create Route from XML description.")                              << endmsg;
+                       error << _("Session: cannot create Route from XML description.") << endmsg;
                        return -1;
                }
 
+               BootMessage (string_compose (_("Loaded track/bus %1"), route->name()));
+
                new_routes.push_back (route);
        }
 
-       add_routes (new_routes);
+       add_routes (new_routes, false);
 
        return 0;
 }
@@ -1779,8 +1370,10 @@ Session::XMLRouteFactory (const XMLNode& node)
        
        DataType type = DataType::AUDIO;
        const XMLProperty* prop = node.property("default-type");
-       if (prop)
+
+       if (prop) {
                type = DataType(prop->value());
+       } 
        
        assert(type != DataType::NIL);
 
@@ -1811,7 +1404,14 @@ Session::load_regions (const XMLNode& node)
 
        for (niter = nlist.begin(); niter != nlist.end(); ++niter) {
                if ((region = XMLRegionFactory (**niter, false)) == 0) {
-                       error << _("Session: cannot create Region from XML description.") << endmsg;
+                       error << _("Session: cannot create Region from XML description.");
+                       const XMLProperty *name = (**niter).property("name");
+
+                       if (name) {
+                               error << " " << string_compose (_("Can not load state for region '%1'"), name->value());
+                       }
+
+                       error << endmsg;
                }
        }
 
@@ -1849,6 +1449,7 @@ Session::XMLAudioRegionFactory (const XMLNode& node, bool full)
        boost::shared_ptr<Source> source;
        boost::shared_ptr<AudioSource> as;
        SourceList sources;
+       SourceList master_sources;
        uint32_t nchans = 1;
        char buf[128];
        
@@ -1860,6 +1461,10 @@ Session::XMLAudioRegionFactory (const XMLNode& node, bool full)
                nchans = atoi (prop->value().c_str());
        }
 
+       if ((prop = node.property ("name")) == 0) {
+               cerr << "no name for this region\n";
+               abort ();
+       }
        
        if ((prop = node.property (X_("source-0"))) == 0) {
                if ((prop = node.property ("source")) == 0) {
@@ -1904,9 +1509,49 @@ Session::XMLAudioRegionFactory (const XMLNode& node, bool full)
                        sources.push_back (as);
                }
        }
-       
+
+       for (uint32_t n=1; n < nchans; ++n) {
+               snprintf (buf, sizeof(buf), X_("master-source-%d"), n);
+               if ((prop = node.property (buf)) != 0) {
+                       
+                       PBD::ID id2 (prop->value());
+                       
+                       if ((source = source_by_id (id2)) == 0) {
+                               error << string_compose(_("Session: XMLNode describing a AudioRegion references an unknown source id =%1"), id2) << endmsg;
+                               return boost::shared_ptr<AudioRegion>();
+                       }
+                       
+                       as = boost::dynamic_pointer_cast<AudioSource>(source);
+                       if (!as) {
+                               error << string_compose(_("Session: XMLNode describing a AudioRegion references a non-audio source id =%1"), id2) << endmsg;
+                               return boost::shared_ptr<AudioRegion>();
+                       }
+                       master_sources.push_back (as);
+               }
+       }
+
        try {
                boost::shared_ptr<AudioRegion> region (boost::dynamic_pointer_cast<AudioRegion> (RegionFactory::create (sources, node)));
+
+               /* a final detail: this is the one and only place that we know how long missing files are */
+
+               if (region->whole_file()) {
+                       for (SourceList::iterator sx = sources.begin(); sx != sources.end(); ++sx) {
+                               boost::shared_ptr<SilentFileSource> sfp = boost::dynamic_pointer_cast<SilentFileSource> (*sx);
+                               if (sfp) {
+                                       sfp->set_length (region->length());
+                               }
+                       }
+               }
+
+               if (!master_sources.empty()) {
+                       if (master_sources.size() == nchans) {
+                               error << _("Session: XMLNode describing an AudioRegion is missing some master sources; ignored") << endmsg;
+                       } else {
+                               region->set_master_sources (master_sources);
+                       }
+               }
+
                return region;
                                                       
        }
@@ -1922,7 +1567,7 @@ Session::XMLMidiRegionFactory (const XMLNode& node, bool full)
        const XMLProperty* prop;
        boost::shared_ptr<Source> source;
        boost::shared_ptr<MidiSource> ms;
-       MidiRegion::SourceList sources;
+       SourceList sources;
        uint32_t nchans = 1;
        
        if (node.name() != X_("Region")) {
@@ -1932,6 +1577,11 @@ Session::XMLMidiRegionFactory (const XMLNode& node, bool full)
        if ((prop = node.property (X_("channels"))) != 0) {
                nchans = atoi (prop->value().c_str());
        }
+       
+       if ((prop = node.property ("name")) == 0) {
+               cerr << "no name for this region\n";
+               abort ();
+       }
 
        // Multiple midi channels?  that's just crazy talk
        assert(nchans == 1);
@@ -1960,6 +1610,17 @@ Session::XMLMidiRegionFactory (const XMLNode& node, bool full)
 
        try {
                boost::shared_ptr<MidiRegion> region (boost::dynamic_pointer_cast<MidiRegion> (RegionFactory::create (sources, node)));
+               /* a final detail: this is the one and only place that we know how long missing files are */
+
+               if (region->whole_file()) {
+                       for (SourceList::iterator sx = sources.begin(); sx != sources.end(); ++sx) {
+                               boost::shared_ptr<SilentFileSource> sfp = boost::dynamic_pointer_cast<SilentFileSource> (*sx);
+                               if (sfp) {
+                                       sfp->set_length (region->length());
+                               }
+                       }
+               }
+
                return region;
        }
 
@@ -1979,30 +1640,40 @@ Session::get_sources_as_xml ()
                node->add_child_nocopy (i->second->get_state());
        }
 
-       /* XXX get MIDI and other sources here */
-
        return *node;
 }
 
 string
-Session::path_from_region_name (string name, string identifier)
+Session::path_from_region_name (DataType type, string name, string identifier)
 {
        char buf[PATH_MAX+1];
        uint32_t n;
-       string dir = discover_best_sound_dir ();
+       SessionDirectory sdir(get_best_session_directory_for_new_source());
+       sys::path source_dir = ((type == DataType::AUDIO)
+               ? sdir.sound_path() : sdir.midi_path());
+
+       string ext = ((type == DataType::AUDIO) ? ".wav" : ".mid");
 
        for (n = 0; n < 999999; ++n) {
                if (identifier.length()) {
-                       snprintf (buf, sizeof(buf), "%s/%s%s%" PRIu32 ".wav", dir.c_str(), name.c_str(), 
-                                 identifier.c_str(), n);
+                       snprintf (buf, sizeof(buf), "%s%s%" PRIu32 "%s", name.c_str(), 
+                                 identifier.c_str(), n, ext.c_str());
                } else {
-                       snprintf (buf, sizeof(buf), "%s/%s-%" PRIu32 ".wav", dir.c_str(), name.c_str(), n);
+                       snprintf (buf, sizeof(buf), "%s-%" PRIu32 "%s", name.c_str(),
+                                       n, ext.c_str());
                }
-               if (access (buf, F_OK) != 0) {
-                       return buf;
+
+               sys::path source_path = source_dir / buf;
+
+               if (!sys::exists (source_path)) {
+                       return source_path.to_string();
                }
        }
 
+       error << string_compose (_("cannot create new file from region name \"%1\" with ident = \"%2\": too many existing files with similar names"),
+                                name, identifier)
+             << endmsg;
+
        return "";
 }
        
@@ -2019,9 +1690,13 @@ Session::load_sources (const XMLNode& node)
        set_dirty();
 
        for (niter = nlist.begin(); niter != nlist.end(); ++niter) {
-
-               if ((source = XMLSourceFactory (**niter)) == 0) {
-                       error << _("Session: cannot create Source from XML description.") << endmsg;
+               try {
+                       if ((source = XMLSourceFactory (**niter)) == 0) {
+                               error << _("Session: cannot create Source from XML description.") << endmsg;
+                       }
+               } catch (MissingSource& err) {
+                       warning << _("A sound file is missing. It will be replaced by silence.") << endmsg;
+                       source = SourceFactory::createSilent (*this, **niter, max_frames, _current_frame_rate);
                }
        }
 
@@ -2031,15 +1706,15 @@ Session::load_sources (const XMLNode& node)
 boost::shared_ptr<Source>
 Session::XMLSourceFactory (const XMLNode& node)
 {
-
        if (node.name() != "Source") {
                return boost::shared_ptr<Source>();
        }
 
        try {
-               return SourceFactory::create (node);
+               /* note: do peak building in another thread when loading session state */
+               return SourceFactory::create (*this, node, true);
        }
-       
+
        catch (failed_constructor& err) {
                error << _("Found a sound file that cannot be used by Ardour. Talk to the progammers.") << endmsg;
                return boost::shared_ptr<Source>();
@@ -2050,40 +1725,37 @@ int
 Session::save_template (string template_name)
 {
        XMLTree tree;
-       string xml_path, bak_path, template_path;
 
        if (_state_of_the_state & CannotSave) {
                return -1;
        }
 
-       DIR* dp;
-       string dir = template_dir();
+       sys::path user_template_dir(user_template_directory());
 
-       if ((dp = opendir (dir.c_str()))) {
-               closedir (dp);
-       } else {
-               if (mkdir (dir.c_str(), S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH)<0) {
-                       error << string_compose(_("Could not create mix templates directory \"%1\" (%2)"), dir, strerror (errno)) << endmsg;
-                       return -1;
-               }
+       try
+       {
+               sys::create_directories (user_template_dir);
+       }
+       catch(sys::filesystem_error& ex)
+       {
+               error << string_compose(_("Could not create mix templates directory \"%1\" (%2)"),
+                               user_template_dir.to_string(), ex.what()) << endmsg;
+               return -1;
        }
 
        tree.set_root (&get_template());
 
-       xml_path = dir;
-       xml_path += template_name;
-       xml_path += _template_suffix;
+       sys::path template_file_path(user_template_dir);
+       template_file_path /= template_name + template_suffix;
 
-       ifstream in(xml_path.c_str());
-       
-       if (in) {
-               warning << string_compose(_("Template \"%1\" already exists - new version not created"), template_name) << endmsg;
+       if (sys::exists (template_file_path))
+       {
+               warning << string_compose(_("Template \"%1\" already exists - new version not created"),
+                               template_file_path.to_string()) << endmsg;
                return -1;
-       } else {
-               in.close();
        }
 
-       if (!tree.write (xml_path)) {
+       if (!tree.write (template_file_path.to_string())) {
                error << _("mix template not saved") << endmsg;
                return -1;
        }
@@ -2094,20 +1766,38 @@ Session::save_template (string template_name)
 int
 Session::rename_template (string old_name, string new_name) 
 {
-       string old_path = template_dir() + old_name + _template_suffix;
-       string new_path = template_dir() + new_name + _template_suffix;
+       sys::path old_path (user_template_directory());
+       old_path /= old_name + template_suffix;
+
+       sys::path new_path(user_template_directory());
+       new_path /= new_name + template_suffix;
 
-       return rename (old_path.c_str(), new_path.c_str());
+       if (sys::exists (new_path)) {
+               warning << string_compose(_("Template \"%1\" already exists - template not renamed"),
+                                         new_path.to_string()) << endmsg;
+               return -1;
+       }
+
+       try {
+               sys::rename (old_path, new_path);
+               return 0;
+       } catch (...) {
+               return -1;
+       }
 }
 
 int
 Session::delete_template (string name) 
 {
-       string template_path = template_dir();
-       template_path += name;
-       template_path += _template_suffix;
+       sys::path path = user_template_directory();
+       path /= name + template_suffix;
 
-       return remove (template_path.c_str());
+       try {
+               sys::remove (path);
+               return 0;
+       } catch (...) {
+               return -1;
+       }
 }
 
 void
@@ -2134,78 +1824,16 @@ Session::refresh_disk_space ()
 #endif
 }
 
-int
-Session::ensure_sound_dir (string path, string& result)
-{
-       string dead;
-       string peak;
-
-       /* Ensure that the parent directory exists */
-       
-       if (mkdir (path.c_str(), 0775)) {
-               if (errno != EEXIST) {
-                       error << string_compose(_("cannot create session directory \"%1\"; ignored"), path) << endmsg;
-                       return -1;
-               }
-       }
-       
-       /* Ensure that the sounds directory exists */
-       
-       result = path;
-       result += '/';
-       result += sound_dir_name;
-       
-       if (mkdir (result.c_str(), 0775)) {
-               if (errno != EEXIST) {
-                       error << string_compose(_("cannot create sounds directory \"%1\"; ignored"), result) << endmsg;
-                       return -1;
-               }
-       }
-
-       dead = path;
-       dead += '/';
-       dead += dead_sound_dir_name;
-       
-       if (mkdir (dead.c_str(), 0775)) {
-               if (errno != EEXIST) {
-                       error << string_compose(_("cannot create dead sounds directory \"%1\"; ignored"), dead) << endmsg;
-                       return -1;
-               }
-       }
-
-       peak = path;
-       peak += '/';
-       peak += peak_dir_name;
-       
-       if (mkdir (peak.c_str(), 0775)) {
-               if (errno != EEXIST) {
-                       error << string_compose(_("cannot create peak file directory \"%1\"; ignored"), peak) << endmsg;
-                       return -1;
-               }
-       }
-       
-       /* callers expect this to be terminated ... */
-                       
-       result += '/';
-       return 0;
-}      
-
 string
-Session::discover_best_sound_dir (bool destructive)
+Session::get_best_session_directory_for_new_source ()
 {
        vector<space_and_path>::iterator i;
-       string result;
-
-       /* destructive files all go into the same place */
-
-       if (destructive) {
-               return tape_dir();
-       }
+       string result = _session_dir->root_path().to_string();
 
        /* handle common case without system calls */
 
        if (session_dirs.size() == 1) {
-               return sound_dir();
+               return result;
        }
 
        /* OK, here's the algorithm we're following here:
@@ -2247,9 +1875,6 @@ Session::discover_best_sound_dir (bool destructive)
        }
 
        if (free_enough >= 2) {
-
-               bool found_it = false;
-
                /* use RR selection process, ensuring that the one
                   picked works OK.
                */
@@ -2262,19 +1887,15 @@ Session::discover_best_sound_dir (bool destructive)
                        }
 
                        if ((*i).blocks * 4096 >= Config->get_disk_choice_space_threshold()) {
-                               if (ensure_sound_dir ((*i).path, result) == 0) {
+                               if (create_session_directory ((*i).path)) {
+                                       result = (*i).path;
                                        last_rr_session_dir = i;
-                                       found_it = true;
-                                       break;
+                                       return result;
                                }
                        }
 
                } while (i != last_rr_session_dir);
 
-               if (!found_it) {
-                       result = sound_dir();
-               }
-
        } else {
 
                /* pick FS with the most freespace (and that
@@ -2288,17 +1909,12 @@ Session::discover_best_sound_dir (bool destructive)
                sort (sorted.begin(), sorted.end(), cmp);
                
                for (i = sorted.begin(); i != sorted.end(); ++i) {
-                       if (ensure_sound_dir ((*i).path, result) == 0) {
+                       if (create_session_directory ((*i).path)) {
+                               result = (*i).path;
                                last_rr_session_dir = i;
-                               break;
+                               return result;
                        }
                }
-               
-               /* if the above fails, fall back to the most simplistic solution */
-               
-               if (i == sorted.end()) {
-                       return sound_dir();
-               } 
        }
 
        return result;
@@ -2309,7 +1925,7 @@ Session::load_playlists (const XMLNode& node)
 {
        XMLNodeList nlist;
        XMLNodeConstIterator niter;
-       Playlist *playlist;
+       boost::shared_ptr<Playlist> playlist;
 
        nlist = node.children();
 
@@ -2330,7 +1946,7 @@ Session::load_unused_playlists (const XMLNode& node)
 {
        XMLNodeList nlist;
        XMLNodeConstIterator niter;
-       Playlist *playlist;
+       boost::shared_ptr<Playlist> playlist;
 
        nlist = node.children();
 
@@ -2345,34 +1961,22 @@ Session::load_unused_playlists (const XMLNode& node)
 
                // now manually untrack it
 
-               track_playlist (playlist, false);
+               track_playlist (false, boost::weak_ptr<Playlist> (playlist));
        }
 
        return 0;
 }
 
-Playlist *
+boost::shared_ptr<Playlist>
 Session::XMLPlaylistFactory (const XMLNode& node)
 {
-       const XMLProperty* type = node.property("type");
-
        try {
-       
-       if ( !type || type->value() == "audio" ) {
-
-               return new AudioPlaylist (*this, node);
-       
-       } else if (type->value() == "midi") {
-
-               return new MidiPlaylist (*this, node);
-       
-       }
-       
-       } catch (failed_constructor& err) {
-               return 0;
+               return PlaylistFactory::create (*this, node);
        }
 
-       return 0;
+       catch (failed_constructor& err) {
+               return boost::shared_ptr<Playlist>();
+       }
 }
 
 int
@@ -2408,123 +2012,36 @@ Session::XMLNamedSelectionFactory (const XMLNode& node)
        }
 }
 
-string
-Session::dead_sound_dir () const
-{
-       string res = _path;
-       res += dead_sound_dir_name;
-       res += '/';
-       return res;
-}
-
-string
-Session::sound_dir () const
-{
-       string res = _path;
-       res += sound_dir_name;
-       res += '/';
-       return res;
-}
-
-string
-Session::tape_dir () const
-{
-       string res = _path;
-       res += tape_dir_name;
-       res += '/';
-       return res;
-}
-
-string
-Session::peak_dir () const
-{
-       string res = _path;
-       res += peak_dir_name;
-       res += '/';
-       return res;
-}
-       
 string
 Session::automation_dir () const
 {
-       string res = _path;
-       res += "automation/";
-       return res;
-}
-
-string
-Session::template_dir ()
-{
-       string path = get_user_ardour_path();
-       path += "templates/";
-
-       return path;
-}
-
-string
-Session::suffixed_search_path (string suffix, bool data)
-{
-       string path;
-
-       path += get_user_ardour_path();
-       if (path[path.length()-1] != ':') {
-               path += ':';
-       }
-
-       if (data) {
-               path += get_system_data_path();
-       } else {
-               path += get_system_module_path();
-       }
-
-       vector<string> split_path;
-       
-       split (path, split_path, ':');
-       path = "";
-
-       for (vector<string>::iterator i = split_path.begin(); i != split_path.end(); ++i) {
-               path += *i;
-               path += suffix;
-               path += '/';
-               
-               if (distance (i, split_path.end()) != 1) {
-                       path += ':';
-               }
-       }
-               
-       return path;
-}
-
-string
-Session::template_path ()
-{
-       return suffixed_search_path (X_("templates"), true);
+       return Glib::build_filename (_path, "automation");
 }
 
 string
-Session::control_protocol_path ()
+Session::analysis_dir () const
 {
-       return suffixed_search_path (X_("surfaces"), false);
+       return Glib::build_filename (_path, "analysis");
 }
 
 int
-Session::load_connections (const XMLNode& node)
+Session::load_bundles (XMLNode const & node)
 {
-       XMLNodeList nlist = node.children();
-       XMLNodeConstIterator niter;
+       XMLNodeList nlist = node.children();
+       XMLNodeConstIterator niter;
 
-       set_dirty();
+       set_dirty();
 
-       for (niter = nlist.begin(); niter != nlist.end(); ++niter) {
-               if ((*niter)->name() == "InputConnection") {
-                       add_connection (new ARDOUR::InputConnection (**niter));
-               } else if ((*niter)->name() == "OutputConnection") {
-                       add_connection (new ARDOUR::OutputConnection (**niter));
-               } else {
-                       error << string_compose(_("Unknown node \"%1\" found in Connections list from state file"), (*niter)->name()) << endmsg;
-                       return -1;
-               }
-       }
+       for (niter = nlist.begin(); niter != nlist.end(); ++niter) {
+               if ((*niter)->name() == "InputBundle") {
+                       add_bundle (boost::shared_ptr<UserBundle> (new UserBundle (**niter, true)));
+               } else if ((*niter)->name() == "OutputBundle") {
+                       add_bundle (boost::shared_ptr<UserBundle> (new UserBundle (**niter, false)));
+               } else {
+                       error << string_compose(_("Unknown node \"%1\" found in Bundles list from state file"), (*niter)->name()) << endmsg;
+                       return -1;
+               }
+       }
 
        return 0;
 }                              
@@ -2565,11 +2082,17 @@ Session::load_route_groups (const XMLNode& node, bool edit)
        return 0;
 }                              
 
+void
+Session::auto_save()
+{
+       save_state (_current_snapshot_name);
+}
+
 static bool
 state_file_filter (const string &str, void *arg)
 {
-       return (str.length() > strlen(Session::statefile_suffix()) &&
-               str.find (Session::statefile_suffix()) == (str.length() - strlen (Session::statefile_suffix())));
+       return (str.length() > strlen(statefile_suffix) &&
+               str.find (statefile_suffix) == (str.length() - strlen (statefile_suffix)));
 }
 
 struct string_cmp {
@@ -2615,12 +2138,6 @@ Session::possible_states () const
        return possible_states(_path);
 }
 
-void
-Session::auto_save()
-{
-       save_state (_current_snapshot_name);
-}
-
 RouteGroup *
 Session::add_edit_group (string name)
 {
@@ -2696,40 +2213,36 @@ Session::edit_group_by_name (string name)
 }
 
 void
-Session::set_meter_hold (float val)
+Session::begin_reversible_command(const string& name)
 {
-       _meter_hold = val;
-       MeterHoldChanged(); // emit
-}
-
-void
-Session::set_meter_falloff (float val)
-{
-       _meter_falloff = val;
-       MeterFalloffChanged(); // emit
-}
-
-
-void
-Session::begin_reversible_command (string name)
-{
-       current_trans = new UndoTransaction;
-       current_trans->set_name (name);
+       UndoTransaction* trans = new UndoTransaction();
+       trans->set_name(name);
+       if (!_current_trans.empty()) {
+               _current_trans.top()->add_command(trans);
+       }
+       _current_trans.push(trans);
 }
 
 void
-Session::commit_reversible_command (Command *cmd)
+Session::commit_reversible_command(Command *cmd)
 {
+       assert(!_current_trans.empty());
        struct timeval now;
 
        if (cmd) {
-               current_trans->add_command (cmd);
+               _current_trans.top()->add_command(cmd);
+       }
+
+       if (_current_trans.top()->empty()) {
+               _current_trans.pop();
+               return;
        }
 
-       gettimeofday (&now, 0);
-       current_trans->set_timestamp (now);
+       gettimeofday(&now, 0);
+       _current_trans.top()->set_timestamp(now);
 
-       history.add (current_trans);
+       _history.add(_current_trans.top());
+       _current_trans.pop();
 }
 
 Session::GlobalRouteBooleanState 
@@ -2739,7 +2252,7 @@ Session::get_global_route_boolean (bool (Route::*method)(void) const)
        boost::shared_ptr<RouteList> r = routes.reader ();
 
        for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
-               if (!(*i)->hidden()) {
+               if (!(*i)->is_hidden()) {
                        RouteBooleanState v;
                        
                        v.first =* i;
@@ -2760,7 +2273,7 @@ Session::get_global_route_metering ()
        boost::shared_ptr<RouteList> r = routes.reader ();
 
        for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
-               if (!(*i)->hidden()) {
+               if (!(*i)->is_hidden()) {
                        RouteMeterState v;
                        
                        v.first =* i;
@@ -2768,162 +2281,60 @@ Session::get_global_route_metering ()
                        
                        s.push_back (v);
                }
-       }
-
-       return s;
-}
-
-void
-Session::set_global_route_metering (GlobalRouteMeterState s, void* arg) 
-{
-       for (GlobalRouteMeterState::iterator i = s.begin(); i != s.end(); ++i) {
-               i->first->set_meter_point (i->second, arg);
-       }
-}
-
-void
-Session::set_global_route_boolean (GlobalRouteBooleanState s, void (Route::*method)(bool, void*), void* arg)
-{
-       for (GlobalRouteBooleanState::iterator i = s.begin(); i != s.end(); ++i) {
-               Route* r = i->first.get();
-               (r->*method) (i->second, arg);
-       }
-}
-
-void
-Session::set_global_mute (GlobalRouteBooleanState s, void* src)
-{
-       set_global_route_boolean (s, &Route::set_mute, src);
-}
-
-void
-Session::set_global_solo (GlobalRouteBooleanState s, void* src)
-{
-       set_global_route_boolean (s, &Route::set_solo, src);
-}
-
-void
-Session::set_global_record_enable (GlobalRouteBooleanState s, void* src)
-{
-       set_global_route_boolean (s, &Route::set_record_enable, src);
-}
-
-#if 0
-UndoAction
-Session::global_mute_memento (void* src)
-{
-       return sigc::bind (mem_fun (*this, &Session::set_global_mute), get_global_route_boolean (&Route::muted), src);
-}
-
-UndoAction
-Session::global_metering_memento (void* src)
-{
-       return sigc::bind (mem_fun (*this, &Session::set_global_route_metering), get_global_route_metering (), src);
-}
-
-UndoAction
-Session::global_solo_memento (void* src)
-{
-       return sigc::bind (mem_fun (*this, &Session::set_global_solo), get_global_route_boolean (&Route::soloed), src);
-}
-
-UndoAction
-Session::global_record_enable_memento (void* src)
-{
-       return sigc::bind (mem_fun (*this, &Session::set_global_record_enable), get_global_route_boolean (&Route::record_enabled), src);
-}
-#endif
+       }
 
-static bool
-template_filter (const string &str, void *arg)
-{
-       return (str.length() > strlen(Session::template_suffix()) &&
-               str.find (Session::template_suffix()) == (str.length() - strlen (Session::template_suffix())));
+       return s;
 }
 
 void
-Session::get_template_list (list<string> &template_names)
+Session::set_global_route_metering (GlobalRouteMeterState s, void* arg) 
 {
-       vector<string *> *templates;
-       PathScanner scanner;
-       string path;
-
-       path = template_path ();
+       for (GlobalRouteMeterState::iterator i = s.begin(); i != s.end(); ++i) {
 
-       templates = scanner (path, template_filter, 0, false, true);
-       
-       vector<string*>::iterator i;
-       for (i = templates->begin(); i != templates->end(); ++i) {
-               string fullpath = *(*i);
-               int start, end;
+               boost::shared_ptr<Route> r = (i->first.lock());
 
-               start = fullpath.find_last_of ('/') + 1;
-               if ((end = fullpath.find_last_of ('.')) <0) {
-                       end = fullpath.length();
+               if (r) {
+                       r->set_meter_point (i->second, arg);
                }
-               
-               template_names.push_back(fullpath.substr(start, (end-start)));
        }
 }
 
-int
-Session::read_favorite_dirs (FavoriteDirs & favs)
+void
+Session::set_global_route_boolean (GlobalRouteBooleanState s, void (Route::*method)(bool, void*), void* arg)
 {
-       string path = get_user_ardour_path();
-       path += "/favorite_dirs";
-
-       ifstream fav (path.c_str());
-
-       favs.clear();
-       
-       if (!fav) {
-               if (errno != ENOENT) {
-                       //error << string_compose (_("cannot open favorite file %1 (%2)"), path, strerror (errno)) << endmsg;
-                       return -1;
-               } else {
-                       return 1;
-               }
-       }
-
-       while (true) {
-
-               string newfav;
+       for (GlobalRouteBooleanState::iterator i = s.begin(); i != s.end(); ++i) {
 
-               getline(fav, newfav);
+               boost::shared_ptr<Route> r = (i->first.lock());
 
-               if (!fav.good()) {
-                       break;
+               if (r) {
+                       Route* rp = r.get();
+                       (rp->*method) (i->second, arg);
                }
-
-               favs.push_back (newfav);
        }
-
-       return 0;
 }
 
-int
-Session::write_favorite_dirs (FavoriteDirs & favs)
+void
+Session::set_global_mute (GlobalRouteBooleanState s, void* src)
 {
-       string path = get_user_ardour_path();
-       path += "/favorite_dirs";
-
-       ofstream fav (path.c_str());
+       set_global_route_boolean (s, &Route::set_mute, src);
+}
 
-       if (!fav) {
-               return -1;
-       }
+void
+Session::set_global_solo (GlobalRouteBooleanState s, void* src)
+{
+       set_global_route_boolean (s, &Route::set_solo, src);
+}
 
-       for (FavoriteDirs::iterator i = favs.begin(); i != favs.end(); ++i) {
-               fav << (*i) << endl;
-       }
-       
-       return 0;
+void
+Session::set_global_record_enable (GlobalRouteBooleanState s, void* src)
+{
+       set_global_route_boolean (s, &Route::set_record_enable, src);
 }
 
 static bool
 accept_all_non_peak_files (const string& path, void *arg)
 {
-       return (path.length() > 5 && path.find (".peak") != (path.length() - 5));
+       return (path.length() > 5 && path.find (peakfile_suffix) != (path.length() - 5));
 }
 
 static bool
@@ -2966,12 +2377,11 @@ Session::find_all_sources (string path, set<string>& result)
                        continue;
                }
 
-               string path = _path; /* /-terminated */
-               path += sound_dir_name;
-               path += '/';
-               path += prop->value();
+               sys::path source_path = _session_dir->sound_path ();
+
+               source_path /= prop->value ();
 
-               result.insert (path);
+               result.insert (source_path.to_string ());
        }
 
        return 0;
@@ -3002,7 +2412,7 @@ Session::find_all_sources_across_snapshots (set<string>& result, bool exclude_th
 
        this_snapshot_path = _path;
        this_snapshot_path += _current_snapshot_name;
-       this_snapshot_path += _statefile_suffix;
+       this_snapshot_path += statefile_suffix;
 
        for (vector<string*>::iterator i = state_files->begin(); i != state_files->end(); ++i) {
 
@@ -3018,11 +2428,22 @@ Session::find_all_sources_across_snapshots (set<string>& result, bool exclude_th
        return 0;
 }
 
+struct RegionCounter {
+    typedef std::map<PBD::ID,boost::shared_ptr<AudioSource> > AudioSourceList;
+    AudioSourceList::iterator iter;
+    boost::shared_ptr<Region> region;
+    uint32_t count;
+    
+    RegionCounter() : count (0) {}
+};
+
 int
 Session::cleanup_sources (Session::cleanup_report& rep)
 {
+       // FIXME: needs adaptation to midi
+       
        vector<boost::shared_ptr<Source> > dead_sources;
-       vector<Playlist*> playlists_tbd;
+       vector<boost::shared_ptr<Playlist> > playlists_tbd;
        PathScanner scanner;
        string sound_path;
        vector<space_and_path>::iterator i;
@@ -3035,6 +2456,7 @@ Session::cleanup_sources (Session::cleanup_report& rep)
        int ret = -1;
                
        _state_of_the_state = (StateOfTheState) (_state_of_the_state | InCleanup);
+
        
        /* step 1: consider deleting all unused playlists */
 
@@ -3061,77 +2483,36 @@ Session::cleanup_sources (Session::cleanup_report& rep)
 
        /* now delete any that were marked for deletion */
 
-       for (vector<Playlist*>::iterator x = playlists_tbd.begin(); x != playlists_tbd.end(); ++x) {
-               PlaylistList::iterator foo;
-
-               if ((foo = unused_playlists.find (*x)) != unused_playlists.end()) {
-                       unused_playlists.erase (foo);
-               }
-               delete *x;
+       for (vector<boost::shared_ptr<Playlist> >::iterator x = playlists_tbd.begin(); x != playlists_tbd.end(); ++x) {
+               (*x)->drop_references ();
        }
 
-       /* step 2: clear the undo/redo history for all playlists */
-
-       for (PlaylistList::iterator x = playlists.begin(); x != playlists.end(); ++x) {
-               (*x)->drop_all_states ();
-       }
+       playlists_tbd.clear ();
 
-       /* step 3: find all un-referenced sources */
+       /* step 2: find all un-used sources */
 
        rep.paths.clear ();
        rep.space = 0;
 
        for (SourceMap::iterator i = sources.begin(); i != sources.end(); ) {
-
+               
                SourceMap::iterator tmp;
 
                tmp = i;
                ++tmp;
 
-               /* only remove files that are not in use and have some size
-                  to them. otherwise we remove the current "nascent"
+               /* do not bother with files that are zero size, otherwise we remove the current "nascent"
                   capture files.
                */
 
-               if (i->second.use_count() == 1 && i->second->length() > 0) {
+               if (!i->second->used() && i->second->length(i->second->timeline_position()) > 0) {
                        dead_sources.push_back (i->second);
-
-                       /* remove this source from our own list to avoid us
-                          adding it to the list of all sources below
-                       */
-
-                       sources.erase (i);
-               }
+                       i->second->GoingAway();
+               } 
 
                i = tmp;
        }
 
-       /* Step 4: get rid of all regions in the region list that use any dead sources
-          in case the sources themselves don't go away (they might be referenced in
-          other snapshots).
-       */
-               
-       for (vector<boost::shared_ptr<Source> >::iterator i = dead_sources.begin(); i != dead_sources.end();++i) {
-
-               for (RegionList::iterator r = regions.begin(); r != regions.end(); ) {
-                       RegionList::iterator tmp;
-
-                       tmp = r;
-                       ++tmp;
-                       
-                       boost::shared_ptr<Region> reg = r->second;
-
-                       for (uint32_t n = 0; n < reg->n_channels(); ++n) {
-                               if (reg->source (n) == (*i)) {
-                                       /* this region is dead */
-                                       remove_region (reg);
-                               }
-                       }
-                       
-                       r = tmp;
-               }
-       }
-
        /* build a list of all the possible sound directories for the session */
 
        for (i = session_dirs.begin(); i != session_dirs.end(); ) {
@@ -3139,8 +2520,8 @@ Session::cleanup_sources (Session::cleanup_report& rep)
                nexti = i;
                ++nexti;
 
-               sound_path += (*i).path;
-               sound_path += sound_dir_name;
+               SessionDirectory sdir ((*i).path);
+               sound_path += sdir.sound_path().to_string();
 
                if (nexti != session_dirs.end()) {
                        sound_path += ':';
@@ -3148,7 +2529,7 @@ Session::cleanup_sources (Session::cleanup_report& rep)
 
                i = nexti;
        }
-       
+
        /* now do the same thing for the files that ended up in the sounds dir(s) 
           but are not referenced as sources in any snapshot.
        */
@@ -3170,13 +2551,16 @@ Session::cleanup_sources (Session::cleanup_report& rep)
         */
        
        for (SourceMap::iterator i = sources.begin(); i != sources.end(); ++i) {
-               boost::shared_ptr<AudioFileSource> fs;
+               boost::shared_ptr<FileSource> fs;
                
-               if ((fs = boost::dynamic_pointer_cast<AudioFileSource> (i->second)) != 0) {
+               if ((fs = boost::dynamic_pointer_cast<FileSource> (i->second)) != 0) {
                        all_sources.insert (fs->path());
                } 
        }
 
+       char tmppath1[PATH_MAX+1];
+       char tmppath2[PATH_MAX+1];
+       
        for (vector<string*>::iterator x = soundfiles->begin(); x != soundfiles->end(); ++x) {
 
                used = false;
@@ -3184,11 +2568,13 @@ Session::cleanup_sources (Session::cleanup_report& rep)
 
                for (set<string>::iterator i = all_sources.begin(); i != all_sources.end(); ++i) {
 
-                       if (spath == *i) {
+                       realpath(spath.c_str(), tmppath1);
+                       realpath((*i).c_str(),  tmppath2);
+
+                       if (strcmp(tmppath1, tmppath2) == 0) {
                                used = true;
                                break;
                        }
-
                }
 
                if (!used) {
@@ -3213,11 +2599,31 @@ Session::cleanup_sources (Session::cleanup_report& rep)
                   on whichever filesystem it was already on.
                */
 
-               newpath = Glib::path_get_dirname (*x);
-               newpath = Glib::path_get_dirname (newpath);
+               if ((*x).find ("/sounds/") != string::npos) {
+
+                       /* old school, go up 1 level */
+
+                       newpath = Glib::path_get_dirname (*x);      // "sounds" 
+                       newpath = Glib::path_get_dirname (newpath); // "session-name"
+
+               } else {
+
+                       /* new school, go up 4 levels */
+                       
+                       newpath = Glib::path_get_dirname (*x);      // "audiofiles" 
+                       newpath = Glib::path_get_dirname (newpath); // "session-name"
+                       newpath = Glib::path_get_dirname (newpath); // "interchange"
+                       newpath = Glib::path_get_dirname (newpath); // "session-dir"
+               }
 
                newpath += '/';
                newpath += dead_sound_dir_name;
+
+               if (g_mkdir_with_parents (newpath.c_str(), 0755) < 0) {
+                       error << string_compose(_("Session: cannot create session peakfile folder \"%1\" (%2)"), newpath, strerror (errno)) << endmsg;
+                       return -1;
+               }
+
                newpath += '/';
                newpath += Glib::path_get_basename ((*x));
                
@@ -3257,13 +2663,12 @@ Session::cleanup_sources (Session::cleanup_report& rep)
                              << endmsg;
                        goto out;
                }
-               
 
                /* see if there an easy to find peakfile for this file, and remove it.
                 */
 
                string peakpath = (*x).substr (0, (*x).find_last_of ('.'));
-               peakpath += ".peak";
+               peakpath += peakfile_suffix;
 
                if (access (peakpath.c_str(), W_OK) == 0) {
                        if (::unlink (peakpath.c_str()) != 0) {
@@ -3275,14 +2680,13 @@ Session::cleanup_sources (Session::cleanup_report& rep)
                                goto out;
                        }
                }
-
        }
 
        ret = 0;
 
        /* dump the history list */
 
-       history.clear ();
+       _history.clear ();
 
        /* save state so we don't end up a session file
           referring to non-existent sources.
@@ -3292,12 +2696,15 @@ Session::cleanup_sources (Session::cleanup_report& rep)
 
   out:
        _state_of_the_state = (StateOfTheState) (_state_of_the_state & ~InCleanup);
+
        return ret;
 }
 
 int
 Session::cleanup_trash_sources (Session::cleanup_report& rep)
 {
+       // FIXME: needs adaptation for MIDI
+       
        vector<space_and_path>::iterator i;
        string dead_sound_dir;
        struct dirent* dentry;
@@ -3363,6 +2770,7 @@ Session::set_dirty ()
 
        _state_of_the_state = StateOfTheState (_state_of_the_state | Dirty);
 
+
        if (!was_dirty) {
                DirtyChanged(); /* EMIT SIGNAL */
        }
@@ -3376,17 +2784,38 @@ Session::set_clean ()
        
        _state_of_the_state = Clean;
 
+
        if (was_dirty) {
                DirtyChanged(); /* EMIT SIGNAL */
        }
 }
 
 void
-Session::add_controllable (Controllable* c)
+Session::set_deletion_in_progress ()
+{
+       _state_of_the_state = StateOfTheState (_state_of_the_state | Deletion);
+}
+
+void
+Session::clear_deletion_in_progress ()
+{
+       _state_of_the_state = StateOfTheState (_state_of_the_state & (~Deletion));
+}
+
+void
+Session::add_controllable (boost::shared_ptr<Controllable> c)
 {
+       /* this adds a controllable to the list managed by the Session.
+          this is a subset of those managed by the Controllable class
+          itself, and represents the only ones whose state will be saved
+          as part of the session.
+       */
+
        Glib::Mutex::Lock lm (controllables_lock);
-       controllables.push_back (c);
+       controllables.insert (c);
 }
+       
+struct null_deleter { void operator()(void const *) const {} };
 
 void
 Session::remove_controllable (Controllable* c)
@@ -3396,10 +2825,16 @@ Session::remove_controllable (Controllable* c)
        }
 
        Glib::Mutex::Lock lm (controllables_lock);
-       controllables.remove (c);
+
+       Controllables::iterator x = controllables.find(
+                boost::shared_ptr<Controllable>(c, null_deleter()));
+
+       if (x != controllables.end()) {
+               controllables.erase (x);
+       }
 }      
 
-Controllable*
+boost::shared_ptr<Controllable>
 Session::controllable_by_id (const PBD::ID& id)
 {
        Glib::Mutex::Lock lm (controllables_lock);
@@ -3410,125 +2845,384 @@ Session::controllable_by_id (const PBD::ID& id)
                }
        }
 
-       return 0;
+       return boost::shared_ptr<Controllable>();
 }
 
 void 
-Session::add_instant_xml (XMLNode& node, const std::string& dir)
+Session::add_instant_xml (XMLNode& node, bool write_to_config)
 {
-       Stateful::add_instant_xml (node, dir);
-       Config->add_instant_xml (node, get_user_ardour_path());
+       Stateful::add_instant_xml (node, _path);
+       if (write_to_config) {
+               Config->add_instant_xml (node);
+       }
 }
 
+XMLNode*
+Session::instant_xml (const string& node_name)
+{
+       return Stateful::instant_xml (node_name, _path);
+}
 
 int 
 Session::save_history (string snapshot_name)
 {
-    XMLTree tree;
-    string xml_path;
-    string bak_path;
-
+       XMLTree tree;
+       
+       if (snapshot_name.empty()) {
+               snapshot_name = _current_snapshot_name;
+       }
+  
+       const string history_filename = snapshot_name + history_suffix;
+       const string backup_filename = history_filename + backup_suffix;
+       const sys::path xml_path = _session_dir->root_path() / history_filename;
+       const sys::path backup_path = _session_dir->root_path() / backup_filename;
 
-    tree.set_root (&history.get_state());
+       if (sys::exists (xml_path)) {
+               try
+               {
+                       sys::rename (xml_path, backup_path);
+               }
+               catch (const sys::filesystem_error& err)
+               {
+                       error << _("could not backup old history file, current history not saved") << endmsg;
+                       return -1;
+               }
+       }
 
-    if (snapshot_name.empty()) {
-       snapshot_name = _current_snapshot_name;
-    }
 
-    xml_path = _path + snapshot_name + ".history"; 
-    cerr << "Saving history to " << xml_path << endmsg;
+       if (!Config->get_save_history() || Config->get_saved_history_depth() < 0) {
+               return 0;
+       }
 
-    bak_path = xml_path + ".bak";
+       tree.set_root (&_history.get_state (Config->get_saved_history_depth()));
 
-    if ((access (xml_path.c_str(), F_OK) == 0) &&
-        (rename (xml_path.c_str(), bak_path.c_str())))
-    {
-        error << _("could not backup old history file, current history not saved.") << endmsg;
-        return -1;
-    }
+       if (!tree.write (xml_path.to_string()))
+       {
+               error << string_compose (_("history could not be saved to %1"), xml_path.to_string()) << endmsg;
 
-    if (!tree.write (xml_path))
-    {
-        error << string_compose (_("history could not be saved to %1"), xml_path) << endmsg;
-
-        /* don't leave a corrupt file lying around if it is
-         * possible to fix.
-         */
-
-        if (unlink (xml_path.c_str())) 
-        {
-            error << string_compose (_("could not remove corrupt history file %1"), xml_path) << endmsg;
-        } else {
-            if (rename (bak_path.c_str(), xml_path.c_str())) 
-            {
-                error << string_compose (_("could not restore history file from backup %1"), bak_path) << endmsg;
-            }
-        }
+               try
+               {
+                       sys::remove (xml_path);
+                       sys::rename (backup_path, xml_path);
+               }
+               catch (const sys::filesystem_error& err)
+               {
+                       error << string_compose (_("could not restore history file from backup %1 (%2)"),
+                                       backup_path.to_string(), err.what()) << endmsg;
+               }
 
-        return -1;
-    }
+               return -1;
+       }
 
-    return 0;
+       return 0;
 }
 
 int
 Session::restore_history (string snapshot_name)
 {
-    XMLTree tree;
-    string xmlpath;
+       XMLTree tree;
 
-    /* read xml */
-    xmlpath = _path + snapshot_name + ".history";
-    cerr << string_compose(_("Loading history from '%1'."), xmlpath) << endmsg;
+       if (snapshot_name.empty()) {
+               snapshot_name = _current_snapshot_name;
+       }
 
-    if (access (xmlpath.c_str(), F_OK)) {
-        error << string_compose(_("%1: session history file \"%2\" doesn't exist!"), _name, xmlpath) << endmsg;
-        return 1;
-    }
+       const string xml_filename = snapshot_name + history_suffix;
+       const sys::path xml_path = _session_dir->root_path() / xml_filename;
 
-    if (!tree.read (xmlpath)) {
-        error << string_compose(_("Could not understand ardour file %1"), xmlpath) << endmsg;
-        return -1;
-    }
+    cerr << "Loading history from " << xml_path.to_string() << endmsg;
 
-    /* replace history */
-    history.clear();
-    for (XMLNodeConstIterator it  = tree.root()->children().begin();
-         it != tree.root()->children().end();
-         it++)
-    {
-        XMLNode *t = *it;
-        UndoTransaction* ut = new UndoTransaction ();
-        struct timeval tv;
-
-        ut->set_name(t->property("name")->value());
-        stringstream ss(t->property("tv_sec")->value());
-        ss >> tv.tv_sec;
-        ss.str(t->property("tv_usec")->value());
-        ss >> tv.tv_usec;
-        ut->set_timestamp(tv);
-
-        for (XMLNodeConstIterator child_it  = t->children().begin();
-             child_it != t->children().end();
-             child_it++)
-        {
-            XMLNode *n = *child_it;
-            Command *c;
-            if (n->name() == "MementoCommand" ||
-                n->name() == "MementoUndoCommand" ||
-                n->name() == "MementoRedoCommand")
-            {
-                c = memento_command_factory(n);
-                if (c)
-                    ut->add_command(c);
-            }
-            else
-            {
-                error << string_compose(_("Couldn't figure out how to make a Command out of a %1 XMLNode."), n->name()) << endmsg;
-            }
-        }
-        history.add(ut);
+       if (!sys::exists (xml_path)) {
+               info << string_compose (_("%1: no history file \"%2\" for this session."),
+                               _name, xml_path.to_string()) << endmsg;
+               return 1;
+       }
+
+       if (!tree.read (xml_path.to_string())) {
+               error << string_compose (_("Could not understand session history file \"%1\""),
+                               xml_path.to_string()) << endmsg;
+               return -1;
+       }
+
+       // replace history
+       _history.clear();
+
+    for (XMLNodeConstIterator it  = tree.root()->children().begin(); it != tree.root()->children().end(); it++) {
+           
+           XMLNode *t = *it;
+           UndoTransaction* ut = new UndoTransaction ();
+           struct timeval tv;
+           
+           ut->set_name(t->property("name")->value());
+           stringstream ss(t->property("tv-sec")->value());
+           ss >> tv.tv_sec;
+           ss.str(t->property("tv-usec")->value());
+           ss >> tv.tv_usec;
+           ut->set_timestamp(tv);
+           
+           for (XMLNodeConstIterator child_it  = t->children().begin();
+                               child_it != t->children().end(); child_it++)
+           {
+                   XMLNode *n = *child_it;
+                   Command *c;
+       
+                   if (n->name() == "MementoCommand" ||
+                                       n->name() == "MementoUndoCommand" ||
+                                       n->name() == "MementoRedoCommand") {
+
+                           if ((c = memento_command_factory(n))) {
+                                   ut->add_command(c);
+                           }
+                           
+                   } else if (n->name() == X_("GlobalRouteStateCommand")) {
+
+                           if ((c = global_state_command_factory (*n))) {
+                                   ut->add_command (c);
+                           }
+                           
+                   } else if (n->name() == "DeltaCommand") {
+                        PBD::ID  id(n->property("midi-source")->value());
+                        boost::shared_ptr<MidiSource> midi_source = 
+                                boost::dynamic_pointer_cast<MidiSource, Source>(source_by_id(id));
+                        if(midi_source) {
+                                ut->add_command(new MidiModel::DeltaCommand(midi_source->model(), *n));                                 
+                        } else {
+                                error << "FIXME: Failed to downcast MidiSource for DeltaCommand" << endmsg;
+                        }
+                   } else {
+                           error << string_compose(_("Couldn't figure out how to make a Command out of a %1 XMLNode."), n->name()) << endmsg;
+                   }
+           }
+
+           _history.add (ut);
     }
 
     return 0;
 }
+
+void
+Session::config_changed (std::string p, bool ours)
+{
+       if (ours) {
+               set_dirty ();
+       }
+       
+       if (p == "seamless-loop") {
+               
+       } else if (p == "rf-speed") {
+               
+       } else if (p == "auto-loop") {
+               
+       } else if (p == "auto-input") {
+               
+               if (Config->get_monitoring_model() == HardwareMonitoring && transport_rolling()) {
+                       /* auto-input only makes a difference if we're rolling */
+                       
+                       boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
+                       
+                       for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
+                               if ((*i)->record_enabled ()) {
+                                       (*i)->monitor_input (!config.get_auto_input());
+                               }
+                       }
+               }
+
+       } else if (p == "punch-in") {
+
+               Location* location;
+               
+               if ((location = _locations.auto_punch_location()) != 0) {
+                       
+                       if (config.get_punch_in ()) {
+                               replace_event (Event::PunchIn, location->start());
+                       } else {
+                               remove_event (location->start(), Event::PunchIn);
+                       }
+               }
+               
+       } else if (p == "punch-out") {
+
+               Location* location;
+               
+               if ((location = _locations.auto_punch_location()) != 0) {
+                       
+                       if (config.get_punch_out()) {
+                               replace_event (Event::PunchOut, location->end());
+                       } else {
+                               clear_events (Event::PunchOut);
+                       }
+               }
+
+       } else if (p == "edit-mode") {
+
+               Glib::Mutex::Lock lm (playlist_lock);
+               
+               for (PlaylistList::iterator i = playlists.begin(); i != playlists.end(); ++i) {
+                       (*i)->set_edit_mode (Config->get_edit_mode ());
+               }
+
+       } else if (p == "use-video-sync") {
+
+               waiting_for_sync_offset = config.get_use_video_sync();
+
+       } else if (p == "mmc-control") {
+
+               //poke_midi_thread ();
+
+       } else if (p == "mmc-device-id" || p == "mmc-receive-id") {
+
+               if (mmc) {
+                       mmc->set_receive_device_id (Config->get_mmc_receive_device_id());
+               }
+
+       } else if (p == "mmc-send-id") {
+
+               if (mmc) {
+                       mmc->set_send_device_id (Config->get_mmc_send_device_id());
+               }
+
+       } else if (p == "midi-control") {
+               
+               //poke_midi_thread ();
+
+       } else if (p == "raid-path") {
+
+               setup_raid_path (config.get_raid_path());
+
+       } else if (p == "smpte-format") {
+
+               sync_time_vars ();
+
+       } else if (p == "video-pullup") {
+
+               sync_time_vars ();
+
+       } else if (p == "seamless-loop") {
+
+               if (play_loop && transport_rolling()) {
+                       // to reset diskstreams etc
+                       request_play_loop (true);
+               }
+
+       } else if (p == "rf-speed") {
+
+               cumulative_rf_motion = 0;
+               reset_rf_scale (0);
+
+       } else if (p == "click-sound") {
+
+               setup_click_sounds (1);
+
+       } else if (p == "click-emphasis-sound") {
+
+               setup_click_sounds (-1);
+
+       } else if (p == "clicking") {
+
+               if (Config->get_clicking()) {
+                       if (_click_io && click_data) { // don't require emphasis data
+                               _clicking = true;
+                       }
+               } else {
+                       _clicking = false;
+               }
+
+       } else if (p == "send-mtc") {
+               
+               /* only set the internal flag if we have
+                  a port.
+               */
+               
+               if (_mtc_port != 0) {
+                       session_send_mtc = Config->get_send_mtc();
+                       if (session_send_mtc) {
+                               /* mark us ready to send */
+                               next_quarter_frame_to_send = 0;
+                       }
+               } else {
+                       session_send_mtc = false;
+               }
+
+       } else if (p == "send-mmc") {
+               
+               /* only set the internal flag if we have
+                  a port.
+               */
+               
+               if (_mmc_port != 0) {
+                       session_send_mmc = Config->get_send_mmc();
+               } else {
+                       mmc = 0;
+                       session_send_mmc = false; 
+               }
+
+       } else if (p == "midi-feedback") {
+               
+               /* only set the internal flag if we have
+                  a port.
+               */
+               
+               if (_mtc_port != 0) {
+                       session_midi_feedback = Config->get_midi_feedback();
+               }
+
+       } else if (p == "jack-time-master") {
+
+               engine().reset_timebase ();
+
+       } else if (p == "native-file-header-format") {
+
+               if (!first_file_header_format_reset) {
+                       reset_native_file_format ();
+               }
+
+               first_file_header_format_reset = false;
+
+       } else if (p == "native-file-data-format") {
+
+               if (!first_file_data_format_reset) {
+                       reset_native_file_format ();
+               }
+
+               first_file_data_format_reset = false;
+
+       } else if (p == "slave-source") {
+                               set_slave_source (Config->get_slave_source());
+       } else if (p == "remote-model") {
+               set_remote_control_ids ();
+       }  else if (p == "denormal-model") {
+               setup_fpu ();
+       } else if (p == "history-depth") {
+               set_history_depth (Config->get_history_depth());
+       } else if (p == "sync-all-route-ordering") {
+               sync_order_keys ("session");
+       } else if (p == "initial-program-change") {
+
+               if (_mmc_port && Config->get_initial_program_change() >= 0) {
+                       MIDI::byte buf[2];
+                       
+                       buf[0] = MIDI::program; // channel zero by default
+                       buf[1] = (Config->get_initial_program_change() & 0x7f);
+
+                       _mmc_port->midimsg (buf, sizeof (buf), 0);
+               }
+       } else if (p == "initial-program-change") {
+
+               if (_mmc_port && Config->get_initial_program_change() >= 0) {
+                       MIDI::byte* buf = new MIDI::byte[2];
+                       
+                       buf[0] = MIDI::program; // channel zero by default
+                       buf[1] = (Config->get_initial_program_change() & 0x7f);
+                       // deliver_midi (_mmc_port, buf, 2);
+               }
+       } else if (p == "solo-mute-override") {
+               catch_up_on_solo_mute_override ();
+       }
+
+       set_dirty ();
+}
+
+void
+Session::set_history_depth (uint32_t d)
+{
+       _history.set_depth (d);
+}