most of the 2.X->3.0 commit (up to rev 4299) except for gtk2_ardour/editor_canvas...
[ardour.git] / libs / ardour / session_state.cc
index 7c4f8c918f77634bf023276b86c20ee668cda38f..cb4a9e5813f25b61c7592b24ca4e513b82031797 100644 (file)
 #endif
 
 #include <glibmm.h>
+#include <glibmm/thread.h>
 
 #include <midi++/mmc.h>
 #include <midi++/port.h>
-#include <pbd/error.h>
 
-#include <glibmm/thread.h>
+#include <pbd/error.h>
 #include <pbd/pathscanner.h>
 #include <pbd/pthread_utils.h>
 #include <pbd/search_path.h>
@@ -64,6 +64,7 @@
 #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>
@@ -77,7 +78,6 @@
 #include <ardour/midi_source.h>
 #include <ardour/sndfile_helpers.h>
 #include <ardour/auditioner.h>
-#include <ardour/export.h>
 #include <ardour/io_processor.h>
 #include <ardour/send.h>
 #include <ardour/processor.h>
@@ -86,6 +86,7 @@
 #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/filename_extensions.h>
 #include <ardour/directory_names.h>
 #include <ardour/template_utils.h>
+#include <ardour/ticker.h>
 
 #include <control_protocol/control_protocol.h>
 
@@ -138,10 +140,17 @@ Session::first_stage_init (string fullpath, string snapshot_name)
 
        _name = _current_snapshot_name = snapshot_name;
 
+       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);
        insert_cnt = 0;
        _transport_speed = 0;
@@ -156,13 +165,14 @@ Session::first_stage_init (string fullpath, string snapshot_name)
        g_atomic_int_set (&_record_status, Disabled);
        loop_changing = 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;
@@ -174,23 +184,20 @@ Session::first_stage_init (string fullpath, string snapshot_name)
        _worst_output_latency = 0;
        _worst_input_latency = 0;
        _worst_track_latency = 0;
-       _state_of_the_state = StateOfTheState(CannotSave|InitialConnecting|Loading|Deletion);
+       _state_of_the_state = StateOfTheState(CannotSave|InitialConnecting|Loading);
+
        _slave = 0;
-       butler_mixdown_buffer = 0;
-       butler_gain_buffer = 0;
-       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);
        _play_range = false;
-       waiting_to_start = false;
        _exporting = false;
+       _exporting_realtime = false;
        _gain_automation_buffer = 0;
        _pan_automation_buffer = 0;
        _npan_buffers = 0;
@@ -217,8 +224,6 @@ Session::first_stage_init (string fullpath, string snapshot_name)
           waveforms for clicks.
        */
        
-       click_data = 0;
-       click_emphasis_data = 0;
        click_length = 0;
        click_emphasis_length = 0;
        _clicking = false;
@@ -231,9 +236,6 @@ Session::first_stage_init (string fullpath, string snapshot_name)
                waiting_for_sync_offset = false;
        }
 
-       _current_frame_rate = 48000;
-       _base_frame_rate = 48000;
-
        last_smpte_when = 0;
        _smpte_offset = 0;
        _smpte_offset_negative = true;
@@ -248,7 +250,7 @@ Session::first_stage_init (string fullpath, string snapshot_name)
 
        /* slave stuff */
 
-       average_slave_delta = 1800;
+       average_slave_delta = 1800; // !!! why 1800 ????
        have_first_delta_accumulator = false;
        delta_accumulator_cnt = 0;
        slave_state = Stopped;
@@ -266,7 +268,7 @@ Session::first_stage_init (string fullpath, string snapshot_name)
 
        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 */
 
@@ -291,12 +293,13 @@ 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;
@@ -317,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);
@@ -344,10 +347,19 @@ Session::second_stage_init (bool new_session)
                return -1;
        }
 
-       //send_full_time_code ();
+       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);
 
@@ -356,7 +368,19 @@ Session::second_stage_init (bool new_session)
        } else {
                _end_location_is_free = false;
        }
+
+       _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;
+       }
        
+       BootMessage (_("Session loading complete"));
+
        return 0;
 }
 
@@ -409,54 +433,132 @@ Session::setup_raid_path (string path)
        AudioFileSource::set_search_path (sound_search_path.to_string ());
        SMFSource::set_search_path (midi_search_path.to_string ());
 
+
        // reset the round-robin soundfile path thingie
-       
+
        last_rr_session_dir = session_dirs.begin();
 }
 
