Adding sends/port inserts to MIDI tracks (not actually working yet though)
[ardour.git] / libs / ardour / session.cc
index ab8d8674142d5d00086bde3182f408c6d7e0145b..3c325ee5385b7d6aa5e92a910d8262ca4714872c 100644 (file)
@@ -71,6 +71,7 @@
 #include <ardour/click.h>
 #include <ardour/data_type.h>
 #include <ardour/buffer_set.h>
+#include <ardour/source_factory.h>
 
 #ifdef HAVE_LIBLO
 #include <ardour/osc.h>
@@ -266,6 +267,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,7 +275,7 @@ 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();
@@ -281,10 +283,12 @@ Session::Session (AudioEngine &eng,
        first_stage_init (fullpath, snapshot_name);
        
        if (create (new_session, mix_template, _engine.frame_rate() * 60 * 5)) {
+               cerr << "create failed\n";
                throw failed_constructor ();
        }
        
        if (second_stage_init (new_session)) {
+               cerr << "2nd state failed\n";
                throw failed_constructor ();
        }
        
@@ -320,13 +324,14 @@ 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 = max (requested_physical_out, _engine.n_physical_outputs());
        n_physical_inputs = max (requested_physical_in, _engine.n_physical_inputs());
@@ -339,13 +344,17 @@ Session::Session (AudioEngine &eng,
 
        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 */
@@ -380,9 +389,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 ();
        
@@ -433,45 +456,57 @@ Session::~Session ()
 #ifdef TRACK_DESTRUCTION
        cerr << "delete regions\n";
 #endif /* TRACK_DESTRUCTION */
-       for (RegionList::iterator i = regions.begin(); i != regions.end(); ) {
-               RegionList::iterator tmp;
-
-               tmp =i;
-               ++tmp;
-
-               delete i->second;
-
-               i = tmp;
+       
+       for (RegionList::iterator i = regions.begin(); i != regions.end(); ++i) {
+               i->second->drop_references ();
        }
+
+       regions.clear ();
        
 #ifdef TRACK_DESTRUCTION
-       cerr << "delete diskstreams\n";
+       cerr << "delete routes\n";
 #endif /* TRACK_DESTRUCTION */
-       for (DiskstreamList::iterator i = diskstreams.begin(); i != diskstreams.end(); ) {
-               DiskstreamList::iterator tmp;
-
-               tmp = i;
-               ++tmp;
+        {
+               RCUWriter<RouteList> writer (routes);
+               boost::shared_ptr<RouteList> r = writer.get_copy ();
+               for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
+                       (*i)->drop_references ();
+               }
+               r->clear ();
+               /* writer goes out of scope and updates master */
+       }
 
-               delete *i;
+       routes.flush ();
 
-               i = tmp;
-       }
+#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 (SourceList::iterator i = sources.begin(); i != sources.end(); ) {
-               SourceList::iterator tmp;
+       for (SourceMap::iterator i = sources.begin(); i != sources.end(); ) {
+               SourceMap::iterator tmp;
 
                tmp = i;
                ++tmp;
 
-               delete i->second;
+               i->second->drop_references ();
 
                i = tmp;
        }
 
+       sources.clear ();
+
 #ifdef TRACK_DESTRUCTION
        cerr << "delete mix groups\n";
 #endif /* TRACK_DESTRUCTION */
@@ -527,10 +562,6 @@ Session::~Session ()
        if (mmc) {
                delete mmc;
        }
-
-       if (state_tree) {
-               delete state_tree;
-       }
 }
 
 void
@@ -867,7 +898,7 @@ Session::playlist_length_changed (Playlist* pl)
 }
 
 void
