Merged with trunk R1304
[ardour.git] / libs / ardour / session.cc
index 9cfaf18cb0a95646c47f763284f75f5a45c226de..eb9e1c69ca3e15b84e089befd56780ec82dacdb6 100644 (file)
@@ -40,6 +40,7 @@
 #include <pbd/pathscanner.h>
 #include <pbd/stl_delete.h>
 #include <pbd/basename.h>
+#include <pbd/stacktrace.h>
 
 #include <ardour/audioengine.h>
 #include <ardour/configuration.h>
@@ -71,6 +72,8 @@
 #include <ardour/click.h>
 #include <ardour/data_type.h>
 #include <ardour/buffer_set.h>
+#include <ardour/source_factory.h>
+#include <ardour/region_factory.h>
 
 #ifdef HAVE_LIBLO
 #include <ardour/osc.h>
@@ -86,10 +89,11 @@ 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::old_sound_dir_name = X_("sounds");
+const char* Session::sound_dir_name = X_("audiofiles");
 const char* Session::peak_dir_name = X_("peaks");
 const char* Session::dead_sound_dir_name = X_("dead_sounds");
+const char* Session::interchange_dir_name = X_("interchange");
 
 Session::compute_peak_t                                Session::compute_peak                   = 0;
 Session::apply_gain_to_buffer_t                Session::apply_gain_to_buffer   = 0;
@@ -97,9 +101,11 @@ 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;
 
+sigc::signal<void> Session::SMPTEOffsetChanged;
+sigc::signal<void> Session::StartTimeChanged;
+sigc::signal<void> Session::EndTimeChanged;
 
 int
 Session::find_session (string str, string& path, string& snapshot, bool& isnew)
