RAII to postpone processor changes/graph recalculation
[ardour.git] / libs / ardour / ardour / session.h
index 43bd7483fbb9ca77187da56fba00f682f000dc14..b2409e3da669f0e0969a40c4f96ba707e82c4bad 100644 (file)
@@ -28,6 +28,7 @@
 #include <set>
 #include <string>
 #include <vector>
+#include <queue>
 #include <stdint.h>
 
 #include <boost/dynamic_bitset.hpp>
 #include "pbd/error.h"
 #include "pbd/event_loop.h"
 #include "pbd/rcu.h"
+#include "pbd/reallocpool.h"
 #include "pbd/statefuldestructible.h"
 #include "pbd/signals.h"
 #include "pbd/undo.h"
 
-#include "evoral/types.hpp"
+#include "lua/luastate.h"
+
+#include "evoral/Range.hpp"
 
 #include "midi++/types.h"
 #include "midi++/mmc.h"
 #include "ardour/chan_count.h"
 #include "ardour/delivery.h"
 #include "ardour/interthread_info.h"
+#include "ardour/luascripting.h"
 #include "ardour/location.h"
 #include "ardour/monitor_processor.h"
+#include "ardour/presentation_info.h"
 #include "ardour/rc_configuration.h"
 #include "ardour/session_configuration.h"
 #include "ardour/session_event.h"
 #include "ardour/interpolation.h"
+#include "ardour/plugin.h"
+#include "ardour/presentation_info.h"
 #include "ardour/route.h"
 #include "ardour/route_graph.h"
 
@@ -80,7 +88,10 @@ class Parser;
 
 namespace PBD {
 class Controllable;
-class ControllableDescriptor;
+}
+
+namespace luabridge {
+       class LuaRef;
 }
 
 namespace Evoral {
@@ -102,6 +113,7 @@ class BufferSet;
 class Bundle;
 class Butler;
 class Click;
+class ControllableDescriptor;
 class Diskstream;
 class ExportHandler;
 class ExportStatus;
@@ -122,6 +134,7 @@ class PluginInfo;
 class Port;
 class PortInsert;
 class ProcessThread;
+class Progress;
 class Processor;
 class Region;
 class Return;
@@ -138,6 +151,7 @@ class Source;
 class Speakers;
 class TempoMap;
 class Track;
+class VCAManager;
 class WindowsVSTPlugin;
 
 extern void setup_enum_writer ();
@@ -153,8 +167,19 @@ private:
        std::string _message;
 };
 