-void
-Session::initialize_start_and_end_locations (nframes_t start, nframes_t end)
+int
+Session::ensure_subdirs ()
 {
-       start_location->set_end (start);
-       _locations.add (start_location);
+       string dir;
 
-       end_location->set_end (end);
-       _locations.add (end_location);
-}
+       dir = session_directory().peak_path().to_string();
 
-bool
-Session::create_session_file ()
-{
-       _state_of_the_state = Clean;
+       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;
+       }
 
-       if (save_state (_current_snapshot_name)) {
-               error << "Could not create new session file" << endmsg;
-               return false;
+       dir = session_directory().sound_path().to_string();
+
+       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 (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;
+       }
+
+       dir = session_directory().dead_sound_path().to_string();
+
+       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;
        }
-       return true;
+
+       dir = session_directory().export_path().to_string();
+
+       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;
+       }
+
+       dir = analysis_dir ();
+
+       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;
+       }
+
+       return 0;
 }
 
-bool
-Session::create_session_file_from_template (const string& template_path)
+int
+Session::create (bool& new_session, const string& mix_template, nframes_t initial_length)
 {
-       sys::path session_file_path(_session_dir->root_path());
 
-       session_file_path /= _name + statefile_suffix;
+       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;
+       }
 
-       try
-       {
-               sys::copy_file (template_path, session_file_path);
+       if (ensure_subdirs ()) {
+               return -1;
        }
-       catch(sys::filesystem_error& ex)
-       {
-               error << string_compose (_("Could not use session template %1 to create new session (%2)."),
-                               template_path, ex.what())
-                       << endmsg;
-               return false;
+
+       /* check new_session so we don't overwrite an existing one */
+
+       if (!mix_template.empty()) {
+               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;
+
+                       } 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;
+                       return -1;
+               }
+
        }
-       return true;
+       
+       /* Instantiate metadata */
+       
+       _metadata = new SessionMetadata ();
+
+       /* set initial start + end point */
+
+       start_location->set_end (0);
+       _locations.add (start_location);
+
+       end_location->set_end (initial_length);
+       _locations.add (end_location);
+
+       _state_of_the_state = Clean;
+
+       save_state ("");
+
+       return 0;
 }
 
+
 int
 Session::load_diskstreams (const XMLNode& node)
 {
@@ -501,7 +603,7 @@ void
 Session::remove_pending_capture_state ()
 {
        sys::path pending_state_file_path(_session_dir->root_path());
-
+       
        pending_state_file_path /= _current_snapshot_name + pending_suffix;
 
        try
@@ -525,12 +627,21 @@ Session::rename_state (string old_name, string new_name)
                /* refuse to rename the current snapshot or the "main" one */
                return;
        }
-       
-       const string old_xml_path = _path + old_name + statefile_suffix;
-       const string new_xml_path = _path + new_name + statefile_suffix;
 
-       if (rename (old_xml_path.c_str(), new_xml_path.c_str()) != 0) {
-               error << string_compose(_("could not rename snapshot %1 to %2"), old_name, new_name) << endmsg;
+       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;
        }
 }
 
@@ -633,7 +744,7 @@ Session::save_state (string snapshot_name, bool pending)
                bool was_dirty = dirty();
 
                _state_of_the_state = StateOfTheState (_state_of_the_state & ~Dirty);
-
+               
                if (was_dirty) {
                        DirtyChanged (); /* EMIT SIGNAL */
                }
@@ -709,7 +820,7 @@ Session::load_state (string snapshot_name)
        }
 
        const XMLProperty* prop;