-Session::diskstream_playlist_changed (Diskstream* dstream)
+Session::diskstream_playlist_changed (boost::shared_ptr<Diskstream> dstream)
 {
        Playlist *playlist;
 
@@ -941,13 +972,10 @@ Session::set_auto_input (bool yn)
                
                if (Config->get_use_hardware_monitoring() && transport_rolling()) {
                        /* auto-input only makes a difference if we're rolling */
+                       
+                       boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
 
-                       /* Even though this can called from RT context we are using
-                          a non-tentative rwlock here,  because the action must occur.
-                          The rarity and short potential lock duration makes this "OK"
-                       */
-                       Glib::RWLock::ReaderLock dsm (diskstream_lock);
-                       for (DiskstreamList::iterator i = diskstreams.begin(); i != diskstreams.end(); ++i) {
+                       for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
                                if ((*i)->record_enabled ()) {
                                        //cerr << "switching to input = " << !auto_input << __FILE__ << __LINE__ << endl << endl;
                                        (*i)->monitor_input (!auto_input);   
@@ -964,16 +992,19 @@ 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);
                        }
                }
        } 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());
@@ -1015,7 +1046,6 @@ Session::auto_punch_start_changed (Location* location)
        if (get_record_enabled() && get_punch_in()) {
                /* capture start has been changed, so save new pending state */
                save_state ("", true);
-                save_history("");
        }
 }      
 
@@ -1246,13 +1276,8 @@ Session::enable_record ()
                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) {
+                       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);   
                                }
@@ -1285,13 +1310,9 @@ Session::disable_record (bool rt_context, bool force)
                        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);
+                       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);   
                                }
@@ -1312,13 +1333,9 @@ 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);
+               boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
                
-               for (DiskstreamList::iterator i = diskstreams.begin(); i != diskstreams.end(); ++i) {
+               for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
                        if (auto_input && (*i)->record_enabled ()) {
                                //cerr << "switching from input" << __FILE__ << __LINE__ << endl << endl;
                                (*i)->monitor_input (false);   
@@ -1337,7 +1354,6 @@ Session::maybe_enable_record ()
        */
 
        save_state ("", true);
-        save_history ("");
 
        if (_transport_speed) {
                if (!punch_in) {
@@ -1442,7 +1458,6 @@ Session::set_block_size (jack_nframes_t nframes)
        */
 
        { 
-               Glib::RWLock::ReaderLock dsm (diskstream_lock);
                        
                current_block_size = nframes;
                
@@ -1461,7 +1476,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);
                }
 
@@ -1641,13 +1657,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,185 +1683,70 @@ 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)
-       */
-
-       do {
-               snprintf (track_name, sizeof(track_name), "Midi %" PRIu32, n+1);
-               if (route_by_name (track_name) == 0) {
-                       break;
-               }
-               n++;
-
-       } while (n < (UINT_MAX-1));
-
-       try {
-               shared_ptr<MidiTrack> track (new MidiTrack (*this, track_name, Route::Flag (0), mode));
+       while (how_many) {
 
-               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;
-                               }
-                       }
-               }
+               /* 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)
+               */
                
-               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();
-                               }
-                       }
+               do {
+                       ++track_id;
 
-                       if (port.length() && track->connect_output (track->output (x), port, this)) {
-                               break;
-                       }
-               }
-
-               if (_control_out) {
-                       vector<string> cports;
-                       uint32_t ni = _control_out->n_inputs();
+                       snprintf (track_name, sizeof(track_name), "Midi %" PRIu32, track_id);
 
-                       for (n = 0; n < ni; ++n) {
-                               cports.push_back (_control_out->input(n)->name());
-                       }
-
-                       track->set_control_outs (cports);
-               }
-#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;
-               return shared_ptr<MidiTrack> ((MidiTrack*) 0);
-       }
-}
-
-
-boost::shared_ptr<Route>
-Session::new_midi_route ()
-{
-       char bus_name[32];
-       uint32_t n = 0;
-       string port;
-
-       /* 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 (!(*i)->hidden()) {
-                                       n++;
-                               }
+                       if (route_by_name (track_name) == 0) {
+                               break;
                        }
-               }
-       }
-
-       do {
-               snprintf (bus_name, sizeof(bus_name), "Bus %" PRIu32, n+1);
-               if (route_by_name (bus_name) == 0) {
-                       break;
-               }
-               n++;
-
-       } while (n < (UINT_MAX-1));
-
-       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 (track_id < (UINT_MAX-1));
 
-                       if (input_auto_connect & AutoConnectPhysical) {
-                               port = _engine.get_nth_physical_input ((n+x)%n_physical_inputs);
-                       } 
+               try {
+                       shared_ptr<MidiTrack> track (new MidiTrack (*this, track_name, Route::Flag (0), mode));
                        
-                       if (port.length() && bus->connect_input (bus->input (x), port, this)) {
-                               break;
+                       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;
                        }
-               }
-
-               for (uint32_t x = 0; x < bus->n_outputs(); ++x) {
                        
-                       port = "";
+                       channels_used += track->n_inputs ().get(DataType::MIDI);
 
-                       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();
-                               }
-                       }
+                       track->DiskstreamChanged.connect (mem_fun (this, &Session::resort_routes));
+                       track->set_remote_control_id (ntracks());
 
-                       if (port.length() && bus->connect_output (bus->output (x), port, this)) {
-                               break;
-                       }
+                       new_routes.push_back (track);
+                       ret.push_back (track);
                }
-#endif
-/*
-               if (_control_out) {
-                       vector<string> cports;
-                       uint32_t ni = _control_out->n_inputs();
 
-                       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 midi track.") << endmsg;
+                       // XXX should we delete the tracks already created? 
+                       ret.clear ();
+                       return ret;
                }
-*/             
-               add_route (bus);
-               return bus;
+               
+               --how_many;
        }
 