+/** Ardour Session */
 class LIBARDOUR_API Session : public PBD::StatefulDestructible, public PBD::ScopedConnectionList, public SessionEventManager
 {
+  private:
+       enum SubState {
+               PendingDeclickIn      = 0x1,  ///< pending de-click fade-in for start
+               PendingDeclickOut     = 0x2,  ///< pending de-click fade-out for stop
+               StopPendingCapture    = 0x4,
+               PendingLoopDeclickIn  = 0x8,  ///< pending de-click fade-in at the start of a loop
+               PendingLoopDeclickOut = 0x10, ///< pending de-click fade-out at the end of a loop
+               PendingLocate         = 0x20,
+       };
+
   public:
        enum RecordState {
                Disabled = 0,
@@ -177,6 +202,12 @@ class LIBARDOUR_API Session : public PBD::StatefulDestructible, public PBD::Scop
        static int get_info_from_path (const std::string& xmlpath, float& sample_rate, SampleFormat& data_format);
        static std::string get_snapshot_from_instant (const std::string& session_dir);
 
+       /** a monotonic counter used for naming user-visible things uniquely
+        * (curently the sidechain port).
+        * Use sparingly to keep the numbers low, prefer PBD::ID for all
+        * internal, not user-visible IDs */
+       static unsigned int next_name_id ();
+
        std::string path() const { return _path; }
        std::string name() const { return _name; }
        std::string snap_name() const { return _current_snapshot_name; }
@@ -193,11 +224,10 @@ class LIBARDOUR_API Session : public PBD::StatefulDestructible, public PBD::Scop
        bool deletion_in_progress() const { return _state_of_the_state & Deletion; }
        bool routes_deletion_in_progress() const { return _route_deletion_in_progress; }
        bool peaks_cleanup_in_progres() const { return _state_of_the_state & PeakCleanup; }
+       bool loading () const { return _state_of_the_state & Loading; }
 
        PBD::Signal0<void> DirtyChanged;
 
-       PBD::Signal1<void, bool> RouteAddedOrRemoved;
-
        const SessionDirectory& session_directory () const { return *(_session_dir.get()); }
 
        static PBD::Signal1<void,std::string> Dialog;
@@ -219,8 +249,15 @@ class LIBARDOUR_API Session : public PBD::StatefulDestructible, public PBD::Scop
        std::string new_audio_source_path_for_embedded (const std::string& existing_path);
        std::string new_audio_source_path (const std::string&, uint32_t nchans, uint32_t chan, bool destructive, bool take_required);
        std::string new_midi_source_path (const std::string&);
-       RouteList new_route_from_template (uint32_t how_many, const std::string& template_path, const std::string& name, PlaylistDisposition pd = NewPlaylist);
-       RouteList new_route_from_template (uint32_t how_many, XMLNode&, const std::string& name, PlaylistDisposition pd = NewPlaylist);
+       /** create a new track or bus from a template (XML path)
+        * @param how_many how many tracks or busses to create
+        * @param template_path path to xml template file
+        * @param name name (prefix) of the route to create
+        * @param pd Playlist disposition
+        * @return list of newly created routes
+        */
+       RouteList new_route_from_template (uint32_t how_many, PresentationInfo::order_t insert_at, const std::string& template_path, const std::string& name, PlaylistDisposition pd = NewPlaylist);
+       RouteList new_route_from_template (uint32_t how_many, PresentationInfo::order_t insert_at, XMLNode&, const std::string& name, PlaylistDisposition pd = NewPlaylist);
        std::vector<std::string> get_paths_for_new_sources (bool allow_replacing, const std::string& import_file_path, uint32_t channels);
 
        int bring_all_sources_into_session (boost::function<void(uint32_t,uint32_t,std::string)> callback);
@@ -228,7 +265,8 @@ class LIBARDOUR_API Session : public PBD::StatefulDestructible, public PBD::Scop
        void process (pframes_t nframes);
 
        BufferSet& get_silent_buffers (ChanCount count = ChanCount::ZERO);
-       BufferSet& get_scratch_buffers (ChanCount count = ChanCount::ZERO, bool silence = true );
+       BufferSet& get_noinplace_buffers (ChanCount count = ChanCount::ZERO);
+       BufferSet& get_scratch_buffers (ChanCount count = ChanCount::ZERO, bool silence = true);
        BufferSet& get_route_buffers (ChanCount count = ChanCount::ZERO, bool silence = true);
        BufferSet& get_mix_buffers (ChanCount count = ChanCount::ZERO);
 
@@ -250,6 +288,14 @@ class LIBARDOUR_API Session : public PBD::StatefulDestructible, public PBD::Scop
                return routes.reader ();
        }
 
+       /* because the set of Stripables consists of objects managed
+        * independently, in multiple containers within the Session (or objects
+        * owned by the session), we fill out a list in-place rather than
+        * return a pointer to a copy of the (RCU) managed list, as happens
+        * with get_routes()
+        */
+
+       void get_stripables (StripableList&) const;
        boost::shared_ptr<RouteList> get_tracks() const;
        boost::shared_ptr<RouteList> get_routes_with_internal_returns() const;
        boost::shared_ptr<RouteList> get_routes_with_regions_at (framepos_t const) const;
@@ -266,20 +312,20 @@ class LIBARDOUR_API Session : public PBD::StatefulDestructible, public PBD::Scop
                bool operator() (boost::shared_ptr<Route>, boost::shared_ptr<Route> b);
        };
 
-       void set_order_hint (int32_t order_hint) {_order_hint = order_hint;};
-       void notify_remote_id_change ();
-       void sync_order_keys ();
+       void notify_presentation_info_change ();
 
        template<class T> void foreach_route (T *obj, void (T::*func)(Route&), bool sort = true);
        template<class T> void foreach_route (T *obj, void (T::*func)(boost::shared_ptr<Route>), bool sort = true);
        template<class T, class A> void foreach_route (T *obj, void (T::*func)(Route&, A), A arg, bool sort = true);
 
        static char session_name_is_legal (const std::string&);
-       bool io_name_is_legal (const std::string&);
-       boost::shared_ptr<Route> route_by_name (std::string);
-       boost::shared_ptr<Route> route_by_id (PBD::ID);
-       boost::shared_ptr<Route> route_by_remote_id (uint32_t id);
-       boost::shared_ptr<Track> track_by_diskstream_id (PBD::ID);
+       bool io_name_is_legal (const std::string&) const;
+       boost::shared_ptr<Route> route_by_name (std::string) const;
+       boost::shared_ptr<Route> route_by_id (PBD::ID) const;
+       boost::shared_ptr<Stripable> get_remote_nth_stripable (PresentationInfo::order_t n, PresentationInfo::Flag) const;
+       boost::shared_ptr<Route> get_remote_nth_route (PresentationInfo::order_t n) const;
+       boost::shared_ptr<Route> route_by_selected_count (uint32_t cnt) const;
+       boost::shared_ptr<Track> track_by_diskstream_id (PBD::ID) const;
        void routes_using_input_from (const std::string& str, RouteList& rl);
 
        bool route_name_unique (std::string) const;
@@ -305,7 +351,7 @@ class LIBARDOUR_API Session : public PBD::StatefulDestructible, public PBD::Scop
        void maybe_enable_record ();
        void disable_record (bool rt_context, bool force = false);
        void step_back_from_record ();
-       
+
        void set_all_tracks_record_enabled(bool);
 
        void maybe_write_autosave ();