-       bool is_old = false;
+       bool is_old = false; // session is _very_ old (pre-2.0)
 
        if ((prop = root.property ("version")) == 0) {
                /* no version implies very old version of Ardour */
@@ -762,6 +873,12 @@ Session::load_options (const XMLNode& node)
 
        Config->set_variables (node, ConfigVariableBase::Session);
 
+       /* now reset MIDI ports because the session can have its own 
+          MIDI configuration.
+       */
+
+       setup_midi ();
+
        if ((child = find_named_node (node, "end-marker-is-free")) != 0) {
                if ((prop = child->property ("val")) != 0) {
                        _end_location_is_free = (prop->value() == "yes");
@@ -821,16 +938,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) {
 
@@ -871,6 +988,8 @@ Session::state(bool full_state)
 
        node->add_child_nocopy (get_options());
 
+       node->add_child_nocopy (_metadata->get_state());
+
        child = node->add_child ("Sources");
 
        if (full_state) {
@@ -940,12 +1059,13 @@ Session::state(bool full_state)
                node->add_child_nocopy (loc.get_state());
        }
        
-       child = node->add_child ("Connections");
+       child = node->add_child ("Bundles");
        {
                Glib::Mutex::Lock lm (bundle_lock);
                for (BundleList::iterator i = _bundles.begin(); i != _bundles.end(); ++i) {
-                       if (!(*i)->dynamic()) {
-                               child->add_child_nocopy ((*i)->get_state());
+                       boost::shared_ptr<UserBundle> b = boost::dynamic_pointer_cast<UserBundle> (*i);
+                       if (b) {
+                               child->add_child_nocopy (b->get_state());
                        }
                }
        }
@@ -1058,6 +1178,17 @@ Session::set_state (const XMLNode& node)
                _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) {
@@ -1080,10 +1211,11 @@ Session::set_state (const XMLNode& node)
 
        /* Object loading order:
 
-       MIDI Control
        Path
        extra
        Options/Config
+       MIDI Control // relies on data from Options/Config
+       Metadata
        Locations
        Sources
        AudioRegions
@@ -1096,9 +1228,6 @@ Session::set_state (const XMLNode& node)
        ControlProtocols
        */
 
-       if (use_config_midi_ports ()) {
-       }
-
        if ((child = find_named_node (node, "extra")) != 0) {
                _extra_xml = new XMLNode (*child);
        }
@@ -1111,6 +1240,15 @@ Session::set_state (const XMLNode& node)
                error << _("Session: XML state has no options section") << endmsg;
        }
 
+       if (use_config_midi_ports ()) {
+       }
+
+       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;
@@ -1184,13 +1322,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_bundles (*child)) {
-               goto out;
+       if ((child = find_named_node (node, "Bundles")) == 0) {
+               warning << _("Session: XML state has no bundles section (2.0 session?)") << endmsg;
+               //goto out;
+       } else {
+               /* 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);
        }
-
+       
        if ((child = find_named_node (node, "EditGroups")) == 0) {
                error << _("Session: XML state has no edit groups section") << endmsg;
                goto out;
@@ -1224,7 +1365,7 @@ Session::set_state (const XMLNode& node)
        } else if (_click_io) {
                _click_io->set_state (*child);
        }
-       
+
        if ((child = find_named_node (node, "ControlProtocols")) != 0) {
                ControlProtocolManager::instance().set_protocol_states (*child);
        }
@@ -1233,14 +1374,6 @@ Session::set_state (const XMLNode& node)
 
        StateReady (); /* EMIT SIGNAL */
 
-       _state_of_the_state = Clean;
-
-       if (state_was_pending) {
-               save_state (_current_snapshot_name);
-               remove_pending_capture_state ();
-               state_was_pending = false;
-       }
-
        return 0;
 
   out:
@@ -1267,10 +1400,12 @@ Session::load_routes (const XMLNode& node)
                        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;
 }
@@ -1318,7 +1453,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;
                }
        }
 
@@ -1356,6 +1498,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];
        
@@ -1415,7 +1558,27 @@ 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)));
 
@@ -1430,6 +1593,14 @@ Session::XMLAudioRegionFactory (const XMLNode& node, bool full)
                        }
                }
 
+               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;
                                                       
        }
@@ -1527,23 +1698,24 @@ Session::path_from_region_name (DataType type, string name, string identifier)
        char buf[PATH_MAX+1];
        uint32_t n;
        SessionDirectory sdir(get_best_session_directory_for_new_source());
-       string sound_dir = ((type == DataType::AUDIO)
-               ? sdir.sound_path().to_string()
-               : sdir.midi_path().to_string());
+       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 "%s", sound_dir.c_str(), name.c_str(), 
+                       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 "%s", sound_dir.c_str(), name.c_str(),
+                       snprintf (buf, sizeof(buf), "%s-%" PRIu32 "%s", name.c_str(),
                                        n, ext.c_str());
                }
 
-               if (!Glib::file_test (buf, Glib::FILE_TEST_EXISTS)) {
-                       return buf;
+               sys::path source_path = source_dir / buf;
+
+               if (!sys::exists (source_path)) {
+                       return source_path.to_string();
                }
        }
 
