Adding sends/port inserts to MIDI tracks (not actually working yet though)
[ardour.git] / libs / ardour / session.cc
index b329c16cc6ee6454009a3bc77e76061b8477dc32..3c325ee5385b7d6aa5e92a910d8262ca4714872c 100644 (file)
 #include <sigc++/bind.h>
 #include <sigc++/retype.h>
 
+#include <glibmm/thread.h>
+#include <glibmm/miscutils.h>
+
 #include <pbd/error.h>
-#include <pbd/lockmonitor.h>
+#include <glibmm/thread.h>
 #include <pbd/pathscanner.h>
 #include <pbd/stl_delete.h>
 #include <pbd/basename.h>
-#include <pbd/dirname.h>
 
 #include <ardour/audioengine.h>
 #include <ardour/configuration.h>
 #include <ardour/session.h>
-#include <ardour/diskstream.h>
 #include <ardour/utils.h>
+#include <ardour/audio_diskstream.h>
 #include <ardour/audioplaylist.h>
 #include <ardour/audioregion.h>
-#include <ardour/source.h>
-#include <ardour/filesource.h>
+#include <ardour/audiofilesource.h>
+#include <ardour/midi_diskstream.h>
+#include <ardour/midi_playlist.h>
+#include <ardour/midi_region.h>
+#include <ardour/smf_source.h>
 #include <ardour/destructive_filesource.h>
-#include <ardour/sndfilesource.h>
 #include <ardour/auditioner.h>
 #include <ardour/recent_sessions.h>
 #include <ardour/redirect.h>
 #include <ardour/slave.h>
 #include <ardour/tempo.h>
 #include <ardour/audio_track.h>
+#include <ardour/midi_track.h>
 #include <ardour/cycle_timer.h>
 #include <ardour/named_selection.h>
 #include <ardour/crossfade.h>
 #include <ardour/playlist.h>
 #include <ardour/click.h>
-#include <ardour/timestamps.h>
+#include <ardour/data_type.h>
+#include <ardour/buffer_set.h>
+#include <ardour/source_factory.h>
+
+#ifdef HAVE_LIBLO
+#include <ardour/osc.h>
+#endif
 
 #include "i18n.h"
 
 using namespace std;
 using namespace ARDOUR;
-//using namespace sigc;
+using namespace PBD;
+using boost::shared_ptr;
 
 const char* Session::_template_suffix = X_(".template");
 const char* Session::_statefile_suffix = X_(".ardour");
 const char* Session::_pending_suffix = X_(".pending");
 const char* Session::sound_dir_name = X_("sounds");
+const char* Session::tape_dir_name = X_("tapes");
 const char* Session::peak_dir_name = X_("peaks");
 const char* Session::dead_sound_dir_name = X_("dead_sounds");
 
@@ -85,6 +98,9 @@ Session::mix_buffers_with_gain_t      Session::mix_buffers_with_gain  = 0;
 Session::mix_buffers_no_gain_t         Session::mix_buffers_no_gain    = 0;
 
 sigc::signal<int> Session::AskAboutPendingState;
+sigc::signal<void> Session::SMPTEOffsetChanged;
+sigc::signal<void> Session::SendFeedback;
+
 
 int
 Session::find_session (string str, string& path, string& snapshot, bool& isnew)
@@ -242,16 +258,24 @@ Session::Session (AudioEngine &eng,
                  string* mix_template)
 
        : _engine (eng),
+         _scratch_buffers(new BufferSet()),
+         _silent_buffers(new BufferSet()),
+         _send_buffers(new BufferSet()),
          _mmc_port (default_mmc_port),
          _mtc_port (default_mtc_port),
          _midi_port (default_midi_port),
          pending_events (2048),
