Fix the interchange/ directory structure for snapshots
[ardour.git] / libs / ardour / session_state.cc
index 731184e8d9af121bf225faeffc31f2d843d20edd..d721eecce9ce160d25f1da5812f313c8a21c793b 100644 (file)
 #include <sys/param.h>
 #endif
 
+#include <glibmm.h>
+
 #include <midi++/mmc.h>
 #include <midi++/port.h>
 #include <pbd/error.h>
-#include <pbd/dirname.h>
-#include <pbd/lockmonitor.h>
+
+#include <glibmm/thread.h>
 #include <pbd/pathscanner.h>
 #include <pbd/pthread_utils.h>
-#include <pbd/basename.h>
 #include <pbd/strsplit.h>
 
 #include <ardour/audioengine.h>
 #include <ardour/configuration.h>
 #include <ardour/session.h>
-#include <ardour/diskstream.h>
+#include <ardour/audio_diskstream.h>
 #include <ardour/utils.h>
 #include <ardour/audioplaylist.h>
-#include <ardour/source.h>
-#include <ardour/filesource.h>
+#include <ardour/audiofilesource.h>
 #include <ardour/destructive_filesource.h>
-#include <ardour/sndfilesource.h>
 #include <ardour/sndfile_helpers.h>
 #include <ardour/auditioner.h>
 #include <ardour/export.h>
 #include <ardour/location.h>
 #include <ardour/audioregion.h>
 #include <ardour/crossfade.h>
+#include <ardour/control_protocol_manager.h>
+#include <ardour/region_factory.h>
+#include <ardour/source_factory.h>
 
 #include "i18n.h"
 #include <locale.h>
 
 using namespace std;
 using namespace ARDOUR;
+using namespace PBD;
 
 void
 Session::first_stage_init (string fullpath, string snapshot_name)
@@ -111,13 +114,12 @@ Session::first_stage_init (string fullpath, string snapshot_name)
        */
 
        _name = _current_snapshot_name = snapshot_name;
-       setup_raid_path (_path);
 
        _current_frame_rate = _engine.frame_rate ();
        _tempo_map = new TempoMap (_current_frame_rate);
        _tempo_map->StateChanged.connect (mem_fun (*this, &Session::tempo_map_changed));
 
-       atomic_set (&processing_prohibited, 0);
+       g_atomic_int_set (&processing_prohibited, 0);
        send_cnt = 0;
        insert_cnt = 0;
        _transport_speed = 0;
@@ -126,8 +128,9 @@ Session::first_stage_init (string fullpath, string snapshot_name)
        _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;
-       atomic_set (&_record_status, Disabled);
+       g_atomic_int_set (&_record_status, Disabled);
        auto_play = false;
        punch_in = false;
        punch_out = false;
@@ -154,6 +157,7 @@ Session::first_stage_init (string fullpath, string snapshot_name)
        _solo_model = InverseMute;
        solo_update_disabled = false;
        currently_soloing = false;
+       _have_captured = false;
        _worst_output_latency = 0;
        _worst_input_latency = 0;
        _worst_track_latency = 0;
@@ -162,27 +166,21 @@ Session::first_stage_init (string fullpath, string snapshot_name)
        _slave_type = None;
        butler_mixdown_buffer = 0;
        butler_gain_buffer = 0;
-       auditioner = 0;
        mmc_control = false;
-       midi_feedback = false;
        midi_control = true;
        mmc = 0;
        post_transport_work = PostTransportWork (0);
-       atomic_set (&butler_should_do_transport_work, 0);
-       atomic_set (&butler_active, 0);
-       atomic_set (&_playback_load, 100);
-       atomic_set (&_capture_load, 100);
-       atomic_set (&_playback_load_min, 100);
-       atomic_set (&_capture_load_min, 100);
-       pending_audition_region = 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;
-       _control_out = 0;
-       _master_out = 0;
        input_auto_connect = AutoConnectOption (0);
        output_auto_connect = AutoConnectOption (0);
-       _have_captured = false;
        waiting_to_start = false;
        _exporting = false;
        _gain_automation_buffer = 0;
@@ -191,14 +189,15 @@ Session::first_stage_init (string fullpath, string snapshot_name)
        pending_abort = false;
        layer_model = MoveAddHigher;
        xfade_model = ShortCrossfade;
+       destructive_index = 0;
+       current_trans = 0;
 
-       /* allocate conversion buffers */
-       _conversion_buffers[ButlerContext] = new char[DiskStream::disk_io_frames() * 4];
-       _conversion_buffers[TransportContext] = new char[DiskStream::disk_io_frames() * 4];
+       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());
 
        last_mmc_step.tv_sec = 0;
        last_mmc_step.tv_usec = 0;
@@ -213,7 +212,6 @@ Session::first_stage_init (string fullpath, string snapshot_name)
           waveforms for clicks.
        */
        
-       _click_io = 0;
        _clicking = false;
        click_requested = false;
        click_data = 0;
@@ -223,6 +221,18 @@ Session::first_stage_init (string fullpath, string snapshot_name)
 
        process_function = &Session::process_with_events;
 