@@ -1591,7 +1763,8 @@ Session::XMLSourceFactory (const XMLNode& node)
        }
 
        try {
-               return SourceFactory::create (*this, node);
+               /* note: do peak building in another thread when loading session state */
+               return SourceFactory::create (*this, node, true);
        }
 
        catch (failed_constructor& err) {
@@ -1642,6 +1815,43 @@ Session::save_template (string template_name)
        return 0;
 }
 
+int
+Session::rename_template (string old_name, string new_name) 
+{
+       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;
+
+       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) 
+{
+       sys::path path = user_template_directory();
+       path /= name + template_suffix;
+
+       try {
+               sys::remove (path);
+               return 0;
+       } catch (...) {
+               return -1;
+       }
+}
+
 void
 Session::refresh_disk_space ()
 {
@@ -1857,29 +2067,33 @@ Session::XMLNamedSelectionFactory (const XMLNode& node)
 string
 Session::automation_dir () const
 {
-       string res = _path;
-       res += "automation/";
-       return res;
+       return Glib::build_filename (_path, "automation");
 }
 
-int
-Session::load_bundles (const XMLNode& node)
+string
+Session::analysis_dir () const
 {
-       XMLNodeList nlist = node.children();
-       XMLNodeConstIterator niter;
-
-       set_dirty();
+       return Glib::build_filename (_path, "analysis");
+}
 
-       for (niter = nlist.begin(); niter != nlist.end(); ++niter) {
-               if ((*niter)->name() == "InputConnection") {
-                       add_bundle (new ARDOUR::InputBundle (**niter));
-               } else if ((*niter)->name() == "OutputConnection") {
-                       add_bundle (new ARDOUR::OutputBundle (**niter));
-               } else {
-                       error << string_compose(_("Unknown node \"%1\" found in Connections list from state file"), (*niter)->name()) << endmsg;
-                       return -1;
-               }
-       }
+int
+Session::load_bundles (XMLNode const & node)
+{
+       XMLNodeList nlist = node.children();
+       XMLNodeConstIterator niter;
+
+       set_dirty();
+
+       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;
 }                              
@@ -1926,6 +2140,56 @@ Session::auto_save()
        save_state (_current_snapshot_name);
 }
 
+static bool
+state_file_filter (const string &str, void *arg)
+{
+       return (str.length() > strlen(statefile_suffix) &&
+               str.find (statefile_suffix) == (str.length() - strlen (statefile_suffix)));
+}
+
+struct string_cmp {
+       bool operator()(const string* a, const string* b) {
+               return *a < *b;
+       }
+};
+
+static string*
+remove_end(string* state)
+{
+       string statename(*state);
+       
+       string::size_type start,end;
+       if ((start = statename.find_last_of ('/')) != string::npos) {
+               statename = statename.substr (start+1);
+       }
+               
+       if ((end = statename.rfind(".ardour")) == string::npos) {
+               end = statename.length();
+       }
+
+       return new string(statename.substr (0, end));
+}
+
+vector<string *> *
+Session::possible_states (string path) 
+{
+       PathScanner scanner;
+       vector<string*>* states = scanner (path, state_file_filter, 0, false, false);
+       
+       transform(states->begin(), states->end(), states->begin(), remove_end);
+       
+       string_cmp cmp;
+       sort (states->begin(), states->end(), cmp);
+       
+       return states;
+}
+
+vector<string *> *
+Session::possible_states () const
+{
+       return possible_states(_path);
+}
+
 RouteGroup *
 Session::add_edit_group (string name)
 {
@@ -2016,6 +2280,10 @@ Session::commit_reversible_command (Command *cmd)
                current_trans->add_command (cmd);
        }
 
+       if (current_trans->empty()) {
+               return;
+       }
+
        gettimeofday (&now, 0);
        current_trans->set_timestamp (now);
 
@@ -2259,6 +2527,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 */
 
@@ -2422,7 +2691,7 @@ Session::cleanup_sources (Session::cleanup_report& rep)
                newpath += dead_sound_dir_name;
 
                if (g_mkdir_with_parents (newpath.c_str(), 0755) < 0) {
-                       error << string_compose(_("Session: cannot create session peakfile dir \"%1\" (%2)"), newpath, strerror (errno)) << endmsg;
+                       error << string_compose(_("Session: cannot create session peakfile folder \"%1\" (%2)"), newpath, strerror (errno)) << endmsg;
                        return -1;
                }
 
@@ -2498,6 +2767,7 @@ Session::cleanup_sources (Session::cleanup_report& rep)
 
   out:
        _state_of_the_state = (StateOfTheState) (_state_of_the_state & ~InCleanup);