@@ -266,6 +272,7 @@ Session::Session (AudioEngine &eng,
          pending_events (2048),
          //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),
@@ -273,18 +280,24 @@ Session::Session (AudioEngine &eng,
 {
        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();
 
        first_stage_init (fullpath, snapshot_name);
        
-       if (create (new_session, mix_template, _engine.frame_rate() * 60 * 5)) {
-               throw failed_constructor ();
+       new_session = !g_file_test (_path.c_str(), GFileTest (G_FILE_TEST_EXISTS | G_FILE_TEST_IS_DIR));
+       if (new_session) {
+               if (create (new_session, mix_template, compute_initial_length())) {
+                       cerr << "create failed\n";
+                       destroy ();
+                       throw failed_constructor ();
+               }
        }
        
        if (second_stage_init (new_session)) {
+               destroy ();
                throw failed_constructor ();
        }
        
@@ -294,6 +307,8 @@ Session::Session (AudioEngine &eng,
 
        _state_of_the_state = StateOfTheState (_state_of_the_state & ~Dirty);
 
+       Config->ParameterChanged.connect (mem_fun (*this, &Session::config_changed));
+
        if (was_dirty) {
                DirtyChanged (); /* EMIT SIGNAL */
        }
@@ -308,7 +323,7 @@ Session::Session (AudioEngine &eng,
                  uint32_t master_out_channels,
                  uint32_t requested_physical_in,
                  uint32_t requested_physical_out,
-                 jack_nframes_t initial_length)
+                 nframes_t initial_length)
 
        : _engine (eng),
          _scratch_buffers(new BufferSet()),
@@ -320,42 +335,61 @@ Session::Session (AudioEngine &eng,
          pending_events (2048),
          //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 = _engine.n_physical_outputs();
+       n_physical_inputs = _engine.n_physical_inputs();
+
+       if (n_physical_inputs) {
+               n_physical_inputs = max (requested_physical_in, n_physical_inputs);
+       }
 
-       n_physical_outputs = max (requested_physical_out, _engine.n_physical_outputs());
-       n_physical_inputs = max (requested_physical_in, _engine.n_physical_inputs());
+       if (n_physical_outputs) {
+               n_physical_outputs = max (requested_physical_out, n_physical_outputs);
+       }
 
        first_stage_init (fullpath, snapshot_name);
-       
-       if (create (new_session, 0, initial_length)) {
-               throw failed_constructor ();
+
+       new_session = !g_file_test (_path.c_str(), GFileTest (G_FILE_TEST_EXISTS | G_FILE_TEST_IS_DIR));
+
+       if (new_session) {
+               if (create (new_session, 0, initial_length)) {
+                       destroy ();
+                       throw failed_constructor ();
+               }
        }
 
        if (control_out_channels) {
                shared_ptr<Route> r (new Route (*this, _("monitor"), -1, control_out_channels, -1, control_out_channels, Route::ControlOut));
-               add_route (r);
+               RouteList rl;
+               rl.push_back (r);
+               add_routes (rl);
                _control_out = r;
        }
 
        if (master_out_channels) {
                shared_ptr<Route> r (new Route (*this, _("master"), -1, master_out_channels, -1, master_out_channels, Route::MasterOut));
-               add_route (r);
+               RouteList rl;
+               rl.push_back (r);
+               add_routes (rl);
                _master_out = r;
        } else {
                /* prohibit auto-connect to master, because there isn't one */
                output_ac = AutoConnectOption (output_ac & ~AutoConnectMaster);
        }
 
-       input_auto_connect = input_ac;
-       output_auto_connect = output_ac;
+       Config->set_input_auto_connect (input_ac);
+       Config->set_output_auto_connect (output_ac);
 
        if (second_stage_init (new_session)) {
+               destroy ();
                throw failed_constructor ();
        }
        
@@ -371,6 +405,12 @@ Session::Session (AudioEngine &eng,
 }
 
 Session::~Session ()
+{
+       destroy ();
+}
+
+void
+Session::destroy ()
 {
        /* if we got to here, leaving pending capture state around
           is a mistake.
@@ -380,9 +420,23 @@ 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 ();
        
@@ -425,53 +479,88 @@ Session::~Session ()
                tmp = i;
                ++tmp;
 
-               delete *i;
+               (*i)->drop_references ();
                
                i = tmp;
        }
+       
+       for (PlaylistList::iterator i = unused_playlists.begin(); i != unused_playlists.end(); ) {
+               PlaylistList::iterator tmp;
 
-#ifdef TRACK_DESTRUCTION
-       cerr << "delete audio regions\n";
-#endif /* TRACK_DESTRUCTION */
-       for (AudioRegionList::iterator i = audio_regions.begin(); i != audio_regions.end(); ) {
-               AudioRegionList::iterator tmp;
-
-               tmp =i;
+               tmp = i;
                ++tmp;
 
-               delete i->second;
-
+               (*i)->drop_references ();
+               
                i = tmp;
        }
        
+       playlists.clear ();
+       unused_playlists.clear ();
+
 #ifdef TRACK_DESTRUCTION
-       cerr << "delete diskstreams\n";
+       cerr << "delete regions\n";
 #endif /* TRACK_DESTRUCTION */
-       for (DiskstreamList::iterator i = diskstreams.begin(); i != diskstreams.end(); ) {
-               DiskstreamList::iterator tmp;
+       
+       for (RegionList::iterator i = regions.begin(); i != regions.end(); ) {
+               RegionList::iterator tmp;
 
                tmp = i;
                ++tmp;
 
-               delete *i;
+               cerr << "dropping refs on a region (" << i->second->name() << " @ " << i->second << ") with UC = " << i->second.use_count() << endl;
+               i->second->drop_references ();
+               cerr << "AFTER: UC = " << i->second.use_count() << endl;
 
                i = tmp;
        }
 
+       regions.clear ();
+
+#ifdef TRACK_DESTRUCTION
+       cerr << "delete routes\n";
+#endif /* TRACK_DESTRUCTION */
+        {
+               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 */
+       {
+              RCUWriter<DiskstreamList> dwriter (diskstreams);
+              boost::shared_ptr<DiskstreamList> dsl = dwriter.get_copy();
+              for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
+                      (*i)->drop_references ();
+              }
+              dsl->clear ();
+       }
+       diskstreams.flush ();
+
 #ifdef TRACK_DESTRUCTION
        cerr << "delete audio sources\n";
 #endif /* TRACK_DESTRUCTION */
-       for (AudioSourceList::iterator i = audio_sources.begin(); i != audio_sources.end(); ) {
-               AudioSourceList::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 */
@@ -527,10 +616,6 @@ Session::~Session ()
        if (mmc) {
                delete mmc;
        }
-
-       if (state_tree) {
-               delete state_tree;
-       }
 }
 
 void
@@ -558,11 +643,11 @@ Session::when_engine_running ()
 
        /* we don't want to run execute this again */
 
-       first_time_running.disconnect ();
-
        set_block_size (_engine.frames_per_cycle());
        set_frame_rate (_engine.frame_rate());
 
+       Config->map_parameters (mem_fun (*this, &Session::config_changed));
+
        /* every time we reconnect, recompute worst case output latencies */
 
        _engine.Running.connect (mem_fun (*this, &Session::set_worst_io_latencies));
@@ -588,7 +673,7 @@ Session::when_engine_running ()
                        
                        if (_click_io->set_state (*child->children().front()) == 0) {
                                
-                               _clicking = click_requested;
+                               _clicking = Config->get_clicking ();
 
                        } else {
 
@@ -606,7 +691,7 @@ Session::when_engine_running ()
                                if (_click_io->add_output_port (first_physical_output, this)) {
                                        // relax, even though its an error
                                } else {
-                                       _clicking = click_requested;
+                                       _clicking = Config->get_clicking ();
                                }
                        }
                }
@@ -619,24 +704,7 @@ Session::when_engine_running ()
        set_worst_io_latencies ();
 
        if (_clicking) {
-                ControlChanged (Clicking); /* EMIT SIGNAL */
-       }
-
-       if (auditioner == 0) {
-
-               /* we delay creating the auditioner till now because
-                  it makes its own connections to ports named
-                  in the ARDOUR_RC config file. the engine has
-                  to be running for this to work.
-               */
-
-               try {
-                       auditioner.reset (new Auditioner (*this));
-               }
-
-               catch (failed_constructor& err) {
-                       warning << _("cannot create Auditioner: no auditioning of regions possible") << endmsg;
-               }
+               // XXX HOW TO ALERT UI TO THIS ? DO WE NEED TO?
        }
 
        /* Create a set of Connection objects that map
@@ -778,6 +846,7 @@ Session::when_engine_running ()
                }
        }
 
+       
        _state_of_the_state = StateOfTheState (_state_of_the_state & ~(CannotSave|Dirty));
 
        /* hook us up to the engine */
@@ -804,6 +873,22 @@ Session::hookup_io ()
 
        _state_of_the_state = StateOfTheState (_state_of_the_state | InitialConnecting);
 
+       if (auditioner == 0) {
+               
+               /* we delay creating the auditioner till now because
+                  it makes its own connections to ports.
+                  the engine has to be running for this to work.
+               */
+               
+               try {
+                       auditioner.reset (new Auditioner (*this));
+               }
+               
+               catch (failed_constructor& err) {
+                       warning << _("cannot create Auditioner: no auditioning of regions possible") << endmsg;
+               }
+       }
+
        /* Tell all IO objects to create their ports */
 
        IO::enable_ports ();
@@ -855,7 +940,7 @@ Session::hookup_io ()
 }
 
 void
-Session::playlist_length_changed (Playlist* pl)
+Session::playlist_length_changed ()
 {
        /* we can't just increase end_location->end() if pl->get_maximum_extent() 
           if larger. if the playlist used to be the longest playlist,
@@ -867,12 +952,12 @@ Session::playlist_length_changed (Playlist* pl)
 }
 
 void
-Session::diskstream_playlist_changed (Diskstream* dstream)
+Session::diskstream_playlist_changed (boost::shared_ptr<Diskstream> dstream)
 {
-       Playlist *playlist;
+       boost::shared_ptr<Playlist> playlist;
 
        if ((playlist = dstream->playlist()) != 0) {
-         playlist->LengthChanged.connect (sigc::bind (mem_fun (this, &Session::playlist_length_changed), playlist));
+               playlist->LengthChanged.connect (mem_fun (this, &Session::playlist_length_changed));
        }
        
        /* see comment in playlist_length_changed () */
@@ -887,142 +972,52 @@ Session::record_enabling_legal () const
        //      return false;
        // }
 
-       if (all_safe) {
+       if (Config->get_all_safe()) {
                return false;
        }
        return true;
 }
 
-void
-Session::set_auto_play (bool yn)
-{
-       if (auto_play != yn) {
-               auto_play = yn; 
-               set_dirty ();
-               ControlChanged (AutoPlay);
-       }
-}
-
-void
-Session::set_auto_return (bool yn)
-{
-       if (auto_return != yn) {
-               auto_return = yn; 
-               set_dirty ();
-               ControlChanged (AutoReturn);
-       }
-}
-
-void
-Session::set_crossfades_active (bool yn)
-{
-       if (crossfades_active != yn) {
-               crossfades_active = yn; 
-               set_dirty ();
-               ControlChanged (CrossFadesActive);
-       }
-}
-
-void
-Session::set_do_not_record_plugins (bool yn)
-{
-       if (do_not_record_plugins != yn) {
-               do_not_record_plugins = yn; 
-               set_dirty ();
-               ControlChanged (RecordingPlugins); 
-       }
-}
-
-void
-Session::set_auto_input (bool yn)
-{
-       if (auto_input != yn) {
-               auto_input = yn;
-               
-               if (Config->get_use_hardware_monitoring() && transport_rolling()) {
-                       /* auto-input only makes a difference if we're rolling */
-
-                       /* 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"
-                       */
-                       Glib::RWLock::ReaderLock dsm (diskstream_lock);
-                       for (DiskstreamList::iterator i = diskstreams.begin(); i != diskstreams.end(); ++i) {
-                               if ((*i)->record_enabled ()) {
-                                       //cerr << "switching to input = " << !auto_input << __FILE__ << __LINE__ << endl << endl;
-                                       (*i)->monitor_input (!auto_input);   
-                               }
-                       }
-               }
-
-               set_dirty();
-               ControlChanged (AutoInput);
-       }
-}
-
 void
 Session::reset_input_monitor_state ()
 {
        if (transport_rolling()) {
-               Glib::RWLock::ReaderLock dsm (diskstream_lock);
-               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);
+                               (*i)->monitor_input (Config->get_monitoring_model() == HardwareMonitoring && !Config->get_auto_input());
                        }
                }
        } else {
-               Glib::RWLock::ReaderLock dsm (diskstream_lock);
-               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());
+                               //cerr << "switching to input = " << !Config->get_auto_input() << __FILE__ << __LINE__ << endl << endl;
+                               (*i)->monitor_input (Config->get_monitoring_model() == HardwareMonitoring);
                        }
                }
        }
 }
 
-
-void
-Session::set_input_auto_connect (bool yn)
-{
-       if (yn) {
-               input_auto_connect = AutoConnectOption (input_auto_connect|AutoConnectPhysical);
-       } else {
-               input_auto_connect = AutoConnectOption (input_auto_connect|~AutoConnectPhysical);
-       }
-       set_dirty ();
-}
-
-bool
-Session::get_input_auto_connect () const
-{
-       return (input_auto_connect & AutoConnectPhysical);
-}
-
-void
-Session::set_output_auto_connect (AutoConnectOption aco)
-{
-       output_auto_connect = aco;
-       set_dirty ();
-}
-
 void
 Session::auto_punch_start_changed (Location* location)
 {
        replace_event (Event::PunchIn, location->start());
 
-       if (get_record_enabled() && get_punch_in()) {
+       if (get_record_enabled() && Config->get_punch_in()) {
                /* capture start has been changed, so save new pending state */
                save_state ("", true);
-                save_history("");
        }
 }      
 
 void
 Session::auto_punch_end_changed (Location* location)
 {
-       jack_nframes_t when_to_stop = location->end();
+       nframes_t when_to_stop = location->end();
        // when_to_stop += _worst_output_latency + _worst_input_latency;
        replace_event (Event::PunchOut, when_to_stop);
 }      
@@ -1030,7 +1025,7 @@ Session::auto_punch_end_changed (Location* location)
 void
 Session::auto_punch_changed (Location* location)
 {
-       jack_nframes_t when_to_stop = location->end();
+       nframes_t when_to_stop = location->end();
 
        replace_event (Event::PunchIn, location->start());
        //when_to_stop += _worst_output_latency + _worst_input_latency;
@@ -1042,7 +1037,7 @@ Session::auto_loop_changed (Location* location)
 {
        replace_event (Event::AutoLoop, location->end(), location->start());
 
-       if (transport_rolling() && get_auto_loop()) {
+       if (transport_rolling() && play_loop) {
 
                //if (_transport_frame < location->start() || _transport_frame > location->end()) {
 
@@ -1053,7 +1048,7 @@ Session::auto_loop_changed (Location* location)
                        request_locate (location->start(), true);
 
                }
-               else if (seamless_loop && !loop_changing) {
+               else if (Config->get_seamless_loop() && !loop_changing) {
                        
                        // schedule a locate-roll to refill the diskstreams at the
                        // previous loop end
@@ -1110,48 +1105,6 @@ Session::set_auto_punch_location (Location* location)
        auto_punch_location_changed (location);
 }
 
-void
-Session::set_punch_in (bool yn)
-{
-       if (punch_in == yn) {
-               return;
-       }
-
-       Location* location;
-
-       if ((location = _locations.auto_punch_location()) != 0) {
-               if ((punch_in = yn) == true) {
-                       replace_event (Event::PunchIn, location->start());
-               } else {
-                       remove_event (location->start(), Event::PunchIn);
-               }
-       }
-
-       set_dirty();
-       ControlChanged (PunchIn); /* EMIT SIGNAL */
-}
-
-void
-Session::set_punch_out (bool yn)
-{
-       if (punch_out == yn) {
-               return;
-       }
-
-       Location* location;
-
-       if ((location = _locations.auto_punch_location()) != 0) {
-               if ((punch_out = yn) == true) {
-                       replace_event (Event::PunchOut, location->end());
-               } else {
-                       clear_events (Event::PunchOut);
-               }
-       }
-
-       set_dirty();
-       ControlChanged (PunchOut); /* EMIT SIGNAL */
-}
-
 void
 Session::set_auto_loop_location (Location* location)
 {
@@ -1245,14 +1198,9 @@ Session::enable_record ()
                _last_record_location = _transport_frame;
                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"
-                       */
-                       Glib::RWLock::ReaderLock dsm (diskstream_lock);
-                       
-                       for (DiskstreamList::iterator i = diskstreams.begin(); i != diskstreams.end(); ++i) {
+               if (Config->get_monitoring_model() == HardwareMonitoring && Config->get_auto_input()) {
+                       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);   
                                }
@@ -1284,14 +1232,10 @@ Session::disable_record (bool rt_context, bool force)
                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"
-                       */
-                       Glib::RWLock::ReaderLock dsm (diskstream_lock);
+               if (Config->get_monitoring_model() == HardwareMonitoring && Config->get_auto_input()) {
+                       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);   
                                }
@@ -1311,15 +1255,11 @@ Session::step_back_from_record ()
 {
        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"
-               */
-               Glib::RWLock::ReaderLock dsm (diskstream_lock);
+       if (Config->get_monitoring_model() == HardwareMonitoring) {
+               boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
                
-               for (DiskstreamList::iterator i = diskstreams.begin(); i != diskstreams.end(); ++i) {
-                       if (auto_input && (*i)->record_enabled ()) {
+               for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
+                       if (Config->get_auto_input() && (*i)->record_enabled ()) {
                                //cerr << "switching from input" << __FILE__ << __LINE__ << endl << endl;
                                (*i)->monitor_input (false);   
                        }
@@ -1332,15 +1272,14 @@ Session::maybe_enable_record ()
 {
        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.
+       /* this function is currently called from somewhere other than an RT thread.
+          this save_state() call therefore doesn't impact anything.
        */
 
        save_state ("", true);
-        save_history ("");
 
        if (_transport_speed) {
-               if (!punch_in) {
+               if (!Config->get_punch_in()) {
                        enable_record ();
                } 
        } else {
@@ -1351,12 +1290,12 @@ Session::maybe_enable_record ()
        set_dirty();
 }
 
-jack_nframes_t
+nframes_t
 Session::audible_frame () const
 {
-       jack_nframes_t ret;
-       jack_nframes_t offset;
-       jack_nframes_t tf;
+       nframes_t ret;
+       nframes_t offset;
+       nframes_t tf;
 
        /* the first of these two possible settings for "offset"
           mean that the audible frame is stationary until 
@@ -1410,22 +1349,23 @@ Session::audible_frame () const
 }
 
 void
-Session::set_frame_rate (jack_nframes_t frames_per_second)
+Session::set_frame_rate (nframes_t frames_per_second)
 {
-       /** \fn void Session::set_frame_size(jack_nframes_t)
+       /** \fn void Session::set_frame_size(nframes_t)
                the AudioEngine object that calls this guarantees 
                that it will not be called while we are also in
                ::process(). Its fine to do things that block
                here.
        */
 
-       _current_frame_rate = frames_per_second;
-       _frames_per_smpte_frame = (double) _current_frame_rate / (double) smpte_frames_per_second;
+       _base_frame_rate = frames_per_second;
+
+       sync_time_vars();
 
        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);
+       // SndFileSource::setup_standard_crossfades (frames_per_second);
 
        set_dirty();
 
@@ -1433,7 +1373,7 @@ Session::set_frame_rate (jack_nframes_t frames_per_second)
 }
 
 void
-Session::set_block_size (jack_nframes_t nframes)
+Session::set_block_size (nframes_t nframes)
 {
        /* the AudioEngine guarantees 
           that it will not be called while we are also in
@@ -1442,7 +1382,6 @@ Session::set_block_size (jack_nframes_t nframes)
        */
 
        { 
-               Glib::RWLock::ReaderLock dsm (diskstream_lock);
                        
                current_block_size = nframes;
                
@@ -1461,7 +1400,8 @@ Session::set_block_size (jack_nframes_t nframes)
                        (*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);
                }
 
@@ -1473,7 +1413,7 @@ void
 Session::set_default_fade (float steepness, float fade_msecs)
 {
 #if 0
-       jack_nframes_t fade_frames;
+       nframes_t fade_frames;
        
        /* Don't allow fade of less 1 frame */
        
@@ -1484,7 +1424,7 @@ Session::set_default_fade (float steepness, float fade_msecs)
 
        } else {
                
-               fade_frames = (jack_nframes_t) floor (fade_msecs * _current_frame_rate * 0.001);
+               fade_frames = (nframes_t) floor (fade_msecs * _current_frame_rate * 0.001);
                
        }
 
@@ -1641,13 +1581,16 @@ Session::resort_routes_using (shared_ptr<RouteList> r)
        
 }
 
-boost::shared_ptr<MidiTrack>
-Session::new_midi_track (TrackMode mode)
+list<boost::shared_ptr<MidiTrack> >
+Session::new_midi_track (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<MidiTrack> > ret;
 
        /* count existing midi tracks */
 
@@ -1664,300 +1607,216 @@ Session::new_midi_track (TrackMode mode)
                }
        }
 
-       /* 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 (how_many) {
 
-       do {
-               snprintf (track_name, sizeof(track_name), "Midi %" 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;
 
-       try {
-               shared_ptr<MidiTrack> track (new MidiTrack (*this, track_name, Route::Flag (0), mode));
+                       snprintf (track_name, sizeof(track_name), "Midi %" PRIu32, track_id);
 
-               if (track->ensure_io (1, 1, false, this)) {
-                       error << string_compose (_("cannot configure %1 in/%2 out configuration for new midi track"), track_name)
-                             << endmsg;
-               }
-#if 0
-               if (nphysical_in) {
-                       for (uint32_t x = 0; x < track->n_inputs() && x < nphysical_in; ++x) {
-                               
-                               port = "";
-                               
-                               if (input_auto_connect & AutoConnectPhysical) {
-                                       port = _engine.get_nth_physical_input ((channels_used+x)%nphysical_in);
-                               } 
-                               
-                               if (port.length() && track->connect_input (track->input (x), port, this)) {
-                                       break;
-                               }
+                       if (route_by_name (track_name) == 0) {
+                               break;
                        }
-               }
-               
-               for (uint32_t x = 0; x < track->n_outputs(); ++x) {
                        
-                       port = "";
-
-                       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();
-                               }
-                       }
+               } while (track_id < (UINT_MAX-1));
 
-                       if (port.length() && track->connect_output (track->output (x), port, this)) {
-                               break;
+               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;
                        }
-               }
-
-               if (_control_out) {
-                       vector<string> cports;
-                       uint32_t ni = _control_out->n_inputs();
+                       
+                       channels_used += track->n_inputs ().get(DataType::MIDI);
 
-                       for (n = 0; n < ni; ++n) {
-                               cports.push_back (_control_out->input(n)->name());
-                       }
+                       track->DiskstreamChanged.connect (mem_fun (this, &Session::resort_routes));
+                       track->set_remote_control_id (ntracks());
 
-                       track->set_control_outs (cports);
+                       new_routes.push_back (track);
+                       ret.push_back (track);
                }
-#endif
-               track->DiskstreamChanged.connect (mem_fun (this, &Session::resort_routes));
 
-               add_route (track);
-
-               track->set_remote_control_id (ntracks());
-               return 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;
        }
 
-       catch (failed_constructor &err) {
-               error << _("Session: could not create new midi track.") << endmsg;
-               return shared_ptr<MidiTrack> ((MidiTrack*) 0);
+       if (!new_routes.empty()) {
+               add_routes (new_routes, false);
+               save_state (_current_snapshot_name);
        }
-}
 
+       return ret;
+}
 
-boost::shared_ptr<Route>
-Session::new_midi_route ()
+list<boost::shared_ptr<AudioTrack> >
+Session::new_audio_track (int input_channels, int output_channels, TrackMode mode, uint32_t how_many)
 {
-       char bus_name[32];
+       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;
+       uint32_t control_id;
+
+       /* count existing audio tracks */
 
-       /* count existing midi busses */
        {
                shared_ptr<RouteList> r = routes.reader ();
 
                for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
-                       if (dynamic_cast<MidiTrack*>((*i).get()) == 0) {
+                       if (dynamic_cast<AudioTrack*>((*i).get()) != 0) {
                                if (!(*i)->hidden()) {
                                        n++;
+                                       channels_used += (*i)->n_inputs().get(DataType::AUDIO);
                                }
                        }
                }
        }
 
-       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;
+       uint32_t nphysical_in;
+       uint32_t nphysical_out;
 
-       } while (n < (UINT_MAX-1));
+       _engine.get_physical_outputs (physoutputs);
+       _engine.get_physical_inputs (physinputs);
+       control_id = 0;
 
-       try {
-               shared_ptr<Route> bus (new Route (*this, bus_name, -1, -1, -1, -1, Route::Flag(0), DataType::MIDI));
-               
-               if (bus->ensure_io (1, 1, false, this)) {
-                       error << (_("cannot configure 1 in/1 out configuration for new midi track"))
-                             << endmsg;
-               }
-#if 0
-               for (uint32_t x = 0; x < bus->n_inputs(); ++x) {
-                       
-                       port = "";
+       while (how_many) {
 
-                       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)) {
-                               break;
-                       }
-               }
+               /* 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)
+               */
+               
 
-               for (uint32_t x = 0; x < bus->n_outputs(); ++x) {
-                       
-                       port = "";
+               do {
+                       ++track_id;
 
-                       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();
-                               }
-                       }
+                       snprintf (track_name, sizeof(track_name), "Audio %" PRIu32, track_id);
 
-                       if (port.length() && bus->connect_output (bus->output (x), port, this)) {
+                       if (route_by_name (track_name) == 0) {
                                break;
                        }
-               }
-#endif
-/*
-               if (_control_out) {
-                       vector<string> cports;
-                       uint32_t ni = _control_out->n_inputs();
+                       
+               } while (track_id < (UINT_MAX-1));
 
-                       for (uint32_t n = 0; n < ni; ++n) {
-                               cports.push_back (_control_out->input(n)->name());
-                       }
-                       bus->set_control_outs (cports);
+               if (Config->get_input_auto_connect() & AutoConnectPhysical) {
+                       nphysical_in = min (n_physical_inputs, (uint32_t) physinputs.size());
+               } else {
+                       nphysical_in = 0;
                }
-*/             
-               add_route (bus);
-               return bus;
-       }
-
-       catch (failed_constructor &err) {
-               error << _("Session: could not create new MIDI route.") << endmsg;
-               return shared_ptr<Route> ((Route*) 0);
-       }
-}
-
-
-shared_ptr<AudioTrack>
-Session::new_audio_track (int input_channels, int output_channels, TrackMode mode)
-{
-       char track_name[32];
-       uint32_t n = 0;
-       uint32_t channels_used = 0;
-       string port;
-       uint32_t nphysical_in;
-       uint32_t nphysical_out;
-
-       /* 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);
+               
+               if (Config->get_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 (Config->get_input_auto_connect() & AutoConnectPhysical) {
+                                               port = physinputs[(channels_used+x)%nphysical_in];
+                                       } 
+                                       
+                                       if (port.length() && track->connect_input (track->input (x), port, this)) {
+                                               break;
+                                       }
                                }
                        }
-               }
-       }
-
-       /* 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 {
-               snprintf (track_name, sizeof(track_name), "Audio %" PRIu32, n+1);
-               if (route_by_name (track_name) == 0) {
-                       break;
-               }
-               n++;
-
-       } while (n < (UINT_MAX-1));
-
-       if (input_auto_connect & AutoConnectPhysical) {
-               nphysical_in = n_physical_inputs;
-       } else {
-               nphysical_in = 0;
-       }
-
-       if (output_auto_connect & AutoConnectPhysical) {
-               nphysical_out = n_physical_outputs;
-       } else {
-               nphysical_out = 0;
-       }
-
-       try {
-               shared_ptr<AudioTrack> track (new AudioTrack (*this, track_name, Route::Flag (0), mode));
-
-               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;
-               }
-
-               if (nphysical_in) {
-                       for (uint32_t x = 0; x < track->n_inputs().get(DataType::AUDIO) && x < nphysical_in; ++x) {
+                       
+                       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 (DataType::AUDIO, (channels_used+x)%nphysical_in);
-                               } 
+                               if (nphysical_out && (Config->get_output_auto_connect() & AutoConnectPhysical)) {
+                                       port = physoutputs[(channels_used+x)%nphysical_out];
+                               } else if (Config->get_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().get(DataType::AUDIO); ++x) {
                        
-                       port = "";
+                       channels_used += track->n_inputs ().get(DataType::AUDIO);
 
-                       if (nphysical_out && (output_auto_connect & AutoConnectPhysical)) {
-                               port = _engine.get_nth_physical_output (DataType::AUDIO, (channels_used+x)%nphysical_out);
-                       } else if (output_auto_connect & AutoConnectMaster) {
-                               if (_master_out) {
-                                       port = _master_out->audio_input (x%_master_out->n_inputs().get(DataType::AUDIO))->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() + control_id + 1);
+                       ++control_id;
 
-                       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().get(DataType::AUDIO);
-
-                       for (n = 0; n < ni; ++n) {
-                               cports.push_back (_control_out->audio_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->DiskstreamChanged.connect (mem_fun (this, &Session::resort_routes));
-
-               add_route (track);
-
-               track->set_remote_control_id (ntracks());
-               return track;
+               
+               --how_many;
        }
 
-       catch (failed_constructor &err) {
-               error << _("Session: could not create new audio track.") << endmsg;
-               return shared_ptr<AudioTrack> ((AudioTrack*) 0);
+       if (!new_routes.empty()) {
+               add_routes (new_routes, false);
+               save_state (_current_snapshot_name);
        }
+
+       return ret;
 }
 
-shared_ptr<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)
 {
        char bus_name[32];
+       uint32_t bus_id = 1;
        uint32_t n = 0;
        string port;
+       RouteList ret;
 
        /* count existing audio busses */
 
@@ -1967,127 +1826,151 @@ Session::new_audio_route (int input_channels, int output_channels)
                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 {
-               shared_ptr<Route> bus (new Route (*this, bus_name, -1, -1, -1, -1, Route::Flag(0), DataType::AUDIO));
+       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().get(DataType::AUDIO); ++x) {
-                       
-                       port = "";
+                       snprintf (bus_name, sizeof(bus_name), "Bus %" PRIu32, bus_id);
 
-                       if (input_auto_connect & AutoConnectPhysical) {
-                               port = _engine.get_nth_physical_input (DataType::AUDIO, (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().get(DataType::AUDIO); ++x) {
+               } while (bus_id < (UINT_MAX-1));
+
+               try {
+                       shared_ptr<Route> bus (new Route (*this, bus_name, -1, -1, -1, -1, Route::Flag(0), DataType::AUDIO));
                        
-                       port = "";
+                       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; n_physical_inputs && x < bus->n_inputs().get(DataType::AUDIO); ++x) {
+                               
+                               port = "";
 
-                       if (output_auto_connect & AutoConnectPhysical) {
-                               port = _engine.get_nth_physical_input (DataType::AUDIO, (n+x)%n_physical_outputs);
-                       } else if (output_auto_connect & AutoConnectMaster) {
-                               if (_master_out) {
-                                       port = _master_out->audio_input (x%_master_out->n_inputs().get(DataType::AUDIO))->name();
+                               if (Config->get_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; n_physical_outputs && x < bus->n_outputs().get(DataType::AUDIO); ++x) {
+                               
+                               port = "";
+                               
+                               if (Config->get_output_auto_connect() & AutoConnectPhysical) {
+                                       port = physoutputs[((n+x)%n_physical_outputs)];
+                               } else if (Config->get_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().get(DataType::AUDIO);
+                       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);
-               return bus;
+
+               --how_many;
        }
 
-       catch (failed_constructor &err) {
-               error << _("Session: could not create new audio route.") << endmsg;
-               return shared_ptr<Route> ((Route*) 0);
+       if (!ret.empty()) {
+               add_routes (ret, false);
+               save_state (_current_snapshot_name);
        }
+
+       return ret;
+
 }
 
 void
-Session::add_route (shared_ptr<Route> route)
+Session::add_routes (RouteList& new_routes, bool save)
 {
        { 
                RCUWriter<RouteList> writer (routes);
                shared_ptr<RouteList> r = writer.get_copy ();
-               r->push_front (route);
+               r->insert (r->end(), new_routes.begin(), new_routes.end());
                resort_routes_using (r);
        }
 
-       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;
-       }
+       for (RouteList::iterator x = new_routes.begin(); x != new_routes.end(); ++x) {
+               
+               boost::weak_ptr<Route> wpr (*x);
 
-       if (route->control()) {
-               _control_out = route;
+               (*x)->solo_changed.connect (sigc::bind (mem_fun (*this, &Session::route_solo_changed), wpr));
+               (*x)->mute_changed.connect (mem_fun (*this, &Session::route_mute_changed));
+               (*x)->output_changed.connect (mem_fun (*this, &Session::set_worst_io_latencies_x));
+               (*x)->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);
-       save_history (_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_with_alloc();
        
        { 
-               Glib::RWLock::WriterLock lm (diskstream_lock);
-               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));
@@ -2095,12 +1978,6 @@ Session::add_diskstream (Diskstream* dstream)
        diskstream_playlist_changed (dstream);
 
        dstream->prepare ();
-
-       set_dirty();
-       save_state (_current_snapshot_name);
-        save_history (_current_snapshot_name);
-
-       DiskstreamAdded (dstream); /* EMIT SIGNAL */
 }
 
 void
@@ -2109,19 +1986,20 @@ Session::remove_route (shared_ptr<Route> route)
        {       
                RCUWriter<RouteList> writer (routes);
                shared_ptr<RouteList> rs = writer.get_copy ();
-               rs->remove (route);
                
+               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 = shared_ptr<Route> ((Route*) 0);
+                       _master_out = shared_ptr<Route> ();
                }
 
                if (route == _control_out) {
-                       _control_out = shared_ptr<Route> ((Route*) 0);
+                       _control_out = shared_ptr<Route> ();
 
                        /* cancel control outs for all routes */
 
@@ -2137,34 +2015,46 @@ Session::remove_route (shared_ptr<Route> route)
                /* writer goes out of scope, forces route list update */
        }
 
-       AudioTrack* at;
-       AudioDiskstream* ds = 0;
+       Track* t;
+       boost::shared_ptr<Diskstream> ds;
        
-       if ((at = dynamic_cast<AudioTrack*>(route.get())) != 0) {
-               ds = &at->audio_diskstream();
+       if ((t = dynamic_cast<Track*>(route.get())) != 0) {
+               ds = t->diskstream();
        }
        
        if (ds) {
 
                {
-                       Glib::RWLock::WriterLock lm (diskstream_lock);
-                       diskstreams.remove (ds);
+                       RCUWriter<DiskstreamList> dsl (diskstreams);
+                       boost::shared_ptr<DiskstreamList> d = dsl.get_copy();
+                       d->remove (ds);
                }
-
-               ds->unref ();
        }
 
        find_current_end ();
        
        update_latency_compensation (false, false);
        set_dirty();
+
+       // We need to disconnect the routes inputs and outputs 
+       route->disconnect_inputs(NULL);
+       route->disconnect_outputs(NULL);
        
-       /* XXX should we disconnect from the Route's signals ? */
+       /* get rid of it from the dead wood collection in the route list manager */
+
+       /* XXX i think this is unsafe as it currently stands, but i am not sure. (pd, october 2nd, 2006) */
+
+       routes.flush ();
+
+       /* try to cause everyone to drop their references */
 
-       save_state (_current_snapshot_name);
-       save_history (_current_snapshot_name);
+       route->drop_references ();
 
-       /* all shared ptrs to route should go out of scope here */
+       /* save the new state of the world */
+
+       if (save_state (_current_snapshot_name)) {
+               save_history (_current_snapshot_name);
+       }
 }      
 
 void
@@ -2174,7 +2064,7 @@ Session::route_mute_changed (void* src)
 }
 
 void
-Session::route_solo_changed (void* src, shared_ptr<Route> route)
+Session::route_solo_changed (void* src, boost::weak_ptr<Route> wpr)
 {      
        if (solo_update_disabled) {
                // We know already
@@ -2182,8 +2072,15 @@ Session::route_solo_changed (void* src, shared_ptr<Route> route)
        }
        
        bool is_track;
-       
-       is_track = (dynamic_cast<AudioTrack*>(route.get()) != 0);
+       boost::shared_ptr<Route> route = wpr.lock ();
+
+       if (!route) {
+               /* should not happen */
+               error << string_compose (_("programming error: %1"), X_("invalid route weak ptr passed to route_solo_changed")) << endmsg;
+               return;
+       }
+
+       is_track = (boost::dynamic_pointer_cast<AudioTrack>(route) != 0);
        
        shared_ptr<RouteList> r = routes.reader ();
 
@@ -2195,7 +2092,7 @@ Session::route_solo_changed (void* src, shared_ptr<Route> route)
                        
                        /* don't mess with busses */
                        
-                       if (dynamic_cast<AudioTrack*>((*i).get()) == 0) {
+                       if (dynamic_cast<Track*>((*i).get()) == 0) {
                                continue;
                        }
                        
@@ -2203,7 +2100,7 @@ Session::route_solo_changed (void* src, shared_ptr<Route> route)
                        
                        /* don't mess with tracks */
                        
-                       if (dynamic_cast<AudioTrack*>((*i).get()) != 0) {
+                       if (dynamic_cast<Track*>((*i).get()) != 0) {
                                continue;
                        }
                }
@@ -2219,7 +2116,7 @@ Session::route_solo_changed (void* src, shared_ptr<Route> route)
                                   then leave it as it is.
                                */
                                
-                               if (_solo_latched) {
+                               if (Config->get_solo_latched()) {
                                        continue;
                                } 
                        }
@@ -2239,7 +2136,7 @@ Session::route_solo_changed (void* src, shared_ptr<Route> route)
         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
                if ((*i)->soloed()) {
                        something_soloed = true;
-                       if (dynamic_cast<AudioTrack*>((*i).get())) {
+                       if (dynamic_cast<Track*>((*i).get())) {
                                if (is_track) {
                                        same_thing_soloed = true;
                                        break;
@@ -2268,16 +2165,6 @@ Session::route_solo_changed (void* src, shared_ptr<Route> route)
        set_dirty();
 }
 
-void
-Session::set_solo_latched (bool yn)
-{
-       if (yn != _solo_latched) {
-               _solo_latched = yn;
-               set_dirty ();
-               ControlChanged (SoloLatch);
-       }
-}
-
 void
 Session::update_route_solo_state ()
 {
@@ -2296,7 +2183,7 @@ Session::update_route_solo_state ()
         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
                if ((*i)->soloed()) {
                        mute = true;
-                       if (dynamic_cast<AudioTrack*>((*i).get())) {
+                       if (dynamic_cast<Track*>((*i).get())) {
                                is_track = true;
                        }
                        break;
@@ -2341,7 +2228,7 @@ Session::modify_solo_mute (bool is_track, bool mute)
                        
                        /* only alter track solo mute */
                        
-                       if (dynamic_cast<AudioTrack*>((*i).get())) {
+                       if (dynamic_cast<Track*>((*i).get())) {
                                if ((*i)->soloed()) {
                                        (*i)->set_solo_mute (!mute);
                                } else {
@@ -2353,7 +2240,7 @@ Session::modify_solo_mute (bool is_track, bool mute)
 
                        /* only alter bus solo mute */
 
-                       if (!dynamic_cast<AudioTrack*>((*i).get())) {
+                       if (!dynamic_cast<Track*>((*i).get())) {
 
                                if ((*i)->soloed()) {
 
@@ -2402,6 +2289,20 @@ Session::route_by_name (string name)
        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)
 {
@@ -2423,7 +2324,7 @@ Session::find_current_end ()
                return;
        }
 
-       jack_nframes_t max = get_maximum_extent ();
+       nframes_t max = get_maximum_extent ();
 
        if (max > end_location->end()) {
                end_location->set_end (max);
@@ -2432,18 +2333,16 @@ Session::find_current_end ()
        }
 }
 
-jack_nframes_t
+nframes_t
 Session::get_maximum_extent () const
 {
-       jack_nframes_t max = 0;
-       jack_nframes_t me; 
+       nframes_t max = 0;
+       nframes_t me; 
 
-       /* Don't take the diskstream lock. Caller must have other ways to
-          ensure atomicity.
-       */
+       boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
 
-       for (DiskstreamList::const_iterator i = diskstreams.begin(); i != diskstreams.end(); ++i) {
-               Playlist* pl = (*i)->playlist();
+       for (DiskstreamList::const_iterator i = dsl->begin(); i != dsl->end(); ++i) {
+               boost::shared_ptr<Playlist> pl = (*i)->playlist();
                if ((me = pl->get_maximum_extent()) > max) {
                        max = me;
                }
@@ -2452,35 +2351,35 @@ Session::get_maximum_extent () const
        return max;
 }
 
-Diskstream *
+boost::shared_ptr<Diskstream>
 Session::diskstream_by_name (string name)
 {
-       Glib::RWLock::ReaderLock lm (diskstream_lock);
+       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 *
+boost::shared_ptr<Diskstream>
 Session::diskstream_by_id (const PBD::ID& id)
 {
-       Glib::RWLock::ReaderLock lm (diskstream_lock);
+       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)
@@ -2506,7 +2405,7 @@ Session::new_region_name (string old)
 
        while (number < (UINT_MAX-1)) {
 
-               AudioRegionList::const_iterator i;
+               RegionList::const_iterator i;
                string sbuf;
 
                number++;
@@ -2514,13 +2413,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) {
+               for (i = regions.begin(); i != regions.end(); ++i) {
                        if (i->second->name() == sbuf) {
                                break;
                        }
                }
                
-               if (i == audio_regions.end()) {
+               if (i == regions.end()) {
                        break;
                }
        }
@@ -2539,11 +2438,13 @@ Session::region_name (string& result, string base, bool newlevel) const
        char buf[16];
        string subbase;
 
+       assert(base.find("/") == string::npos);
+
        if (base == "") {
                
                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.";
@@ -2579,7 +2480,7 @@ 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) {
+                               for (RegionList::const_iterator i = regions.begin(); i != regions.end(); ++i) {
                                        if (i->second->name() == result) {
                                                name_taken = true;
                                                break;
@@ -2601,52 +2502,42 @@ Session::region_name (string& result, string base, bool newlevel) const
 }      
 
 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;
 
        { 
                Glib::Mutex::Lock lm (region_lock);
 
-               if ((ar = dynamic_cast<AudioRegion*> (region)) != 0) {
-
-                       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;
+                       pair<RegionList::key_type,RegionList::mapped_type> entry;
 
-                               entry.first = region->id();
-                               entry.second = ar;
+                       entry.first = region->id();
+                       entry.second = region;
 
-                               pair<AudioRegionList::iterator,bool> x = audio_regions.insert (entry);
-                               
-                               if (!x.second) {
-                                       return;
-                               }
+                       pair<RegionList::iterator,bool> x = regions.insert (entry);
 
-                               added = true;
-                       } 
 
-               } else {
+                       if (!x.second) {
+                               return;
+                       }
 
-                       fatal << _("programming error: ")
-                             << X_("unknown region type passed to Session::add_region()")
-                             << endmsg;
-                       /*NOTREACHED*/
+                       added = true;
+               } 
 
-               }
        }
 
        /* mark dirty because something has changed even if we didn't
@@ -2656,15 +2547,21 @@ Session::add_region (Region* region)
        set_dirty();
        
        if (added) {
-               region->GoingAway.connect (mem_fun (*this, &Session::remove_region));
-               region->StateChanged.connect (sigc::bind (mem_fun (*this, &Session::region_changed), region));
-               AudioRegionAdded (ar); /* EMIT SIGNAL */
+               region->GoingAway.connect (sigc::bind (mem_fun (*this, &Session::remove_region), boost::weak_ptr<Region>(region)));
+               region->StateChanged.connect (sigc::bind (mem_fun (*this, &Session::region_changed), boost::weak_ptr<Region>(region)));
+               RegionAdded (region); /* EMIT SIGNAL */
        }
 }
 
 void
-Session::region_changed (Change what_changed, Region* region)
+Session::region_changed (Change what_changed, boost::weak_ptr<Region> weak_region)
 {
+       boost::shared_ptr<Region> region (weak_region.lock ());
+
+       if (!region) {
+               return;
+       }
+
        if (what_changed & Region::HiddenChanged) {
                /* relay hidden changes */
                RegionHiddenChange (region);
@@ -2672,33 +2569,23 @@ Session::region_changed (Change what_changed, Region* region)
 }
 
 void
-Session::region_renamed (Region* region)
+Session::remove_region (boost::weak_ptr<Region> weak_region)
 {
-       add_region (region);
-}
+       RegionList::iterator i;
+       boost::shared_ptr<Region> region (weak_region.lock ());
+
+       if (!region) {
+               return;
+       }
 
-void
-Session::remove_region (Region* region)
-{
-       AudioRegionList::iterator i;
-       AudioRegion* ar = 0;
        bool removed = false;
-       
+
        { 
                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;
                }
        }
 
@@ -2709,66 +2596,75 @@ Session::remove_region (Region* region)
        set_dirty();
 
        if (removed) {
-                AudioRegionRemoved(ar); /* EMIT SIGNAL */
+                RegionRemoved(region); /* EMIT SIGNAL */
        }
 }
 
-Region*
-Session::find_whole_file_parent (Region& child)
+boost::shared_ptr<Region>
+Session::find_whole_file_parent (boost::shared_ptr<Region const> child)
 {
-       AudioRegionList::iterator i;
-       AudioRegion* region;
+       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;
 
                if (region->whole_file()) {
 
-                       if (child.source_equivalent (*region)) {
+                       if (child->source_equivalent (region)) {
                                return region;
                        }
                }
        } 
 
-       return 0;
+       return boost::shared_ptr<Region> ();
 }      
 
 void
-Session::find_equivalent_playlist_regions (Region& region, vector<Region*>& 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)
                (*i)->get_region_list_equivalent_regions (region, result);
 }
 
 int
-Session::destroy_region (Region* region)
+Session::destroy_region (boost::shared_ptr<Region> region)
 {
-       AudioRegion* aregion;
-
-       if ((aregion = dynamic_cast<AudioRegion*> (region)) == 0) {
-               return 0;
+       vector<boost::shared_ptr<Source> > srcs;
+               
+       {
+               boost::shared_ptr<AudioRegion> aregion;
+               
+               if ((aregion = boost::dynamic_pointer_cast<AudioRegion> (region)) == 0) {
+                       return 0;
+               }
+               
+               if (aregion->playlist()) {
+                       aregion->playlist()->destroy_region (region);
+               }
+               
+               for (uint32_t n = 0; n < aregion->n_channels(); ++n) {
+                       srcs.push_back (aregion->source (n));
+               }
        }
 
-       if (aregion->playlist()) {
-               aregion->playlist()->destroy_region (region);
-       }
+       region->drop_references ();
 
-       vector<Source*> srcs;
-       
-       for (uint32_t n = 0; n < aregion->n_channels(); ++n) {
-               srcs.push_back (&aregion->source (n));
-       }
+       for (vector<boost::shared_ptr<Source> >::iterator i = srcs.begin(); i != srcs.end(); ++i) {
 
-       for (vector<Source*>::iterator i = srcs.begin(); i != srcs.end(); ++i) {
-               
-               if ((*i)->use_cnt() == 0) {
-                       AudioFileSource* afs = dynamic_cast<AudioFileSource*>(*i);
+               if (!(*i)->used()) {
+                       boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*i);
+                       
                        if (afs) {
                                (afs)->mark_for_remove ();
                        }
-                       delete *i;
+                       
+                       (*i)->drop_references ();
+                       
+                       cerr << "source was not used by any playlist\n";
                }
        }
 
@@ -2776,9 +2672,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;
@@ -2787,12 +2683,12 @@ Session::destroy_regions (list<Region*> regions)
 int
 Session::remove_last_capture ()
 {
-       list<Region*> r;
-
-       Glib::RWLock::ReaderLock lm (diskstream_lock);
+       list<boost::shared_ptr<Region> > r;
+       
+       boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
        
-       for (DiskstreamList::iterator i = diskstreams.begin(); i != diskstreams.end(); ++i) {
-               list<Region*>& l = (*i)->last_capture_regions();
+       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());
@@ -2805,66 +2701,73 @@ 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_audio_source (AudioSource* source)
+Session::add_source (boost::shared_ptr<Source> source)
 {
-       pair<AudioSourceList::key_type, AudioSourceList::mapped_type> entry;
+       pair<SourceMap::key_type, SourceMap::mapped_type> entry;
+       pair<SourceMap::iterator,bool> result;
 
-       {
-               Glib::Mutex::Lock lm (audio_source_lock);
-               entry.first = source->id();
-               entry.second = source;
-               audio_sources.insert (entry);
-       }
-       
-       source->GoingAway.connect (mem_fun (this, &Session::remove_source));
-       set_dirty();
+       entry.first = source->id();
+       entry.second = source;
        
-       SourceAdded (source); /* EMIT SIGNAL */
+       {
+               Glib::Mutex::Lock lm (source_lock);
+               result = sources.insert (entry);
+       }
+
+       if (result.second) {
+               source->GoingAway.connect (sigc::bind (mem_fun (this, &Session::remove_source), boost::weak_ptr<Source> (source)));
+               set_dirty();
+       }
 }
 
 void
-Session::remove_source (Source* source)
+Session::remove_source (boost::weak_ptr<Source> src)
 {
-       AudioSourceList::iterator i;
+       SourceMap::iterator i;
+       boost::shared_ptr<Source> source = src.lock();
 
-       { 
-               Glib::Mutex::Lock lm (audio_source_lock);
+       if (!source) {
+               return;
+       } 
 
-               if ((i = audio_sources.find (source->id())) != audio_sources.end()) {
-                       audio_sources.erase (i);
-               } 
+       { 
+               Glib::Mutex::Lock lm (source_lock);
+               
+               { 
+                       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);
-                save_history (_current_snapshot_name);
        }
-
-       SourceRemoved(source); /* EMIT SIGNAL */
 }
 
-Source *
+boost::shared_ptr<Source>
 Session::source_by_id (const PBD::ID& id)
 {
-       Glib::Mutex::Lock lm (audio_source_lock);
-       AudioSourceList::iterator i;
-       Source* source = 0;
+       Glib::Mutex::Lock lm (source_lock);
+       SourceMap::iterator i;
+       boost::shared_ptr<Source> source;
 
-       if ((i = audio_sources.find (id)) != audio_sources.end()) {
+       if ((i = sources.find (id)) != sources.end()) {
                source = i->second;
        }
 
@@ -2874,17 +2777,11 @@ Session::source_by_id (const PBD::ID& id)
 }
 
 string
-Session::peak_path_from_audio_path (string audio_path)
+Session::peak_path_from_audio_path (string audio_path) const
 {
-       /* 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 = peak_dir ();
        res += PBD::basename_nosuffix (audio_path);
        res += ".peak";
 
@@ -3030,11 +2927,7 @@ Session::audio_path_from_name (string name, uint32_t nchan, uint32_t chan, bool
 
                        spath = (*i).path;
 
-                       if (destructive) {
-                               spath += tape_dir_name;
-                       } else {
-                               spath += sound_dir_name;
-                       }
+                       spath += sound_dir (false);
 
                        if (destructive) {
                                if (nchan < 2) {
@@ -3050,6 +2943,7 @@ Session::audio_path_from_name (string name, uint32_t nchan, uint32_t chan, bool
                                } else {
                                        snprintf (buf, sizeof(buf), "%s/T%04d-%s.wav", spath.c_str(), cnt, legalized.c_str());
                                }
+
                        } else {
 
                                spath += '/';
@@ -3070,9 +2964,10 @@ Session::audio_path_from_name (string name, uint32_t nchan, uint32_t chan, bool
                                }
                        }
 
-                       if (access (buf, F_OK) == 0) {
+                       if (g_file_test (buf, G_FILE_TEST_EXISTS)) {
                                existing++;
-                       }
+                       } 
+
                }
 
                if (existing == 0) {
@@ -3081,6 +2976,7 @@ Session::audio_path_from_name (string name, uint32_t nchan, uint32_t chan, bool
 
                if (cnt > limit) {
                        error << string_compose(_("There are already %1 recordings for %2, which I consider too many."), limit, name) << endmsg;
+                       destroy ();
                        throw failed_constructor();
                }
        }
@@ -3091,11 +2987,8 @@ Session::audio_path_from_name (string name, uint32_t nchan, uint32_t chan, bool
 
        string foo = buf;
 
-       if (destructive) {
-               spath = tape_dir ();
-       } else {
-               spath = discover_best_sound_dir ();
-       }
+       spath = discover_best_sound_dir ();
+       spath += '/';
 
        string::size_type pos = foo.find_last_of ('/');
        
@@ -3108,24 +3001,127 @@ Session::audio_path_from_name (string name, uint32_t nchan, uint32_t chan, bool
        return spath;
 }
 
-AudioFileSource *
+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, *this, 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 */
 
-       /* this might throw failed_constructor(), which is OK */
-       
        if (destructive) {
-               return new DestructiveFileSource (spath,
-                                                 Config->get_native_file_data_format(),
-                                                 Config->get_native_file_header_format(),
-                                                 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 SndFileSource (spath, 
-                                         Config->get_native_file_data_format(),
-                                         Config->get_native_file_header_format(),
-                                         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;
+               }
+
        }
+
+       return path;
 }
 
 string
@@ -3191,19 +3187,18 @@ Session::midi_path_from_name (string name)
        return spath;
 }
 
-MidiSource *
+boost::shared_ptr<MidiSource>
 Session::create_midi_source_for_session (MidiDiskstream& ds)
 {
        string spath = midi_path_from_name (ds.name());
-
-       /* this might throw failed_constructor(), which is OK */
-       return new SMFSource (spath);
+       
+       return boost::dynamic_pointer_cast<SMFSource> (SourceFactory::createWritable (DataType::MIDI, *this, spath, false, frame_rate()));
 }
 
 
 /* Playlist management */
 
-Playlist *
+boost::shared_ptr<Playlist>
 Session::playlist_by_name (string name)
 {
        Glib::Mutex::Lock lm (playlist_lock);
@@ -3217,11 +3212,12 @@ Session::playlist_by_name (string name)
                        return* i;
                }
        }
-       return 0;
+
+       return boost::shared_ptr<Playlist>();
 }
 
 void
-Session::add_playlist (Playlist* playlist)
+Session::add_playlist (boost::shared_ptr<Playlist> playlist)
 {
        if (playlist->hidden()) {
                return;
@@ -3231,9 +3227,8 @@ Session::add_playlist (Playlist* playlist)
                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->InUse.connect (sigc::bind (mem_fun (*this, &Session::track_playlist), boost::weak_ptr<Playlist>(playlist)));
+                       playlist->GoingAway.connect (sigc::bind (mem_fun (*this, &Session::remove_playlist), boost::weak_ptr<Playlist>(playlist)));
                }
        }
 
@@ -3243,15 +3238,39 @@ Session::add_playlist (Playlist* playlist)
 }
 
 void
-Session::track_playlist (Playlist* pl, bool inuse)
+Session::get_playlists (vector<boost::shared_ptr<Playlist> >& s)
+{
+       { 
+               Glib::Mutex::Lock lm (playlist_lock);
+               for (PlaylistList::iterator i = playlists.begin(); i != playlists.end(); ++i) {
+                       s.push_back (*i);
+               }
+               for (PlaylistList::iterator i = unused_playlists.begin(); i != unused_playlists.end(); ++i) {
+                       s.push_back (*i);
+               }
+       }
+}
+
+void
+Session::track_playlist (bool inuse, boost::weak_ptr<Playlist> wpl)
 {
+       boost::shared_ptr<Playlist> pl(wpl.lock());
+
+       if (!pl) {
+               return;
+       }
+
        PlaylistList::iterator x;
 
+       if (pl->hidden()) {
+               /* its not supposed to be visible */
+               return;
+       }
+
        { 
                Glib::Mutex::Lock lm (playlist_lock);
 
                if (!inuse) {
-                       //cerr << "shifting playlist to unused: " << pl->name() << endl;
 
                        unused_playlists.insert (pl);
                        
@@ -3261,8 +3280,7 @@ Session::track_playlist (Playlist* pl, bool inuse)
 
                        
                } else {
-                       //cerr << "shifting playlist to used: " << pl->name() << endl;
-                       
+
                        playlists.insert (pl);
                        
                        if ((x = unused_playlists.find (pl)) != unused_playlists.end()) {
@@ -3273,20 +3291,24 @@ Session::track_playlist (Playlist* pl, bool inuse)
 }
 
 void
-Session::remove_playlist (Playlist* playlist)
+Session::remove_playlist (boost::weak_ptr<Playlist> weak_playlist)
 {
        if (_state_of_the_state & Deletion) {
                return;
        }
 
+       boost::shared_ptr<Playlist> playlist (weak_playlist.lock());
+
+       if (!playlist) {
+               return;
+       }
+
        { 
                Glib::Mutex::Lock lm (playlist_lock);
-               // cerr << "removing playlist: " << playlist->name() << endl;
 
                PlaylistList::iterator i;
 
                i = find (playlists.begin(), playlists.end(), playlist);
-
                if (i != playlists.end()) {
                        playlists.erase (i);
                }
@@ -3304,50 +3326,47 @@ 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);
        schedule_butler_transport_work ();
 }
 
+void
+Session::audition_playlist ()
+{
+       Event* ev = new Event (Event::Audition, Event::Add, Event::Immediate, 0, 0.0);
+       ev->region.reset ();
+       queue_event (ev);
+}
+
 void
 Session::non_realtime_set_audition ()
 {
-       if (pending_audition_region == (AudioRegion*) 0xfeedface) {
+       if (!pending_audition_region) {
                auditioner->audition_current_playlist ();
-       } else if (pending_audition_region) {
-               auditioner->audition_region (*pending_audition_region);
+       } else {
+               auditioner->audition_region (pending_audition_region);
+               pending_audition_region.reset ();
        }
-       pending_audition_region = 0;
        AuditionActive (true); /* EMIT SIGNAL */
 }
 
 void
-Session::audition_playlist ()
+Session::audition_region (boost::shared_ptr<Region> r)
 {
        Event* ev = new Event (Event::Audition, Event::Add, Event::Immediate, 0, 0.0);
-       ev->set_ptr ((void*) 0xfeedface);
+       ev->region = r;
        queue_event (ev);
 }
 
-void
-Session::audition_region (Region& r)
-{
-       AudioRegion* ar = dynamic_cast<AudioRegion*>(&r);
-       if (ar) {
-               Event* ev = new Event (Event::Audition, Event::Add, Event::Immediate, 0, 0.0);
-               ev->set_ptr (ar);
-               queue_event (ev);
-       }
-}
-
 void
 Session::cancel_audition ()
 {
        if (auditioner->active()) {
                auditioner->cancel_audition ();
-                AuditionActive (false); /* EMIT SIGNAL */
+               AuditionActive (false); /* EMIT SIGNAL */
        }
 }
 
@@ -3360,17 +3379,35 @@ Session::RoutePublicOrderSorter::operator() (boost::shared_ptr<Route> a, boost::
 void
 Session::remove_empty_sounds ()
 {
-
        PathScanner scanner;
-       string dir;
-
-       dir = sound_dir ();
 
-       vector<string *>* possible_audiofiles = scanner (dir, "\\.wav$", false, true);
+       vector<string *>* possible_audiofiles = scanner (sound_dir(), "\\.(wav|aiff|caf|w64)$", false, true);
        
+       Glib::Mutex::Lock lm (source_lock);
+       
+       regex_t compiled_tape_track_pattern;
+       int err;
+
+       if ((err = regcomp (&compiled_tape_track_pattern, "/T[0-9][0-9][0-9][0-9]-", REG_EXTENDED|REG_NOSUB))) {
+
+               char msg[256];
+               
+               regerror (err, &compiled_tape_track_pattern, msg, sizeof (msg));
+               
+               error << string_compose (_("Cannot compile tape track regexp for use (%1)"), msg) << endmsg;
+               return;
+       }
+
        for (vector<string *>::iterator i = possible_audiofiles->begin(); i != possible_audiofiles->end(); ++i) {
+               
+               /* never remove files that appear to be a tape track */
 
-               if (AudioFileSource::is_empty (*(*i))) {
+               if (regexec (&compiled_tape_track_pattern, (*i)->c_str(), 0, 0, 0) == 0) {
+                       delete *i;
+                       continue;
+               }
+                       
+               if (AudioFileSource::is_empty (*this, *(*i))) {
 
                        unlink ((*i)->c_str());
                        
@@ -3426,10 +3463,11 @@ Session::set_all_mute (bool yn)
 uint32_t
 Session::n_diskstreams () const
 {
-       Glib::RWLock::ReaderLock lm (diskstream_lock);
        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++;
                }
@@ -3448,7 +3486,11 @@ Session::graph_reordered ()
                return;
        }
        
-       Glib::RWLock::ReaderLock lm2 (diskstream_lock);
+       /* every track/bus asked for this to be handled but it was deferred because
+          we were connecting. do it now.
+       */
+
+       request_input_change_handling ();
 
        resort_routes ();
 
@@ -3456,7 +3498,9 @@ Session::graph_reordered ()
           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 ();
        }
 }
@@ -3479,9 +3523,9 @@ Session::record_enable_change_all (bool yn)
        shared_ptr<RouteList> r = routes.reader ();
        
        for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
-               AudioTrack* at;
+               Track* at;
 
-               if ((at = dynamic_cast<AudioTrack*>((*i).get())) != 0) {
+               if ((at = dynamic_cast<Track*>((*i).get())) != 0) {
                        at->set_record_enable (yn, this);
                }
        }
@@ -3513,7 +3557,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();
 }
@@ -3525,18 +3569,28 @@ Session::remove_redirect (Redirect* redirect)
        Insert* insert;
        PortInsert* port_insert;
        PluginInsert* plugin_insert;
-
+       
        if ((insert = dynamic_cast<Insert *> (redirect)) != 0) {
                if ((port_insert = dynamic_cast<PortInsert *> (insert)) != 0) {
-                       _port_inserts.remove (port_insert);
+                       list<PortInsert*>::iterator x = find (_port_inserts.begin(), _port_inserts.end(), port_insert);
+                       if (x != _port_inserts.end()) {
+                               insert_bitset[port_insert->bit_slot()] = false;
+                               _port_inserts.erase (x);
+                       }
                } else if ((plugin_insert = dynamic_cast<PluginInsert *> (insert)) != 0) {
                        _plugin_inserts.remove (plugin_insert);
                } else {
-                       fatal << _("programming error: unknown type of Insert deleted!") << endmsg;
+                       fatal << string_compose (_("programming error: %1"),
+                                                X_("unknown type of Insert deleted!")) 
+                             << endmsg;
                        /*NOTREACHED*/
                }
        } else if ((send = dynamic_cast<Send *> (redirect)) != 0) {
-               _sends.remove (send);
+               list<Send*>::iterator x = find (_sends.begin(), _sends.end(), send);
+               if (x != _sends.end()) {
+                       send_bitset[send->bit_slot()] = false;
+                       _sends.erase (x);
+               }
        } else {
                fatal << _("programming error: unknown type of Redirect deleted!") << endmsg;
                /*NOTREACHED*/
@@ -3545,16 +3599,35 @@ Session::remove_redirect (Redirect* redirect)
        set_dirty();
 }
 
-jack_nframes_t
+nframes_t
 Session::available_capture_duration ()
 {
-       const double scale = 4096.0 / sizeof (Sample);
-       
+       float sample_bytes_on_disk;
+
+       switch (Config->get_native_file_data_format()) {
+       case FormatFloat:
+               sample_bytes_on_disk = 4;
+               break;
+
+       case FormatInt24:
+               sample_bytes_on_disk = 3;
+               break;
+
+       default: 
+               /* impossible, but keep some gcc versions happy */
+               fatal << string_compose (_("programming error: %1"),
+                                        X_("illegal native file data format"))
+                     << endmsg;
+               /*NOTREACHED*/
+       }
+
+       double scale = 4096.0 / sample_bytes_on_disk;
+
        if (_total_free_4k_blocks * scale > (double) max_frames) {
                return max_frames;
        }
        
-       return (jack_nframes_t) floor (_total_free_4k_blocks * scale);
+       return (nframes_t) floor (_total_free_4k_blocks * scale);
 }
 
 void
@@ -3606,23 +3679,6 @@ Session::connection_by_name (string name) const
        return 0;
 }
 
-void
-Session::set_edit_mode (EditMode mode)
-{
-       _edit_mode = mode;
-       
-       { 
-               Glib::Mutex::Lock lm (playlist_lock);
-               
-               for (PlaylistList::iterator i = playlists.begin(); i != playlists.end(); ++i) {
-                       (*i)->set_edit_mode (mode);
-               }
-       }
-
-       set_dirty ();
-       ControlChanged (EditingMode); /* EMIT SIGNAL */
-}
-
 void
 Session::tempo_map_changed (Change ignored)
 {
@@ -3644,20 +3700,70 @@ Session::ensure_buffers (ChanCount howmany)
        allocate_pan_automation_buffers (current_block_size, howmany.get(DataType::AUDIO), false);
 }
 
-string
-Session::next_send_name ()
+uint32_t
+Session::next_insert_id ()
+{
+       /* this doesn't really loop forever. just think about it */
+
+       while (true) {
+               for (boost::dynamic_bitset<uint32_t>::size_type n = 0; n < insert_bitset.size(); ++n) {
+                       if (!insert_bitset[n]) {
+                               insert_bitset[n] = true;
+                               cerr << "Returning " << n << " as insert ID\n";
+                               return n;
+                               
+                       }
+               }
+               
+               /* none available, so resize and try again */
+
+               insert_bitset.resize (insert_bitset.size() + 16, false);
+       }
+}
+
+uint32_t
+Session::next_send_id ()
 {
-       char buf[32];
-       snprintf (buf, sizeof (buf), "send %" PRIu32, ++send_cnt);
-       return buf;
+       /* this doesn't really loop forever. just think about it */
+
+       while (true) {
+               for (boost::dynamic_bitset<uint32_t>::size_type n = 0; n < send_bitset.size(); ++n) {
+                       if (!send_bitset[n]) {
+                               send_bitset[n] = true;
+                               cerr << "Returning " << n << " as send ID\n";
+                               return n;
+                               
+                       }
+               }
+               
+               /* none available, so resize and try again */
+
+               send_bitset.resize (send_bitset.size() + 16, false);
+       }
 }
 
-string
-Session::next_insert_name ()
+void
+Session::mark_send_id (uint32_t id)
 {
-       char buf[32];
-       snprintf (buf, sizeof (buf), "insert %" PRIu32, ++insert_cnt);
-       return buf;
+       if (id >= send_bitset.size()) {
+               send_bitset.resize (id+16, false);
+       }
+       if (send_bitset[id]) {
+               warning << string_compose (_("send ID %1 appears to be in use already"), id) << endmsg;
+       }
+       send_bitset[id] = true;
+}
+
+void
+Session::mark_insert_id (uint32_t id)
+{
+       if (id >= insert_bitset.size()) {
+               insert_bitset.resize (id+16, false);
+       }
+       if (insert_bitset[id]) {
+               warning << string_compose (_("insert ID %1 appears to be in use already"), id) << endmsg;
+       }
+       insert_bitset[id] = true;
 }
 
 /* Named Selection management */
@@ -3713,11 +3819,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__);
-       Glib::RWLock::ReaderLock lm2 (diskstream_lock);
+       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);
        }
 }
@@ -3736,12 +3840,6 @@ Session::route_name_unique (string n) const
        return true;
 }
 
-int
-Session::cleanup_audio_file_source (AudioFileSource& fs)
-{
-       return fs.move_to_trash (dead_sound_dir_name);
-}
-
 uint32_t
 Session::n_playlists () const
 {
@@ -3750,17 +3848,7 @@ Session::n_playlists () const
 }
 
 void
-Session::set_solo_model (SoloModel sm)
-{
-       if (sm != _solo_model) {
-               _solo_model = sm;
-               ControlChanged (SoloingModel);
-               set_dirty ();
-       }
-}
-
-void
-Session::allocate_pan_automation_buffers (jack_nframes_t nframes, uint32_t howmany, bool force)
+Session::allocate_pan_automation_buffers (nframes_t nframes, uint32_t howmany, bool force)
 {
        if (!force && howmany <= _npan_buffers) {
                return;
@@ -3791,9 +3879,9 @@ Session::freeze (InterThreadInfo& itt)
 
        for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
 
-               AudioTrack *at;
+               Track *at;
 
-               if ((at = dynamic_cast<AudioTrack*>((*i).get())) != 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.
                        */
@@ -3805,29 +3893,29 @@ Session::freeze (InterThreadInfo& itt)
 }
 
 int
-Session::write_one_audio_track (AudioTrack& track, jack_nframes_t start, jack_nframes_t len,   
-                              bool overwrite, vector<Source*>& srcs, InterThreadInfo& itt)
-{
-       int              ret = -1;
-       Playlist*        playlist = 0;
-       AudioFileSource* fsource = 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;
+Session::write_one_audio_track (AudioTrack& track, nframes_t start, nframes_t len,     
+                              bool overwrite, vector<boost::shared_ptr<Source> >& srcs, InterThreadInfo& itt)
+{
+       int ret = -1;
+       boost::shared_ptr<Playlist> playlist;
+       boost::shared_ptr<AudioFileSource> fsource;
+       uint32_t x;
+       char buf[PATH_MAX+1];
+       string dir;
+       ChanCount nchans(track.audio_diskstream()->n_channels());
+       nframes_t position;
+       nframes_t this_chunk;
+       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;
+       const nframes_t chunk_size = (128 * 1024)/4;
 
        g_atomic_int_set (&processing_prohibited, 1);
        
        /* call tree *MUST* hold route_lock */
        
-       if ((playlist = track.diskstream().playlist()) == 0) {
+       if ((playlist = track.diskstream()->playlist()) == 0) {
                goto out;
        }
 
@@ -3854,11 +3942,8 @@ Session::write_one_audio_track (AudioTrack& track, jack_nframes_t start, jack_nf
                }
                
                try {
-                       fsource =  new SndFileSource (buf, 
-                                                     Config->get_native_file_data_format(),
-                                                     Config->get_native_file_header_format(),
-                                                     frame_rate());
-                                                           
+                       fsource = boost::dynamic_pointer_cast<AudioFileSource> (
+                               SourceFactory::createWritable (DataType::AUDIO, *this, buf, false, frame_rate()));
                }
                
                catch (failed_constructor& err) {
@@ -3866,7 +3951,7 @@ Session::write_one_audio_track (AudioTrack& track, jack_nframes_t start, jack_nf
                        goto out;
                }
 
-               srcs.push_back(fsource);
+               srcs.push_back (fsource);
        }
 
        /* XXX need to flush all redirects */
@@ -3887,9 +3972,9 @@ Session::write_one_audio_track (AudioTrack& track, jack_nframes_t start, jack_nf
                }
 
                uint32_t n = 0;
-               for (vector<Source*>::iterator src=srcs.begin(); src != srcs.end(); ++src, ++n) {
-                       AudioFileSource* afs = dynamic_cast<AudioFileSource*>(*src);
-
+               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;
@@ -3911,8 +3996,9 @@ Session::write_one_audio_track (AudioTrack& track, jack_nframes_t start, jack_nf
                time (&now);
                xnow = localtime (&now);
                
-               for (vector<Source*>::iterator src=srcs.begin(); src != srcs.end(); ++src) {
-                       AudioFileSource* afs = dynamic_cast<AudioFileSource*>(*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);
+                       
                        if (afs) {
                                afs->update_header (position, *xnow, now);
                        }
@@ -3920,24 +4006,31 @@ Session::write_one_audio_track (AudioTrack& track, jack_nframes_t start, jack_nf
                
                /* build peakfile for new source */
                
-               for (vector<Source*>::iterator src=srcs.begin(); src != srcs.end(); ++src) {
-                       AudioFileSource* afs = dynamic_cast<AudioFileSource*>(*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);
                        if (afs) {
                                afs->build_peaks ();
                        }
                }
-               
+
+               /* construct a region to represent the bounced material */
+
+               boost::shared_ptr<Region> aregion = RegionFactory::create (srcs, 0, srcs.front()->length(), 
+                                                                          region_name_from_path (srcs.front()->name(), true));
+
                ret = 0;
        }
                
   out:
        if (ret) {
-               for (vector<Source*>::iterator src=srcs.begin(); src != srcs.end(); ++src) {
-                       AudioFileSource* afs = dynamic_cast<AudioFileSource*>(*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);
+
                        if (afs) {
                                afs->mark_for_remove ();
                        }
-                       delete *src;
+
+                       (*src)->drop_references ();
                }
        }
 
@@ -3986,7 +4079,7 @@ Session::ntracks () const
        shared_ptr<RouteList> r = routes.reader ();
 
        for (RouteList::const_iterator i = r->begin(); i != r->end(); ++i) {
-               if (dynamic_cast<AudioTrack*> ((*i).get())) {
+               if (dynamic_cast<Track*> ((*i).get())) {
                        ++n;
                }
        }
@@ -4001,7 +4094,7 @@ Session::nbusses () const
        shared_ptr<RouteList> r = routes.reader ();
 
        for (RouteList::const_iterator i = r->begin(); i != r->end(); ++i) {
-               if (dynamic_cast<AudioTrack*> ((*i).get()) == 0) {
+               if (dynamic_cast<Track*> ((*i).get()) == 0) {
                        ++n;
                }
        }
@@ -4010,22 +4103,14 @@ Session::nbusses () const
 }
 
 void
-Session::set_layer_model (LayerModel lm)
+Session::add_automation_list(AutomationList *al)
 {
-       if (lm != layer_model) {
-               layer_model = lm;
-               set_dirty ();
-               ControlChanged (LayeringModel);
-       }
+       automation_lists[al->id()] = al;
 }
 
-void
-Session::set_xfade_model (CrossfadeModel xm)
+nframes_t
+Session::compute_initial_length ()
 {
-       if (xm != xfade_model) {
-               xfade_model = xm;
-               set_dirty ();
-               ControlChanged (CrossfadingModel);
-       }
+       return _engine.frame_rate() * 60 * 5;
 }