+       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;
@@ -244,7 +254,7 @@ Session::first_stage_init (string fullpath, string snapshot_name)
        shuttle_speed_threshold = 5;
        rf_speed = 2.0;
        _meter_hold = 100; // XXX unknown units: number of calls to meter::set()
-       _meter_falloff = 1.5f; // XXX unknown units: refresh_rate
+       _meter_falloff = 0.375f; // XXX unknown units: refresh_rate
        max_level = 0;
        min_level = 0;
 
@@ -258,17 +268,22 @@ Session::first_stage_init (string fullpath, string snapshot_name)
        /* 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 */
 
-       Region::CheckNewRegion.connect (mem_fun (*this, &Session::add_region));
-       Source::SourceCreated.connect (mem_fun (*this, &Session::add_source));
+       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));
-       DiskStream::DiskStreamCreated.connect (mem_fun (*this, &Session::add_diskstream));
        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));
 
        IO::MoreOutputs.connect (mem_fun (*this, &Session::ensure_passthru_buffers));
 
@@ -282,7 +297,7 @@ Session::first_stage_init (string fullpath, string snapshot_name)
 int
 Session::second_stage_init (bool new_session)
 {
-       SndFileSource::set_peak_dir (peak_dir());
+       AudioFileSource::set_peak_dir (peak_dir());
 
        if (!new_session) {
                if (load_state (_current_snapshot_name)) {
@@ -299,14 +314,14 @@ Session::second_stage_init (bool new_session)
                return -1;
        }
 
-       if (init_feedback ()) {
-               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,
@@ -342,7 +357,8 @@ Session::second_stage_init (bool new_session)
        _engine.transport_locate (0);
        deliver_mmc (MIDI::MachineControl::cmdMmcReset, 0);
        deliver_mmc (MIDI::MachineControl::cmdLocate, 0);
-       send_all_midi_feedback();
+
+       ControlProtocolManager::instance().set_session (*this);
 
        if (new_session) {
                _end_location_is_free = true;
@@ -400,13 +416,23 @@ Session::setup_raid_path (string path)
 
        if (colons == 0) {
 
-               /* no multiple search path, just one directory (common case) */
+               /* no multiple search path, just one location (common case) */
 
                sp.path = path;
                sp.blocks = 0;
                session_dirs.push_back (sp);
+
+               string fspath;
+
+               /* sounds dir */
+
+               fspath += sp.path;
+               if (fspath[fspath.length()-1] != '/') {
+                       fspath += '/';
+               }
+               fspath += sound_dir (false);
                
-               FileSource::set_search_path (path + sound_dir_name);
+               AudioFileSource::set_search_path (fspath);
 
                return;
        }
@@ -417,16 +443,17 @@ Session::setup_raid_path (string path)
                
                sp.blocks = 0;
                sp.path = remaining.substr (0, colon);
+               session_dirs.push_back (sp);
+
+               /* add sounds to file search path */
 
                fspath += sp.path;
                if (fspath[fspath.length()-1] != '/') {
                        fspath += '/';
                }
-               fspath += sound_dir_name;
+               fspath += sound_dir (false);
                fspath += ':';
 
-               session_dirs.push_back (sp);
-
                remaining = remaining.substr (colon+1);
        }
 
@@ -435,18 +462,20 @@ Session::setup_raid_path (string path)
                sp.blocks = 0;
                sp.path = remaining;
 
+               fspath += ':';
                fspath += sp.path;
                if (fspath[fspath.length()-1] != '/') {
                        fspath += '/';
                }
-               fspath += sound_dir_name;
+               fspath += sound_dir (false);
+               fspath += ':';
 
                session_dirs.push_back (sp);
        }
 
-       /* set the FileSource search path */
+       /* set the AudioFileSource search path */
 
-       FileSource::set_search_path (fspath);
+       AudioFileSource::set_search_path (fspath);
 
        /* reset the round-robin soundfile path thingie */
 
@@ -457,119 +486,91 @@ int
 Session::create (bool& new_session, string* mix_template, jack_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;
+
+       if (g_mkdir_with_parents (_path.c_str(), 0755) < 0) {
+               error << string_compose(_("Session: cannot create session dir \"%1\" (%2)"), _path, strerror (errno)) << endmsg;
+               return -1;
        }
 
        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 (dir.c_str(), 0755) < 0) {
+               error << string_compose(_("Session: cannot create session peakfile dir \"%1\" (%2)"), dir, 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;
-               }
-       }
-
-       dir = tape_dir ();
-
-       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 (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 = dead_sound_dir ();
 
-       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 (g_mkdir_with_parents (dir.c_str(), 0755) < 0) {
+               error << string_compose(_("Session: cannot create session dead sounds dir \"%1\" (%2)"), dir, strerror (errno)) << endmsg;
+               return -1;
        }
 
        dir = automation_dir ();
 
-       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 (g_mkdir_with_parents (dir.c_str(), 0755) < 0) {
+               error << string_compose(_("Session: cannot create session automation dir \"%1\" (%2)"), dir, strerror (errno)) << endmsg;
+               return -1;
        }
 
-       
+
        /* check new_session so we don't overwrite an existing one */
-       
+
        if (mix_template) {
-               if (new_session){
-                       std::string in_path = *mix_template;
+               std::string in_path = *mix_template;
+
+               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;
 
-                       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;
                }
+
        }
 
-       if (new_session) {
+       /* set initial start + end point */
 
-               /* set an initial end point */
+       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)) {
-                       return -1;
-               }
+       if (save_state (_current_snapshot_name)) {
+               save_history (_current_snapshot_name);
+               return -1;
        }
 
        return 0;
@@ -585,11 +586,10 @@ Session::load_diskstreams (const XMLNode& node)
 
        for (citer = clist.begin(); citer != clist.end(); ++citer) {
                
-               DiskStream* dstream;
 
                try {
-                       dstream = new DiskStream (*this, **citer);
-                       /* added automatically by DiskStreamCreated handler */
+                       boost::shared_ptr<AudioDiskstream> dstream (new AudioDiskstream (*this, **citer));
+                       add_diskstream (dstream);
                } 
                
                catch (failed_constructor& err) {
@@ -654,6 +654,8 @@ Session::save_state (string snapshot_name, bool pending)
 
        }
 
+       cerr << "actually writing state\n";
+
        if (!tree.write (xml_path)) {
                error << string_compose (_("state could not be saved to %1"), xml_path) << endmsg;
 
@@ -675,9 +677,10 @@ Session::save_state (string snapshot_name, bool pending)
        }
 
        if (!pending) {
+                save_history(snapshot_name);
 
                bool was_dirty = dirty();
-               
+
                _state_of_the_state = StateOfTheState (_state_of_the_state & ~Dirty);
                
                if (was_dirty) {
@@ -867,6 +870,11 @@ Session::load_options (const XMLNode& node)
                        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 );
@@ -981,6 +989,12 @@ Session::load_options (const XMLNode& node)
                }
        }
 
+       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 ((child = find_named_node (node, "layer-model")) != 0) {
                if ((prop = child->property ("val")) != 0) {
                        if (prop->value() == X_("LaterHigher")) {
@@ -1115,6 +1129,10 @@ Session::get_options () const
        child = opthead->add_child ("rf-speed");
        child->add_property ("val", buf);
 
+       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);
@@ -1166,6 +1184,8 @@ Session::get_options () const
        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");
@@ -1228,7 +1248,7 @@ Session::get_template()
           sources in their state node. 
        */
        
-       disable_record ();
+       disable_record (false);
 
        return state(false);
 }
@@ -1282,39 +1302,54 @@ Session::state(bool full_state)
                }
        }
 
+       /* save the ID counter */
+       
+       snprintf (buf, sizeof (buf), "%" PRIu64, ID::counter());
+       node->add_property ("id-counter", buf);
+
+       /* various options */
+
        node->add_child_nocopy (get_options());
 
        child = node->add_child ("Sources");
 
        if (full_state) {
-               LockMonitor sl (source_lock, __LINE__, __FILE__);
+               Glib::Mutex::Lock sl (audio_source_lock);
 
-               for (SourceList::iterator siter = sources.begin(); siter != sources.end(); ++siter) {
-                       
-                       /* Don't save information about FileSources that are empty */
+               for (AudioSourceList::iterator siter = audio_sources.begin(); siter != audio_sources.end(); ++siter) {
                        
-                       FileSource* fs;
+                       /* Don't save information about AudioFileSources that are empty */
                        
-                       if ((fs = dynamic_cast<FileSource*> ((*siter).second)) != 0) {
-                               if (fs->length() == 0) {
-                                       continue;
+                       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);
+
+                               /* destructive file sources are OK if they are empty, because
+                                  we will re-use them every time.
+                               */
+
+                               if (!dfs) {
+                                       if (fs->length() == 0) {
+                                               continue;
+                                       }
                                }
                        }
                        
-                       child->add_child_nocopy ((*siter).second->get_state());
+                       child->add_child_nocopy (siter->second->get_state());
                }
        }
 
        child = node->add_child ("Regions");
 
        if (full_state) { 
-               LockMonitor rl (region_lock, __LINE__, __FILE__);
+               Glib::Mutex::Lock rl (region_lock);
 
                for (AudioRegionList::const_iterator i = audio_regions.begin(); i != audio_regions.end(); ++i) {
                        
                        /* only store regions not attached to playlists */
 
-                       if ((*i).second->playlist() == 0) {
+                       if (i->second->playlist() == 0) {
                                child->add_child_nocopy (i->second->state (true));
                        }
                }
@@ -1323,8 +1358,8 @@ Session::state(bool full_state)
        child = node->add_child ("DiskStreams");
 
        { 
-               RWLockMonitor dl (diskstream_lock, false, __LINE__, __FILE__);
-               for (DiskStreamList::iterator i = diskstreams.begin(); i != diskstreams.end(); ++i) {
+               boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
+               for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
                        if (!(*i)->hidden()) {
                                child->add_child_nocopy ((*i)->get_state());
                        }
@@ -1335,7 +1370,7 @@ Session::state(bool full_state)
        
        child = node->add_child ("Connections");
        {
-               LockMonitor lm (connection_lock, __LINE__, __FILE__);
+               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());
@@ -1345,10 +1380,10 @@ Session::state(bool full_state)
 
        child = node->add_child ("Routes");
        {
-               RWLockMonitor lm (route_lock, false, __LINE__, __FILE__);
+               boost::shared_ptr<RouteList> r = routes.reader ();
                
                RoutePublicOrderSorter cmp;
-               RouteList public_order(routes);
+               RouteList public_order (*r);
                public_order.sort (cmp);
                
                for (RouteList::iterator i = public_order.begin(); i != public_order.end(); ++i) {
@@ -1433,7 +1468,7 @@ Session::set_state (const XMLNode& node)
 
        _state_of_the_state = StateOfTheState (_state_of_the_state|CannotSave);
        
-       if (node.name() != "Session"){
+       if (node.name() != X_("Session")){
                fatal << _("programming error: Session: incorrect XML node sent to set_state()") << endmsg;
                return -1;
        }
@@ -1443,6 +1478,23 @@ Session::set_state (const XMLNode& node)
        if ((prop = node.property ("name")) != 0) {
                _name = prop->value ();
        }
+
+       setup_raid_path(_path);
+
+       if ((prop = node.property (X_("id-counter"))) != 0) {
+               uint64_t x;
+               sscanf (prop->value().c_str(), "%" PRIu64, &x);
+               ID::init_counter (x);
+       } else {
+               /* old sessions used a timebased counter, so fake
+                  the startup ID counter based on a standard
+                  timestamp.
+               */
+               time_t now;
+               time (&now);
+               ID::init_counter (now);
+       }
+
        
        IO::disable_ports ();
        IO::disable_connecting ();
@@ -1455,7 +1507,7 @@ Session::set_state (const XMLNode& node)
        Options
        Sources
        AudioRegions
-       DiskStreams
+       AudioDiskstreams
        Connections
        Locations
        Routes
@@ -1551,9 +1603,17 @@ Session::set_state (const XMLNode& node)
        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;
+       }
+
        _locations.save_state (_("initial state"));
 
        if ((child = find_named_node (node, "EditGroups")) == 0) {
@@ -1621,7 +1681,7 @@ Session::load_routes (const XMLNode& node)
 {
        XMLNodeList nlist;
        XMLNodeConstIterator niter;
-       Route *route;
+       RouteList new_routes;
 
        nlist = node.children();
 
@@ -1629,28 +1689,34 @@ Session::load_routes (const XMLNode& node)
 
        for (niter = nlist.begin(); niter != nlist.end(); ++niter) {
 
-               if ((route = XMLRouteFactory (**niter)) == 0) {
+               boost::shared_ptr<Route> route (XMLRouteFactory (**niter));
+
+               if (route == 0) {
                        error << _("Session: cannot create Route from XML description.")                              << endmsg;
                        return -1;
                }
 
-               add_route (route);
+               new_routes.push_back (route);
        }
 
+       add_routes (new_routes);
+
        return 0;
 }
 
-Route *
+boost::shared_ptr<Route>
 Session::XMLRouteFactory (const XMLNode& node)
 {
        if (node.name() != "Route") {
-               return 0;
+               return boost::shared_ptr<Route> ((Route*) 0);
        }
 
        if (node.property ("diskstream") != 0 || node.property ("diskstream-id") != 0) {
-               return new AudioTrack (*this, node);
+               boost::shared_ptr<Route> x (new AudioTrack (*this, node));
+               return x;
        } else {
-               return new Route (*this, node);
+               boost::shared_ptr<Route> x (new Route (*this, node));
+               return x;
        }
 }
 
@@ -1659,14 +1725,13 @@ Session::load_regions (const XMLNode& node)
 {
        XMLNodeList nlist;
        XMLNodeConstIterator niter;
-       AudioRegion* region;
+       boost::shared_ptr<AudioRegion> region;
 
        nlist = node.children();
 
        set_dirty();
 
        for (niter = nlist.begin(); niter != nlist.end(); ++niter) {
-
                if ((region = XMLRegionFactory (**niter, false)) == 0) {
                        error << _("Session: cannot create Region from XML description.") << endmsg;
                }
@@ -1675,18 +1740,18 @@ Session::load_regions (const XMLNode& node)
        return 0;
 }
 
-AudioRegion *
+boost::shared_ptr<AudioRegion>
 Session::XMLRegionFactory (const XMLNode& node, bool full)
 {
        const XMLProperty* prop;
-       id_t s_id;
-       Source* source;
-       AudioRegion::SourceList sources;
+       boost::shared_ptr<Source> source;
+       boost::shared_ptr<AudioSource> as;
+       SourceList sources;
        uint32_t nchans = 1;
        char buf[128];
        
        if (node.name() != X_("Region")) {
-               return 0;
+               return boost::shared_ptr<AudioRegion>();
        }
 
        if ((prop = node.property (X_("channels"))) != 0) {
@@ -1697,41 +1762,55 @@ Session::XMLRegionFactory (const XMLNode& node, bool full)
        if ((prop = node.property (X_("source-0"))) == 0) {
                if ((prop = node.property ("source")) == 0) {
                        error << _("Session: XMLNode describing a AudioRegion is incomplete (no source)") << endmsg;
-                       return 0;
+                       return boost::shared_ptr<AudioRegion>();
                }
        }
 
-       sscanf (prop->value().c_str(), "%" PRIu64, &s_id);
+       PBD::ID s_id (prop->value());
 
-       if ((source = get_source (s_id)) == 0) {
+       if ((source = source_by_id (s_id)) == 0) {
                error << string_compose(_("Session: XMLNode describing a AudioRegion references an unknown source id =%1"), s_id) << endmsg;
-               return 0;
+               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"), s_id) << endmsg;
+               return boost::shared_ptr<AudioRegion>();
        }
 
-       sources.push_back(source);
+       sources.push_back (as);
 
        /* pickup other channels */
 
        for (uint32_t n=1; n < nchans; ++n) {
                snprintf (buf, sizeof(buf), X_("source-%d"), n);
                if ((prop = node.property (buf)) != 0) {
-                       sscanf (prop->value().c_str(), "%" PRIu64, &s_id);
                        
-                       if ((source = get_source (s_id)) == 0) {
-                               error << string_compose(_("Session: XMLNode describing a AudioRegion references an unknown source id =%1"), s_id) << endmsg;
-                               return 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>();
                        }
-                       sources.push_back(source);
+                       
+                       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>();
+                       }
+                       sources.push_back (as);
                }
        }
        
-       
        try {
-               return new AudioRegion (sources, node);
+               boost::shared_ptr<AudioRegion> region (boost::dynamic_pointer_cast<AudioRegion> (RegionFactory::create (sources, node)));
+               return region;
+                                                      
        }
 
        catch (failed_constructor& err) {
-               return 0;
+               return boost::shared_ptr<AudioRegion>();
        }
 }
 
@@ -1740,12 +1819,14 @@ Session::get_sources_as_xml ()
 
 {
        XMLNode* node = new XMLNode (X_("Sources"));
-       LockMonitor lm (source_lock, __LINE__, __FILE__);
+       Glib::Mutex::Lock lm (audio_source_lock);
 
-       for (SourceList::iterator i = sources.begin(); i != sources.end(); ++i) {
-               node->add_child_nocopy ((*i).second->get_state());
+       for (AudioSourceList::iterator i = audio_sources.begin(); i != audio_sources.end(); ++i) {
+               node->add_child_nocopy (i->second->get_state());
        }
 
+       /* XXX get MIDI and other sources here */
+
        return *node;
 }
 
@@ -1777,7 +1858,7 @@ Session::load_sources (const XMLNode& node)
 {
        XMLNodeList nlist;
        XMLNodeConstIterator niter;
-       Source* source;
+       boost::shared_ptr<Source> source;
 
        nlist = node.children();
 
@@ -1793,37 +1874,21 @@ Session::load_sources (const XMLNode& node)
        return 0;
 }
 
-Source *
+boost::shared_ptr<Source>
 Session::XMLSourceFactory (const XMLNode& node)
 {
-       Source *src = 0;
-
        if (node.name() != "Source") {
-               return 0;
+               return boost::shared_ptr<Source>();
        }
 
-
        try {
-               if (node.property (X_("destructive")) != 0) {
-                       src = new DestructiveFileSource (node, frame_rate());
-               } else {
-                       src = new FileSource (node, frame_rate());
-               }
+               return SourceFactory::create (*this, node);
        }
        
        catch (failed_constructor& err) {
-
-               try {
-                       src = new SndFileSource (node);
-               }
-
-               catch (failed_constructor& err) {
-                       error << _("Found a sound file that cannot be used by Ardour. See the progammers.") << endmsg;
-                       return 0;
-               } 
+               error << _("Found a sound file that cannot be used by Ardour. Talk to the progammers.") << endmsg;
+               return boost::shared_ptr<Source>();
        }
-
-       return src;
 }
 
 int
@@ -1842,7 +1907,7 @@ Session::save_template (string template_name)
        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) {
+               if (g_mkdir_with_parents (dir.c_str(), S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH)) {
                        error << string_compose(_("Could not create mix templates directory \"%1\" (%2)"), dir, strerror (errno)) << endmsg;
                        return -1;
                }
@@ -1896,7 +1961,7 @@ Session::refresh_disk_space ()
 #if HAVE_SYS_VFS_H
        struct statfs statfsbuf;
        vector<space_and_path>::iterator i;
-       LockMonitor lm (space_lock, __LINE__, __FILE__);
+       Glib::Mutex::Lock lm (space_lock);
        double scale;
 
        /* get freespace on every FS that is part of the session path */
@@ -1922,11 +1987,9 @@ Session::ensure_sound_dir (string path, string& result)
 
        /* 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;
-               }
+       if (g_mkdir_with_parents (path.c_str(), 0775)) {
+               error << string_compose(_("cannot create session directory \"%1\"; ignored"), path) << endmsg;
+               return -1;
        }
        
        /* Ensure that the sounds directory exists */
@@ -1935,33 +1998,27 @@ Session::ensure_sound_dir (string path, string& result)
        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;
-               }
+       if (g_mkdir_with_parents (result.c_str(), 0775)) {
+               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;
-               }
+       if (g_mkdir_with_parents (dead.c_str(), 0775)) {
+               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;
-               }
+       if (g_mkdir_with_parents (peak.c_str(), 0775)) {
+               error << string_compose(_("cannot create peak file directory \"%1\"; ignored"), peak) << endmsg;
+               return -1;
        }
        
        /* callers expect this to be terminated ... */
@@ -1976,12 +2033,6 @@ Session::discover_best_sound_dir (bool destructive)
        vector<space_and_path>::iterator i;
        string result;
 
-       /* destructive files all go into the same place */
-
-       if (destructive) {
-               return tape_dir();
-       }
-
        /* handle common case without system calls */
 
        if (session_dirs.size() == 1) {
@@ -2187,26 +2238,41 @@ Session::dead_sound_dir () const
 }
 
 string
-Session::sound_dir () const
+Session::sound_dir (bool with_path) const
 {
-       string res = _path;
-       res += sound_dir_name;
-       res += '/';
-       return res;
-}
+       /* support old session structure */
 
-string
-Session::tape_dir () const
-{
-       string res = Config->get_tape_dir();
+       struct stat statbuf;
+       string old_nopath;
+       string old_withpath;
 
-       if (!res.empty()) {
-               return res;
+       old_nopath += old_sound_dir_name;
+       old_nopath += '/';
+       
+       old_withpath = _path;
+       old_withpath += old_sound_dir_name;
+       old_withpath += '/';
+
+       if (stat (old_withpath.c_str(), &statbuf) == 0) {
+               if (with_path)
+                       return old_withpath;
+               
+               return old_nopath;
        }
 
-       res = _path;
-       res += tape_dir_name;
+       string res;
+
+       if (with_path) {
+               res = _path;
+       }
+
+       res += interchange_dir_name;
+       res += '/';
+       res += legalize_for_path (_name);
+       res += '/';
+       res += sound_dir_name;
        res += '/';
+
        return res;
 }
 
@@ -2230,22 +2296,27 @@ Session::automation_dir () const
 string
 Session::template_dir ()
 {
-       string path = Config->get_user_ardour_path();
+       string path = get_user_ardour_path();
        path += "templates/";
 
        return path;
 }
 
 string
-Session::template_path ()
+Session::suffixed_search_path (string suffix, bool data)
 {
        string path;
 
-       path += Config->get_user_ardour_path();
+       path += get_user_ardour_path();
        if (path[path.length()-1] != ':') {
                path += ':';
        }
-       path += Config->get_system_ardour_path();
+
+       if (data) {
+               path += get_system_data_path();
+       } else {
+               path += get_system_module_path();
+       }
 
        vector<string> split_path;
        
@@ -2254,7 +2325,8 @@ Session::template_path ()
 
        for (vector<string>::iterator i = split_path.begin(); i != split_path.end(); ++i) {
                path += *i;
-               path += "templates/";
+               path += suffix;
+               path += '/';
                
                if (distance (i, split_path.end()) != 1) {
                        path += ':';
@@ -2264,6 +2336,18 @@ Session::template_path ()
        return path;
 }
 
+string
+Session::template_path ()
+{
+       return suffixed_search_path (X_("templates"), true);
+}
+
+string
+Session::control_protocol_path ()
+{
+       return suffixed_search_path (X_("surfaces"), false);
+}
+
 int
 Session::load_connections (const XMLNode& node)
 {
@@ -2303,18 +2387,18 @@ Session::load_route_groups (const XMLNode& node, bool edit)
 {
        XMLNodeList nlist = node.children();
        XMLNodeConstIterator niter;
-       RouteGroup* route;
+       RouteGroup* rg;
 
        set_dirty();
 
        for (niter = nlist.begin(); niter != nlist.end(); ++niter) {
                if ((*niter)->name() == "RouteGroup") {
                        if (edit) {
-                               route = add_edit_group ("");
-                               route->set_state (**niter);
+                               rg = add_edit_group ("");
+                               rg->set_state (**niter);
                        } else {
-                               route = add_mix_group ("");
-                               route->set_state (**niter);
+                               rg = add_mix_group ("");
+                               rg->set_state (**niter);
                        }
                }
        }
@@ -2322,23 +2406,6 @@ Session::load_route_groups (const XMLNode& node, bool edit)
        return 0;
 }                              
 
-void
-Session::swap_configuration(Configuration** new_config)
-{
-       RWLockMonitor lm (route_lock, true, __LINE__, __FILE__); // jlc - WHY?
-       Configuration* tmp = *new_config;
-       *new_config = Config;
-       Config = tmp;
-       set_dirty();
-}
-
-void
-Session::copy_configuration(Configuration* new_config)
-{
-       RWLockMonitor lm (route_lock, true, __LINE__, __FILE__);
-       new_config = new Configuration(*Config);
-}
-
 static bool
 state_file_filter (const string &str, void *arg)
 {
@@ -2362,7 +2429,7 @@ remove_end(string* state)
                statename = statename.substr (start+1);
        }
                
-       if ((end = statename.rfind(".ardour")) < 0) {
+       if ((end = statename.rfind(".ardour")) == string::npos) {
                end = statename.length();
        }
 
@@ -2398,7 +2465,7 @@ Session::auto_save()
 RouteGroup *
 Session::add_edit_group (string name)
 {
-       RouteGroup* rg = new RouteGroup (name);
+       RouteGroup* rg = new RouteGroup (*this, name);
        edit_groups.push_back (rg);
        edit_group_added (rg); /* EMIT SIGNAL */
        set_dirty();
@@ -2408,7 +2475,7 @@ Session::add_edit_group (string name)
 RouteGroup *
 Session::add_mix_group (string name)
 {
-       RouteGroup* rg = new RouteGroup (name, RouteGroup::Relative);
+       RouteGroup* rg = new RouteGroup (*this, name, RouteGroup::Relative);
        mix_groups.push_back (rg);
        mix_group_added (rg); /* EMIT SIGNAL */
        set_dirty();
@@ -2485,43 +2552,40 @@ Session::set_meter_falloff (float val)
 
 
 void
-Session::begin_reversible_command (string name, UndoAction* private_undo)
+Session::begin_reversible_command (string name)
 {
-       current_cmd.clear ();
-       current_cmd.set_name (name);
-
-       if (private_undo) {
-               current_cmd.add_undo (*private_undo);
-       }
+       current_trans = new UndoTransaction;
+       current_trans->set_name (name);
 }
 
 void
-Session::commit_reversible_command (UndoAction* private_redo)
+Session::commit_reversible_command (Command *cmd)
 {
        struct timeval now;
 
-       if (private_redo) {
-               current_cmd.add_redo_no_execute (*private_redo);
+       if (cmd) {
+               current_trans->add_command (cmd);
        }
 
        gettimeofday (&now, 0);
-       current_cmd.set_timestamp (now);
+       current_trans->set_timestamp (now);
 
-       history.add (current_cmd);
+       history.add (current_trans);
 }
 
 Session::GlobalRouteBooleanState 
 Session::get_global_route_boolean (bool (Route::*method)(void) const)
 {
        GlobalRouteBooleanState s;
-       RWLockMonitor lm (route_lock, false, __LINE__, __FILE__);
+       boost::shared_ptr<RouteList> r = routes.reader ();
 
-       for (RouteList::iterator i = routes.begin(); i != routes.end(); ++i) {
+       for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
                if (!(*i)->hidden()) {
                        RouteBooleanState v;
                        
                        v.first =* i;
-                       v.second = ((*i)->*method)();
+                       Route* r = (*i).get();
+                       v.second = (r->*method)();
                        
                        s.push_back (v);
                }
@@ -2534,9 +2598,9 @@ Session::GlobalRouteMeterState
 Session::get_global_route_metering ()
 {
        GlobalRouteMeterState s;
-       RWLockMonitor lm (route_lock, false, __LINE__, __FILE__);
+       boost::shared_ptr<RouteList> r = routes.reader ();
 
-       for (RouteList::iterator i = routes.begin(); i != routes.end(); ++i) {
+       for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
                if (!(*i)->hidden()) {
                        RouteMeterState v;
                        
@@ -2562,7 +2626,8 @@ 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) {
-               (i->first->*method) (i->second, arg);
+               Route* r = i->first.get();
+               (r->*method) (i->second, arg);
        }
 }
 
@@ -2584,6 +2649,7 @@ 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)
 {
@@ -2607,6 +2673,7 @@ 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)
@@ -2643,7 +2710,7 @@ Session::get_template_list (list<string> &template_names)
 int
 Session::read_favorite_dirs (FavoriteDirs & favs)
 {
-       string path = Config->get_user_ardour_path();
+       string path = get_user_ardour_path();
        path += "/favorite_dirs";
 
        ifstream fav (path.c_str());
@@ -2678,7 +2745,7 @@ Session::read_favorite_dirs (FavoriteDirs & favs)
 int
 Session::write_favorite_dirs (FavoriteDirs & favs)
 {
-       string path = Config->get_user_ardour_path();
+       string path = get_user_ardour_path();
        path += "/favorite_dirs";
 
        ofstream fav (path.c_str());
@@ -2795,7 +2862,7 @@ Session::find_all_sources_across_snapshots (set<string>& result, bool exclude_th
 int
 Session::cleanup_sources (Session::cleanup_report& rep)
 {
-       vector<Source*> dead_sources;
+       vector<boost::shared_ptr<Source> > dead_sources;
        vector<Playlist*> playlists_tbd;
        PathScanner scanner;
        string sound_path;
@@ -2855,9 +2922,9 @@ Session::cleanup_sources (Session::cleanup_report& rep)
        rep.paths.clear ();
        rep.space = 0;
 
-       for (SourceList::iterator i = sources.begin(); i != sources.end(); ) {
+       for (AudioSourceList::iterator i = audio_sources.begin(); i != audio_sources.end(); ) {
 
-               SourceList::iterator tmp;
+               AudioSourceList::iterator tmp;
 
                tmp = i;
                ++tmp;
@@ -2867,14 +2934,14 @@ Session::cleanup_sources (Session::cleanup_report& rep)
                   capture files.
                */
 
-               if ((*i).second->use_cnt() == 0 && (*i).second->length() > 0) {
+               if (i->second.use_count() == 1 && i->second->length() > 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);
+                       audio_sources.erase (i);
                }
 
                i = tmp;
@@ -2885,19 +2952,19 @@ Session::cleanup_sources (Session::cleanup_report& rep)
           other snapshots).
        */
                
-       for (vector<Source*>::iterator i = dead_sources.begin(); i != dead_sources.end();++i) {
+       for (vector<boost::shared_ptr<Source> >::iterator i = dead_sources.begin(); i != dead_sources.end();++i) {
 
                for (AudioRegionList::iterator r = audio_regions.begin(); r != audio_regions.end(); ) {
                        AudioRegionList::iterator tmp;
-                       AudioRegion* ar;
+                       boost::shared_ptr<AudioRegion> ar;
 
                        tmp = r;
                        ++tmp;
                        
-                       ar = (*r).second;
+                       ar = r->second;
 
                        for (uint32_t n = 0; n < ar->n_channels(); ++n) {
-                               if (&ar->source (n) == (*i)) {
+                               if (ar->source (n) == (*i)) {
                                        /* this region is dead */
                                        remove_region (ar);
                                }
@@ -2938,20 +3005,17 @@ Session::cleanup_sources (Session::cleanup_report& rep)
           state file on disk still references sources we may have already
           dropped.
        */
-
+       
        find_all_sources_across_snapshots (all_sources, true);
 
-       /* add our current source list
+       /*  add our current source list
         */
-
-       for (SourceList::iterator i = sources.begin(); i != sources.end(); ++i) {
-               FileSource* fs;
-               SndFileSource* sfs;
+       
+       for (AudioSourceList::iterator i = audio_sources.begin(); i != audio_sources.end(); ++i) {
+               boost::shared_ptr<AudioFileSource> fs;
                
-               if ((fs = dynamic_cast<FileSource*> ((*i).second)) != 0) {
+               if ((fs = boost::dynamic_pointer_cast<AudioFileSource> (i->second)) != 0) {
                        all_sources.insert (fs->path());
-               } else if ((sfs = dynamic_cast<SndFileSource*> ((*i).second)) != 0) {
-                       all_sources.insert (sfs->path());
                } 
        }
 
@@ -2991,13 +3055,13 @@ Session::cleanup_sources (Session::cleanup_report& rep)
                   on whichever filesystem it was already on.
                */
 
-               newpath = PBD::dirname (*x);
-               newpath = PBD::dirname (newpath);
+               newpath = Glib::path_get_dirname (*x);
+               newpath = Glib::path_get_dirname (newpath);
 
                newpath += '/';
                newpath += dead_sound_dir_name;
                newpath += '/';
-               newpath += PBD::basename ((*x));
+               newpath += Glib::path_get_basename ((*x));
                
                if (access (newpath.c_str(), F_OK) == 0) {
                        
@@ -3138,7 +3202,7 @@ void
 Session::set_dirty ()
 {
        bool was_dirty = dirty();
-       
+
        _state_of_the_state = StateOfTheState (_state_of_the_state | Dirty);
 
        if (!was_dirty) {
@@ -3159,3 +3223,154 @@ Session::set_clean ()
        }
 }
 
+void
+Session::add_controllable (Controllable* c)
+{
+       Glib::Mutex::Lock lm (controllables_lock);
+       controllables.push_back (c);
+}
+
+void
+Session::remove_controllable (Controllable* c)
+{
+       if (_state_of_the_state | Deletion) {
+               return;
+       }
+
+       Glib::Mutex::Lock lm (controllables_lock);
+       controllables.remove (c);
+}      
+
+Controllable*
+Session::controllable_by_id (const PBD::ID& id)
+{
+       Glib::Mutex::Lock lm (controllables_lock);
+       
+       for (Controllables::iterator i = controllables.begin(); i != controllables.end(); ++i) {
+               if ((*i)->id() == id) {
+                       return *i;
+               }
+       }
+
+       return 0;
+}
+
+void 
+Session::add_instant_xml (XMLNode& node, const std::string& dir)
+{
+       Stateful::add_instant_xml (node, dir);
+       Config->add_instant_xml (node, get_user_ardour_path());
+}
+
+
+int 
+Session::save_history (string snapshot_name)
+{
+    XMLTree tree;
+    string xml_path;
+    string bak_path;
+    
+    tree.set_root (&history.get_state());
+
+    if (snapshot_name.empty()) {
+       snapshot_name = _current_snapshot_name;
+    }
+
+    xml_path = _path + snapshot_name + ".history"; 
+
+    bak_path = xml_path + ".bak";
+
+    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;
+    }
+
+    cerr << "actually writing history\n";
+
+    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;
+            }
+        }
+
+        return -1;
+    }
+
+    return 0;
+}
+
+int
+Session::restore_history (string snapshot_name)
+{
+    XMLTree tree;
+    string xmlpath;
+
+    /* read xml */
+    xmlpath = _path + snapshot_name + ".history";
+    cerr << string_compose(_("Loading history from '%1'."), xmlpath) << endmsg;
+
+    if (access (xmlpath.c_str(), F_OK)) {
+        error << string_compose(_("%1: session history file \"%2\" doesn't exist!"), _name, xmlpath) << endmsg;
+        return 1;
+    }
+
+    if (!tree.read (xmlpath)) {
+        error << string_compose(_("Could not understand ardour file %1"), xmlpath) << 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")
+            {
+                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);
+    }
+
+    return 0;
+}