+
        return ret;
 }
 
@@ -2571,6 +2841,7 @@ Session::set_dirty ()
 
        _state_of_the_state = StateOfTheState (_state_of_the_state | Dirty);
 
+
        if (!was_dirty) {
                DirtyChanged(); /* EMIT SIGNAL */
        }
@@ -2584,6 +2855,7 @@ Session::set_clean ()
        
        _state_of_the_state = Clean;
 
+
        if (was_dirty) {
                DirtyChanged(); /* EMIT SIGNAL */
        }
@@ -2593,6 +2865,7 @@ void
 Session::set_deletion_in_progress ()
 {
        _state_of_the_state = StateOfTheState (_state_of_the_state | Deletion);
+
 }
 
 void
@@ -2642,10 +2915,12 @@ Session::controllable_by_id (const PBD::ID& id)
 }
 
 void 
-Session::add_instant_xml (XMLNode& node)
+Session::add_instant_xml (XMLNode& node, bool write_to_config)
 {
        Stateful::add_instant_xml (node, _path);
-       Config->add_instant_xml (node);
+       if (write_to_config) {
+               Config->add_instant_xml (node);
+       }
 }
 
 XMLNode*
@@ -2659,8 +2934,6 @@ Session::save_history (string snapshot_name)
 {
        XMLTree tree;
        
-       tree.set_root (&_history.get_state (Config->get_saved_history_depth()));
-
        if (snapshot_name.empty()) {
                snapshot_name = _current_snapshot_name;
        }
@@ -2682,6 +2955,13 @@ Session::save_history (string snapshot_name)
                }
        }
 
+
+       if (!Config->get_save_history() || Config->get_saved_history_depth() < 0) {
+               return 0;
+       }
+
+       tree.set_root (&_history.get_state (Config->get_saved_history_depth()));
+
        if (!tree.write (xml_path.to_string()))
        {
                error << string_compose (_("history could not be saved to %1"), xml_path.to_string()) << endmsg;
@@ -2715,7 +2995,7 @@ Session::restore_history (string snapshot_name)
        const string xml_filename = snapshot_name + history_suffix;
        const sys::path xml_path = _session_dir->root_path() / xml_filename;
 
-       info << string_compose(_("Loading history from '%1'."), xml_path.to_string()) << endmsg;
+    cerr << "Loading history from " << xml_path.to_string() << endmsg;
 
        if (!sys::exists (xml_path)) {
                info << string_compose (_("%1: no history file \"%2\" for this session."),
@@ -2739,22 +3019,21 @@ Session::restore_history (string snapshot_name)
            struct timeval tv;
            
            ut->set_name(t->property("name")->value());
-           stringstream ss(t->property("tv_sec")->value());
+           stringstream ss(t->property("tv-sec")->value());
            ss >> tv.tv_sec;
-           ss.str(t->property("tv_usec")->value());
+           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++)
+                               child_it != t->children().end(); child_it++)
            {
                    XMLNode *n = *child_it;
                    Command *c;
        
                    if (n->name() == "MementoCommand" ||
-                       n->name() == "MementoUndoCommand" ||
-                       n->name() == "MementoRedoCommand") {
+                                       n->name() == "MementoUndoCommand" ||
+                                       n->name() == "MementoRedoCommand") {
 
                            if ((c = memento_command_factory(n))) {
                                    ut->add_command(c);
@@ -2766,8 +3045,16 @@ Session::restore_history (string snapshot_name)
                                    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;
                    }
            }
@@ -2968,6 +3255,31 @@ Session::config_changed (const char* parameter_name)
                set_remote_control_ids ();
        }  else if (PARAM_IS ("denormal-model")) {
                setup_fpu ();
+       } else if (PARAM_IS ("history-depth")) {
+               set_history_depth (Config->get_history_depth());
+       } else if (PARAM_IS ("sync-all-route-ordering")) {
+               sync_order_keys ("session");
+       } else if (PARAM_IS ("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 (PARAM_IS ("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 (PARAM_IS ("solo-mute-override")) {
+               catch_up_on_solo_mute_override ();
        }
 
        set_dirty ();
@@ -2975,3 +3287,9 @@ Session::config_changed (const char* parameter_name)
 #undef PARAM_IS
 
 }
+
+void
+Session::set_history_depth (uint32_t d)
+{
+       _history.set_depth (d);
+}