Use a shared_ptr for SessionPlaylists so that it can be explicitly destroyed in ...
[ardour.git] / libs / ardour / session.cc
index a5fbe25a8fc7dac8f0292a9cdf91d1bc3a00a22a..9cb4cc32849506a0fd00e14bd0c2afc1ad76e658 100644 (file)
@@ -37,6 +37,7 @@
 
 #include "pbd/error.h"
 #include <glibmm/thread.h>
+#include "pbd/boost_debug.h"
 #include "pbd/pathscanner.h"
 #include "pbd/stl_delete.h"
 #include "pbd/basename.h"
@@ -62,6 +63,7 @@
 #include "ardour/crossfade.h"
 #include "ardour/cycle_timer.h"
 #include "ardour/data_type.h"
+#include "ardour/debug.h"
 #include "ardour/filename_extensions.h"
 #include "ardour/internal_send.h"
 #include "ardour/io_processor.h"
@@ -84,6 +86,7 @@
 #include "ardour/session_directory.h"
 #include "ardour/session_directory.h"
 #include "ardour/session_metadata.h"
+#include "ardour/session_playlists.h"
 #include "ardour/slave.h"
 #include "ardour/smf_source.h"
 #include "ardour/source_factory.h"
@@ -97,6 +100,7 @@ using namespace std;
 using namespace ARDOUR;
 using namespace PBD;
 using boost::shared_ptr;
+using boost::weak_ptr;
 
 bool Session::_disable_all_loaded_plugins = false;
 