-         midi_requests (128), // the size of this should match the midi request pool size
+         //midi_requests (128), // the size of this should match the midi request pool size
+         _send_smpte_update (false),
+         diskstreams (new DiskstreamList),
+         routes (new RouteList),
+         auditioner ((Auditioner*) 0),
+         _click_io ((IO*) 0),
          main_outs (0)
 {
        bool new_session;
 
-       cerr << "Loading session " << fullpath << " using snapshot " << snapshot_name << endl;
+       cerr << "Loading session " << fullpath << " using snapshot " << snapshot_name << " (1)" << endl;
 
        n_physical_outputs = _engine.n_physical_outputs();
        n_physical_inputs =  _engine.n_physical_inputs();
@@ -259,10 +283,12 @@ Session::Session (AudioEngine &eng,
        first_stage_init (fullpath, snapshot_name);
        
        if (create (new_session, mix_template, _engine.frame_rate() * 60 * 5)) {
+               cerr << "create failed\n";
                throw failed_constructor ();
        }
        
        if (second_stage_init (new_session)) {
+               cerr << "2nd state failed\n";
                throw failed_constructor ();
        }
        
@@ -289,17 +315,23 @@ Session::Session (AudioEngine &eng,
                  jack_nframes_t initial_length)
 
        : _engine (eng),
+         _scratch_buffers(new BufferSet()),
+         _silent_buffers(new BufferSet()),
+         _send_buffers(new BufferSet()),
          _mmc_port (default_mmc_port),
          _mtc_port (default_mtc_port),
          _midi_port (default_midi_port),
          pending_events (2048),
-         midi_requests (16),
+         //midi_requests (16),
+         _send_smpte_update (false),
+         diskstreams (new DiskstreamList),
+         routes (new RouteList),
          main_outs (0)
 
 {
        bool new_session;
 
-       cerr << "Loading session " << fullpath << " using snapshot " << snapshot_name << endl;
+       cerr << "Loading session " << fullpath << " using snapshot " << snapshot_name << " (2)" << endl;
 
        n_physical_outputs = max (requested_physical_out, _engine.n_physical_outputs());
        n_physical_inputs = max (requested_physical_in, _engine.n_physical_inputs());
@@ -311,16 +343,18 @@ Session::Session (AudioEngine &eng,
        }
 
        if (control_out_channels) {
-               Route* r;
-               r = new Route (*this, _("monitor"), -1, control_out_channels, -1, control_out_channels, Route::ControlOut);
-               add_route (r);
+               shared_ptr<Route> r (new Route (*this, _("monitor"), -1, control_out_channels, -1, control_out_channels, Route::ControlOut));
+               RouteList rl;
+               rl.push_back (r);
+               add_routes (rl);
                _control_out = r;
        }
 
        if (master_out_channels) {
-               Route* r;
-               r = new Route (*this, _("master"), -1, master_out_channels, -1, master_out_channels, Route::MasterOut);
-               add_route (r);
+               shared_ptr<Route> r (new Route (*this, _("master"), -1, master_out_channels, -1, master_out_channels, Route::MasterOut));
+               RouteList rl;
+               rl.push_back (r);
+               add_routes (rl);
                _master_out = r;
        } else {
                /* prohibit auto-connect to master, because there isn't one */
@@ -355,12 +389,25 @@ Session::~Session ()
 
        _state_of_the_state = StateOfTheState (CannotSave|Deletion);
        _engine.remove_session ();
+
+       GoingAway (); /* EMIT SIGNAL */
        
-       going_away (); /* EMIT SIGNAL */
+       /* do this */
+
+       notify_callbacks ();
+
+       /* clear history so that no references to objects are held any more */
+
+       history.clear ();
+
+       /* clear state tree so that no references to objects are held any more */
        
+       if (state_tree) {
+               delete state_tree;
+       }
+
        terminate_butler_thread ();
-       terminate_midi_thread ();
-       terminate_feedback ();
+       //terminate_midi_thread ();
        
        if (click_data && click_data != default_click) {
                delete [] click_data;
@@ -372,23 +419,12 @@ Session::~Session ()
 
        clear_clicks ();
 
-       if (_click_io) {
-               delete _click_io;
-       }
-
-
-       if (auditioner) {
-               delete auditioner;
-       }
-
-       for (vector<Sample*>::iterator i = _passthru_buffers.begin(); i != _passthru_buffers.end(); ++i) {
-               free(*i);
-       }
-
-       for (vector<Sample*>::iterator i = _silent_buffers.begin(); i != _silent_buffers.end(); ++i) {
-               free(*i);
-       }
+       delete _scratch_buffers;
+       delete _silent_buffers;
+       delete _send_buffers;
 
+       AudioDiskstream::free_working_buffers();
+       
 #undef TRACK_DESTRUCTION
 #ifdef TRACK_DESTRUCTION
        cerr << "delete named selections\n";
@@ -418,58 +454,59 @@ Session::~Session ()
        }
 
 #ifdef TRACK_DESTRUCTION
-       cerr << "delete audio regions\n";
+       cerr << "delete regions\n";
 #endif /* TRACK_DESTRUCTION */
-       for (AudioRegionList::iterator i = audio_regions.begin(); i != audio_regions.end(); ) {
-               AudioRegionList::iterator tmp;
-
-               tmp =i;
-               ++tmp;
-
-               delete (*i).second;
-
-               i = tmp;
+       
+       for (RegionList::iterator i = regions.begin(); i != regions.end(); ++i) {
+               i->second->drop_references ();
        }
+
+       regions.clear ();
        
 #ifdef TRACK_DESTRUCTION
        cerr << "delete routes\n";
 #endif /* TRACK_DESTRUCTION */
-       for (RouteList::iterator i = routes.begin(); i != routes.end(); ) {
-               RouteList::iterator tmp;
-               tmp = i;
-               ++tmp;
-               delete *i;
-               i = tmp;
+        {
+               RCUWriter<RouteList> writer (routes);
+               boost::shared_ptr<RouteList> r = writer.get_copy ();
+               for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
+                       (*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 */
-       for (DiskStreamList::iterator i = diskstreams.begin(); i != diskstreams.end(); ) {
-               DiskStreamList::iterator tmp;
-
-               tmp = i;
-               ++tmp;
-
-               delete *i;
-
-               i = tmp;
-       }
+       {
+              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 sources\n";
+       cerr << "delete audio sources\n";
 #endif /* TRACK_DESTRUCTION */
-       for (SourceList::iterator i = sources.begin(); i != sources.end(); ) {
-               SourceList::iterator tmp;
+       for (SourceMap::iterator i = sources.begin(); i != sources.end(); ) {
+               SourceMap::iterator tmp;
 
                tmp = i;
                ++tmp;
 
-               delete (*i).second;
+               i->second->drop_references ();
 
                i = tmp;
        }
 
+       sources.clear ();
+
 #ifdef TRACK_DESTRUCTION
        cerr << "delete mix groups\n";
 #endif /* TRACK_DESTRUCTION */
@@ -525,14 +562,10 @@ Session::~Session ()
        if (mmc) {
                delete mmc;
        }
-
-       if (state_tree) {
-               delete state_tree;
-       }
 }
 
 void
-Session::set_worst_io_latencies (bool take_lock)
+Session::set_worst_io_latencies ()
 {
        _worst_output_latency = 0;
        _worst_input_latency = 0;
@@ -541,18 +574,12 @@ Session::set_worst_io_latencies (bool take_lock)
                return;
        }
 
-       if (take_lock) {
-               route_lock.read_lock ();
-       }
+       boost::shared_ptr<RouteList> r = routes.reader ();
        
-       for (RouteList::iterator i = routes.begin(); i != routes.end(); ++i) {
+       for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
                _worst_output_latency = max (_worst_output_latency, (*i)->output_latency());
                _worst_input_latency = max (_worst_input_latency, (*i)->input_latency());
        }
-
-       if (take_lock) {
-               route_lock.unlock ();
-       }
 }
 
 void
@@ -569,7 +596,7 @@ Session::when_engine_running ()
 
        /* every time we reconnect, recompute worst case output latencies */
 
-       _engine.Running.connect (sigc::bind (mem_fun (*this, &Session::set_worst_io_latencies), true));
+       _engine.Running.connect (mem_fun (*this, &Session::set_worst_io_latencies));
 
        if (synced_to_jack()) {
                _engine.transport_stop ();
@@ -584,7 +611,7 @@ Session::when_engine_running ()
        try {
                XMLNode* child = 0;
                
-               _click_io = new ClickIO (*this, "click", 0, 0, -1, -1);
+               _click_io.reset (new ClickIO (*this, "click", 0, 0, -1, -1));
 
                if (state_tree && (child = find_named_node (*state_tree->root(), "Click")) != 0) {
 
@@ -604,8 +631,8 @@ Session::when_engine_running ()
                        
                        /* default state for Click */
 
-                       first_physical_output = _engine.get_nth_physical_output (0);
-                       
+                       first_physical_output = _engine.get_nth_physical_output (DataType::AUDIO, 0);
+
                        if (first_physical_output.length()) {
                                if (_click_io->add_output_port (first_physical_output, this)) {
                                        // relax, even though its an error
@@ -620,7 +647,7 @@ Session::when_engine_running ()
                error << _("cannot setup Click I/O") << endmsg;
        }
 
-       set_worst_io_latencies (true);
+       set_worst_io_latencies ();
 
        if (_clicking) {
                 ControlChanged (Clicking); /* EMIT SIGNAL */
@@ -635,7 +662,7 @@ Session::when_engine_running ()
                */
 
                try {
-                       auditioner = new Auditioner (*this);
+                       auditioner.reset (new Auditioner (*this));
                }
 
                catch (failed_constructor& err) {
@@ -656,7 +683,7 @@ Session::when_engine_running ()
                Connection* c = new OutputConnection (buf, true);
 
                c->add_port ();
-               c->add_connection (0, _engine.get_nth_physical_output (np));
+               c->add_connection (0, _engine.get_nth_physical_output (DataType::AUDIO, np));
 
                add_connection (c);
        }
@@ -668,7 +695,7 @@ Session::when_engine_running ()
                Connection* c = new InputConnection (buf, true);
 
                c->add_port ();
-               c->add_connection (0, _engine.get_nth_physical_input (np));
+               c->add_connection (0, _engine.get_nth_physical_input (DataType::AUDIO, np));
 
                add_connection (c);
        }
@@ -683,8 +710,8 @@ Session::when_engine_running ()
 
                c->add_port ();
                c->add_port ();
-               c->add_connection (0, _engine.get_nth_physical_output (np));
-               c->add_connection (1, _engine.get_nth_physical_output (np+1));
+               c->add_connection (0, _engine.get_nth_physical_output (DataType::AUDIO, np));
+               c->add_connection (1, _engine.get_nth_physical_output (DataType::AUDIO, np+1));
 
                add_connection (c);
        }
@@ -697,8 +724,8 @@ Session::when_engine_running ()
 
                c->add_port ();
                c->add_port ();
-               c->add_connection (0, _engine.get_nth_physical_input (np));
-               c->add_connection (1, _engine.get_nth_physical_input (np+1));
+               c->add_connection (0, _engine.get_nth_physical_input (DataType::AUDIO, np));
+               c->add_connection (1, _engine.get_nth_physical_input (DataType::AUDIO, np+1));
 
                add_connection (c);
        }
@@ -722,16 +749,18 @@ Session::when_engine_running ()
                        
                        _master_out->defer_pan_reset ();
                        
-                       while ((int) _master_out->n_inputs() < _master_out->input_maximum()) {
-                               if (_master_out->add_input_port ("", this)) {
+                       while (_master_out->n_inputs().get(DataType::AUDIO)
+                                       < _master_out->input_maximum().get(DataType::AUDIO)) {
+                               if (_master_out->add_input_port ("", this, DataType::AUDIO)) {
                                        error << _("cannot setup master inputs") 
                                              << endmsg;
                                        break;
                                }
                        }
                        n = 0;
-                       while ((int) _master_out->n_outputs() < _master_out->output_maximum()) {
-                               if (_master_out->add_output_port (_engine.get_nth_physical_output (n), this)) {
+                       while (_master_out->n_outputs().get(DataType::AUDIO)
+                                       < _master_out->output_maximum().get(DataType::AUDIO)) {
+                               if (_master_out->add_output_port (_engine.get_nth_physical_output (DataType::AUDIO, n), this, DataType::AUDIO)) {
                                        error << _("cannot setup master outputs")
                                              << endmsg;
                                        break;
@@ -745,7 +774,7 @@ Session::when_engine_running ()
 
                Connection* c = new OutputConnection (_("Master Out"), true);
 
-               for (uint32_t n = 0; n < _master_out->n_inputs (); ++n) {
+               for (uint32_t n = 0; n < _master_out->n_inputs ().get_total(); ++n) {
                        c->add_port ();
                        c->add_connection ((int) n, _master_out->input(n)->name());
                }
@@ -758,7 +787,7 @@ Session::when_engine_running ()
 
        insert_cnt = 0;
        
-       for (slist<PortInsert*>::iterator i = _port_inserts.begin(); i != _port_inserts.end(); ++i) {
+       for (list<PortInsert*>::iterator i = _port_inserts.begin(); i != _port_inserts.end(); ++i) {
                uint32_t id;
 
                if (sscanf ((*i)->name().c_str(), "%*s %u", &id) == 1) {
@@ -770,7 +799,7 @@ Session::when_engine_running ()
 
        send_cnt = 0;
 
-       for (slist<Send*>::iterator i = _sends.begin(); i != _sends.end(); ++i) {
+       for (list<Send*>::iterator i = _sends.begin(); i != _sends.end(); ++i) {
                uint32_t id;
                
                if (sscanf ((*i)->name().c_str(), "%*s %u", &id) == 1) {
@@ -786,6 +815,12 @@ Session::when_engine_running ()
 
        _engine.set_session (this);
 
+#ifdef HAVE_LIBLO
+       /* and to OSC */
+
+       osc->set_session (*this);
+#endif
+
        _state_of_the_state = Clean;
 
        DirtyChanged (); /* EMIT SIGNAL */
@@ -807,7 +842,7 @@ Session::hookup_io ()
        if (_control_out) {
                uint32_t n;
 
-               while ((int) _control_out->n_inputs() < _control_out->input_maximum()) {
+               while (_control_out->n_inputs().get(DataType::AUDIO) < _control_out->input_maximum().get(DataType::AUDIO)) {
                        if (_control_out->add_input_port ("", this)) {
                                error << _("cannot setup control inputs")
                                      << endmsg;
@@ -815,8 +850,8 @@ Session::hookup_io ()
                        }
                }
                n = 0;
-               while ((int) _control_out->n_outputs() < _control_out->output_maximum()) {
-                       if (_control_out->add_output_port (_engine.get_nth_physical_output (n), this)) {
+               while (_control_out->n_outputs().get(DataType::AUDIO) < _control_out->output_maximum().get(DataType::AUDIO)) {
+                       if (_control_out->add_output_port (_engine.get_nth_physical_output (DataType::AUDIO, n), this)) {
                                error << _("cannot set up master outputs")
                                      << endmsg;
                                break;
@@ -863,7 +898,7 @@ Session::playlist_length_changed (Playlist* pl)
 }
 
 void
-Session::diskstream_playlist_changed (DiskStream* dstream)
+Session::diskstream_playlist_changed (boost::shared_ptr<Diskstream> dstream)
 {
        Playlist *playlist;
 
@@ -937,13 +972,10 @@ Session::set_auto_input (bool yn)
                
                if (Config->get_use_hardware_monitoring() && transport_rolling()) {
                        /* auto-input only makes a difference if we're rolling */
+                       
+                       boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
 
-                       /* Even though this can called from RT context we are using
-                          a non-tentative rwlock here,  because the action must occur.
-                          The rarity and short potential lock duration makes this "OK"
-                       */
-                       RWLockMonitor dsm (diskstream_lock, false, __LINE__, __FILE__);
-                       for (DiskStreamList::iterator i = diskstreams.begin(); i != diskstreams.end(); ++i) {
+                       for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
                                if ((*i)->record_enabled ()) {
                                        //cerr << "switching to input = " << !auto_input << __FILE__ << __LINE__ << endl << endl;
                                        (*i)->monitor_input (!auto_input);   
@@ -960,16 +992,19 @@ void
 Session::reset_input_monitor_state ()
 {
        if (transport_rolling()) {
-               RWLockMonitor dsm (diskstream_lock, false, __LINE__, __FILE__);
-               for (DiskStreamList::iterator i = diskstreams.begin(); i != diskstreams.end(); ++i) {
+
+               boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
+
+               for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
                        if ((*i)->record_enabled ()) {
                                //cerr << "switching to input = " << !auto_input << __FILE__ << __LINE__ << endl << endl;
                                (*i)->monitor_input (Config->get_use_hardware_monitoring() && !auto_input);
                        }
                }
        } else {
-               RWLockMonitor dsm (diskstream_lock, false, __LINE__, __FILE__);
-               for (DiskStreamList::iterator i = diskstreams.begin(); i != diskstreams.end(); ++i) {
+               boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
+
+               for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
                        if ((*i)->record_enabled ()) {
                                //cerr << "switching to input = " << !auto_input << __FILE__ << __LINE__ << endl << endl;
                                (*i)->monitor_input (Config->get_use_hardware_monitoring());
@@ -1235,19 +1270,14 @@ void
 Session::enable_record ()
 {
        /* XXX really atomic compare+swap here */
-       if (atomic_read (&_record_status) != Recording) {
-               atomic_set (&_record_status, Recording);
+       if (g_atomic_int_get (&_record_status) != Recording) {
+               g_atomic_int_set (&_record_status, Recording);
                _last_record_location = _transport_frame;
-               send_mmc_in_another_thread (MIDI::MachineControl::cmdRecordStrobe);
+               deliver_mmc(MIDI::MachineControl::cmdRecordStrobe, _last_record_location);
 
                if (Config->get_use_hardware_monitoring() && auto_input) {
-                       /* Even though this can be called from RT context we are using
-                          a non-tentative rwlock here,  because the action must occur.
-                          The rarity and short potential lock duration makes this "OK"
-                       */
-                       RWLockMonitor dsm (diskstream_lock, false, __LINE__, __FILE__);
-                       
-                       for (DiskStreamList::iterator i = diskstreams.begin(); i != diskstreams.end(); ++i) {
+                       boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
+                       for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
                                if ((*i)->record_enabled ()) {
                                        (*i)->monitor_input (true);   
                                }
@@ -1259,30 +1289,30 @@ Session::enable_record ()
 }
 
 void
-Session::disable_record (bool force)
+Session::disable_record (bool rt_context, bool force)
 {
        RecordState rs;
 
-       if ((rs = (RecordState) atomic_read (&_record_status)) != Disabled) {
+       if ((rs = (RecordState) g_atomic_int_get (&_record_status)) != Disabled) {
 
                if (!Config->get_latched_record_enable () || force) {
-                       atomic_set (&_record_status, Disabled);
+                       g_atomic_int_set (&_record_status, Disabled);
                } else {
                        if (rs == Recording) {
-                               atomic_set (&_record_status, Enabled);
+                               g_atomic_int_set (&_record_status, Enabled);
                        }
                }
 
-               send_mmc_in_another_thread (MIDI::MachineControl::cmdRecordExit);
+               // FIXME: timestamp correct? [DR]
+               // FIXME FIXME FIXME: rt_context?  this must be called in the process thread.
+               // does this /need/ to be sent in all cases?
+               if (rt_context)
+                       deliver_mmc (MIDI::MachineControl::cmdRecordExit, _transport_frame);
 
                if (Config->get_use_hardware_monitoring() && auto_input) {
-                       /* Even though this can be called from RT context we are using
-                          a non-tentative rwlock here,  because the action must occur.
-                          The rarity and short potential lock duration makes this "OK"
-                       */
-                       RWLockMonitor dsm (diskstream_lock, false, __LINE__, __FILE__);
+                       boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
                        
-                       for (DiskStreamList::iterator i = diskstreams.begin(); i != diskstreams.end(); ++i) {
+                       for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
                                if ((*i)->record_enabled ()) {
                                        (*i)->monitor_input (false);   
                                }
@@ -1290,23 +1320,22 @@ Session::disable_record (bool force)
                }
                
                RecordStateChanged (); /* emit signal */
-               remove_pending_capture_state ();
+
+               if (!rt_context) {
+                       remove_pending_capture_state ();
+               }
        }
 }
 
 void
 Session::step_back_from_record ()
 {
-       atomic_set (&_record_status, Enabled);
+       g_atomic_int_set (&_record_status, Enabled);
 
        if (Config->get_use_hardware_monitoring()) {
-               /* Even though this can be called from RT context we are using
-                  a non-tentative rwlock here,  because the action must occur.
-                  The rarity and short potential lock duration makes this "OK"
-               */
-               RWLockMonitor dsm (diskstream_lock, false, __LINE__, __FILE__);
+               boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
                
-               for (DiskStreamList::iterator i = diskstreams.begin(); i != diskstreams.end(); ++i) {
+               for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
                        if (auto_input && (*i)->record_enabled ()) {
                                //cerr << "switching from input" << __FILE__ << __LINE__ << endl << endl;
                                (*i)->monitor_input (false);   
@@ -1318,7 +1347,7 @@ Session::step_back_from_record ()
 void
 Session::maybe_enable_record ()
 {
-       atomic_set (&_record_status, Enabled);
+       g_atomic_int_set (&_record_status, Enabled);
 
        /* XXX this save should really happen in another thread. its needed so that
           pending capture state can be recovered if we crash.
@@ -1331,7 +1360,7 @@ Session::maybe_enable_record ()
                        enable_record ();
                } 
        } else {
-               send_mmc_in_another_thread (MIDI::MachineControl::cmdRecordPause);
+               deliver_mmc (MIDI::MachineControl::cmdRecordPause, _transport_frame);
                RecordStateChanged (); /* EMIT SIGNAL */
        }
 
@@ -1411,6 +1440,9 @@ Session::set_frame_rate (jack_nframes_t frames_per_second)
 
        Route::set_automation_interval ((jack_nframes_t) ceil ((double) frames_per_second * 0.25));
 
+       // XXX we need some equivalent to this, somehow
+       // DestructiveFileSource::setup_standard_crossfades (frames_per_second);
+
        set_dirty();
 
        /* XXX need to reset/reinstantiate all LADSPA plugins */
@@ -1426,25 +1458,10 @@ Session::set_block_size (jack_nframes_t nframes)
        */
 
        { 
-               RWLockMonitor lm (route_lock, false, __LINE__, __FILE__);
-               RWLockMonitor dsm (diskstream_lock, false, __LINE__, __FILE__);
-               vector<Sample*>::iterator i;
-               uint32_t np;
                        
                current_block_size = nframes;
                
-               for (np = 0, i = _passthru_buffers.begin(); i != _passthru_buffers.end(); ++i, ++np) {
-                       free (*i);
-               }
-
-               for (vector<Sample*>::iterator i = _silent_buffers.begin(); i != _silent_buffers.end(); ++i) {
-                       free (*i);
-               }
-
-               _passthru_buffers.clear ();
-               _silent_buffers.clear ();
-
-               ensure_passthru_buffers (np);
+               ensure_buffers(_scratch_buffers->available());
 
                if (_gain_automation_buffer) {
                        delete [] _gain_automation_buffer;
@@ -1453,15 +1470,18 @@ Session::set_block_size (jack_nframes_t nframes)
 
                allocate_pan_automation_buffers (nframes, _npan_buffers, true);
 
-               for (RouteList::iterator i = routes.begin(); i != routes.end(); ++i) {
+               boost::shared_ptr<RouteList> r = routes.reader ();
+
+               for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
                        (*i)->set_block_size (nframes);
                }
                
-               for (DiskStreamList::iterator i = diskstreams.begin(); i != diskstreams.end(); ++i) {
+               boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
+               for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
                        (*i)->set_block_size (nframes);
                }
 
-               set_worst_io_latencies (false);
+               set_worst_io_latencies ();
        }
 }
 
@@ -1489,7 +1509,7 @@ Session::set_default_fade (float steepness, float fade_msecs)
 
        {
                // jlc, WTF is this!
-               RWLockMonitor lm (route_lock, false, __LINE__, __FILE__);
+               Glib::RWLock::ReaderLock lm (route_lock);
                AudioRegion::set_default_fade (steepness, fade_frames);
        }
 
@@ -1503,7 +1523,7 @@ Session::set_default_fade (float steepness, float fade_msecs)
 }
 
 struct RouteSorter {
-    bool operator() (Route* r1, Route* r2) {
+    bool operator() (boost::shared_ptr<Route> r1, boost::shared_ptr<Route> r2) {
            if (r1->fed_by.find (r2) != r1->fed_by.end()) {
                    return false;
            } else if (r2->fed_by.find (r1) != r2->fed_by.end()) {
@@ -1525,9 +1545,9 @@ struct RouteSorter {
 };
 
 static void
-trace_terminal (Route* r1, Route* rbase)
+trace_terminal (shared_ptr<Route> r1, shared_ptr<Route> rbase)
 {
-       Route* r2;
+       shared_ptr<Route> r2;
 
        if ((r1->fed_by.find (rbase) != r1->fed_by.end()) && (rbase->fed_by.find (r1) != rbase->fed_by.end())) {
                info << string_compose(_("feedback loop setup between %1 and %2"), r1->name(), rbase->name()) << endmsg;
@@ -1536,13 +1556,13 @@ trace_terminal (Route* r1, Route* rbase)
 
        /* make a copy of the existing list of routes that feed r1 */
 
-       set<Route *> existing = r1->fed_by;
+       set<shared_ptr<Route> > existing = r1->fed_by;
 
        /* for each route that feeds r1, recurse, marking it as feeding
           rbase as well.
        */
 
-       for (set<Route *>::iterator i = existing.begin(); i != existing.end(); ++i) {
+       for (set<shared_ptr<Route> >::iterator i = existing.begin(); i != existing.end(); ++i) {
                r2 =* i;
 
                /* r2 is a route that feeds r1 which somehow feeds base. mark
@@ -1572,7 +1592,7 @@ trace_terminal (Route* r1, Route* rbase)
 }
 
 void
-Session::resort_routes (void* src)
+Session::resort_routes ()
 {
        /* don't do anything here with signals emitted
           by Routes while we are being destroyed.
@@ -1582,304 +1602,445 @@ Session::resort_routes (void* src)
                return;
        }
 
-       /* Caller MUST hold the route_lock */
 
-       RouteList::iterator i, j;
+       {
 
-       for (i = routes.begin(); i != routes.end(); ++i) {
+               RCUWriter<RouteList> writer (routes);
+               shared_ptr<RouteList> r = writer.get_copy ();
+               resort_routes_using (r);
+               /* writer goes out of scope and forces update */
+       }
 
+}
+void
+Session::resort_routes_using (shared_ptr<RouteList> r)
+{
+       RouteList::iterator i, j;
+       
+       for (i = r->begin(); i != r->end(); ++i) {
+               
                (*i)->fed_by.clear ();
                
-               for (j = routes.begin(); j != routes.end(); ++j) {
-
+               for (j = r->begin(); j != r->end(); ++j) {
+                       
                        /* although routes can feed themselves, it will
                           cause an endless recursive descent if we
                           detect it. so don't bother checking for
                           self-feeding.
                        */
-
+                       
                        if (*j == *i) {
                                continue;
                        }
-
+                       
                        if ((*j)->feeds (*i)) {
                                (*i)->fed_by.insert (*j);
                        } 
                }
        }
        
-       for (i = routes.begin(); i != routes.end(); ++i) {
+       for (i = r->begin(); i != r->end(); ++i) {
                trace_terminal (*i, *i);
        }
-
+       
        RouteSorter cmp;
-       routes.sort (cmp);
-
+       r->sort (cmp);
+       
 #if 0
        cerr << "finished route resort\n";
        
-       for (i = routes.begin(); i != routes.end(); ++i) {
+       for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
                cerr << " " << (*i)->name() << " signal order = " << (*i)->order_key ("signal") << endl;
        }
        cerr << endl;
 #endif
-
+       
 }
 
-AudioTrack*
-Session::new_audio_track (int input_channels, int output_channels, TrackMode mode)
+list<boost::shared_ptr<MidiTrack> >
+Session::new_midi_track (TrackMode mode, uint32_t how_many)
 {
-       AudioTrack *track;
        char track_name[32];
+       uint32_t track_id = 0;
        uint32_t n = 0;
        uint32_t channels_used = 0;
        string port;
-       uint32_t nphysical_in;
-       uint32_t nphysical_out;
+       RouteList new_routes;
+       list<boost::shared_ptr<MidiTrack> > ret;
 
-       /* count existing audio tracks */
+       /* count existing midi tracks */
 
        {
-               RWLockMonitor lm (route_lock, false, __LINE__, __FILE__);
-               for (RouteList::iterator i = routes.begin(); i != routes.end(); ++i) {
-                       if (dynamic_cast<AudioTrack*>(*i) != 0) {
+               shared_ptr<RouteList> r = routes.reader ();
+
+               for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
+                       if (dynamic_cast<MidiTrack*>((*i).get()) != 0) {
                                if (!(*i)->hidden()) {
                                        n++;
-                                       channels_used += (*i)->n_inputs();
+                                       channels_used += (*i)->n_inputs().get(DataType::MIDI);
                                }
                        }
                }
        }
 
-       /* check for duplicate route names, since we might have pre-existing
-          routes with this name (e.g. create Audio1, Audio2, delete Audio1,
-          save, close,restart,add new route - first named route is now
-          Audio2)
-       */
+       while (how_many) {
 
-       do {
-               snprintf (track_name, sizeof(track_name), "Audio %" PRIu32, n+1);
-               if (route_by_name (track_name) == 0) {
-                       break;
-               }
-               n++;
+               /* check for duplicate route names, since we might have pre-existing
+                  routes with this name (e.g. create Midi1, Midi2, delete Midi1,
+                  save, close,restart,add new route - first named route is now
+                  Midi2)
+               */
+               
 
-       } while (n < (UINT_MAX-1));
+               do {
+                       ++track_id;
 
-       if (input_auto_connect & AutoConnectPhysical) {
-               nphysical_in = n_physical_inputs;
-       } else {
-               nphysical_in = 0;
+                       snprintf (track_name, sizeof(track_name), "Midi %" PRIu32, track_id);
+
+                       if (route_by_name (track_name) == 0) {
+                               break;
+                       }
+                       
+               } while (track_id < (UINT_MAX-1));
+
+               try {
+                       shared_ptr<MidiTrack> track (new MidiTrack (*this, track_name, Route::Flag (0), mode));
+                       
+                       if (track->ensure_io (ChanCount(DataType::MIDI, 1), ChanCount(DataType::MIDI, 1), false, this)) {
+                               error << "cannot configure 1 in/1 out configuration for new midi track" << endmsg;
+                       }
+                       
+                       channels_used += track->n_inputs ().get(DataType::MIDI);
+
+                       track->DiskstreamChanged.connect (mem_fun (this, &Session::resort_routes));
+                       track->set_remote_control_id (ntracks());
+
+                       new_routes.push_back (track);
+                       ret.push_back (track);
+               }
+
+               catch (failed_constructor &err) {
+                       error << _("Session: could not create new midi track.") << endmsg;
+                       // XXX should we delete the tracks already created? 
+                       ret.clear ();
+                       return ret;
+               }
+               
+               --how_many;
        }
 
-       if (output_auto_connect & AutoConnectPhysical) {
-               nphysical_out = n_physical_outputs;
-       } else {
-               nphysical_out = 0;
+       if (!new_routes.empty()) {
+               add_routes (new_routes, false);
+               save_state (_current_snapshot_name);
        }
 
-       try {
-               track = new AudioTrack (*this, track_name, Route::Flag (0), mode);
+       return ret;
+}
 
-               if (track->ensure_io (input_channels, output_channels, false, this)) {
-                       error << string_compose (_("cannot configure %1 in/%2 out configuration for new audio track"),
-                                         input_channels, output_channels)
-                             << endmsg;
+list<boost::shared_ptr<AudioTrack> >
+Session::new_audio_track (int input_channels, int output_channels, TrackMode mode, uint32_t how_many)
+{
+       char track_name[32];
+       uint32_t track_id = 0;
+       uint32_t n = 0;
+       uint32_t channels_used = 0;
+       string port;
+       RouteList new_routes;
+       list<boost::shared_ptr<AudioTrack> > ret;
+
+       /* count existing audio tracks */
+
+       {
+               shared_ptr<RouteList> r = routes.reader ();
+
+               for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
+                       if (dynamic_cast<AudioTrack*>((*i).get()) != 0) {
+                               if (!(*i)->hidden()) {
+                                       n++;
+                                       channels_used += (*i)->n_inputs().get(DataType::AUDIO);
+                               }
+                       }
                }
+       }
+
+       vector<string> physinputs;
+       vector<string> physoutputs;
+       uint32_t nphysical_in;
+       uint32_t nphysical_out;
+
+       _engine.get_physical_outputs (physoutputs);
+       _engine.get_physical_inputs (physinputs);
+
+       while (how_many) {
+
+               /* check for duplicate route names, since we might have pre-existing
+                  routes with this name (e.g. create Audio1, Audio2, delete Audio1,
+                  save, close,restart,add new route - first named route is now
+                  Audio2)
+               */
+               
+
+               do {
+                       ++track_id;
+
+                       snprintf (track_name, sizeof(track_name), "Audio %" PRIu32, track_id);
 
-               if (nphysical_in) {
-                       for (uint32_t x = 0; x < track->n_inputs() && x < nphysical_in; ++x) {
+                       if (route_by_name (track_name) == 0) {
+                               break;
+                       }
+                       
+               } while (track_id < (UINT_MAX-1));
+
+               if (input_auto_connect & AutoConnectPhysical) {
+                       nphysical_in = min (n_physical_inputs, (uint32_t) physinputs.size());
+               } else {
+                       nphysical_in = 0;
+               }
+               
+               if (output_auto_connect & AutoConnectPhysical) {
+                       nphysical_out = min (n_physical_outputs, (uint32_t) physinputs.size());
+               } else {
+                       nphysical_out = 0;
+               }
+               
+               try {
+                       shared_ptr<AudioTrack> track (new AudioTrack (*this, track_name, Route::Flag (0), mode));
+                       
+                       if (track->ensure_io (ChanCount(DataType::AUDIO, input_channels), ChanCount(DataType::AUDIO, output_channels), false, this)) {
+                               error << string_compose (_("cannot configure %1 in/%2 out configuration for new audio track"),
+                                                        input_channels, output_channels)
+                                     << endmsg;
+                       }
+                       
+                       if (nphysical_in) {
+                               for (uint32_t x = 0; x < track->n_inputs().get(DataType::AUDIO) && x < nphysical_in; ++x) {
+                                       
+                                       port = "";
+                                       
+                                       if (input_auto_connect & AutoConnectPhysical) {
+                                               port = physinputs[(channels_used+x)%nphysical_in];
+                                       } 
+                                       
+                                       if (port.length() && track->connect_input (track->input (x), port, this)) {
+                                               break;
+                                       }
+                               }
+                       }
+                       
+                       for (uint32_t x = 0; x < track->n_outputs().get(DataType::MIDI); ++x) {
                                
                                port = "";
                                
-                               if (input_auto_connect & AutoConnectPhysical) {
-                                       port = _engine.get_nth_physical_input ((channels_used+x)%nphysical_in);
-                               } 
+                               if (nphysical_out && (output_auto_connect & AutoConnectPhysical)) {
+                                       port = physoutputs[(channels_used+x)%nphysical_out];
+                               } else if (output_auto_connect & AutoConnectMaster) {
+                                       if (_master_out) {
+                                               port = _master_out->input (x%_master_out->n_inputs().get(DataType::AUDIO))->name();
+                                       }
+                               }
                                
-                               if (port.length() && track->connect_input (track->input (x), port, this)) {
+                               if (port.length() && track->connect_output (track->output (x), port, this)) {
                                        break;
                                }
                        }
-               }
-               
-               for (uint32_t x = 0; x < track->n_outputs(); ++x) {
                        
-                       port = "";
+                       channels_used += track->n_inputs ().get(DataType::AUDIO);
 
-                       if (nphysical_out && (output_auto_connect & AutoConnectPhysical)) {
-                               port = _engine.get_nth_physical_output ((channels_used+x)%nphysical_out);
-                       } else if (output_auto_connect & AutoConnectMaster) {
-                               if (_master_out) {
-                                       port = _master_out->input (x%_master_out->n_inputs())->name();
+                       if (_control_out) {
+                               vector<string> cports;
+                               uint32_t ni = _control_out->n_inputs().get(DataType::AUDIO);
+                               
+                               for (n = 0; n < ni; ++n) {
+                                       cports.push_back (_control_out->input(n)->name());
                                }
+                               
+                               track->set_control_outs (cports);
                        }
+                       
+                       track->DiskstreamChanged.connect (mem_fun (this, &Session::resort_routes));
+                       track->set_remote_control_id (ntracks());
 
-                       if (port.length() && track->connect_output (track->output (x), port, this)) {
-                               break;
-                       }
+                       new_routes.push_back (track);
+                       ret.push_back (track);
                }
 
-               if (_control_out) {
-                       vector<string> cports;
-                       uint32_t ni = _control_out->n_inputs();
-
-                       for (n = 0; n < ni; ++n) {
-                               cports.push_back (_control_out->input(n)->name());
-                       }
-
-                       track->set_control_outs (cports);
+               catch (failed_constructor &err) {
+                       error << _("Session: could not create new audio track.") << endmsg;
+                       // XXX should we delete the tracks already created? 
+                       ret.clear ();
+                       return ret;
                }
-
-               track->diskstream_changed.connect (mem_fun (this, &Session::resort_routes));
-
-               add_route (track);
-
-               track->set_remote_control_id (ntracks());
+               
+               --how_many;
        }
 
-       catch (failed_constructor &err) {
-               error << _("Session: could not create new audio track.") << endmsg;
-               return 0;
+       if (!new_routes.empty()) {
+               add_routes (new_routes, false);
+               save_state (_current_snapshot_name);
        }
 
-       return track;
+       return ret;
 }
 
-Route*
-Session::new_audio_route (int input_channels, int output_channels)
+Session::RouteList
+Session::new_audio_route (int input_channels, int output_channels, uint32_t how_many)
 {
-       Route *bus;
        char bus_name[32];
+       uint32_t bus_id = 1;
        uint32_t n = 0;
        string port;
+       RouteList ret;
 
        /* count existing audio busses */
 
        {
-               RWLockMonitor lm (route_lock, false, __LINE__, __FILE__);
-               for (RouteList::iterator i = routes.begin(); i != routes.end(); ++i) {
-                       if (dynamic_cast<AudioTrack*>(*i) == 0) {
+               shared_ptr<RouteList> r = routes.reader ();
+
+               for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
+                       if (dynamic_cast<AudioTrack*>((*i).get()) == 0) {
                                if (!(*i)->hidden()) {
-                                       n++;
+                                       bus_id++;
                                }
                        }
                }
        }
 
-       do {
-               snprintf (bus_name, sizeof(bus_name), "Bus %" PRIu32, n+1);
-               if (route_by_name (bus_name) == 0) {
-                       break;
-               }
-               n++;
+       vector<string> physinputs;
+       vector<string> physoutputs;
 
-       } while (n < (UINT_MAX-1));
+       _engine.get_physical_outputs (physoutputs);
+       _engine.get_physical_inputs (physinputs);
 
-       try {
-               bus = new Route (*this, bus_name, -1, -1, -1, -1);
+       while (how_many) {
 
-               if (bus->ensure_io (input_channels, output_channels, false, this)) {
-                       error << string_compose (_("cannot configure %1 in/%2 out configuration for new audio track"),
-                                         input_channels, output_channels)
-                             << endmsg;
-               }
+               do {
+                       ++bus_id;
 
-               for (uint32_t x = 0; x < bus->n_inputs(); ++x) {
-                       
-                       port = "";
+                       snprintf (bus_name, sizeof(bus_name), "Bus %" PRIu32, bus_id);
 
-                       if (input_auto_connect & AutoConnectPhysical) {
-                               port = _engine.get_nth_physical_input ((n+x)%n_physical_inputs);
-                       } 
-                       
-                       if (port.length() && bus->connect_input (bus->input (x), port, this)) {
+                       if (route_by_name (bus_name) == 0) {
                                break;
                        }
-               }
 
-               for (uint32_t x = 0; x < bus->n_outputs(); ++x) {
-                       
-                       port = "";
+               } while (bus_id < (UINT_MAX-1));
 
-                       if (output_auto_connect & AutoConnectPhysical) {
-                               port = _engine.get_nth_physical_input ((n+x)%n_physical_outputs);
-                       } else if (output_auto_connect & AutoConnectMaster) {
-                               if (_master_out) {
-                                       port = _master_out->input (x%_master_out->n_inputs())->name();
+               try {
+                       shared_ptr<Route> bus (new Route (*this, bus_name, -1, -1, -1, -1, Route::Flag(0), DataType::AUDIO));
+                       
+                       if (bus->ensure_io (ChanCount(DataType::AUDIO, input_channels), ChanCount(DataType::AUDIO, output_channels), false, this)) {
+                               error << string_compose (_("cannot configure %1 in/%2 out configuration for new audio track"),
+                                                        input_channels, output_channels)
+                                     << endmsg;
+                       }
+                       
+                       for (uint32_t x = 0; x < bus->n_inputs().get(DataType::AUDIO); ++x) {
+                               
+                               port = "";
+                               
+                               if (input_auto_connect & AutoConnectPhysical) {
+                                       port = physinputs[((n+x)%n_physical_inputs)];
+                               } 
+                               
+                               if (port.length() && bus->connect_input (bus->input (x), port, this)) {
+                                       break;
                                }
                        }
-
-                       if (port.length() && bus->connect_output (bus->output (x), port, this)) {
-                               break;
+                       
+                       for (uint32_t x = 0; x < bus->n_outputs().get(DataType::AUDIO); ++x) {
+                               
+                               port = "";
+                               
+                               if (output_auto_connect & AutoConnectPhysical) {
+                                       port = physoutputs[((n+x)%n_physical_outputs)];
+                               } else if (output_auto_connect & AutoConnectMaster) {
+                                       if (_master_out) {
+                                               port = _master_out->input (x%_master_out->n_inputs().get(DataType::AUDIO))->name();
+                                       }
+                               }
+                               
+                               if (port.length() && bus->connect_output (bus->output (x), port, this)) {
+                                       break;
+                               }
+                       }
+                       
+                       if (_control_out) {
+                               vector<string> cports;
+                               uint32_t ni = _control_out->n_inputs().get(DataType::AUDIO);
+                               
+                               for (uint32_t n = 0; n < ni; ++n) {
+                                       cports.push_back (_control_out->input(n)->name());
+                               }
+                               bus->set_control_outs (cports);
                        }
-               }
 
-               if (_control_out) {
-                       vector<string> cports;
-                       uint32_t ni = _control_out->n_inputs();
+                       ret.push_back (bus);
+               }
+       
 
-                       for (uint32_t n = 0; n < ni; ++n) {
-                               cports.push_back (_control_out->input(n)->name());
-                       }
-                       bus->set_control_outs (cports);
+               catch (failed_constructor &err) {
+                       error << _("Session: could not create new audio route.") << endmsg;
+                       ret.clear ();
+                       return ret;
                }
-               
-               add_route (bus);
+
+               --how_many;
        }
 
-       catch (failed_constructor &err) {
-               error << _("Session: could not create new route.") << endmsg;
-               return 0;
+       if (!ret.empty()) {
+               add_routes (ret, false);
+               save_state (_current_snapshot_name);
        }
 
-       return bus;
+       return ret;
+
 }
 
 void
-Session::add_route (Route* route)
+Session::add_routes (RouteList& new_routes, bool save)
 {
        { 
-               RWLockMonitor lm (route_lock, true, __LINE__, __FILE__);
-               routes.push_front (route);
-               resort_routes(0);
-       }
-
-       route->solo_changed.connect (sigc::bind (mem_fun (*this, &Session::route_solo_changed), route));
-       route->mute_changed.connect (mem_fun (*this, &Session::route_mute_changed));
-       route->output_changed.connect (mem_fun (*this, &Session::set_worst_io_latencies_x));
-       route->redirects_changed.connect (mem_fun (*this, &Session::update_latency_compensation_proxy));
-
-       if (route->master()) {
-               _master_out = route;
+               RCUWriter<RouteList> writer (routes);
+               shared_ptr<RouteList> r = writer.get_copy ();
+               r->insert (r->end(), new_routes.begin(), new_routes.end());
+               resort_routes_using (r);
        }
 
-       if (route->control()) {
-               _control_out = route;
+       for (RouteList::iterator x = new_routes.begin(); x != new_routes.end(); ++x) {
+               (*x)->solo_changed.connect (sigc::bind (mem_fun (*this, &Session::route_solo_changed), (*x)));
+               (*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)->redirects_changed.connect (mem_fun (*this, &Session::update_latency_compensation_proxy));
+               
+               if ((*x)->master()) {
+                       _master_out = (*x);
+               }
+               
+               if ((*x)->control()) {
+                       _control_out = (*x);
+               }
        }
 
        set_dirty();
-       save_state (_current_snapshot_name);
 
-       RouteAdded (route); /* EMIT SIGNAL */
+       if (save) {
+               save_state (_current_snapshot_name);
+       }
+
+       RouteAdded (new_routes); /* EMIT SIGNAL */
 }
 
 void
-Session::add_diskstream (DiskStream* dstream)
+Session::add_diskstream (boost::shared_ptr<Diskstream> dstream)
 {
        /* need to do this in case we're rolling at the time, to prevent false underruns */
-       dstream->do_refill(0, 0);
+       dstream->do_refill_with_alloc();
        
        { 
-               RWLockMonitor lm (diskstream_lock, true, __LINE__, __FILE__);
-               diskstreams.push_back (dstream);
+               RCUWriter<DiskstreamList> writer (diskstreams);
+               boost::shared_ptr<DiskstreamList> ds = writer.get_copy();
+               ds->push_back (dstream);
        }
 
-       /* take a reference to the diskstream, preventing it from
-          ever being deleted until the session itself goes away,
-          or chooses to remove it for its own purposes.
-       */
-
-       dstream->ref();
        dstream->set_block_size (current_block_size);
 
        dstream->PlaylistChanged.connect (sigc::bind (mem_fun (*this, &Session::diskstream_playlist_changed), dstream));
@@ -1887,56 +2048,59 @@ Session::add_diskstream (DiskStream* dstream)
        diskstream_playlist_changed (dstream);
 
        dstream->prepare ();
-
-       set_dirty();
-       save_state (_current_snapshot_name);
-
-       DiskStreamAdded (dstream); /* EMIT SIGNAL */
 }
 
 void
-Session::remove_route (Route& route)
+Session::remove_route (shared_ptr<Route> route)
 {
        {       
-               RWLockMonitor lm (route_lock, true, __LINE__, __FILE__);
-               routes.remove (&route);
+               RCUWriter<RouteList> writer (routes);
+               shared_ptr<RouteList> rs = writer.get_copy ();
+               rs->remove (route);
                
                /* deleting the master out seems like a dumb
                   idea, but its more of a UI policy issue
                   than our concern.
                */
 
-               if (&route == _master_out) {
-                       _master_out = 0;
+               if (route == _master_out) {
+                       _master_out = shared_ptr<Route> ((Route*) 0);
                }
 
-               if (&route == _control_out) {
-                       _control_out = 0;
+               if (route == _control_out) {
+                       _control_out = shared_ptr<Route> ((Route*) 0);
 
                        /* cancel control outs for all routes */
 
                        vector<string> empty;
 
-                       for (RouteList::iterator r = routes.begin(); r != routes.end(); ++r) {
+                       for (RouteList::iterator r = rs->begin(); r != rs->end(); ++r) {
                                (*r)->set_control_outs (empty);
                        }
                }
 
                update_route_solo_state ();
+               
+               /* writer goes out of scope, forces route list update */
        }
 
-       {
-               RWLockMonitor lm (diskstream_lock, true, __LINE__, __FILE__);
-
-               AudioTrack* at;
+       Track* t;
+       boost::shared_ptr<Diskstream> ds;
+       
+       if ((t = dynamic_cast<Track*>(route.get())) != 0) {
+               ds = t->diskstream();
+       }
+       
+       if (ds) {
 
-               if ((at = dynamic_cast<AudioTrack*>(&route)) != 0) {
-                       diskstreams.remove (&at->disk_stream());
-                       at->disk_stream().unref ();
+               {
+                       RCUWriter<DiskstreamList> dsl (diskstreams);
+                       boost::shared_ptr<DiskstreamList> d = dsl.get_copy();
+                       d->remove (ds);
                }
-
-               find_current_end ();
        }
+
+       find_current_end ();
        
        update_latency_compensation (false, false);
        set_dirty();
@@ -1945,7 +2109,9 @@ Session::remove_route (Route& route)
 
        save_state (_current_snapshot_name);
 
-       delete &route;
+       /* try to cause everyone to drop their references */
+
+       route->drop_references ();
 }      
 
 void
@@ -1955,19 +2121,20 @@ Session::route_mute_changed (void* src)
 }
 
 void
-Session::route_solo_changed (void* src, Route* route)
+Session::route_solo_changed (void* src, shared_ptr<Route> route)
 {      
        if (solo_update_disabled) {
                // We know already
                return;
        }
        
-       RWLockMonitor lm (route_lock, false, __LINE__, __FILE__);
        bool is_track;
        
-       is_track = (dynamic_cast<AudioTrack*>(route) != 0);
+       is_track = (dynamic_cast<Track*>(route.get()) != 0);
        
-       for (RouteList::iterator i = routes.begin(); i != routes.end(); ++i) {
+       shared_ptr<RouteList> r = routes.reader ();
+
+       for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
                
                /* soloing a track mutes all other tracks, soloing a bus mutes all other busses */
                
@@ -1975,7 +2142,7 @@ Session::route_solo_changed (void* src, Route* route)
                        
                        /* don't mess with busses */
                        
-                       if (dynamic_cast<AudioTrack*>(*i) == 0) {
+                       if (dynamic_cast<Track*>((*i).get()) == 0) {
                                continue;
                        }
                        
@@ -1983,7 +2150,7 @@ Session::route_solo_changed (void* src, Route* route)
                        
                        /* don't mess with tracks */
                        
-                       if (dynamic_cast<AudioTrack*>(*i) != 0) {
+                       if (dynamic_cast<Track*>((*i).get()) != 0) {
                                continue;
                        }
                }
@@ -2016,10 +2183,10 @@ Session::route_solo_changed (void* src, Route* route)
        bool same_thing_soloed = false;
        bool signal = false;
 
-        for (RouteList::iterator i = routes.begin(); i != routes.end(); ++i) {
+        for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
                if ((*i)->soloed()) {
                        something_soloed = true;
-                       if (dynamic_cast<AudioTrack*>(*i)) {
+                       if (dynamic_cast<Track*>((*i).get())) {
                                if (is_track) {
                                        same_thing_soloed = true;
                                        break;
@@ -2070,11 +2237,13 @@ Session::update_route_solo_state ()
        /* this is where we actually implement solo by changing
           the solo mute setting of each track.
        */
-               
-        for (RouteList::iterator i = routes.begin(); i != routes.end(); ++i) {
+       
+       shared_ptr<RouteList> r = routes.reader ();
+
+        for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
                if ((*i)->soloed()) {
                        mute = true;
-                       if (dynamic_cast<AudioTrack*>(*i)) {
+                       if (dynamic_cast<Track*>((*i).get())) {
                                is_track = true;
                        }
                        break;
@@ -2090,7 +2259,7 @@ Session::update_route_solo_state ()
 
                /* nothing is soloed */
 
-               for (RouteList::iterator i = routes.begin(); i != routes.end(); ++i) {
+               for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
                        (*i)->set_solo_mute (false);
                }
                
@@ -2111,13 +2280,15 @@ Session::update_route_solo_state ()
 void
 Session::modify_solo_mute (bool is_track, bool mute)
 {
-        for (RouteList::iterator i = routes.begin(); i != routes.end(); ++i) {
+       shared_ptr<RouteList> r = routes.reader ();
+
+        for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
                
                if (is_track) {
                        
                        /* only alter track solo mute */
                        
-                       if (dynamic_cast<AudioTrack*>(*i)) {
+                       if (dynamic_cast<Track*>((*i).get())) {
                                if ((*i)->soloed()) {
                                        (*i)->set_solo_mute (!mute);
                                } else {
@@ -2129,7 +2300,7 @@ Session::modify_solo_mute (bool is_track, bool mute)
 
                        /* only alter bus solo mute */
 
-                       if (!dynamic_cast<AudioTrack*>(*i)) {
+                       if (!dynamic_cast<Track*>((*i).get())) {
 
                                if ((*i)->soloed()) {
 
@@ -2161,45 +2332,60 @@ Session::catch_up_on_solo ()
           basis, but needs the global overview that only the session
           has.
        */
-        RWLockMonitor lm (route_lock, false, __LINE__, __FILE__);
        update_route_solo_state();
 }      
                
-Route *
+shared_ptr<Route>
 Session::route_by_name (string name)
 {
-       RWLockMonitor lm (route_lock, false, __LINE__, __FILE__);
+       shared_ptr<RouteList> r = routes.reader ();
 
-       for (RouteList::iterator i = routes.begin(); i != routes.end(); ++i) {
+       for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
                if ((*i)->name() == name) {
-                       returni;
+                       return *i;
                }
        }
 
-       return 0;
+       return shared_ptr<Route> ((Route*) 0);
+}
+
+shared_ptr<Route>
+Session::route_by_id (PBD::ID id)
+{
+       shared_ptr<RouteList> r = routes.reader ();
+
+       for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
+               if ((*i)->id() == id) {
+                       return *i;
+               }
+       }
+
+       return shared_ptr<Route> ((Route*) 0);
+}
+
+shared_ptr<Route>
+Session::route_by_remote_id (uint32_t id)
+{
+       shared_ptr<RouteList> r = routes.reader ();
+
+       for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
+               if ((*i)->remote_control_id() == id) {
+                       return *i;
+               }
+       }
+
+       return shared_ptr<Route> ((Route*) 0);
 }
 
 void
 Session::find_current_end ()
 {
-       jack_nframes_t max = 0;
-       jack_nframes_t me; 
-
        if (_state_of_the_state & Loading) {
                return;
        }
 
-       /* Don't take the diskstream lock. Caller must have other ways to
-          ensure atomicity.
-       */
+       jack_nframes_t max = get_maximum_extent ();
 
-       for (DiskStreamList::iterator i = diskstreams.begin(); i != diskstreams.end(); ++i) {
-               Playlist* pl = (*i)->playlist();
-               if ((me = pl->get_maximum_extent()) > max) {
-                       max = me;
-               }
-       }
-       
        if (max > end_location->end()) {
                end_location->set_end (max);
                set_dirty();
@@ -2207,35 +2393,53 @@ Session::find_current_end ()
        }
 }
 
-DiskStream *
+jack_nframes_t
+Session::get_maximum_extent () const
+{
+       jack_nframes_t max = 0;
+       jack_nframes_t me; 
+
+       boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
+
+       for (DiskstreamList::const_iterator i = dsl->begin(); i != dsl->end(); ++i) {
+               Playlist* pl = (*i)->playlist();
+               if ((me = pl->get_maximum_extent()) > max) {
+                       max = me;
+               }
+       }
+
+       return max;
+}
+
+boost::shared_ptr<Diskstream>
 Session::diskstream_by_name (string name)
 {
-       RWLockMonitor lm (diskstream_lock, false, __LINE__, __FILE__);
+       boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
 
-       for (DiskStreamList::iterator i = diskstreams.begin(); i != diskstreams.end(); ++i) {
+       for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
                if ((*i)->name() == name) {
-                       returni;
+                       return *i;
                }
        }
 
-       return 0;
+       return boost::shared_ptr<Diskstream>((Diskstream*) 0);
 }
 
-DiskStream *
-Session::diskstream_by_id (id_t id)
+boost::shared_ptr<Diskstream>
+Session::diskstream_by_id (const PBD::ID& id)
 {
-       RWLockMonitor lm (diskstream_lock, false, __LINE__, __FILE__);
+       boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
 
-       for (DiskStreamList::iterator i = diskstreams.begin(); i != diskstreams.end(); ++i) {
+       for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
                if ((*i)->id() == id) {
                        return *i;
                }
        }
 
-       return 0;
+       return boost::shared_ptr<Diskstream>((Diskstream*) 0);
 }
 
-/* AudioRegion management */
+/* Region management */
 
 string
 Session::new_region_name (string old)
@@ -2261,7 +2465,7 @@ Session::new_region_name (string old)
 
        while (number < (UINT_MAX-1)) {
 
-               AudioRegionList::const_iterator i;
+               RegionList::const_iterator i;
                string sbuf;
 
                number++;
@@ -2269,13 +2473,13 @@ Session::new_region_name (string old)
                snprintf (buf, len, "%s%" PRIu32, old.substr (0, last_period + 1).c_str(), number);
                sbuf = buf;
 
-               for (i = audio_regions.begin(); i != audio_regions.end(); ++i) {
-                       if ((*i).second->name() == sbuf) {
+               for (i = regions.begin(); i != regions.end(); ++i) {
+                       if (i->second->name() == sbuf) {
                                break;
                        }
                }
                
-               if (i == audio_regions.end()) {
+               if (i == regions.end()) {
                        break;
                }
        }
@@ -2294,11 +2498,13 @@ Session::region_name (string& result, string base, bool newlevel) const
        char buf[16];
        string subbase;
 
+       assert(base.find("/") == string::npos);
+
        if (base == "") {
                
-               LockMonitor lm (region_lock, __LINE__, __FILE__);
+               Glib::Mutex::Lock lm (region_lock);
 
-               snprintf (buf, sizeof (buf), "%d", (int)audio_regions.size() + 1);
+               snprintf (buf, sizeof (buf), "%d", (int)regions.size() + 1);
 
                
                result = "region.";
@@ -2313,19 +2519,18 @@ Session::region_name (string& result, string base, bool newlevel) const
                } else {
                        string::size_type pos;
 
-                       if ((pos = base.find_last_of ('-')) == string::npos) {
-                               pos = base.find_last_of ('.');
-                       }
+                       pos = base.find_last_of ('.');
 
                        /* pos may be npos, but then we just use entire base */
 
                        subbase = base.substr (0, pos);
+
                }
-               
+
                bool name_taken = true;
                
                {
-                       LockMonitor lm (region_lock, __LINE__, __FILE__);
+                       Glib::Mutex::Lock lm (region_lock);
                        
                        for (int n = 1; n < 5000; ++n) {
                                
@@ -2335,8 +2540,8 @@ Session::region_name (string& result, string base, bool newlevel) const
                                
                                name_taken = false;
                                
-                               for (AudioRegionList::const_iterator i = audio_regions.begin(); i != audio_regions.end(); ++i) {
-                                       if ((*i).second->name() == result) {
+                               for (RegionList::const_iterator i = regions.begin(); i != regions.end(); ++i) {
+                                       if (i->second->name() == result) {
                                                name_taken = true;
                                                break;
                                        }
@@ -2353,57 +2558,46 @@ Session::region_name (string& result, string base, bool newlevel) const
                        /*NOTREACHED*/
                }
        }
-
        return 0;
 }      
 
 void
-Session::add_region (Region* region)
+Session::add_region (boost::shared_ptr<Region> region)
 {
-       AudioRegion* ar = 0;
-       AudioRegion* oar = 0;
+       boost::shared_ptr<Region> other;
        bool added = false;
 
        { 
-               LockMonitor lm (region_lock, __LINE__, __FILE__);
-
-               if ((ar = dynamic_cast<AudioRegion*> (region)) != 0) {
+               Glib::Mutex::Lock lm (region_lock);
 
-                       AudioRegionList::iterator x;
+               RegionList::iterator x;
 
-                       for (x = audio_regions.begin(); x != audio_regions.end(); ++x) {
+               for (x = regions.begin(); x != regions.end(); ++x) {
 
-                               oar = dynamic_cast<AudioRegion*> (x->second);
+                       other = x->second;
 
-                               if (ar->region_list_equivalent (*oar)) {
-                                       break;
-                               }
+                       if (region->region_list_equivalent (other)) {
+                               break;
                        }
+               }
 
-                       if (x == audio_regions.end()) {
+               if (x == regions.end()) {
 
-                               pair<AudioRegionList::key_type, AudioRegionList::mapped_type> entry;
-       
-                               entry.first = region->id();
-                               entry.second = ar;
+                       pair<RegionList::key_type,RegionList::mapped_type> entry;
 
-                               pair<AudioRegionList::iterator,bool> x = audio_regions.insert (entry);
-                               
-                               if (!x.second) {
-                                       return;
-                               }
+                       entry.first = region->id();
+                       entry.second = region;
 
-                               added = true;
-                       } 
+                       pair<RegionList::iterator,bool> x = regions.insert (entry);
 
-               } else {
 
-                       fatal << _("programming error: ")
-                             << X_("unknown region type passed to Session::add_region()")
-                             << endmsg;
-                       /*NOTREACHED*/
+                       if (!x.second) {
+                               return;
+                       }
+
+                       added = true;
+               } 
 
-               }
        }
 
        /* mark dirty because something has changed even if we didn't
@@ -2413,14 +2607,14 @@ Session::add_region (Region* region)
        set_dirty();
        
        if (added) {
-               region->GoingAway.connect (mem_fun (*this, &Session::remove_region));
+               region->GoingAway.connect (sigc::bind (mem_fun (*this, &Session::remove_region), region));
                region->StateChanged.connect (sigc::bind (mem_fun (*this, &Session::region_changed), region));
-               AudioRegionAdded (ar); /* EMIT SIGNAL */
+               RegionAdded (region); /* EMIT SIGNAL */
        }
 }
 
 void
-Session::region_changed (Change what_changed, Region* region)
+Session::region_changed (Change what_changed, boost::shared_ptr<Region> region)
 {
        if (what_changed & Region::HiddenChanged) {
                /* relay hidden changes */
@@ -2429,31 +2623,23 @@ Session::region_changed (Change what_changed, Region* region)
 }
 
 void
-Session::region_renamed (Region* region)
+Session::region_renamed (boost::shared_ptr<Region> region)
 {
        add_region (region);
 }
 
 void
-Session::remove_region (Region* region)
+Session::remove_region (boost::shared_ptr<Region> region)
 {
-       AudioRegionList::iterator i;
-       AudioRegion* ar = 0;
+       RegionList::iterator i;
        bool removed = false;
-
+       
        { 
-               LockMonitor lm (region_lock, __LINE__, __FILE__);
+               Glib::Mutex::Lock lm (region_lock);
 
-               if ((ar = dynamic_cast<AudioRegion*> (region)) != 0) {
-                       if ((i = audio_regions.find (region->id())) != audio_regions.end()) {
-                               audio_regions.erase (i);
-                               removed = true;
-                       } 
-               } else {
-                       fatal << _("programming error: ") 
-                             << X_("unknown region type passed to Session::remove_region()")
-                             << endmsg;
-                       /*NOTREACHED*/
+               if ((i = regions.find (region->id())) != regions.end()) {
+                       regions.erase (i);
+                       removed = true;
                }
        }
 
@@ -2464,71 +2650,69 @@ Session::remove_region (Region* region)
        set_dirty();
 
        if (removed) {
-                AudioRegionRemoved(ar); /* EMIT SIGNAL */
+                RegionRemoved(region); /* EMIT SIGNAL */
        }
 }
 
-AudioRegion*
-Session::find_whole_file_parent (AudioRegion& child)
+boost::shared_ptr<Region>
+Session::find_whole_file_parent (Region& child)
 {
-       AudioRegionList::iterator i;
-       AudioRegion* region;
-       LockMonitor lm (region_lock, __LINE__, __FILE__);
+       RegionList::iterator i;
+       boost::shared_ptr<Region> region;
+       
+       Glib::Mutex::Lock lm (region_lock);
 
-       for (i = audio_regions.begin(); i != audio_regions.end(); ++i) {
+       for (i = regions.begin(); i != regions.end(); ++i) {
 
-               region = (*i).second;
+               region = i->second;
 
                if (region->whole_file()) {
 
-                       if (child.source_equivalent (*region)) {
+                       if (child.source_equivalent (region)) {
                                return region;
                        }
                }
        } 
 
-       return 0;
+       return boost::shared_ptr<AudioRegion> ((AudioRegion*) 0);
 }      
 
 void
-Session::find_equivalent_playlist_regions (AudioRegion& region, vector<AudioRegion*>& result)
+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) {
-
-               AudioPlaylist* pl;
-
-               if ((pl = dynamic_cast<AudioPlaylist*>(*i)) == 0) {
-                       continue;
-               }
-
-               pl->get_region_list_equivalent_regions (region, result);
-       }
+       for (PlaylistList::iterator i = playlists.begin(); i != playlists.end(); ++i)
+               (*i)->get_region_list_equivalent_regions (region, result);
 }
 
 int
-Session::destroy_region (Region* region)
+Session::destroy_region (boost::shared_ptr<Region> region)
 {
-       AudioRegion* aregion;
+       boost::shared_ptr<AudioRegion> aregion;
 
-       if ((aregion = dynamic_cast<AudioRegion*> (region)) == 0) {
+       if ((aregion = boost::dynamic_pointer_cast<AudioRegion> (region)) == 0) {
                return 0;
        }
-
+       
        if (aregion->playlist()) {
                aregion->playlist()->destroy_region (region);
        }
 
-       vector<Source*> srcs;
+       vector<boost::shared_ptr<Source> > srcs;
        
        for (uint32_t n = 0; n < aregion->n_channels(); ++n) {
-               srcs.push_back (&aregion->source (n));
+               srcs.push_back (aregion->source (n));
        }
 
-       for (vector<Source*>::iterator i = srcs.begin(); i != srcs.end(); ++i) {
+       for (vector<boost::shared_ptr<Source> >::iterator i = srcs.begin(); i != srcs.end(); ++i) {
                
-               if ((*i)->use_cnt() == 0) {
-                       (*i)->mark_for_remove ();
-                       delete *i;
+               if ((*i).use_count() == 1) {
+                       boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*i);
+
+                       if (afs) {
+                               (afs)->mark_for_remove ();
+                       }
+                       
+                       (*i)->drop_references ();
                }
        }
 
@@ -2536,9 +2720,9 @@ Session::destroy_region (Region* region)
 }
 
 int
-Session::destroy_regions (list<Region*> regions)
+Session::destroy_regions (list<boost::shared_ptr<Region> > regions)
 {
-       for (list<Region*>::iterator i = regions.begin(); i != regions.end(); ++i) {
+       for (list<boost::shared_ptr<Region> >::iterator i = regions.begin(); i != regions.end(); ++i) {
                destroy_region (*i);
        }
        return 0;
@@ -2547,12 +2731,12 @@ Session::destroy_regions (list<Region*> regions)
 int
 Session::remove_last_capture ()
 {
-       list<Region*> r;
-
-       RWLockMonitor lm (diskstream_lock, false, __LINE__, __FILE__);
+       list<boost::shared_ptr<Region> > r;
        
-       for (DiskStreamList::iterator i = diskstreams.begin(); i != diskstreams.end(); ++i) {
-               list<Region*>& l = (*i)->last_capture_regions();
+       boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
+       
+       for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
+               list<boost::shared_ptr<Region> >& l = (*i)->last_capture_regions();
                
                if (!l.empty()) {
                        r.insert (r.end(), l.begin(), l.end());
@@ -2565,73 +2749,221 @@ Session::remove_last_capture ()
 }
 
 int
-Session::remove_region_from_region_list (Region& r)
+Session::remove_region_from_region_list (boost::shared_ptr<Region> r)
 {
-       remove_region (&r);
+       remove_region (r);
        return 0;
 }
 
 /* Source Management */
-
 void
-Session::add_source (Source* source)
+Session::add_source (boost::shared_ptr<Source> source)
 {
-       pair<SourceList::key_type, SourceList::mapped_type> entry;
+       cerr << "add new source " << source->name() << endl;
+
+       pair<SourceMap::key_type, SourceMap::mapped_type> entry;
+       pair<SourceMap::iterator,bool> result;
+
+       entry.first = source->id();
+       entry.second = source;
        
        {
-               LockMonitor lm (source_lock, __LINE__, __FILE__);
-               entry.first = source->id();
-               entry.second = source;
-               sources.insert (entry);
+               Glib::Mutex::Lock lm (source_lock);
+               result = sources.insert (entry);
        }
-       
-       source->GoingAway.connect (mem_fun (this, &Session::remove_source));
+
+       if (!result.second) {
+               cerr << "\tNOT inserted ? " << result.second << endl;
+       }
+
+       source->GoingAway.connect (sigc::bind (mem_fun (this, &Session::remove_source), boost::weak_ptr<Source> (source)));
        set_dirty();
        
        SourceAdded (source); /* EMIT SIGNAL */
 }
 
 void
-Session::remove_source (Source* source)
+Session::remove_source (boost::weak_ptr<Source> src)
 {
-       SourceList::iterator i;
+       SourceMap::iterator i;
+       boost::shared_ptr<Source> source = src.lock();
 
-       { 
-               LockMonitor lm (source_lock, __LINE__, __FILE__);
-
-               if ((i = sources.find (source->id())) != sources.end()) {
-                       sources.erase (i);
+       if (!source) {
+               cerr << "removing a source DEAD\n";
+       } else {
+               cerr << "removing a source " << source->name () << endl;
+               
+               { 
+                       Glib::Mutex::Lock lm (source_lock);
+                       
+                       if ((i = sources.find (source->id())) != sources.end()) {
+                               sources.erase (i);
+                       } 
+               }
+               
+               if (!_state_of_the_state & InCleanup) {
+                       
+                       /* save state so we don't end up with a session file
+                          referring to non-existent sources.
+                       */
+                       
+                       save_state (_current_snapshot_name);
                }
+               
+               SourceRemoved(source); /* EMIT SIGNAL */
        }
+}
 
-       if (!_state_of_the_state & InCleanup) {
+boost::shared_ptr<Source>
+Session::source_by_id (const PBD::ID& id)
+{
+       Glib::Mutex::Lock lm (source_lock);
+       SourceMap::iterator i;
+       boost::shared_ptr<Source> source;
 
-               /* save state so we don't end up with a session file
-                  referring to non-existent sources.
-               */
-               
-               save_state (_current_snapshot_name);
+       if ((i = sources.find (id)) != sources.end()) {
+               source = i->second;
        }
 
-       SourceRemoved(source); /* EMIT SIGNAL */
+       /* XXX search MIDI or other searches here */
+       
+       return source;
 }
 
-Source *
-Session::get_source (ARDOUR::id_t id)
+string
+Session::peak_path_from_audio_path (string audio_path)
 {
-       LockMonitor lm (source_lock, __LINE__, __FILE__);
-       SourceList::iterator i;
-       Source* source = 0;
+       /* XXX hardly bombproof! fix me */
+
+       string res;
+
+       res = Glib::path_get_dirname (audio_path);
+       res = Glib::path_get_dirname (res);
+       res += '/';
+       res += peak_dir_name;
+       res += '/';
+       res += PBD::basename_nosuffix (audio_path);
+       res += ".peak";
+
+       return res;
+}
+
+string
+Session::change_audio_path_by_name (string path, string oldname, string newname, bool destructive)
+{
+       string look_for;
+       string old_basename = PBD::basename_nosuffix (oldname);
+       string new_legalized = legalize_for_path (newname);
+
+       /* note: we know (or assume) the old path is already valid */
+
+       if (destructive) {
+               
+               /* destructive file sources have a name of the form:
+
+                   /path/to/Tnnnn-NAME(%[LR])?.wav
+                 
+                   the task here is to replace NAME with the new name.
+               */
+               
+               /* find last slash */
+
+               string dir;
+               string prefix;
+               string::size_type slash;
+               string::size_type dash;
+
+               if ((slash = path.find_last_of ('/')) == string::npos) {
+                       return "";
+               }
+
+               dir = path.substr (0, slash+1);
+
+               /* '-' is not a legal character for the NAME part of the path */
+
+               if ((dash = path.find_last_of ('-')) == string::npos) {
+                       return "";
+               }
+
+               prefix = path.substr (slash+1, dash-(slash+1));
+
+               path = dir;
+               path += prefix;
+               path += '-';
+               path += new_legalized;
+               path += ".wav";  /* XXX gag me with a spoon */
+               
+       } else {
+               
+               /* non-destructive file sources have a name of the form:
+
+                   /path/to/NAME-nnnnn(%[LR])?.wav
+                 
+                   the task here is to replace NAME with the new name.
+               */
+               
+               string dir;
+               string suffix;
+               string::size_type slash;
+               string::size_type dash;
+               string::size_type postfix;
+
+               /* find last slash */
+
+               if ((slash = path.find_last_of ('/')) == string::npos) {
+                       return "";
+               }
+
+               dir = path.substr (0, slash+1);
+
+               /* '-' is not a legal character for the NAME part of the path */
+
+               if ((dash = path.find_last_of ('-')) == string::npos) {
+                       return "";
+               }
+
+               suffix = path.substr (dash+1);
+               
+               // Suffix is now everything after the dash. Now we need to eliminate
+               // the nnnnn part, which is done by either finding a '%' or a '.'
+
+               postfix = suffix.find_last_of ("%");
+               if (postfix == string::npos) {
+                       postfix = suffix.find_last_of ('.');
+               }
+
+               if (postfix != string::npos) {
+                       suffix = suffix.substr (postfix);
+               } else {
+                       error << "Logic error in Session::change_audio_path_by_name(), please report to the developers" << endl;
+                       return "";
+               }
+
+               const uint32_t limit = 10000;
+               char buf[PATH_MAX+1];
+
+               for (uint32_t cnt = 1; cnt <= limit; ++cnt) {
+
+                       snprintf (buf, sizeof(buf), "%s%s-%u%s", dir.c_str(), newname.c_str(), cnt, suffix.c_str());
+
+                       if (access (buf, F_OK) != 0) {
+                               path = buf;
+                               break;
+                       }
+                       path = "";
+               }
+
+               if (path == "") {
+                       error << "FATAL ERROR! Could not find a " << endl;
+               }
 
-       if ((i = sources.find (id)) != sources.end()) {
-               source = (*i).second;
        }
 
-       return source;
+       return path;
 }
 
-FileSource *
-Session::create_file_source (DiskStream& ds, int32_t chan, bool destructive)
+string
+Session::audio_path_from_name (string name, uint32_t nchan, uint32_t chan, bool destructive)
 {
        string spath;
        uint32_t cnt;
@@ -2640,13 +2972,13 @@ Session::create_file_source (DiskStream& ds, int32_t chan, bool destructive)
        string legalized;
 
        buf[0] = '\0';
-       legalized = legalize_for_path (ds.name());
+       legalized = legalize_for_path (name);
 
        /* find a "version" of the file name that doesn't exist in
           any of the possible directories.
        */
-       
-       for (cnt = 1; cnt <= limit; ++cnt) {
+
+       for (cnt = (destructive ? ++destructive_index : 1); cnt <= limit; ++cnt) {
 
                vector<space_and_path>::iterator i;
                uint32_t existing = 0;
@@ -2654,22 +2986,45 @@ Session::create_file_source (DiskStream& ds, int32_t chan, bool destructive)
                for (i = session_dirs.begin(); i != session_dirs.end(); ++i) {
 
                        spath = (*i).path;
-                       spath += sound_dir_name;
-                       spath += '/';
-                       spath += legalized;
-
-                       if (ds.n_channels() < 2) {
-                               snprintf (buf, sizeof(buf), "%s-%u.wav", spath.c_str(), cnt);
-                       } else if (ds.n_channels() == 2) {
-                               if (chan == 0) {
-                                       snprintf (buf, sizeof(buf), "%s-%u%%L.wav", spath.c_str(), cnt);
+
+                       if (destructive) {
+                               spath += tape_dir_name;
+                       } else {
+                               spath += sound_dir_name;
+                       }
+
+                       if (destructive) {
+                               if (nchan < 2) {
+                                       snprintf (buf, sizeof(buf), "%s/T%04d-%s.wav", spath.c_str(), cnt, legalized.c_str());
+                               } else if (nchan == 2) {
+                                       if (chan == 0) {
+                                               snprintf (buf, sizeof(buf), "%s/T%04d-%s%%L.wav", spath.c_str(), cnt, legalized.c_str());
+                                       } else {
+                                               snprintf (buf, sizeof(buf), "%s/T%04d-%s%%R.wav", spath.c_str(), cnt, legalized.c_str());
+                                       }
+                               } else if (nchan < 26) {
+                                       snprintf (buf, sizeof(buf), "%s/T%04d-%s%%%c.wav", spath.c_str(), cnt, legalized.c_str(), 'a' + chan);
                                } else {
-                                       snprintf (buf, sizeof(buf), "%s-%u%%R.wav", spath.c_str(), cnt);
+                                       snprintf (buf, sizeof(buf), "%s/T%04d-%s.wav", spath.c_str(), cnt, legalized.c_str());
                                }
-                       } else if (ds.n_channels() < 26) {
-                               snprintf (buf, sizeof(buf), "%s-%u%%%c.wav", spath.c_str(), cnt, 'a' + chan);
                        } else {
-                               snprintf (buf, sizeof(buf), "%s-%u.wav", spath.c_str(), cnt);
+
+                               spath += '/';
+                               spath += legalized;
+
+                               if (nchan < 2) {
+                                       snprintf (buf, sizeof(buf), "%s-%u.wav", spath.c_str(), cnt);
+                               } else if (nchan == 2) {
+                                       if (chan == 0) {
+                                               snprintf (buf, sizeof(buf), "%s-%u%%L.wav", spath.c_str(), cnt);
+                                       } else {
+                                               snprintf (buf, sizeof(buf), "%s-%u%%R.wav", spath.c_str(), cnt);
+                                       }
+                               } else if (nchan < 26) {
+                                       snprintf (buf, sizeof(buf), "%s-%u%%%c.wav", spath.c_str(), cnt, 'a' + chan);
+                               } else {
+                                       snprintf (buf, sizeof(buf), "%s-%u.wav", spath.c_str(), cnt);
+                               }
                        }
 
                        if (access (buf, F_OK) == 0) {
@@ -2680,11 +3035,11 @@ Session::create_file_source (DiskStream& ds, int32_t chan, bool destructive)
                if (existing == 0) {
                        break;
                }
-       }
 
-       if (cnt > limit) {
-               error << string_compose(_("There are already %1 recordings for %2, which I consider too many."), limit, ds.name()) << endmsg;
-               throw failed_constructor();
+               if (cnt > limit) {
+                       error << string_compose(_("There are already %1 recordings for %2, which I consider too many."), limit, name) << endmsg;
+                       throw failed_constructor();
+               }
        }
 
        /* we now have a unique name for the file, but figure out where to
@@ -2693,7 +3048,11 @@ Session::create_file_source (DiskStream& ds, int32_t chan, bool destructive)
 
        string foo = buf;
 
-       spath = discover_best_sound_dir ();
+       if (destructive) {
+               spath = tape_dir ();
+       } else {
+               spath = discover_best_sound_dir ();
+       }
 
        string::size_type pos = foo.find_last_of ('/');
        
@@ -2703,33 +3062,209 @@ Session::create_file_source (DiskStream& ds, int32_t chan, bool destructive)
                spath += foo.substr (pos + 1);
        }
 
-       /* this might throw failed_constructor(), which is OK */
+       return spath;
+}
+
+boost::shared_ptr<AudioFileSource>
+Session::create_audio_source_for_session (AudioDiskstream& ds, uint32_t chan, bool destructive)
+{
+       string spath = audio_path_from_name (ds.name(), ds.n_channels().get(DataType::AUDIO), chan, destructive);
+       return boost::dynamic_pointer_cast<AudioFileSource> (SourceFactory::createWritable (DataType::AUDIO, spath, destructive, frame_rate()));
+}
+
+// FIXME: _terrible_ code duplication
+string
+Session::change_midi_path_by_name (string path, string oldname, string newname, bool destructive)
+{
+       string look_for;
+       string old_basename = PBD::basename_nosuffix (oldname);
+       string new_legalized = legalize_for_path (newname);
+
+       /* note: we know (or assume) the old path is already valid */
 
        if (destructive) {
-               return new DestructiveFileSource (spath, frame_rate());
+               
+               /* destructive file sources have a name of the form:
+
+                   /path/to/Tnnnn-NAME(%[LR])?.wav
+                 
+                   the task here is to replace NAME with the new name.
+               */
+               
+               /* find last slash */
+
+               string dir;
+               string prefix;
+               string::size_type slash;
+               string::size_type dash;
+
+               if ((slash = path.find_last_of ('/')) == string::npos) {
+                       return "";
+               }
+
+               dir = path.substr (0, slash+1);
+
+               /* '-' is not a legal character for the NAME part of the path */
+
+               if ((dash = path.find_last_of ('-')) == string::npos) {
+                       return "";
+               }
+
+               prefix = path.substr (slash+1, dash-(slash+1));
+
+               path = dir;
+               path += prefix;
+               path += '-';
+               path += new_legalized;
+               path += ".mid";  /* XXX gag me with a spoon */
+               
        } else {
-               return new FileSource (spath, frame_rate());
+               
+               /* non-destructive file sources have a name of the form:
+
+                   /path/to/NAME-nnnnn(%[LR])?.wav
+                 
+                   the task here is to replace NAME with the new name.
+               */
+               
+               string dir;
+               string suffix;
+               string::size_type slash;
+               string::size_type dash;
+               string::size_type postfix;
+
+               /* find last slash */
+
+               if ((slash = path.find_last_of ('/')) == string::npos) {
+                       return "";
+               }
+
+               dir = path.substr (0, slash+1);
+
+               /* '-' is not a legal character for the NAME part of the path */
+
+               if ((dash = path.find_last_of ('-')) == string::npos) {
+                       return "";
+               }
+
+               suffix = path.substr (dash+1);
+               
+               // Suffix is now everything after the dash. Now we need to eliminate
+               // the nnnnn part, which is done by either finding a '%' or a '.'
+
+               postfix = suffix.find_last_of ("%");
+               if (postfix == string::npos) {
+                       postfix = suffix.find_last_of ('.');
+               }
+
+               if (postfix != string::npos) {
+                       suffix = suffix.substr (postfix);
+               } else {
+                       error << "Logic error in Session::change_midi_path_by_name(), please report to the developers" << endl;
+                       return "";
+               }
+
+               const uint32_t limit = 10000;
+               char buf[PATH_MAX+1];
+
+               for (uint32_t cnt = 1; cnt <= limit; ++cnt) {
+
+                       snprintf (buf, sizeof(buf), "%s%s-%u%s", dir.c_str(), newname.c_str(), cnt, suffix.c_str());
+
+                       if (access (buf, F_OK) != 0) {
+                               path = buf;
+                               break;
+                       }
+                       path = "";
+               }
+
+               if (path == "") {
+                       error << "FATAL ERROR! Could not find a " << endl;
+               }
+
        }
-}
 
-/* Playlist management */
+       return path;
+}
 
-Playlist *
-Session::get_playlist (string name)
+string
+Session::midi_path_from_name (string name)
 {
-       Playlist* ret = 0;
+       string spath;
+       uint32_t cnt;
+       char buf[PATH_MAX+1];
+       const uint32_t limit = 10000;
+       string legalized;
+
+       buf[0] = '\0';
+       legalized = legalize_for_path (name);
+
+       /* find a "version" of the file name that doesn't exist in
+          any of the possible directories.
+       */
+
+       for (cnt = 1; cnt <= limit; ++cnt) {
+
+               vector<space_and_path>::iterator i;
+               uint32_t existing = 0;
+
+               for (i = session_dirs.begin(); i != session_dirs.end(); ++i) {
+
+                       // FIXME: different directory from audio?
+                       spath = (*i).path + sound_dir_name + "/" + legalized;
 
-       if ((ret = playlist_by_name (name)) == 0) {
-               ret = new AudioPlaylist (*this, name);
+                       snprintf (buf, sizeof(buf), "%s-%u.mid", spath.c_str(), cnt);
+
+                       if (access (buf, F_OK) == 0) {
+                               existing++;
+                       }
+               }
+
+               if (existing == 0) {
+                       break;
+               }
+
+               if (cnt > limit) {
+                       error << string_compose(_("There are already %1 recordings for %2, which I consider too many."), limit, name) << endmsg;
+                       throw failed_constructor();
+               }
        }
 
-       return ret;
+       /* we now have a unique name for the file, but figure out where to
+          actually put it.
+       */
+
+       string foo = buf;
+
+       // FIXME: different directory than audio?
+       spath = discover_best_sound_dir ();
+
+       string::size_type pos = foo.find_last_of ('/');
+       
+       if (pos == string::npos) {
+               spath += foo;
+       } else {
+               spath += foo.substr (pos + 1);
+       }
+
+       return spath;
+}
+
+boost::shared_ptr<MidiSource>
+Session::create_midi_source_for_session (MidiDiskstream& ds)
+{
+       string spath = midi_path_from_name (ds.name());
+       
+       return boost::dynamic_pointer_cast<SMFSource> (SourceFactory::createWritable (DataType::MIDI, spath, false, frame_rate()));
 }
 
+
+/* Playlist management */
+
 Playlist *
 Session::playlist_by_name (string name)
 {
-       LockMonitor lm (playlist_lock, __LINE__, __FILE__);
+       Glib::Mutex::Lock lm (playlist_lock);
        for (PlaylistList::iterator i = playlists.begin(); i != playlists.end(); ++i) {
                if ((*i)->name() == name) {
                        return* i;
@@ -2751,12 +3286,12 @@ Session::add_playlist (Playlist* playlist)
        }
 
        { 
-               LockMonitor lm (playlist_lock, __LINE__, __FILE__);
+               Glib::Mutex::Lock lm (playlist_lock);
                if (find (playlists.begin(), playlists.end(), playlist) == playlists.end()) {
                        playlists.insert (playlists.begin(), playlist);
                        // playlist->ref();
                        playlist->InUse.connect (mem_fun (*this, &Session::track_playlist));
-                       playlist->GoingAway.connect (mem_fun (*this, &Session::remove_playlist));
+                       playlist->GoingAway.connect (sigc::bind (mem_fun (*this, &Session::remove_playlist), playlist));
                }
        }
 
@@ -2771,7 +3306,7 @@ Session::track_playlist (Playlist* pl, bool inuse)
        PlaylistList::iterator x;
 
        { 
-               LockMonitor lm (playlist_lock, __LINE__, __FILE__);
+               Glib::Mutex::Lock lm (playlist_lock);
 
                if (!inuse) {
                        //cerr << "shifting playlist to unused: " << pl->name() << endl;
@@ -2803,7 +3338,7 @@ Session::remove_playlist (Playlist* playlist)
        }
 
        { 
-               LockMonitor lm (playlist_lock, __LINE__, __FILE__);
+               Glib::Mutex::Lock lm (playlist_lock);
                // cerr << "removing playlist: " << playlist->name() << endl;
 
                PlaylistList::iterator i;
@@ -2827,7 +3362,7 @@ Session::remove_playlist (Playlist* playlist)
 }
 
 void 
-Session::set_audition (AudioRegion* r)
+Session::set_audition (boost::shared_ptr<Region> r)
 {
        pending_audition_region = r;
        post_transport_work = PostTransportWork (post_transport_work | PostTransportAudition);
@@ -2835,30 +3370,30 @@ Session::set_audition (AudioRegion* r)
 }
 
 void
-Session::non_realtime_set_audition ()
+Session::audition_playlist ()
 {
-       if (pending_audition_region == (AudioRegion*) 0xfeedface) {
-               auditioner->audition_current_playlist ();
-       } else if (pending_audition_region) {
-               auditioner->audition_region (*pending_audition_region);
-       }
-       pending_audition_region = 0;
-       AuditionActive (true); /* EMIT SIGNAL */
+       Event* ev = new Event (Event::Audition, Event::Add, Event::Immediate, 0, 0.0);
+       ev->region.reset ();
+       queue_event (ev);
 }
 
 void
-Session::audition_playlist ()
+Session::non_realtime_set_audition ()
 {
-       Event* ev = new Event (Event::Audition, Event::Add, Event::Immediate, 0, 0.0);
-       ev->set_ptr ((void*) 0xfeedface);
-       queue_event (ev);
+       if (!pending_audition_region) {
+               auditioner->audition_current_playlist ();
+       } else {
+               auditioner->audition_region (pending_audition_region);
+               pending_audition_region.reset ();
+       }
+       AuditionActive (true); /* EMIT SIGNAL */
 }
 
 void
-Session::audition_region (AudioRegion& r)
+Session::audition_region (boost::shared_ptr<Region> r)
 {
        Event* ev = new Event (Event::Audition, Event::Add, Event::Immediate, 0, 0.0);
-       ev->set_ptr (&r);
+       ev->region = r;
        queue_event (ev);
 }
 
@@ -2867,12 +3402,12 @@ Session::cancel_audition ()
 {
        if (auditioner->active()) {
                auditioner->cancel_audition ();
-                AuditionActive (false); /* EMIT SIGNAL */
+               AuditionActive (false); /* EMIT SIGNAL */
        }
 }
 
 bool
-Session::RoutePublicOrderSorter::operator() (Route* a, Route* b)
+Session::RoutePublicOrderSorter::operator() (boost::shared_ptr<Route> a, boost::shared_ptr<Route> b)
 {
        return a->order_key(N_("signal")) < b->order_key(N_("signal"));
 }
@@ -2890,7 +3425,7 @@ Session::remove_empty_sounds ()
        
        for (vector<string *>::iterator i = possible_audiofiles->begin(); i != possible_audiofiles->end(); ++i) {
 
-               if (FileSource::is_empty (*(*i))) {
+               if (AudioFileSource::is_empty (*(*i))) {
 
                        unlink ((*i)->c_str());
                        
@@ -2915,50 +3450,14 @@ Session::is_auditioning () const
        }
 }
 
-
-string
-Session::peak_path_from_audio_path (string audio_path)
-{
-       /* XXX hardly bombproof! fix me */
-
-       string res;
-
-       res = PBD::dirname (audio_path);
-       res = PBD::dirname (res);
-       res += '/';
-       res += peak_dir_name;
-       res += '/';
-       res += PBD::basename_nosuffix (audio_path);
-       res += ".peak";
-
-       return res;
-}
-
-string
-Session::old_peak_path_from_audio_path (string audio_path)
-{
-       /* This is a hangover from when audio and peak files
-          lived in the same directory. We need it to to 
-          be able to open old sessions.
-       */
-
-       /* XXX hardly bombproof! fix me */
-
-       string res = audio_path.substr (0, audio_path.find_last_of ('.'));
-       res += ".peak";
-       return res;
-}
-
 void
 Session::set_all_solo (bool yn)
 {
-       {
-               RWLockMonitor lm (route_lock, false, __LINE__, __FILE__);
-               
-               for (RouteList::iterator i = routes.begin(); i != routes.end(); ++i) {
-                       if (!(*i)->hidden()) {
-                               (*i)->set_solo (yn, this);
-                       }
+       shared_ptr<RouteList> r = routes.reader ();
+       
+       for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
+               if (!(*i)->hidden()) {
+                       (*i)->set_solo (yn, this);
                }
        }
 
@@ -2968,13 +3467,11 @@ Session::set_all_solo (bool yn)
 void
 Session::set_all_mute (bool yn)
 {
-       {
-               RWLockMonitor lm (route_lock, false, __LINE__, __FILE__);
-               
-               for (RouteList::iterator i = routes.begin(); i != routes.end(); ++i) {
-                       if (!(*i)->hidden()) {
-                               (*i)->set_mute (yn, this);
-                       }
+       shared_ptr<RouteList> r = routes.reader ();
+       
+       for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
+               if (!(*i)->hidden()) {
+                       (*i)->set_mute (yn, this);
                }
        }
 
@@ -2984,10 +3481,11 @@ Session::set_all_mute (bool yn)
 uint32_t
 Session::n_diskstreams () const
 {
-       RWLockMonitor lm (diskstream_lock, false, __LINE__, __FILE__);
        uint32_t n = 0;
 
-       for (DiskStreamList::const_iterator i = diskstreams.begin(); i != diskstreams.end(); ++i) {
+       boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
+
+       for (DiskstreamList::const_iterator i = dsl->begin(); i != dsl->end(); ++i) {
                if (!(*i)->hidden()) {
                        n++;
                }
@@ -2995,17 +3493,6 @@ Session::n_diskstreams () const
        return n;
 }
 
-void 
-Session::foreach_diskstream (void (DiskStream::*func)(void)) 
-{
-       RWLockMonitor lm (diskstream_lock, false, __LINE__, __FILE__);
-       for (DiskStreamList::iterator i = diskstreams.begin(); i != diskstreams.end(); ++i) {
-               if (!(*i)->hidden()) {
-                       ((*i)->*func)();
-               }
-       }
-}
-
 void
 Session::graph_reordered ()
 {
@@ -3016,17 +3503,16 @@ Session::graph_reordered ()
        if (_state_of_the_state & InitialConnecting) {
                return;
        }
-
-       RWLockMonitor lm1 (route_lock, true, __LINE__, __FILE__);
-       RWLockMonitor lm2 (diskstream_lock, false, __LINE__, __FILE__);
-
-       resort_routes (0);
+       
+       resort_routes ();
 
        /* force all diskstreams to update their capture offset values to 
           reflect any changes in latencies within the graph.
        */
        
-       for (DiskStreamList::iterator i = diskstreams.begin(); i != diskstreams.end(); ++i) {
+       boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
+
+       for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
                (*i)->set_capture_offset ();
        }
 }
@@ -3046,12 +3532,12 @@ Session::record_enable_all ()
 void
 Session::record_enable_change_all (bool yn)
 {
-       RWLockMonitor lm1 (route_lock, false, __LINE__, __FILE__);
+       shared_ptr<RouteList> r = routes.reader ();
        
-       for (RouteList::iterator i = routes.begin(); i != routes.end(); ++i) {
-               AudioTrack* at;
+       for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
+               Track* at;
 
-               if ((at = dynamic_cast<AudioTrack*>(*i)) != 0) {
+               if ((at = dynamic_cast<Track*>((*i).get())) != 0) {
                        at->set_record_enable (yn, this);
                }
        }
@@ -3083,7 +3569,7 @@ Session::add_redirect (Redirect* redirect)
                /*NOTREACHED*/
        }
 
-       redirect->GoingAway.connect (mem_fun (*this, &Session::remove_redirect));
+       redirect->GoingAway.connect (sigc::bind (mem_fun (*this, &Session::remove_redirect), redirect));
 
        set_dirty();
 }
@@ -3131,7 +3617,7 @@ void
 Session::add_connection (ARDOUR::Connection* connection)
 {
        {
-               LockMonitor (connection_lock, __LINE__, __FILE__);
+               Glib::Mutex::Lock guard (connection_lock);
                _connections.push_back (connection);
        }
        
@@ -3146,7 +3632,7 @@ Session::remove_connection (ARDOUR::Connection* connection)
        bool removed = false;
 
        {
-               LockMonitor (connection_lock, __LINE__, __FILE__);
+               Glib::Mutex::Lock guard (connection_lock);
                ConnectionList::iterator i = find (_connections.begin(), _connections.end(), connection);
                
                if (i != _connections.end()) {
@@ -3165,7 +3651,7 @@ Session::remove_connection (ARDOUR::Connection* connection)
 ARDOUR::Connection *
 Session::connection_by_name (string name) const
 {
-       LockMonitor lm (connection_lock, __LINE__, __FILE__);
+       Glib::Mutex::Lock lm (connection_lock);
 
        for (ConnectionList::const_iterator i = _connections.begin(); i != _connections.end(); ++i) {
                if ((*i)->name() == name) {
@@ -3182,7 +3668,7 @@ Session::set_edit_mode (EditMode mode)
        _edit_mode = mode;
        
        { 
-               LockMonitor lm (playlist_lock, __LINE__, __FILE__);
+               Glib::Mutex::Lock lm (playlist_lock);
                
                for (PlaylistList::iterator i = playlists.begin(); i != playlists.end(); ++i) {
                        (*i)->set_edit_mode (mode);
@@ -3200,30 +3686,18 @@ Session::tempo_map_changed (Change ignored)
        set_dirty ();
 }
 
+/** Ensures that all buffers (scratch, send, silent, etc) are allocated for
+ * the given count with the current block size.
+ */
 void
-Session::ensure_passthru_buffers (uint32_t howmany)
+Session::ensure_buffers (ChanCount howmany)
 {
-       while (howmany > _passthru_buffers.size()) {
-               Sample *p;
-#ifdef NO_POSIX_MEMALIGN
-               p =  (Sample *) malloc(current_block_size * sizeof(Sample));
-#else
-               posix_memalign((void **)&p,16,current_block_size * 4);
-#endif                 
-               _passthru_buffers.push_back (p);
-
-               *p = 0;
-               
-#ifdef NO_POSIX_MEMALIGN
-               p =  (Sample *) malloc(current_block_size * sizeof(Sample));
-#else
-               posix_memalign((void **)&p,16,current_block_size * 4);
-#endif                 
-               memset (p, 0, sizeof (Sample) * current_block_size);
-               _silent_buffers.push_back (p);
-
-       }
-       allocate_pan_automation_buffers (current_block_size, howmany, false);
+       // FIXME: NASTY assumption (midi block size == audio block size)
+       _scratch_buffers->ensure_buffers(howmany, current_block_size);
+       _send_buffers->ensure_buffers(howmany, current_block_size);
+       _silent_buffers->ensure_buffers(howmany, current_block_size);
+       
+       allocate_pan_automation_buffers (current_block_size, howmany.get(DataType::AUDIO), false);
 }
 
 string
@@ -3247,7 +3721,7 @@ Session::next_insert_name ()
 NamedSelection *
 Session::named_selection_by_name (string name)
 {
-       LockMonitor lm (named_selection_lock, __LINE__, __FILE__);
+       Glib::Mutex::Lock lm (named_selection_lock);
        for (NamedSelectionList::iterator i = named_selections.begin(); i != named_selections.end(); ++i) {
                if ((*i)->name == name) {
                        return* i;
@@ -3260,7 +3734,7 @@ void
 Session::add_named_selection (NamedSelection* named_selection)
 {
        { 
-               LockMonitor lm (named_selection_lock, __LINE__, __FILE__);
+               Glib::Mutex::Lock lm (named_selection_lock);
                named_selections.insert (named_selections.begin(), named_selection);
        }
 
@@ -3275,7 +3749,7 @@ Session::remove_named_selection (NamedSelection* named_selection)
        bool removed = false;
 
        { 
-               LockMonitor lm (named_selection_lock, __LINE__, __FILE__);
+               Glib::Mutex::Lock lm (named_selection_lock);
 
                NamedSelectionList::iterator i = find (named_selections.begin(), named_selections.end(), named_selection);
 
@@ -3295,11 +3769,9 @@ Session::remove_named_selection (NamedSelection* named_selection)
 void
 Session::reset_native_file_format ()
 {
-       // jlc - WHY take routelock?
-       //RWLockMonitor lm1 (route_lock, true, __LINE__, __FILE__);
-       RWLockMonitor lm2 (diskstream_lock, false, __LINE__, __FILE__);
+       boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
 
-       for (DiskStreamList::iterator i = diskstreams.begin(); i != diskstreams.end(); ++i) {
+       for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
                (*i)->reset_write_sources (false);
        }
 }
@@ -3307,9 +3779,9 @@ Session::reset_native_file_format ()
 bool
 Session::route_name_unique (string n) const
 {
-       RWLockMonitor lm (route_lock, false, __LINE__, __FILE__);
+       shared_ptr<RouteList> r = routes.reader ();
        
-       for (RouteList::const_iterator i = routes.begin(); i != routes.end(); ++i) {
+       for (RouteList::const_iterator i = r->begin(); i != r->end(); ++i) {
                if ((*i)->name() == n) {
                        return false;
                }
@@ -3319,15 +3791,15 @@ Session::route_name_unique (string n) const
 }
 
 int
-Session::remove_file_source (FileSource& fs)
+Session::cleanup_audio_file_source (boost::shared_ptr<AudioFileSource> fs)
 {
-       return fs.move_to_trash (dead_sound_dir_name);
+       return fs->move_to_trash (dead_sound_dir_name);
 }
 
 uint32_t
 Session::n_playlists () const
 {
-       LockMonitor lm (playlist_lock, __LINE__, __FILE__);
+       Glib::Mutex::Lock lm (playlist_lock);
        return playlists.size();
 }
 
@@ -3366,23 +3838,16 @@ Session::allocate_pan_automation_buffers (jack_nframes_t nframes, uint32_t howma
        _npan_buffers = howmany;
 }
 
-void 
-Session::add_instant_xml (XMLNode& node, const std::string& dir)
-{
-       Stateful::add_instant_xml (node, dir);
-       Config->add_instant_xml (node, Config->get_user_ardour_path());
-}
-
 int
 Session::freeze (InterThreadInfo& itt)
 {
-       RWLockMonitor lm (route_lock, false, __LINE__, __FILE__);
+       shared_ptr<RouteList> r = routes.reader ();
 
-       for (RouteList::iterator i = routes.begin(); i != routes.end(); ++i) {
+       for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
 
-               AudioTrack *at;
+               Track *at;
 
-               if ((at = dynamic_cast<AudioTrack*>(*i)) != 0) {
+               if ((at = dynamic_cast<Track*>((*i).get())) != 0) {
                        /* XXX this is wrong because itt.progress will keep returning to zero at the start
                           of every track.
                        */
@@ -3394,27 +3859,30 @@ Session::freeze (InterThreadInfo& itt)
 }
 
 int
-Session::write_one_track (AudioTrack& track, jack_nframes_t start, jack_nframes_t len,         bool overwrite, vector<Source*>& srcs,
-                         InterThreadInfo& itt)
+Session::write_one_audio_track (AudioTrack& track, jack_nframes_t start, jack_nframes_t len,   
+                              bool overwrite, vector<boost::shared_ptr<Source> >& srcs, InterThreadInfo& itt)
 {
-       int ret = -1;
-       Playlist* playlist;
-       FileSource* fsource;
-       uint32_t x;
-       char buf[PATH_MAX+1];
-       string dir;
-       uint32_t nchans;
-       jack_nframes_t position;
-       jack_nframes_t this_chunk;
-       jack_nframes_t to_do;
-       vector<Sample*> buffers;
-       const jack_nframes_t chunk_size = (256 * 1024)/4;
-
-       atomic_set (&processing_prohibited, 1);
+       boost::shared_ptr<AudioFileSource> fsource;
+       
+       int              ret = -1;
+       Playlist*        playlist = 0;
+       uint32_t         x;
+       char             buf[PATH_MAX+1];
+       string           dir;
+       ChanCount        nchans(track.audio_diskstream()->n_channels());
+       jack_nframes_t   position;
+       jack_nframes_t   this_chunk;
+       jack_nframes_t   to_do;
+       BufferSet        buffers;
+
+       // any bigger than this seems to cause stack overflows in called functions
+       const jack_nframes_t chunk_size = (128 * 1024)/4;
+
+       g_atomic_int_set (&processing_prohibited, 1);
        
        /* call tree *MUST* hold route_lock */
        
-       if ((playlist = track.disk_stream().playlist()) == 0) {
+       if ((playlist = track.diskstream()->playlist()) == 0) {
                goto out;
        }
 
@@ -3423,12 +3891,10 @@ Session::write_one_track (AudioTrack& track, jack_nframes_t start, jack_nframes_
        if (track.has_external_redirects()) {
                goto out;
        }
-
-       nchans = track.disk_stream().n_channels();
        
        dir = discover_best_sound_dir ();
 
-       for (uint32_t chan_n=0; chan_n < nchans; ++chan_n) {
+       for (uint32_t chan_n=0; chan_n < nchans.get(DataType::AUDIO); ++chan_n) {
 
                for (x = 0; x < 99999; ++x) {
                        snprintf (buf, sizeof(buf), "%s/%s-%d-bounce-%" PRIu32 ".wav", dir.c_str(), playlist->name().c_str(), chan_n, x+1);
@@ -3443,7 +3909,7 @@ Session::write_one_track (AudioTrack& track, jack_nframes_t start, jack_nframes_
                }
                
                try {
-                       fsource = new FileSource (buf, frame_rate());
+                       fsource = boost::dynamic_pointer_cast<AudioFileSource> (SourceFactory::createWritable (DataType::AUDIO, buf, false, frame_rate()));
                }
                
                catch (failed_constructor& err) {
@@ -3451,7 +3917,7 @@ Session::write_one_track (AudioTrack& track, jack_nframes_t start, jack_nframes_
                        goto out;
                }
 
-               srcs.push_back(fsource);
+               srcs.push_back (fsource);
        }
 
        /* XXX need to flush all redirects */
@@ -3460,29 +3926,25 @@ Session::write_one_track (AudioTrack& track, jack_nframes_t start, jack_nframes_
        to_do = len;
 
        /* create a set of reasonably-sized buffers */
+       buffers.ensure_buffers(nchans, chunk_size);
+       buffers.set_count(nchans);
 
-       for (vector<Sample*>::iterator i = _passthru_buffers.begin(); i != _passthru_buffers.end(); ++i) {
-               Sample* b;
-#ifdef NO_POSIX_MEMALIGN
-               b =  (Sample *) malloc(chunk_size * sizeof(Sample));
-#else
-               posix_memalign((void **)&b,16,chunk_size * 4);
-#endif                 
-               buffers.push_back (b);
-       }
-       
        while (to_do && !itt.cancel) {
                
                this_chunk = min (to_do, chunk_size);
                
-               if (track.export_stuff (buffers, nchans, start, this_chunk)) {
+               if (track.export_stuff (buffers, start, this_chunk)) {
                        goto out;
                }
 
                uint32_t n = 0;
-               for (vector<Source*>::iterator src=srcs.begin(); src != srcs.end(); ++src, ++n) {
-                       if ((*src)->write (buffers[n], this_chunk) != this_chunk) {
-                               goto out;
+               for (vector<boost::shared_ptr<Source> >::iterator src=srcs.begin(); src != srcs.end(); ++src, ++n) {
+                       boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
+                       
+                       if (afs) {
+                               if (afs->write (buffers.get_audio(n).data(this_chunk), this_chunk) != this_chunk) {
+                                       goto out;
+                               }
                        }
                }
                
@@ -3500,14 +3962,21 @@ Session::write_one_track (AudioTrack& track, jack_nframes_t start, jack_nframes_
                time (&now);
                xnow = localtime (&now);
                
-               for (vector<Source*>::iterator src=srcs.begin(); src != srcs.end(); ++src) {
-                       dynamic_cast<FileSource*>((*src))->update_header (position, *xnow, now);
+               for (vector<boost::shared_ptr<Source> >::iterator src=srcs.begin(); src != srcs.end(); ++src) {
+                       boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
+                       
+                       if (afs) {
+                               afs->update_header (position, *xnow, now);
+                       }
                }
                
                /* build peakfile for new source */
                
-               for (vector<Source*>::iterator src=srcs.begin(); src != srcs.end(); ++src) {
-                       dynamic_cast<FileSource*>(*src)->build_peaks ();
+               for (vector<boost::shared_ptr<Source> >::iterator src=srcs.begin(); src != srcs.end(); ++src) {
+                       boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
+                       if (afs) {
+                               afs->build_peaks ();
+                       }
                }
                
                ret = 0;
@@ -3515,40 +3984,63 @@ Session::write_one_track (AudioTrack& track, jack_nframes_t start, jack_nframes_
                
   out:
        if (ret) {
-               for (vector<Source*>::iterator src=srcs.begin(); src != srcs.end(); ++src) {
-                       dynamic_cast<FileSource*>(*src)->mark_for_remove ();
-                       delete *src;
-               }
-       }
+               for (vector<boost::shared_ptr<Source> >::iterator src = srcs.begin(); src != srcs.end(); ++src) {
+                       boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
 
-       for (vector<Sample*>::iterator i = buffers.begin(); i != buffers.end(); ++i) {
-               free(*i);
+                       if (afs) {
+                               afs->mark_for_remove ();
+                       }
+
+                       (*src)->drop_references ();
+               }
        }
 
-       atomic_set (&processing_prohibited, 0);
+       g_atomic_int_set (&processing_prohibited, 0);
 
        itt.done = true;
 
        return ret;
 }
 
-vector<Sample*>&
-Session::get_silent_buffers (uint32_t howmany)
+BufferSet&
+Session::get_silent_buffers (ChanCount count)
 {
-       for (uint32_t i = 0; i < howmany; ++i) {
-               memset (_silent_buffers[i], 0, sizeof (Sample) * current_block_size);
+       assert(_silent_buffers->available() >= count);
+       _silent_buffers->set_count(count);
+
+       for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
+               for (size_t i=0; i < count.get(*t); ++i) {
+                       _silent_buffers->get(*t, i).clear();
+               }
        }
-       return _silent_buffers;
+       
+       return *_silent_buffers;
+}
+
+BufferSet&
+Session::get_scratch_buffers (ChanCount count)
+{
+       assert(_scratch_buffers->available() >= count);
+       _scratch_buffers->set_count(count);
+       return *_scratch_buffers;
+}
+
+BufferSet&
+Session::get_send_buffers (ChanCount count)
+{
+       assert(_send_buffers->available() >= count);
+       _send_buffers->set_count(count);
+       return *_send_buffers;
 }
 
 uint32_t 
 Session::ntracks () const
 {
        uint32_t n = 0;
-       RWLockMonitor lm (route_lock, false, __LINE__, __FILE__);
+       shared_ptr<RouteList> r = routes.reader ();
 
-       for (RouteList::const_iterator i = routes.begin(); i != routes.end(); ++i) {
-               if (dynamic_cast<AudioTrack*> (*i)) {
+       for (RouteList::const_iterator i = r->begin(); i != r->end(); ++i) {
+               if (dynamic_cast<Track*> ((*i).get())) {
                        ++n;
                }
        }
@@ -3560,10 +4052,10 @@ uint32_t
 Session::nbusses () const
 {
        uint32_t n = 0;
-       RWLockMonitor lm (route_lock, false, __LINE__, __FILE__);
+       shared_ptr<RouteList> r = routes.reader ();
 
-       for (RouteList::const_iterator i = routes.begin(); i != routes.end(); ++i) {
-               if (dynamic_cast<AudioTrack*> (*i) == 0) {
+       for (RouteList::const_iterator i = r->begin(); i != r->end(); ++i) {
+               if (dynamic_cast<Track*> ((*i).get()) == 0) {
                        ++n;
                }
        }
@@ -3591,3 +4083,14 @@ Session::set_xfade_model (CrossfadeModel xm)
        }
 }
 
+void
+Session::add_curve(Curve *curve)
+{
+    curves[curve->id()] = curve;
+}
+
+void
+Session::add_automation_list(AutomationList *al)
+{
+    automation_lists[al->id()] = al;
+}