-       catch (failed_constructor &err) {
-               error << _("Session: could not create new MIDI route.") << endmsg;
-               return shared_ptr<Route> ((Route*) 0);
+       if (!new_routes.empty()) {
+               add_routes (new_routes, false);
+               save_state (_current_snapshot_name);
        }
-}
 
+       return ret;
+}
 
-shared_ptr<AudioTrack>
-Session::new_audio_track (int input_channels, int output_channels, TrackMode mode)
+list<boost::shared_ptr<AudioTrack> >
+Session::new_audio_track (int input_channels, int output_channels, TrackMode mode, uint32_t how_many)
 {
        char track_name[32];
+       uint32_t track_id = 0;
        uint32_t n = 0;
        uint32_t channels_used = 0;
        string port;
-       uint32_t nphysical_in;
-       uint32_t nphysical_out;
+       RouteList new_routes;
+       list<boost::shared_ptr<AudioTrack> > ret;
 
        /* count existing audio tracks */
 
@@ -1859,105 +1763,133 @@ Session::new_audio_track (int input_channels, int output_channels, TrackMode mod
                }
        }
 
-       /* 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)
-       */
+       vector<string> physinputs;
+       vector<string> physoutputs;
+       uint32_t nphysical_in;
+       uint32_t nphysical_out;
 