@@ -379,7 +425,7 @@ class LIBARDOUR_API Session : public PBD::StatefulDestructible, public PBD::Scop
 
        framepos_t last_transport_start () const { return _last_roll_location; }
        void goto_end ();
-       void goto_start ();
+       void goto_start (bool and_roll = false);
        void use_rf_shuttle_speed ();
        void allow_auto_play (bool yn);
        void request_transport_speed (double speed, bool as_default = true);
@@ -391,6 +437,7 @@ class LIBARDOUR_API Session : public PBD::StatefulDestructible, public PBD::Scop
        void request_input_change_handling ();
 
        bool locate_pending() const { return static_cast<bool>(post_transport_work()&PostTransportLocate); }
+       bool declick_out_pending() const { return static_cast<bool>(transport_sub_state&(PendingDeclickOut)); }
        bool transport_locked () const;
 
        int wipe ();
@@ -424,6 +471,7 @@ class LIBARDOUR_API Session : public PBD::StatefulDestructible, public PBD::Scop
        void set_auto_punch_location (Location *);
        void set_auto_loop_location (Location *);
        void set_session_extents (framepos_t start, framepos_t end);
+       void set_end_is_free (bool);
        int location_name(std::string& result, std::string base = std::string(""));
 
        pframes_t get_block_size()        const { return current_block_size; }
@@ -461,7 +509,23 @@ class LIBARDOUR_API Session : public PBD::StatefulDestructible, public PBD::Scop
        };
 
        int save_as (SaveAs&);
+       /** save session
+        * @param snapshot_name name of the session (use an empty string for the current name)
+        * @param pending save a 'recovery', not full state (default: false)
+        * @param switch_to_snapshot switch to given snapshot after saving (default: false)
+        * @param template_only save a session template (default: false)
+        * @return zero on success
+        */
        int save_state (std::string snapshot_name, bool pending = false, bool switch_to_snapshot = false, bool template_only = false);
+
+       enum ArchiveEncode {
+               NO_ENCODE,
+               FLAC_16BIT,
+               FLAC_24BIT
+       };
+
+       int archive_session (const std::string&, const std::string&, ArchiveEncode compress_audio = FLAC_16BIT, bool only_used_sources = false, Progress* p = 0);
+
        int restore_state (std::string snapshot_name);
        int save_template (std::string template_name, bool replace_existing = false);
        int save_history (std::string snapshot_name = "");