@@ -129,7 +133,6 @@ Session::Session (AudioEngine &eng,
          _midi_port (default_midi_port),
          _midi_clock_port (default_midi_clock_port),
          _session_dir (new SessionDirectory(fullpath)),
-         pending_events (2048),
          state_tree (0),
          _butler (new Butler (this)),
          _post_transport_work (0),
@@ -149,6 +152,8 @@ Session::Session (AudioEngine &eng,
          _have_rec_enabled_diskstream (false)
 
 {
+       playlists.reset (new SessionPlaylists);
+       
        bool new_session;
 
        interpolation.add_channel_to (0, 0);
@@ -215,7 +220,6 @@ Session::Session (AudioEngine &eng,
          _midi_port (default_midi_port),
          _midi_clock_port (default_midi_clock_port),
          _session_dir ( new SessionDirectory(fullpath)),
-         pending_events (2048),
          state_tree (0),
          _butler (new Butler (this)),
          _post_transport_work (0),
@@ -234,6 +238,8 @@ Session::Session (AudioEngine &eng,
          _metadata (new SessionMetadata()),
          _have_rec_enabled_diskstream (false)
 {
+       playlists.reset (new SessionPlaylists);
+
        bool new_session;
 
        interpolation.add_channel_to (0, 0);
@@ -329,6 +335,8 @@ Session::~Session ()
 void
 Session::destroy ()
 {
+       vector<void*> debug_pointers;
+
        /* if we got to here, leaving pending capture state around
           is a mistake.
        */
@@ -374,14 +382,17 @@ Session::destroy ()
        delete _silent_buffers;
        delete _mix_buffers;
 
+       /* clear out any pending dead wood from RCU managed objects */
+
+       routes.flush ();
+       diskstreams.flush ();
+       _bundles.flush ();
+       
        AudioDiskstream::free_working_buffers();
 
        Route::SyncOrderKeys.clear();
 
-#undef TRACK_DESTRUCTION
-#ifdef TRACK_DESTRUCTION
-       cerr << "delete named selections\n";
-#endif /* TRACK_DESTRUCTION */
+       DEBUG_TRACE (DEBUG::Destruction, "delete named selections\n");
        for (NamedSelectionList::iterator i = named_selections.begin(); i != named_selections.end(); ) {
                NamedSelectionList::iterator tmp;
 
@@ -392,98 +403,70 @@ Session::destroy ()
                i = tmp;
        }
 
-#ifdef TRACK_DESTRUCTION
-       cerr << "delete playlists\n";
-#endif /* TRACK_DESTRUCTION */
-       for (PlaylistList::iterator i = playlists.begin(); i != playlists.end(); ) {
-               PlaylistList::iterator tmp;
-
-               tmp = i;
-               ++tmp;
-
-               (*i)->drop_references ();
-
-               i = tmp;
-       }
-
-       for (PlaylistList::iterator i = unused_playlists.begin(); i != unused_playlists.end(); ) {
-               PlaylistList::iterator tmp;
-
-               tmp = i;
-               ++tmp;
-
-               (*i)->drop_references ();
-
-               i = tmp;
-       }
-
-       playlists.clear ();
-       unused_playlists.clear ();
-
-#ifdef TRACK_DESTRUCTION
-       cerr << "delete regions\n";
-#endif /* TRACK_DESTRUCTION */
-
+       DEBUG_TRACE (DEBUG::Destruction, "delete regions\n");
        for (RegionList::iterator i = regions.begin(); i != regions.end(); ) {
                RegionList::iterator tmp;
 
                tmp = i;
                ++tmp;
-
+               
+               DEBUG_TRACE(DEBUG::Destruction, string_compose ("Dropping for region %1 (%2); pre-ref = %2\n", i->second->name(), i->second.get(), i->second.use_count()));
                i->second->drop_references ();
-
+               DEBUG_TRACE(DEBUG::Destruction, string_compose ("region post ref = %1\n", i->second.use_count()));
                i = tmp;
        }
 
        regions.clear ();
 
-#ifdef TRACK_DESTRUCTION
-       cerr << "delete routes\n";
-#endif /* TRACK_DESTRUCTION */
+       DEBUG_TRACE (DEBUG::Destruction, "delete routes\n");
+       
+       /* reset these three references to special routes before we do the usual route delete thing */
+
+       auditioner.reset ();
+       _master_out.reset ();
+       _control_out.reset ();
+
        {
                RCUWriter<RouteList> writer (routes);
                boost::shared_ptr<RouteList> r = writer.get_copy ();
                for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
+                       DEBUG_TRACE(DEBUG::Destruction, string_compose ("Dropping for route %1 ; pre-ref = %2\n", (*i)->name(), (*i).use_count()));
                        (*i)->drop_references ();
                }
                r->clear ();
                /* writer goes out of scope and updates master */
        }
-
        routes.flush ();
 
-#ifdef TRACK_DESTRUCTION
-       cerr << "delete diskstreams\n";
-#endif /* TRACK_DESTRUCTION */
-       {
-              RCUWriter<DiskstreamList> dwriter (diskstreams);
-              boost::shared_ptr<DiskstreamList> dsl = dwriter.get_copy();
-              for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
-                      (*i)->drop_references ();
-              }
-              dsl->clear ();
-       }
-       diskstreams.flush ();
-
-#ifdef TRACK_DESTRUCTION
-       cerr << "delete audio sources\n";
-#endif /* TRACK_DESTRUCTION */
+       DEBUG_TRACE (DEBUG::Destruction, "delete diskstreams\n");
+       {
+               RCUWriter<DiskstreamList> dwriter (diskstreams);
+               boost::shared_ptr<DiskstreamList> dsl = dwriter.get_copy();
+               for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
+                       DEBUG_TRACE(DEBUG::Destruction, string_compose ("Dropping for diskstream %1 ; pre-ref = %2\n", (*i)->name(), (*i).use_count()));
+                       (*i)->drop_references ();
+               }
+               dsl->clear ();
+       }
+       diskstreams.flush ();
+
+       DEBUG_TRACE (DEBUG::Destruction, "delete sources\n");
        for (SourceMap::iterator i = sources.begin(); i != sources.end(); ) {
                SourceMap::iterator tmp;
 
                tmp = i;
                ++tmp;
 
+               DEBUG_TRACE(DEBUG::Destruction, string_compose ("Dropping for source %1 ; pre-ref = %2\n", i->second->path(), i->second.use_count()));
                i->second->drop_references ();
 
                i = tmp;
        }
+
        sources.clear ();
 
 
-#ifdef TRACK_DESTRUCTION
-       cerr << "delete route groups\n";
-#endif /* TRACK_DESTRUCTION */
+       DEBUG_TRACE (DEBUG::Destruction, "delete route groups\n");
        for (list<RouteGroup *>::iterator i = _route_groups.begin(); i != _route_groups.end(); ++i) {
                delete *i;
        }
@@ -491,6 +474,13 @@ Session::destroy ()
        Crossfade::set_buffer_size (0);
 
        delete mmc;
+
+       /* not strictly necessary, but doing it here allows the shared_ptr debugging to work */
+       playlists.reset ();
+
+       boost_debug_list_ptrs ();
+
+       DEBUG_TRACE (DEBUG::Destruction, "Session::destroy() done\n");
 }
 
 void
@@ -524,6 +514,7 @@ Session::when_engine_running ()
        BootMessage (_("Using configuration"));
 
        Config->map_parameters (bind (mem_fun (*this, &Session::config_changed), false));
+       config.map_parameters (bind (mem_fun (*this, &Session::config_changed), true));
 
        /* every time we reconnect, recompute worst case output latencies */
 
@@ -930,7 +921,7 @@ Session::reset_input_monitor_state ()
 void
 Session::auto_punch_start_changed (Location* location)
 {
-       replace_event (Event::PunchIn, location->start());
+       replace_event (SessionEvent::PunchIn, location->start());
 
        if (get_record_enabled() && config.get_punch_in()) {
                /* capture start has been changed, so save new pending state */
@@ -943,7 +934,7 @@ Session::auto_punch_end_changed (Location* location)
 {
        nframes_t when_to_stop = location->end();
        // when_to_stop += _worst_output_latency + _worst_input_latency;
-       replace_event (Event::PunchOut, when_to_stop);
+       replace_event (SessionEvent::PunchOut, when_to_stop);
 }
 
 void
@@ -951,15 +942,15 @@ Session::auto_punch_changed (Location* location)
 {
        nframes_t when_to_stop = location->end();
 
-       replace_event (Event::PunchIn, location->start());
+       replace_event (SessionEvent::PunchIn, location->start());
        //when_to_stop += _worst_output_latency + _worst_input_latency;
-       replace_event (Event::PunchOut, when_to_stop);
+       replace_event (SessionEvent::PunchOut, when_to_stop);
 }
 
 void
 Session::auto_loop_changed (Location* location)
 {
-       replace_event (Event::AutoLoop, location->end(), location->start());
+       replace_event (SessionEvent::AutoLoop, location->end(), location->start());
 
        if (transport_rolling() && play_loop) {
 
@@ -968,7 +959,7 @@ Session::auto_loop_changed (Location* location)
 
                if (_transport_frame < location->start() || _transport_frame > location->end()) {
                        // relocate to beginning of loop
-                       clear_events (Event::LocateRoll);
+                       clear_events (SessionEvent::LocateRoll);
 
                        request_locate (location->start(), true);
 
@@ -980,8 +971,8 @@ Session::auto_loop_changed (Location* location)
                        loop_changing = true;
 
                        if (location->end() > last_loopend) {
-                               clear_events (Event::LocateRoll);
-                               Event *ev = new Event (Event::LocateRoll, Event::Add, last_loopend, last_loopend, 0, true);
+                               clear_events (SessionEvent::LocateRoll);
+                               SessionEvent *ev = new SessionEvent (SessionEvent::LocateRoll, SessionEvent::Add, last_loopend, last_loopend, 0, true);
                                queue_event (ev);
                        }
 
@@ -1001,8 +992,8 @@ Session::set_auto_punch_location (Location* location)
                auto_punch_end_changed_connection.disconnect();
                auto_punch_changed_connection.disconnect();
                existing->set_auto_punch (false, this);
-               remove_event (existing->start(), Event::PunchIn);
-               clear_events (Event::PunchOut);
+               remove_event (existing->start(), SessionEvent::PunchIn);
+               clear_events (SessionEvent::PunchOut);
                auto_punch_location_changed (0);
        }
 
@@ -1043,7 +1034,7 @@ Session::set_auto_loop_location (Location* location)
                auto_loop_end_changed_connection.disconnect();
                auto_loop_changed_connection.disconnect();
                existing->set_auto_loop (false, this);
-               remove_event (existing->end(), Event::AutoLoop);
+               remove_event (existing->end(), SessionEvent::AutoLoop);
                auto_loop_location_changed (0);
        }
 
@@ -1444,15 +1435,18 @@ trace_terminal (shared_ptr<Route> r1, shared_ptr<Route> rbase)
 
        /* make a copy of the existing list of routes that feed r1 */
 
-       set<shared_ptr<Route> > existing = r1->fed_by;
+       set<weak_ptr<Route> > existing = r1->fed_by;
 
        /* for each route that feeds r1, recurse, marking it as feeding
           rbase as well.
        */
 
-       for (set<shared_ptr<Route> >::iterator i = existing.begin(); i != existing.end(); ++i) {
-               r2 =* i;
-
+       for (set<weak_ptr<Route> >::iterator i = existing.begin(); i != existing.end(); ++i) {
+               if (!(r2 = (*i).lock ())) {
+                       /* (*i) went away, ignore it */
+                       continue;
+               }
+               
                /* r2 is a route that feeds r1 which somehow feeds base. mark
                   base as being fed by r2
                */
@@ -1463,7 +1457,7 @@ trace_terminal (shared_ptr<Route> r1, shared_ptr<Route> rbase)
 
                        /* 2nd level feedback loop detection. if r1 feeds or is fed by r2,
                           stop here.
-                        */
+                       */
 
                        if ((r1->fed_by.find (r2) != r1->fed_by.end()) && (r2->fed_by.find (r1) != r2->fed_by.end())) {
                                continue;
@@ -1769,7 +1763,9 @@ Session::new_audio_track (int input_channels, int output_channels, TrackMode mod
                shared_ptr<AudioTrack> track;
 
                try {
-                       track = boost::shared_ptr<AudioTrack>((new AudioTrack (*this, track_name, Route::Flag (0), mode)));
+                       AudioTrack* at = new AudioTrack (*this, track_name, Route::Flag (0), mode);
+                       // boost_debug_shared_ptr_mark_interesting (at, typeid (at).name());
+                       track = boost::shared_ptr<AudioTrack>(at);
 
                        if (track->input()->ensure_io (ChanCount(DataType::AUDIO, input_channels), false, this)) {
                                error << string_compose (_("cannot configure %1 in/%2 out configuration for new audio track"),
@@ -1904,7 +1900,7 @@ Session::set_remote_control_ids ()
 
 
 RouteList
-Session::new_audio_route (int input_channels, int output_channels, RouteGroup* route_group, uint32_t how_many)
+Session::new_audio_route (bool aux, int input_channels, int output_channels, RouteGroup* route_group, uint32_t how_many)
 {
        char bus_name[32];
        uint32_t bus_id = 1;
@@ -2007,6 +2003,10 @@ Session::new_audio_route (int input_channels, int output_channels, RouteGroup* r
                        bus->set_remote_control_id (control_id);
                        ++control_id;
 
+                       if (aux) {
+                               bus->add_internal_return ();
+                       }
+
                        ret.push_back (bus);
                }
 
@@ -2151,7 +2151,7 @@ Session::add_routes (RouteList& new_routes, bool save)
                (*x)->solo_changed.connect (sigc::bind (mem_fun (*this, &Session::route_solo_changed), wpr));
                (*x)->mute_changed.connect (mem_fun (*this, &Session::route_mute_changed));
                (*x)->output()->changed.connect (mem_fun (*this, &Session::set_worst_io_latencies_x));
-               (*x)->processors_changed.connect (bind (mem_fun (*this, &Session::update_latency_compensation), false, false));
+               (*x)->processors_changed.connect (mem_fun (*this, &Session::route_processors_changed));
                (*x)->route_group_changed.connect (hide (mem_fun (*this, &Session::route_group_changed)));
 
                if ((*x)->is_master()) {
@@ -2254,7 +2254,6 @@ Session::globally_add_internal_sends (boost::shared_ptr<Route> dest, Placement p
        add_internal_sends (dest, p, t);
 }
 
-
 void
 Session::add_internal_sends (boost::shared_ptr<Route> dest, Placement p, boost::shared_ptr<RouteList> senders)
 {
@@ -2274,6 +2273,8 @@ Session::add_internal_sends (boost::shared_ptr<Route> dest, Placement p, boost::
 
                (*i)->listen_via (dest, p, true, true);
        }
+
+       graph_reordered ();
 }
 
 void
@@ -2358,6 +2359,18 @@ Session::remove_route (shared_ptr<Route> route)
        route->input()->disconnect (0);
        route->output()->disconnect (0);
 
+       /* if the route had internal sends sending to it, remove them */
+       if (route->internal_return()) {
+
+               boost::shared_ptr<RouteList> r = routes.reader ();
+               for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
+                       boost::shared_ptr<Send> s = (*i)->internal_send_for (route);
+                       if (s) {
+                               (*i)->remove_processor (s);
+                       }
+               }
+       }       
+
        update_latency_compensation (false, false);
        set_dirty();
 
@@ -2421,7 +2434,7 @@ Session::route_solo_changed (void* /*src*/, boost::weak_ptr<Route> wpr)
        shared_ptr<RouteList> r = routes.reader ();
        int32_t delta;
 
-       if (route->soloed()) {
+       if (route->self_soloed()) {
                delta = 1;
        } else {
                delta = -1;
@@ -2432,27 +2445,30 @@ Session::route_solo_changed (void* /*src*/, boost::weak_ptr<Route> wpr)
        */
 
        solo_update_disabled = true;
+
        for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
                bool via_sends_only;
 
-               if ((*i)->feeds (route, &via_sends_only) && !(*i)->is_hidden() && !(*i)->is_master() && !(*i)->is_control()) {
-                       //if (!via_sends_only) {
-                               /* do it */
-                               (*i)->mod_solo_level (delta);
-                               //}
-               }
+
+               if ((*i) == route || !(*i)->solo_isolated() || !(*i)->is_master() || !(*i)->is_control() || (*i)->is_hidden()) {
+                       continue;
+               } else if ((*i)->feeds (route, &via_sends_only)) {
+                       if (!via_sends_only) {
+                               (*i)->mod_solo_by_others (delta);
+                       }
+               } 
        }
 
        /* make sure master is never muted by solo */
 
-       if (_master_out && route != _master_out && _master_out->solo_level() == 0 && !_master_out->soloed()) {
-               _master_out->mod_solo_level (1);
-       }
-
+       if (_master_out && route != _master_out && _master_out->soloed_by_others() == 0 && !_master_out->soloed()) {
+               _master_out->mod_solo_by_others (1);
+       }
        /* ditto for control outs make sure master is never muted by solo */
 
-       if (_control_out && route != _control_out && _control_out && _control_out->solo_level() == 0) {
-               _control_out->mod_solo_level (1);
+       if (_control_out && route != _control_out && _control_out && _control_out->soloed_by_others() == 0) {
+               _control_out->mod_solo_by_others (1);
        }
 
        solo_update_disabled = false;
@@ -2473,7 +2489,7 @@ Session::update_route_solo_state (boost::shared_ptr<RouteList> r)
        }
 
        for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
-               if (!(*i)->is_master() && !(*i)->is_control() && !(*i)->is_hidden() && (*i)->soloed()) {
+               if (!(*i)->is_master() && !(*i)->is_control() && !(*i)->is_hidden() && (*i)->self_soloed()) {
                        something_soloed = true;
                        break;
                }
@@ -2485,6 +2501,20 @@ Session::update_route_solo_state (boost::shared_ptr<RouteList> r)
        }
 }
 
+boost::shared_ptr<RouteList> 
+Session::get_routes_with_internal_returns() const
+{
+       shared_ptr<RouteList> r = routes.reader ();
+       boost::shared_ptr<RouteList> rl (new RouteList);
+
+       for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
+               if ((*i)->internal_return ()) {
+                       rl->push_back (*i);
+               }
+       }
+       return rl;
+}
+
 shared_ptr<Route>
 Session::route_by_name (string name)
 {
@@ -2885,13 +2915,6 @@ Session::find_whole_file_parent (boost::shared_ptr<Region const> child)
        return boost::shared_ptr<Region> ();
 }
 
-void
-Session::find_equivalent_playlist_regions (boost::shared_ptr<Region> region, vector<boost::shared_ptr<Region> >& result)
-{
-       for (PlaylistList::iterator i = playlists.begin(); i != playlists.end(); ++i)
-               (*i)->get_region_list_equivalent_regions (region, result);
-}
-
 int
 Session::destroy_region (boost::shared_ptr<Region> region)
 {
@@ -3017,23 +3040,6 @@ Session::remove_source (boost::weak_ptr<Source> src)
        }
 }
 
-/** Return the number of playlists (not regions) that contain @a src */
-uint32_t
-Session::source_use_count (boost::shared_ptr<const Source> src) const
-{
-       uint32_t count = 0;
-       for (PlaylistList::const_iterator p = playlists.begin(); p != playlists.end(); ++p) {
-               for (Playlist::RegionList::const_iterator r = (*p)->region_list().begin();
-                               r != (*p)->region_list().end(); ++r) {
-                       if ((*r)->uses_source(src)) {
-                               ++count;
-                               break;
-                       }
-               }
-       }
-       return count;
-}
-
 boost::shared_ptr<Source>
 Session::source_by_id (const PBD::ID& id)
 {
@@ -3180,7 +3186,7 @@ Session::change_source_path_by_name (string path, string oldname, string newname
        return path;
 }
 
-/** Return the full path (in some session directory) for a new embedded source.
+/** Return the full path (in some session directory) for a new within-session source.
  * \a name must be a session-unique name that does not contain slashes
  *         (e.g. as returned by new_*_source_name)
  */
@@ -3301,16 +3307,16 @@ Session::new_audio_source_name (const string& base, uint32_t nchan, uint32_t cha
        return Glib::path_get_basename(buf);
 }
 
-/** Create a new embedded audio source */
+/** Create a new within-session audio source */
 boost::shared_ptr<AudioFileSource>
 Session::create_audio_source_for_session (AudioDiskstream& ds, uint32_t chan, bool destructive)
 {
        const size_t n_chans = ds.n_channels().n_audio();
        const string name    = new_audio_source_name (ds.name(), n_chans, chan, destructive);
        const string path    = new_source_path_from_name(DataType::AUDIO, name);
+
        return boost::dynamic_pointer_cast<AudioFileSource> (
-                       SourceFactory::createWritable (
-                                       DataType::AUDIO, *this, path, true, destructive, frame_rate()));
+               SourceFactory::createWritable (DataType::AUDIO, *this, path, destructive, frame_rate()));
 }
 
 /** Return a unique name based on \a base for a new internal MIDI source */
@@ -3362,7 +3368,7 @@ Session::new_midi_source_name (const string& base)
 }
 
 
-/** Create a new embedded MIDI source */
+/** Create a new within-session MIDI source */
 boost::shared_ptr<MidiSource>
 Session::create_midi_source_for_session (MidiDiskstream& ds)
 {
@@ -3371,46 +3377,10 @@ Session::create_midi_source_for_session (MidiDiskstream& ds)
 
        return boost::dynamic_pointer_cast<SMFSource> (
                        SourceFactory::createWritable (
-                                       DataType::MIDI, *this, path, true, false, frame_rate()));
+                                       DataType::MIDI, *this, path, false, frame_rate()));
 }
 
 
-/* Playlist management */
-
-boost::shared_ptr<Playlist>
-Session::playlist_by_name (string name)
-{
-       Glib::Mutex::Lock lm (playlist_lock);
-       for (PlaylistList::iterator i = playlists.begin(); i != playlists.end(); ++i) {
-               if ((*i)->name() == name) {
-                       return* i;
-               }
-       }
-       for (PlaylistList::iterator i = unused_playlists.begin(); i != unused_playlists.end(); ++i) {
-               if ((*i)->name() == name) {
-                       return* i;
-               }
-       }
-
-       return boost::shared_ptr<Playlist>();
-}
-
-void
-Session::unassigned_playlists (std::list<boost::shared_ptr<Playlist> > & list)
-{
-       Glib::Mutex::Lock lm (playlist_lock);
-       for (PlaylistList::iterator i = playlists.begin(); i != playlists.end(); ++i) {
-               if (!(*i)->get_orig_diskstream_id().to_s().compare ("0")) {
-                       list.push_back (*i);
-               }
-       }
-       for (PlaylistList::iterator i = unused_playlists.begin(); i != unused_playlists.end(); ++i) {
-               if (!(*i)->get_orig_diskstream_id().to_s().compare ("0")) {
-                       list.push_back (*i);
-               }
-       }
-}
-
 void
 Session::add_playlist (boost::shared_ptr<Playlist> playlist, bool unused)
 {
@@ -3418,13 +3388,9 @@ Session::add_playlist (boost::shared_ptr<Playlist> playlist, bool unused)
                return;
        }
 
-       {
-               Glib::Mutex::Lock lm (playlist_lock);
-               if (find (playlists.begin(), playlists.end(), playlist) == playlists.end()) {
-                       playlists.insert (playlists.begin(), playlist);
-                       playlist->InUse.connect (sigc::bind (mem_fun (*this, &Session::track_playlist), boost::weak_ptr<Playlist>(playlist)));
-                       playlist->GoingAway.connect (sigc::bind (mem_fun (*this, &Session::remove_playlist), boost::weak_ptr<Playlist>(playlist)));
-               }
+       bool existing = playlists->add (playlist);
+       if (!existing) {
+               playlist->GoingAway.connect (sigc::bind (mem_fun (*this, &Session::remove_playlist), boost::weak_ptr<Playlist>(playlist)));
        }
 
        if (unused) {
@@ -3432,61 +3398,6 @@ Session::add_playlist (boost::shared_ptr<Playlist> playlist, bool unused)
        }
 
        set_dirty();
-
-       PlaylistAdded (playlist); /* EMIT SIGNAL */
-}
-
-void
-Session::get_playlists (vector<boost::shared_ptr<Playlist> >& s)
-{
-       {
-               Glib::Mutex::Lock lm (playlist_lock);
-               for (PlaylistList::iterator i = playlists.begin(); i != playlists.end(); ++i) {
-                       s.push_back (*i);
-               }
-               for (PlaylistList::iterator i = unused_playlists.begin(); i != unused_playlists.end(); ++i) {
-                       s.push_back (*i);
-               }
-       }
-}
-
-void
-Session::track_playlist (bool inuse, boost::weak_ptr<Playlist> wpl)
-{
-       boost::shared_ptr<Playlist> pl(wpl.lock());
-
-       if (!pl) {
-               return;
-       }
-
-       PlaylistList::iterator x;
-
-       if (pl->hidden()) {
-               /* its not supposed to be visible */
-               return;
-       }
-
-       {
-               Glib::Mutex::Lock lm (playlist_lock);
-
-               if (!inuse) {
-
-                       unused_playlists.insert (pl);
-
-                       if ((x = playlists.find (pl)) != playlists.end()) {
-                               playlists.erase (x);
-                       }
-
-
-               } else {
-
-                       playlists.insert (pl);
-
-                       if ((x = unused_playlists.find (pl)) != unused_playlists.end()) {
-                               unused_playlists.erase (x);
-                       }
-               }
-       }
 }
 
 void
@@ -3502,26 +3413,9 @@ Session::remove_playlist (boost::weak_ptr<Playlist> weak_playlist)
                return;
        }
 
-       {
-               Glib::Mutex::Lock lm (playlist_lock);
-
-               PlaylistList::iterator i;
-
-               i = find (playlists.begin(), playlists.end(), playlist);
-               if (i != playlists.end()) {
-                       playlists.erase (i);
-               }
-
-               i = find (unused_playlists.begin(), unused_playlists.end(), playlist);
-               if (i != unused_playlists.end()) {
-                       unused_playlists.erase (i);
-               }
-
-       }
+       playlists->remove (playlist);
 
        set_dirty();
-
-       PlaylistRemoved (playlist); /* EMIT SIGNAL */
 }
 
 void
@@ -3535,7 +3429,7 @@ Session::set_audition (boost::shared_ptr<Region> r)
 void
 Session::audition_playlist ()
 {
-       Event* ev = new Event (Event::Audition, Event::Add, Event::Immediate, 0, 0.0);
+       SessionEvent* ev = new SessionEvent (SessionEvent::Audition, SessionEvent::Add, SessionEvent::Immediate, 0, 0.0);
        ev->region.reset ();
        queue_event (ev);
 }
@@ -3555,7 +3449,7 @@ Session::non_realtime_set_audition ()
 void
 Session::audition_region (boost::shared_ptr<Region> r)
 {
-       Event* ev = new Event (Event::Audition, Event::Add, Event::Immediate, 0, 0.0);
+       SessionEvent* ev = new SessionEvent (SessionEvent::Audition, SessionEvent::Add, SessionEvent::Immediate, 0, 0.0);
        ev->region = r;
        queue_event (ev);
 }
@@ -3683,10 +3577,10 @@ void
 Session::graph_reordered ()
 {
        /* don't do this stuff if we are setting up connections
-          from a set_state() call or creating new tracks.
+          from a set_state() call or creating new tracks. Ditto for deletion.
        */
 
-       if (_state_of_the_state & InitialConnecting) {
+       if (_state_of_the_state & (InitialConnecting|Deletion)) {
                return;
        }
 
@@ -3712,12 +3606,20 @@ Session::graph_reordered ()
 void
 Session::record_disenable_all ()
 {
+       if (!writable()) {
+               return;
+       }
+
        record_enable_change_all (false);
 }
 
 void
 Session::record_enable_all ()
 {
+       if (!writable()) {
+               return;
+       }
+
        record_enable_change_all (true);
 }
 
@@ -3725,16 +3627,33 @@ void
 Session::record_enable_change_all (bool yn)
 {
        shared_ptr<RouteList> r = routes.reader ();
+       RouteList* tracks = new RouteList;
 
        for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
                boost::shared_ptr<Track> t;
 
+               if (boost::dynamic_pointer_cast<Track>(*i) != 0) {
+                       tracks->push_back (*i);
+               }
+       }
+
+       SessionEvent* ev = new SessionEvent (SessionEvent::SetRecordEnable, SessionEvent::Add, SessionEvent::Immediate, 0, 0.0, yn);
+
+       ev->routes = tracks;
+       ev->Complete.connect (mem_fun (*this, &Session::cleanup_event));
+       queue_event (ev);
+}
+
+void
+Session::do_record_enable_change_all (RouteList* rl, bool yn)
+{
+       for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
+               boost::shared_ptr<Track> t;
+
                if ((t = boost::dynamic_pointer_cast<Track>(*i)) != 0) {
                        t->set_record_enable (yn, this);
                }
        }
-
-       /* since we don't keep rec-enable state, don't mark session dirty */
 }
 
 void
@@ -3756,7 +3675,7 @@ Session::remove_processor (Processor* processor)
        } else if ((send = dynamic_cast<Send *> (processor)) != 0) {
                send_bitset[send->bit_slot()] = false;
        } else if ((retrn = dynamic_cast<Return *> (processor)) != 0) {
-               return_bitset[send->bit_slot()] = false;
+               return_bitset[retrn->bit_slot()] = false;
        }
 
        set_dirty();
@@ -3853,13 +3772,7 @@ Session::tempo_map_changed (Change)
 {
        clear_clicks ();
 
-       for (PlaylistList::iterator i = playlists.begin(); i != playlists.end(); ++i) {
-               (*i)->update_after_tempo_map_change ();
-       }
-
-       for (PlaylistList::iterator i = unused_playlists.begin(); i != unused_playlists.end(); ++i) {
-               (*i)->update_after_tempo_map_change ();
-       }
+       playlists->update_after_tempo_map_change ();
 
        set_dirty ();
 }
@@ -4080,13 +3993,6 @@ Session::route_name_internal (string n) const
        return false;
 }
 
-uint32_t
-Session::n_playlists () const
-{
-       Glib::Mutex::Lock lm (playlist_lock);
-       return playlists.size();
-}
-
 void
 Session::allocate_pan_automation_buffers (nframes_t nframes, uint32_t howmany, bool force)
 {
@@ -4192,7 +4098,7 @@ Session::write_one_track (AudioTrack& track, nframes_t start, nframes_t end,
 
                try {
                        fsource = boost::dynamic_pointer_cast<AudioFileSource> (
-                               SourceFactory::createWritable (DataType::AUDIO, *this, buf, true, false, frame_rate()));
+                               SourceFactory::createWritable (DataType::AUDIO, *this, buf, false, frame_rate()));
                }
 
                catch (failed_constructor& err) {
@@ -4472,3 +4378,33 @@ Session::get_available_sync_options () const
 
        return ret;
 }
+
+boost::shared_ptr<RouteList>
+Session::get_routes_with_regions_at (nframes64_t const p) const
+{
+       shared_ptr<RouteList> r = routes.reader ();
+       shared_ptr<RouteList> rl (new RouteList);
+
+       for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
+               boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
+               if (!tr) {
+                       continue;
+               }
+               
+               boost::shared_ptr<Diskstream> ds = tr->diskstream ();
+               if (!ds) {
+                       continue;
+               }
+
+               boost::shared_ptr<Playlist> pl = ds->playlist ();
+               if (!pl) {
+                       continue;
+               }
+               
+               if (pl->has_region_at (p)) {
+                       rl->push_back (*i);
+               }
+       }
+
+       return rl;
+}