-       do {
-               snprintf (track_name, sizeof(track_name), "Audio %" PRIu32, n+1);
-               if (route_by_name (track_name) == 0) {
-                       break;
-               }
-               n++;
+       _engine.get_physical_outputs (physoutputs);
+       _engine.get_physical_inputs (physinputs);
 
-       } while (n < (UINT_MAX-1));
+       while (how_many) {
 
-       if (input_auto_connect & AutoConnectPhysical) {
-               nphysical_in = n_physical_inputs;
-       } else {
-               nphysical_in = 0;
-       }
+               /* 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)
+               */
+               
 
-       if (output_auto_connect & AutoConnectPhysical) {
-               nphysical_out = n_physical_outputs;
-       } else {
-               nphysical_out = 0;
-       }
+               do {
+                       ++track_id;
 
-       try {
-               shared_ptr<AudioTrack> track (new AudioTrack (*this, track_name, Route::Flag (0), mode));
+                       snprintf (track_name, sizeof(track_name), "Audio %" PRIu32, track_id);
 
-               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 (route_by_name (track_name) == 0) {
+                               break;
+                       }
+                       
+               } while (track_id < (UINT_MAX-1));
 
-               if (nphysical_in) {
-                       for (uint32_t x = 0; x < track->n_inputs().get(DataType::AUDIO) && x < nphysical_in; ++x) {
+               if (input_auto_connect & AutoConnectPhysical) {
+                       nphysical_in = min (n_physical_inputs, (uint32_t) physinputs.size());
+               } else {
+                       nphysical_in = 0;
+               }
+               
+               if (output_auto_connect & AutoConnectPhysical) {
+                       nphysical_out = min (n_physical_outputs, (uint32_t) physinputs.size());
+               } else {
+                       nphysical_out = 0;
+               }
+               
+               try {
+                       shared_ptr<AudioTrack> track (new AudioTrack (*this, track_name, Route::Flag (0), mode));
+                       
+                       if (track->ensure_io (ChanCount(DataType::AUDIO, input_channels), ChanCount(DataType::AUDIO, output_channels), false, this)) {
+                               error << string_compose (_("cannot configure %1 in/%2 out configuration for new audio track"),
+                                                        input_channels, output_channels)
+                                     << endmsg;
+                       }
+                       
+                       if (nphysical_in) {
+                               for (uint32_t x = 0; x < track->n_inputs().get(DataType::AUDIO) && x < nphysical_in; ++x) {
+                                       
+                                       port = "";
+                                       
+                                       if (input_auto_connect & AutoConnectPhysical) {
+                                               port = physinputs[(channels_used+x)%nphysical_in];
+                                       } 
+                                       
+                                       if (port.length() && track->connect_input (track->input (x), port, this)) {
+                                               break;
+                                       }
+                               }
+                       }
+                       
+                       for (uint32_t x = 0; x < track->n_outputs().get(DataType::MIDI); ++x) {
                                
                                port = "";
                                
-                               if (input_auto_connect & AutoConnectPhysical) {
-                                       port = _engine.get_nth_physical_input (DataType::AUDIO, (channels_used+x)%nphysical_in);
-                               } 
+                               if (nphysical_out && (output_auto_connect & AutoConnectPhysical)) {
+                                       port = physoutputs[(channels_used+x)%nphysical_out];
+                               } else if (output_auto_connect & AutoConnectMaster) {
+                                       if (_master_out) {
+                                               port = _master_out->input (x%_master_out->n_inputs().get(DataType::AUDIO))->name();
+                                       }
+                               }
                                
-                               if (port.length() && track->connect_input (track->input (x), port, this)) {
+                               if (port.length() && track->connect_output (track->output (x), port, this)) {
                                        break;
                                }
                        }
-               }
-               
-               for (uint32_t x = 0; x < track->n_outputs().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());
 
-                       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 +1899,148 @@ 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) {
-                       
-                       port = "";
+               } while (bus_id < (UINT_MAX-1));
 
-                       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();
+               try {
+                       shared_ptr<Route> bus (new Route (*this, bus_name, -1, -1, -1, -1, Route::Flag(0), DataType::AUDIO));
+                       
+                       if (bus->ensure_io (ChanCount(DataType::AUDIO, input_channels), ChanCount(DataType::AUDIO, output_channels), false, this)) {
+                               error << string_compose (_("cannot configure %1 in/%2 out configuration for new audio track"),
+                                                        input_channels, output_channels)
+                                     << endmsg;
+                       }
+                       
+                       for (uint32_t x = 0; x < bus->n_inputs().get(DataType::AUDIO); ++x) {
+                               
+                               port = "";
+                               
+                               if (input_auto_connect & AutoConnectPhysical) {
+                                       port = physinputs[((n+x)%n_physical_inputs)];
+                               } 
+                               
+                               if (port.length() && bus->connect_input (bus->input (x), port, this)) {
+                                       break;
                                }
                        }
-
-                       if (port.length() && bus->connect_output (bus->output (x), port, this)) {
-                               break;
+                       
+                       for (uint32_t x = 0; x < bus->n_outputs().get(DataType::AUDIO); ++x) {
+                               
+                               port = "";
+                               
+                               if (output_auto_connect & AutoConnectPhysical) {
+                                       port = physoutputs[((n+x)%n_physical_outputs)];
+                               } else if (output_auto_connect & AutoConnectMaster) {
+                                       if (_master_out) {
+                                               port = _master_out->input (x%_master_out->n_inputs().get(DataType::AUDIO))->name();
+                                       }
+                               }
+                               
+                               if (port.length() && bus->connect_output (bus->output (x), port, this)) {
+                                       break;
+                               }
+                       }
+                       
+                       if (_control_out) {
+                               vector<string> cports;
+                               uint32_t ni = _control_out->n_inputs().get(DataType::AUDIO);
+                               
+                               for (uint32_t n = 0; n < ni; ++n) {
+                                       cports.push_back (_control_out->input(n)->name());
+                               }
+                               bus->set_control_outs (cports);
                        }
-               }
 
-               if (_control_out) {
-                       vector<string> cports;
-                       uint32_t ni = _control_out->n_inputs().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;
-       }
-
-       if (route->control()) {
-               _control_out = route;
+       for (RouteList::iterator x = new_routes.begin(); x != new_routes.end(); ++x) {
+               (*x)->solo_changed.connect (sigc::bind (mem_fun (*this, &Session::route_solo_changed), (*x)));
+               (*x)->mute_changed.connect (mem_fun (*this, &Session::route_mute_changed));
+               (*x)->output_changed.connect (mem_fun (*this, &Session::set_worst_io_latencies_x));
+               (*x)->redirects_changed.connect (mem_fun (*this, &Session::update_latency_compensation_proxy));
+               
+               if ((*x)->master()) {
+                       _master_out = (*x);
+               }
+               
+               if ((*x)->control()) {
+                       _control_out = (*x);
+               }
        }
 
        set_dirty();
-       save_state (_current_snapshot_name);
-       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 +2048,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
@@ -2138,20 +2085,19 @@ Session::remove_route (shared_ptr<Route> route)
        }
 
        Track* t;
-       Diskstream* ds = 0;
+       boost::shared_ptr<Diskstream> ds;
        
        if ((t = dynamic_cast<Track*>(route.get())) != 0) {
-               ds = &t->diskstream();
+               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 ();
@@ -2162,9 +2108,10 @@ Session::remove_route (shared_ptr<Route> route)
        /* XXX should we disconnect from the Route's signals ? */
 
        save_state (_current_snapshot_name);
-       save_history (_current_snapshot_name);
 
-       /* all shared ptrs to route should go out of scope here */
+       /* try to cause everyone to drop their references */
+
+       route->drop_references ();
 }      
 
 void
@@ -2402,6 +2349,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)
 {
@@ -2438,11 +2399,9 @@ Session::get_maximum_extent () const
        jack_nframes_t max = 0;
        jack_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) {
+       for (DiskstreamList::const_iterator i = dsl->begin(); i != dsl->end(); ++i) {
                Playlist* pl = (*i)->playlist();
                if ((me = pl->get_maximum_extent()) > max) {
                        max = me;
@@ -2452,32 +2411,32 @@ 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);
 }
 
 /* Region management */
@@ -2603,8 +2562,9 @@ Session::region_name (string& result, string base, bool newlevel) const
 }      
 
 void
-Session::add_region (Region* region)
+Session::add_region (boost::shared_ptr<Region> region)
 {
+       boost::shared_ptr<Region> other;
        bool added = false;
 
        { 
@@ -2614,7 +2574,9 @@ Session::add_region (Region* region)
 
                for (x = regions.begin(); x != regions.end(); ++x) {
 
-                       if (region->region_list_equivalent (*x->second)) {
+                       other = x->second;
+
+                       if (region->region_list_equivalent (other)) {
                                break;
                        }
                }
@@ -2628,6 +2590,7 @@ Session::add_region (Region* region)
 
                        pair<RegionList::iterator,bool> x = regions.insert (entry);
 
+
                        if (!x.second) {
                                return;
                        }
@@ -2639,19 +2602,19 @@ Session::add_region (Region* region)
 
        /* mark dirty because something has changed even if we didn't
           add the region to the region list.
-          */
-
+       */
+       
        set_dirty();
-
+       
        if (added) {
-               region->GoingAway.connect (mem_fun (*this, &Session::remove_region));
+               region->GoingAway.connect (sigc::bind (mem_fun (*this, &Session::remove_region), region));
                region->StateChanged.connect (sigc::bind (mem_fun (*this, &Session::region_changed), region));
                RegionAdded (region); /* EMIT SIGNAL */
        }
 }
 
 void
-Session::region_changed (Change what_changed, Region* region)
+Session::region_changed (Change what_changed, boost::shared_ptr<Region> region)
 {
        if (what_changed & Region::HiddenChanged) {
                /* relay hidden changes */
@@ -2660,17 +2623,17 @@ Session::region_changed (Change what_changed, Region* region)
 }
 
 void
-Session::region_renamed (Region* region)
+Session::region_renamed (boost::shared_ptr<Region> region)
 {
        add_region (region);
 }
 
 void
-Session::remove_region (Region* region)
+Session::remove_region (boost::shared_ptr<Region> region)
 {
        RegionList::iterator i;
        bool removed = false;
-
+       
        { 
                Glib::Mutex::Lock lm (region_lock);
 
@@ -2678,25 +2641,25 @@ Session::remove_region (Region* region)
                        regions.erase (i);
                        removed = true;
                }
-
        }
 
        /* mark dirty because something has changed even if we didn't
           remove the region from the region list.
-          */
+       */
 
        set_dirty();
 
        if (removed) {
-               RegionRemoved(region); /* EMIT SIGNAL */
+                RegionRemoved(region); /* EMIT SIGNAL */
        }
 }
 
-Region*
+boost::shared_ptr<Region>
 Session::find_whole_file_parent (Region& child)
 {
        RegionList::iterator i;
-       Region* region;
+       boost::shared_ptr<Region> region;
+       
        Glib::Mutex::Lock lm (region_lock);
 
        for (i = regions.begin(); i != regions.end(); ++i) {
@@ -2705,49 +2668,51 @@ Session::find_whole_file_parent (Region& child)
 
                if (region->whole_file()) {
 
-                       if (child.source_equivalent (*region)) {
+                       if (child.source_equivalent (region)) {
                                return region;
                        }
                }
        } 
 
-       return 0;
+       return boost::shared_ptr<AudioRegion> ((AudioRegion*) 0);
 }      
 
 void
-Session::find_equivalent_playlist_regions (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;
+       boost::shared_ptr<AudioRegion> aregion;
 
-       if ((aregion = dynamic_cast<AudioRegion*> (region)) == 0) {
+       if ((aregion = boost::dynamic_pointer_cast<AudioRegion> (region)) == 0) {
                return 0;
        }
-
+       
        if (aregion->playlist()) {
                aregion->playlist()->destroy_region (region);
        }
 
-       vector<Source*> srcs;
+       vector<boost::shared_ptr<Source> > srcs;
        
        for (uint32_t n = 0; n < aregion->n_channels(); ++n) {
-               srcs.push_back (&aregion->source (n));
+               srcs.push_back (aregion->source (n));
        }
 
-       for (vector<Source*>::iterator i = srcs.begin(); i != srcs.end(); ++i) {
+       for (vector<boost::shared_ptr<Source> >::iterator i = srcs.begin(); i != srcs.end(); ++i) {
                
-               if ((*i)->use_cnt() == 0) {
-                       AudioFileSource* afs = dynamic_cast<AudioFileSource*>(*i);
+               if ((*i).use_count() == 1) {
+                       boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*i);
+
                        if (afs) {
                                (afs)->mark_for_remove ();
                        }
-                       delete *i;
+                       
+                       (*i)->drop_references ();
                }
        }
 
@@ -2755,9 +2720,9 @@ Session::destroy_region (Region* region)
 }
 
 int
-Session::destroy_regions (list<Region*> regions)
+Session::destroy_regions (list<boost::shared_ptr<Region> > regions)
 {
-       for (list<Region*>::iterator i = regions.begin(); i != regions.end(); ++i) {
+       for (list<boost::shared_ptr<Region> >::iterator i = regions.begin(); i != regions.end(); ++i) {
                destroy_region (*i);
        }
        return 0;
@@ -2766,12 +2731,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());
@@ -2784,63 +2749,77 @@ Session::remove_last_capture ()
 }
 
 int
-Session::remove_region_from_region_list (Region& r)
+Session::remove_region_from_region_list (boost::shared_ptr<Region> r)
 {
-       remove_region (&r);
+       remove_region (r);
        return 0;
 }
 
 /* Source Management */
 void
-Session::add_source (Source* source)
+Session::add_source (boost::shared_ptr<Source> source)
 {
-       pair<SourceList::key_type, SourceList::mapped_type> entry;
+       cerr << "add new source " << source->name() << endl;
 
-       {
-               Glib::Mutex::Lock lm (source_lock);
-               entry.first = source->id();
-               entry.second = source;
-               sources.insert (entry);
-       }
+       pair<SourceMap::key_type, SourceMap::mapped_type> entry;
+       pair<SourceMap::iterator,bool> result;
+
+       entry.first = source->id();
+       entry.second = source;
        
-       source->GoingAway.connect (mem_fun (this, &Session::remove_source));
+       {
+               Glib::Mutex::Lock lm (source_lock);
+               result = sources.insert (entry);
+       }
+
+       if (!result.second) {
+               cerr << "\tNOT inserted ? " << result.second << endl;
+       }
+
+       source->GoingAway.connect (sigc::bind (mem_fun (this, &Session::remove_source), boost::weak_ptr<Source> (source)));
        set_dirty();
        
        SourceAdded (source); /* EMIT SIGNAL */
 }
 
 void
-Session::remove_source (Source* source)
+Session::remove_source (boost::weak_ptr<Source> src)
 {
-       SourceList::iterator i;
+       SourceMap::iterator i;
+       boost::shared_ptr<Source> source = src.lock();
 
-       { 
-               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.
-               */
+       if (!source) {
+               cerr << "removing a source DEAD\n";
+       } else {
+               cerr << "removing a source " << source->name () << endl;
                
-               save_state (_current_snapshot_name);
-                save_history (_current_snapshot_name);
+               { 
+                       Glib::Mutex::Lock lm (source_lock);
+                       
+                       if ((i = sources.find (source->id())) != sources.end()) {
+                               sources.erase (i);
+                       } 
+               }
+               
+               if (!_state_of_the_state & InCleanup) {
+                       
+                       /* save state so we don't end up with a session file
+                          referring to non-existent sources.
+                       */
+                       
+                       save_state (_current_snapshot_name);
+               }
+               
+               SourceRemoved(source); /* EMIT SIGNAL */
        }
-
-       SourceRemoved(source); /* EMIT SIGNAL */
 }
 
-Source *
+boost::shared_ptr<Source>
 Session::source_by_id (const PBD::ID& id)
 {
        Glib::Mutex::Lock lm (source_lock);
-       SourceList::iterator i;
-       Source* source = 0;
+       SourceMap::iterator i;
+       boost::shared_ptr<Source> source;
 
        if ((i = sources.find (id)) != sources.end()) {
                source = i->second;
@@ -3086,24 +3065,126 @@ 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, 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
@@ -3169,13 +3250,12 @@ 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, spath, false, frame_rate()));
 }
 
 
@@ -3211,7 +3291,7 @@ Session::add_playlist (Playlist* playlist)
                        playlists.insert (playlists.begin(), playlist);
                        // playlist->ref();
                        playlist->InUse.connect (mem_fun (*this, &Session::track_playlist));
-                       playlist->GoingAway.connect (mem_fun (*this, &Session::remove_playlist));
+                       playlist->GoingAway.connect (sigc::bind (mem_fun (*this, &Session::remove_playlist), playlist));
                }
        }
 
@@ -3282,50 +3362,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 */
        }
 }
 
@@ -3404,10 +3481,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++;
                }
@@ -3426,15 +3504,15 @@ Session::graph_reordered ()
                return;
        }
        
-       Glib::RWLock::ReaderLock lm2 (diskstream_lock);
-
        resort_routes ();
 
        /* force all diskstreams to update their capture offset values to 
           reflect any changes in latencies within the graph.
        */
        
-       for (DiskstreamList::iterator i = diskstreams.begin(); i != diskstreams.end(); ++i) {
+       boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
+
+       for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
                (*i)->set_capture_offset ();
        }
 }
@@ -3491,7 +3569,7 @@ Session::add_redirect (Redirect* redirect)
                /*NOTREACHED*/
        }
 
-       redirect->GoingAway.connect (mem_fun (*this, &Session::remove_redirect));
+       redirect->GoingAway.connect (sigc::bind (mem_fun (*this, &Session::remove_redirect), redirect));
 
        set_dirty();
 }