@@ -517,20 +581,40 @@ class LIBARDOUR_API Session : public PBD::StatefulDestructible, public PBD::Scop
        StateOfTheState state_of_the_state() const { return _state_of_the_state; }
 
        class StateProtector {
-                                               public:
-               StateProtector (Session* s) : _session (s) {
-                       g_atomic_int_inc (&s->_suspend_save);
-               }
-               ~StateProtector () {
-                       if (g_atomic_int_dec_and_test (&_session->_suspend_save)) {
-                               while (_session->_save_queued) {
-                                       _session->_save_queued = false;
-                                       _session->save_state ("");
+               public:
+                       StateProtector (Session* s) : _session (s) {
+                               g_atomic_int_inc (&s->_suspend_save);
+                       }
+                       ~StateProtector () {
+                               if (g_atomic_int_dec_and_test (&_session->_suspend_save)) {
+                                       while (_session->_save_queued) {
+                                               _session->_save_queued = false;
+                                               _session->save_state ("");
+                                       }
                                }
                        }
-               }
-                                               private:
-               Session * _session;
+               private:
+                       Session * _session;
+       };
+
+       class ProcessorChangeBlocker {
+               public:
+                       ProcessorChangeBlocker (Session* s, bool rc = true)
+                               : _session (s)
+                               , _reconfigure_on_delete (rc)
+                       {
+                               g_atomic_int_inc (&s->_ignore_route_processor_changes);
+                       }
+                       ~ProcessorChangeBlocker () {
+                               if (g_atomic_int_dec_and_test (&_session->_ignore_route_processor_changes)) {
+                                       if (_reconfigure_on_delete) {
+                                               _session->route_processors_changed (RouteProcessorChange ());
+                                       }
+                               }
+                       }
+               private:
+                       Session* _session;
+                       bool _reconfigure_on_delete;
        };
 
        void add_route_group (RouteGroup *);
@@ -559,23 +643,25 @@ class LIBARDOUR_API Session : public PBD::StatefulDestructible, public PBD::Scop
        std::list<boost::shared_ptr<AudioTrack> > new_audio_track (
                int input_channels,
                int output_channels,
-               TrackMode mode = Normal,
-               RouteGroup* route_group = 0,
-               uint32_t how_many = 1,
-               std::string name_template = ""
-               );
-
-       RouteList new_audio_route (
-               int input_channels, int output_channels, RouteGroup* route_group, uint32_t how_many, std::string name_template = ""
+               RouteGroup* route_group,
+               uint32_t how_many,
+               std::string name_template,
+               PresentationInfo::order_t order,
+               TrackMode mode = Normal
                );
 
        std::list<boost::shared_ptr<MidiTrack> > new_midi_track (
                const ChanCount& input, const ChanCount& output,
-               boost::shared_ptr<PluginInfo> instrument = boost::shared_ptr<PluginInfo>(),
-               TrackMode mode = Normal,
-               RouteGroup* route_group = 0, uint32_t how_many = 1, std::string name_template = ""
+               boost::shared_ptr<PluginInfo> instrument,
+               Plugin::PresetRecord* pset,
+               RouteGroup* route_group, uint32_t how_many, std::string name_template,
+               PresentationInfo::order_t,
+               TrackMode mode = Normal
                );
 
+       RouteList new_audio_route (int input_channels, int output_channels, RouteGroup* route_group, uint32_t how_many, std::string name_template, PresentationInfo::Flag, PresentationInfo::order_t);
+       RouteList new_midi_route (RouteGroup* route_group, uint32_t how_many, std::string name_template, boost::shared_ptr<PluginInfo> instrument, Plugin::PresetRecord*, PresentationInfo::Flag, PresentationInfo::order_t);
+
        void remove_routes (boost::shared_ptr<RouteList>);
        void remove_route (boost::shared_ptr<Route>);
 
@@ -631,8 +717,8 @@ class LIBARDOUR_API Session : public PBD::StatefulDestructible, public PBD::Scop
        bool   synced_to_ltc () const { return config.get_external_sync() && Config->get_sync_source() == LTC && g_atomic_int_get (const_cast<gint*>(&_ltc_active)); }
 
        double transport_speed() const { return _transport_speed; }
-       bool   transport_stopped() const { return _transport_speed == 0.0f; }
-       bool   transport_rolling() const { return _transport_speed != 0.0f; }
+       bool   transport_stopped() const { return _transport_speed == 0.0; }
+       bool   transport_rolling() const { return _transport_speed != 0.0; }
 
        bool silent () { return _silent; }
 
@@ -659,7 +745,7 @@ class LIBARDOUR_API Session : public PBD::StatefulDestructible, public PBD::Scop
        boost::shared_ptr<ExportHandler> get_export_handler ();
        boost::shared_ptr<ExportStatus> get_export_status ();
 
-       int start_audio_export (framepos_t position);
+       int start_audio_export (framepos_t position, bool realtime = false, bool region_export = false, bool comensate_master_latency = false);
 
        PBD::Signal1<int, framecnt_t> ProcessExport;
        static PBD::Signal2<void,std::string, std::string> Exported;
@@ -693,6 +779,9 @@ class LIBARDOUR_API Session : public PBD::StatefulDestructible, public PBD::Scop
        */
        static PBD::Signal2<int, framecnt_t, framecnt_t> AskAboutSampleRateMismatch;
 
+       /** non interactive message */
+       static PBD::Signal2<void, framecnt_t, framecnt_t> NotifyAboutSampleRateMismatch;
+
        /** handlers should return !0 for use pending state, 0 for ignore it.
         */
        static PBD::Signal0<int> AskAboutPendingState;
@@ -723,6 +812,13 @@ class LIBARDOUR_API Session : public PBD::StatefulDestructible, public PBD::Scop
 
        PBD::Signal1<void,bool> AuditionActive;
 
+       /* session script */
+       void register_lua_function (const std::string&, const std::string&, const LuaScriptParamList&);
+       void unregister_lua_function (const std::string& name);
+       std::vector<std::string> registered_lua_functions ();
+       uint32_t registered_lua_function_count () const { return _n_lua_scripts; }
+       void scripts_changed (); // called from lua, updates _n_lua_scripts
+
        /* flattening stuff */
 
        boost::shared_ptr<Region> write_one_track (Track&, framepos_t start, framepos_t end,
@@ -736,19 +832,18 @@ class LIBARDOUR_API Session : public PBD::StatefulDestructible, public PBD::Scop
        bool soloing() const { return _non_soloed_outs_muted; }
        bool listening() const { return _listen_cnt > 0; }
        bool solo_isolated() const { return _solo_isolated_cnt > 0; }
+       void cancel_all_solo ();
 
        static const SessionEvent::RTeventCallback rt_cleanup;
 
-       void set_solo (boost::shared_ptr<RouteList>, bool, SessionEvent::RTeventCallback after = rt_cleanup, bool group_override = false);
        void clear_all_solo_state (boost::shared_ptr<RouteList>);
-       void set_just_one_solo (boost::shared_ptr<Route>, bool, SessionEvent::RTeventCallback after = rt_cleanup);
-       void set_mute (boost::shared_ptr<RouteList>, bool, SessionEvent::RTeventCallback after = rt_cleanup, bool group_override = false);
-       void set_listen (boost::shared_ptr<RouteList>, bool, SessionEvent::RTeventCallback after = rt_cleanup, bool group_override = false);
-       void set_record_enabled (boost::shared_ptr<RouteList>, bool, SessionEvent::RTeventCallback after = rt_cleanup, bool group_override = false);
-       void set_record_safe (boost::shared_ptr<RouteList>, bool yn, SessionEvent::RTeventCallback after = rt_cleanup, bool group_override = false);
-       void set_solo_isolated (boost::shared_ptr<RouteList>, bool, SessionEvent::RTeventCallback after = rt_cleanup, bool group_override = false);
-       void set_monitoring (boost::shared_ptr<RouteList>, MonitorChoice, SessionEvent::RTeventCallback after = rt_cleanup, bool group_override = false);
-       void set_exclusive_input_active (boost::shared_ptr<RouteList> rt, bool onoff, bool flip_others=false);
+
+       /* Control-based methods */
+
+       void set_controls (boost::shared_ptr<ControlList>, double val, PBD::Controllable::GroupControlDisposition);
+       void set_control (boost::shared_ptr<AutomationControl>, double val, PBD::Controllable::GroupControlDisposition);
+
+       void set_exclusive_input_active (boost::shared_ptr<RouteList> rt, bool onoff, bool flip_others = false);
 
        PBD::Signal1<void,bool> SoloActive;
        PBD::Signal0<void> SoloChanged;
@@ -820,13 +915,11 @@ class LIBARDOUR_API Session : public PBD::StatefulDestructible, public PBD::Scop
        /** Undo some transactions.
         * @param n Number of transactions to undo.
         */
-       void undo (uint32_t n) {
-               _history.undo (n);
-       }
-
-       void redo (uint32_t n) {
-               _history.redo (n);
-       }
+       void undo (uint32_t n);
+       /** Redo some transactions.
+        * @param n Number of transactions to undo.
+        */
+       void redo (uint32_t n);
 
        UndoHistory& history() { return _history; }
 
@@ -835,13 +928,38 @@ class LIBARDOUR_API Session : public PBD::StatefulDestructible, public PBD::Scop
        std::string next_undo() const { return _history.next_undo(); }
        std::string next_redo() const { return _history.next_redo(); }
 
+       /** begin collecting undo information
+        *
+        * This call must always be followed by either
+        * begin_reversible_command() or commit_reversible_command()
+        *
+        * @param cmd_name human readable name for the undo operation
+        */
        void begin_reversible_command (const std::string& cmd_name);
        void begin_reversible_command (GQuark);
+       /** abort an open undo command
+        * This must only be called after begin_reversible_command ()
+        */
        void abort_reversible_command ();
+       /** finalize an undo command and commit pending transactions
+        *
+        * This must only be called after begin_reversible_command ()
+        * @param cmd (additional) command to add
+        */
        void commit_reversible_command (Command* cmd = 0);
 
        void add_command (Command *const cmd);
 
+       /** create an StatefulDiffCommand from the given object and add it to the stack.
+        *
+        * This function must only be called after  begin_reversible_command.
+        * Failing to do so may lead to a crash.
+        *
+        * @param sfd the object to diff
+        * @returns the allocated StatefulDiffCommand (already added via add_command)
+        */
+       PBD::StatefulDiffCommand* add_stateful_diff_command (boost::shared_ptr<PBD::StatefulDestructible> sfd);
+
        /** @return The list of operations that are currently in progress */
        std::list<GQuark> const & current_operations () {
                return _current_trans_quarks;
@@ -916,8 +1034,10 @@ class LIBARDOUR_API Session : public PBD::StatefulDestructible, public PBD::Scop
 
        /* Controllables */
 
+       boost::shared_ptr<Processor> processor_by_id (PBD::ID) const;
+
        boost::shared_ptr<PBD::Controllable> controllable_by_id (const PBD::ID&);
-       boost::shared_ptr<PBD::Controllable> controllable_by_descriptor (const PBD::ControllableDescriptor&);
+       boost::shared_ptr<PBD::Controllable> controllable_by_descriptor (const ARDOUR::ControllableDescriptor&);
 
        void add_controllable (boost::shared_ptr<PBD::Controllable>);
        void remove_controllable (PBD::Controllable*);
@@ -926,6 +1046,8 @@ class LIBARDOUR_API Session : public PBD::StatefulDestructible, public PBD::Scop
 
        SessionConfiguration config;
 
+       SessionConfiguration* cfg () { return &config; }
+
        bool exporting () const {
                return _exporting;
        }
@@ -1045,11 +1167,18 @@ class LIBARDOUR_API Session : public PBD::StatefulDestructible, public PBD::Scop
        void reconnect_ltc_input ();
        void reconnect_ltc_output ();
 
+       VCAManager& vca_manager() { return *_vca_manager; }
+
+       void auto_connect_thread_wakeup ();
+
+
   protected:
        friend class AudioEngine;
        void set_block_size (pframes_t nframes);
        void set_frame_rate (framecnt_t nframes);
+#ifdef USE_TRACKS_CODE_FEATURES
        void reconnect_existing_routes (bool withLock, bool reconnect_master = true, bool reconnect_inputs = true, bool reconnect_outputs = true);
+#endif
 
   protected:
        friend class Route;
@@ -1060,14 +1189,9 @@ class LIBARDOUR_API Session : public PBD::StatefulDestructible, public PBD::Scop
        int  create (const std::string& mix_template, BusProfile*);
        void destroy ();
 
-       enum SubState {
-               PendingDeclickIn      = 0x1,  ///< pending de-click fade-in for start
-               PendingDeclickOut     = 0x2,  ///< pending de-click fade-out for stop
-               StopPendingCapture    = 0x4,
-               PendingLoopDeclickIn  = 0x8,  ///< pending de-click fade-in at the start of a loop
-               PendingLoopDeclickOut = 0x10, ///< pending de-click fade-out at the end of a loop
-               PendingLocate         = 0x20,
-       };
+       static guint _name_id_counter;
+       static void init_name_id_counter (guint n);
+       static unsigned int name_id_counter ();
 
        /* stuff used in process() should be close together to
           maximise cache hits
@@ -1081,13 +1205,14 @@ class LIBARDOUR_API Session : public PBD::StatefulDestructible, public PBD::Scop
        process_function_type    last_process_function;
        bool                    _bounce_processing_active;
        bool                     waiting_for_sync_offset;
-       framecnt_t              _base_frame_rate;
-       framecnt_t              _current_frame_rate;  //this includes video pullup offset
-       framecnt_t              _nominal_frame_rate;  //ignores audioengine setting, "native" SR
+       framecnt_t              _base_frame_rate;     // sample-rate of the session at creation time, "native" SR
+       framecnt_t              _nominal_frame_rate;  // overridden by audioengine setting
+       framecnt_t              _current_frame_rate;  // this includes video pullup offset
        int                      transport_sub_state;
        mutable gint            _record_status;
        framepos_t              _transport_frame;
        Location*               _session_range_location; ///< session range, or 0 if there is nothing in the session yet
+       bool                    _session_range_end_is_free;
        Slave*                  _slave;
        bool                    _silent;
 
@@ -1140,8 +1265,8 @@ class LIBARDOUR_API Session : public PBD::StatefulDestructible, public PBD::Scop
        void process_without_events (pframes_t);
        void process_with_events    (pframes_t);
        void process_audition       (pframes_t);
-       int  process_export         (pframes_t);
-       int  process_export_fw      (pframes_t);
+       void process_export         (pframes_t);
+       void process_export_fw      (pframes_t);
 
        void block_processing() { g_atomic_int_set (&processing_prohibited, 1); }
        void unblock_processing() { g_atomic_int_set (&processing_prohibited, 0); }
@@ -1177,8 +1302,11 @@ class LIBARDOUR_API Session : public PBD::StatefulDestructible, public PBD::Scop
        framepos_t post_export_position;
 
        bool _exporting;
-       bool _export_started;
        bool _export_rolling;
+       bool _realtime_export;
+       bool _region_export;
+       framepos_t _export_preroll;
+       framepos_t _export_latency;
 
        boost::shared_ptr<ExportHandler> export_handler;
        boost::shared_ptr<ExportStatus>  export_status;
@@ -1271,6 +1399,21 @@ class LIBARDOUR_API Session : public PBD::StatefulDestructible, public PBD::Scop
        bool              pending_abort;
        bool              pending_auto_loop;
 
+       PBD::ReallocPool _mempool;
+       LuaState lua;
+       Glib::Threads::Mutex lua_lock;
+       luabridge::LuaRef * _lua_run;
+       luabridge::LuaRef * _lua_add;
+       luabridge::LuaRef * _lua_del;
+       luabridge::LuaRef * _lua_list;
+       luabridge::LuaRef * _lua_load;
+       luabridge::LuaRef * _lua_save;
+       luabridge::LuaRef * _lua_cleanup;
+       uint32_t            _n_lua_scripts;
+
+       void setup_lua ();
+       void try_run_lua (pframes_t);
+
        Butler* _butler;
 
        static const PostTransportWork ProcessCannotProceedMask =
@@ -1322,7 +1465,7 @@ class LIBARDOUR_API Session : public PBD::StatefulDestructible, public PBD::Scop
        void             auto_loop_changed (Location *);
        void             auto_loop_declick_range (Location *, framepos_t &, framepos_t &);
 
-       int  ensure_engine (uint32_t desired_sample_rate);
+       int  ensure_engine (uint32_t desired_sample_rate, bool);
        void pre_engine_init (std::string path);
        int  post_engine_init ();
        int  immediately_post_engine ();
@@ -1370,6 +1513,51 @@ class LIBARDOUR_API Session : public PBD::StatefulDestructible, public PBD::Scop
        pthread_cond_t  _rt_emit_cond;
        bool            _rt_emit_pending;
 
+       /* Auto Connect Thread */
+       static void *auto_connect_thread (void *);
+       void auto_connect_thread_run ();
+       void auto_connect_thread_start ();
+       void auto_connect_thread_terminate ();
+
+       pthread_t       _auto_connect_thread;
+       bool            _ac_thread_active;
+       pthread_mutex_t _auto_connect_mutex;
+       pthread_cond_t  _auto_connect_cond;
+
+       struct AutoConnectRequest {
+               public:
+               AutoConnectRequest (boost::shared_ptr <Route> r, bool ci,
+                               const ChanCount& is,
+                               const ChanCount& os,
+                               const ChanCount& io,
+                               const ChanCount& oo)
+                       : route (boost::weak_ptr<Route> (r))
+                       , connect_inputs (ci)
+                       , input_start (is)
+                       , output_start (os)
+                       , input_offset (io)
+                       , output_offset (oo)
+               {}
+
+               boost::weak_ptr <Route> route;
+               bool connect_inputs;
+               ChanCount input_start;
+               ChanCount output_start;
+               ChanCount input_offset;
+               ChanCount output_offset;
+       };
+
+       typedef std::queue<AutoConnectRequest> AutoConnectQueue;
+       Glib::Threads::Mutex  _auto_connect_queue_lock;
+       AutoConnectQueue _auto_connect_queue;
+       guint _latency_recompute_pending;
+
+       void get_physical_ports (std::vector<std::string>& inputs, std::vector<std::string>& outputs, DataType type,
+                                MidiPortFlags include = MidiPortFlags (0),
+                                MidiPortFlags exclude = MidiPortFlags (0));
+
+       void auto_connect (const AutoConnectRequest&);
+       void queue_latency_recompute ();
 
        /* SessionEventManager interface */
 
@@ -1503,6 +1691,7 @@ class LIBARDOUR_API Session : public PBD::StatefulDestructible, public PBD::Scop
 
        TempoMap    *_tempo_map;
        void          tempo_map_changed (const PBD::PropertyChange&);
+       void          gui_tempo_map_changed ();
 
        /* edit/mix groups */
 
@@ -1517,8 +1706,8 @@ class LIBARDOUR_API Session : public PBD::StatefulDestructible, public PBD::Scop
 
        SerializedRCUManager<RouteList>  routes;
 
-       void add_routes (RouteList&, bool input_auto_connect, bool output_auto_connect, bool save);
-       void add_routes_inner (RouteList&, bool input_auto_connect, bool output_auto_connect);
+       void add_routes (RouteList&, bool input_auto_connect, bool output_auto_connect, bool save, PresentationInfo::order_t);
+       void add_routes_inner (RouteList&, bool input_auto_connect, bool output_auto_connect, PresentationInfo::order_t);
        bool _adding_routes_in_progress;
        bool _reconnecting_routes_in_progress;
        bool _route_deletion_in_progress;
@@ -1532,9 +1721,7 @@ class LIBARDOUR_API Session : public PBD::StatefulDestructible, public PBD::Scop
 
        bool find_route_name (std::string const &, uint32_t& id, std::string& name, bool);
        void count_existing_track_channels (ChanCount& in, ChanCount& out);
-       void auto_connect_route (boost::shared_ptr<Route> route, ChanCount& existing_inputs, ChanCount& existing_outputs,
-                                bool with_lock, bool connect_inputs = true,
-                                ChanCount input_start = ChanCount (), ChanCount output_start = ChanCount ());
+       void auto_connect_route (boost::shared_ptr<Route>, bool, const ChanCount&, const ChanCount&, const ChanCount& io = ChanCount(), const ChanCount& oo = ChanCount());
        void midi_output_change_handler (IOChange change, void* /*src*/, boost::weak_ptr<Route> midi_track);
 
        /* track numbering */
@@ -1542,12 +1729,13 @@ class LIBARDOUR_API Session : public PBD::StatefulDestructible, public PBD::Scop
        void reassign_track_numbers ();
        uint32_t _track_number_decimals;
 
-       /* mixer stuff */
+       /* solo/mute/notifications */
+
+       void route_listen_changed (PBD::Controllable::GroupControlDisposition, boost::weak_ptr<Route>);
+       void route_mute_changed ();
+       void route_solo_changed (bool self_solo_change, PBD::Controllable::GroupControlDisposition group_override, boost::weak_ptr<Route>);
+       void route_solo_isolated_changed (boost::weak_ptr<Route>);
 
-       void route_listen_changed (bool group_override, boost::weak_ptr<Route>);
-       void route_mute_changed (void *src);
-       void route_solo_changed (bool self_solo_change, bool group_override, boost::weak_ptr<Route>);
-       void route_solo_isolated_changed (void *src, boost::weak_ptr<Route>);
        void update_route_solo_state (boost::shared_ptr<RouteList> r = boost::shared_ptr<RouteList>());
 
        void listen_position_changed ();
@@ -1772,8 +1960,8 @@ class LIBARDOUR_API Session : public PBD::StatefulDestructible, public PBD::Scop
 
        /* realtime "apply to set of routes" operations */
        template<typename T> SessionEvent*
-               get_rt_event (boost::shared_ptr<RouteList> rl, T targ, SessionEvent::RTeventCallback after, bool group_override,
-                             void (Session::*method) (boost::shared_ptr<RouteList>, T, bool)) {
+               get_rt_event (boost::shared_ptr<RouteList> rl, T targ, SessionEvent::RTeventCallback after, PBD::Controllable::GroupControlDisposition group_override,
+                             void (Session::*method) (boost::shared_ptr<RouteList>, T, PBD::Controllable::GroupControlDisposition)) {
                SessionEvent* ev = new SessionEvent (SessionEvent::RealTimeOperation, SessionEvent::Add, SessionEvent::Immediate, 0, 0.0);
                ev->rt_slot = boost::bind (method, this, rl, targ, group_override);
                ev->rt_return = after;
@@ -1782,15 +1970,30 @@ class LIBARDOUR_API Session : public PBD::StatefulDestructible, public PBD::Scop
                return ev;
        }
 
-       void rt_set_solo (boost::shared_ptr<RouteList>, bool yn, bool group_override);
-       void rt_clear_all_solo_state (boost::shared_ptr<RouteList>, bool yn, bool group_override);
-       void rt_set_just_one_solo (boost::shared_ptr<RouteList>, bool yn, bool /* ignored*/ );
-       void rt_set_mute (boost::shared_ptr<RouteList>, bool yn, bool group_override);
-       void rt_set_listen (boost::shared_ptr<RouteList>, bool yn, bool group_override);
-       void rt_set_solo_isolated (boost::shared_ptr<RouteList>, bool yn, bool group_override);
-       void rt_set_record_enabled (boost::shared_ptr<RouteList>, bool yn, bool group_override);
-       void rt_set_record_safe (boost::shared_ptr<RouteList>, bool yn, bool group_override);
-       void rt_set_monitoring (boost::shared_ptr<RouteList>, MonitorChoice, bool group_override);
+       /* specialized version realtime "apply to set of routes" operations */
+       template<typename T1, typename T2> SessionEvent*
+               get_rt_event (boost::shared_ptr<RouteList> rl, T1 t1arg, T2 t2arg, SessionEvent::RTeventCallback after, PBD::Controllable::GroupControlDisposition group_override,
+                             void (Session::*method) (boost::shared_ptr<RouteList>, T1, T2, PBD::Controllable::GroupControlDisposition)) {
+               SessionEvent* ev = new SessionEvent (SessionEvent::RealTimeOperation, SessionEvent::Add, SessionEvent::Immediate, 0, 0.0);
+               ev->rt_slot = boost::bind (method, this, rl, t1arg, t2arg, group_override);
+               ev->rt_return = after;
+               ev->event_loop = PBD::EventLoop::get_event_loop_for_thread ();
+
+               return ev;
+       }
+
+       /* specialized version realtime "apply to set of controls" operations */
+       SessionEvent* get_rt_event (boost::shared_ptr<ControlList> cl, double arg, PBD::Controllable::GroupControlDisposition group_override) {
+               SessionEvent* ev = new SessionEvent (SessionEvent::RealTimeOperation, SessionEvent::Add, SessionEvent::Immediate, 0, 0.0);
+               ev->rt_slot = boost::bind (&Session::rt_set_controls, this, cl, arg, group_override);
+               ev->rt_return = Session::rt_cleanup;
+               ev->event_loop = PBD::EventLoop::get_event_loop_for_thread ();
+
+               return ev;
+       }
+
+       void rt_set_controls (boost::shared_ptr<ControlList>, double val, PBD::Controllable::GroupControlDisposition group_override);
+       void rt_clear_all_solo_state (boost::shared_ptr<RouteList>, bool yn, PBD::Controllable::GroupControlDisposition group_override);
 
        /** temporary list of Diskstreams used only during load of 2.X sessions */
        std::list<boost::shared_ptr<Diskstream> > _diskstreams_2X;
@@ -1821,9 +2024,10 @@ class LIBARDOUR_API Session : public PBD::StatefulDestructible, public PBD::Scop
        */
        GraphEdges _current_route_graph;
 
-       uint32_t next_control_id () const;
-       int32_t _order_hint;
-       bool ignore_route_processor_changes;
+       void ensure_route_presentation_info_gap (PresentationInfo::order_t, uint32_t gap_size);
+
+       friend class    ProcessorChangeBlocker;
+       gint            _ignore_route_processor_changes; /* atomic */
 
        MidiClockTicker* midi_clock;
 
@@ -1848,6 +2052,17 @@ class LIBARDOUR_API Session : public PBD::StatefulDestructible, public PBD::Scop
        static const uint32_t session_end_shift;
 
        std::string _template_state_dir;
+
+       VCAManager* _vca_manager;
+
+       boost::shared_ptr<Route> get_midi_nth_route_by_id (PresentationInfo::order_t n) const;
+
+       std::string created_with;
+
+       void midi_track_presentation_info_changed (PBD::PropertyChange const &, boost::weak_ptr<MidiTrack>);
+       void rewire_selected_midi (boost::shared_ptr<MidiTrack>);
+       void rewire_midi_selection_ports ();
+       boost::weak_ptr<MidiTrack> current_midi_target;
 };