@@ -3691,11 +3769,9 @@ Session::remove_named_selection (NamedSelection* named_selection)
 void
 Session::reset_native_file_format ()
 {
-       // jlc - WHY take routelock?
-       //RWLockMonitor lm1 (route_lock, true, __LINE__, __FILE__);
-       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);
        }
 }
@@ -3715,9 +3791,9 @@ Session::route_name_unique (string n) const
 }
 
 int
-Session::cleanup_audio_file_source (AudioFileSource& fs)
+Session::cleanup_audio_file_source (boost::shared_ptr<AudioFileSource> fs)
 {
-       return fs.move_to_trash (dead_sound_dir_name);
+       return fs->move_to_trash (dead_sound_dir_name);
 }
 
 uint32_t
@@ -3784,15 +3860,16 @@ 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)
+                              bool overwrite, vector<boost::shared_ptr<Source> >& srcs, InterThreadInfo& itt)
 {
+       boost::shared_ptr<AudioFileSource> fsource;
+       
        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());
+       ChanCount        nchans(track.audio_diskstream()->n_channels());
        jack_nframes_t   position;
        jack_nframes_t   this_chunk;
        jack_nframes_t   to_do;
@@ -3805,7 +3882,7 @@ Session::write_one_audio_track (AudioTrack& track, jack_nframes_t start, jack_nf
        
        /* call tree *MUST* hold route_lock */
        
-       if ((playlist = track.diskstream().playlist()) == 0) {
+       if ((playlist = track.diskstream()->playlist()) == 0) {
                goto out;
        }
 
@@ -3832,11 +3909,7 @@ 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, buf, false, frame_rate()));
                }
                
                catch (failed_constructor& err) {
@@ -3844,7 +3917,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 */
@@ -3865,9 +3938,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;
@@ -3889,8 +3962,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);
                        }
@@ -3898,8 +3972,8 @@ 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 ();
                        }
@@ -3910,12 +3984,14 @@ Session::write_one_audio_track (AudioTrack& track, jack_nframes_t start, jack_nf
                
   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 ();
                }
        }
 
@@ -4007,3 +4083,14 @@ Session::set_xfade_model (CrossfadeModel xm)
        }
 }
 
+void
+Session::add_curve(Curve *curve)
+{
+    curves[curve->id()] = curve;
+}
+
+void
+Session::add_automation_list(AutomationList *al)
+{
+    automation_lists[al->id()] = al;
+}