Merged with trunk R1304
[ardour.git] / libs / ardour / session.cc
index 3c325ee5385b7d6aa5e92a910d8262ca4714872c..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>
@@ -72,6 +73,7 @@
 #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>
@@ -87,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;
@@ -98,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)
@@ -282,13 +287,17 @@ 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 ();
+       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)) {
-               cerr << "2nd state failed\n";
+               destroy ();
                throw failed_constructor ();
        }
        
@@ -298,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 */
        }
@@ -312,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()),
@@ -333,13 +344,26 @@ Session::Session (AudioEngine &eng,
 
        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());
+       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);
+       }
+
+       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) {
@@ -361,10 +385,11 @@ Session::Session (AudioEngine &eng,
                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 ();
        }
        
@@ -380,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.
@@ -398,7 +429,7 @@ Session::~Session ()
 
        /* clear history so that no references to objects are held any more */
 
-       history.clear ();
+       _history.clear ();
 
        /* clear state tree so that no references to objects are held any more */
        
@@ -448,21 +479,44 @@ 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;
+
+               tmp = i;
+               ++tmp;
+
+               (*i)->drop_references ();
+               
+               i = tmp;
+       }
+       
+       playlists.clear ();
+       unused_playlists.clear ();
 
 #ifdef TRACK_DESTRUCTION
        cerr << "delete regions\n";
 #endif /* TRACK_DESTRUCTION */
        
-       for (RegionList::iterator i = regions.begin(); i != regions.end(); ++i) {
+       for (RegionList::iterator i = regions.begin(); i != regions.end(); ) {
+               RegionList::iterator tmp;
+
+               tmp = i;
+               ++tmp;
+
+               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 */
@@ -589,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));
@@ -619,7 +673,7 @@ Session::when_engine_running ()
                        
                        if (_click_io->set_state (*child->children().front()) == 0) {
                                
-                               _clicking = click_requested;
+                               _clicking = Config->get_clicking ();
 
                        } else {
 
@@ -637,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 ();
                                }
                        }
                }
@@ -650,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
@@ -809,6 +846,7 @@ Session::when_engine_running ()
                }
        }
 
+       
        _state_of_the_state = StateOfTheState (_state_of_the_state & ~(CannotSave|Dirty));
 
        /* hook us up to the engine */
@@ -835,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 ();
@@ -886,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,
@@ -900,10 +954,10 @@ Session::playlist_length_changed (Playlist* pl)
 void
 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 () */
@@ -918,76 +972,12 @@ 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 */
-                       
-                       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 (!auto_input);   
-                               }
-                       }
-               }
-
-               set_dirty();
-               ControlChanged (AutoInput);
-       }
-}
-
 void
 Session::reset_input_monitor_state ()
 {
@@ -998,7 +988,7 @@ Session::reset_input_monitor_state ()
                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 {
@@ -1006,44 +996,19 @@ Session::reset_input_monitor_state ()
 
                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);
        }
@@ -1052,7 +1017,7 @@ Session::auto_punch_start_changed (Location* location)
 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);
 }      
@@ -1060,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;
@@ -1072,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()) {
 
@@ -1083,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
@@ -1140,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)
 {
@@ -1275,7 +1198,7 @@ Session::enable_record ()
                _last_record_location = _transport_frame;
                deliver_mmc(MIDI::MachineControl::cmdRecordStrobe, _last_record_location);
 
-               if (Config->get_use_hardware_monitoring() && auto_input) {
+               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 ()) {
@@ -1309,7 +1232,7 @@ 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) {
+               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) {
@@ -1332,11 +1255,11 @@ Session::step_back_from_record ()
 {
        g_atomic_int_set (&_record_status, Enabled);
 
-       if (Config->get_use_hardware_monitoring()) {
+       if (Config->get_monitoring_model() == HardwareMonitoring) {
                boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
                
                for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
-                       if (auto_input && (*i)->record_enabled ()) {
+                       if (Config->get_auto_input() && (*i)->record_enabled ()) {
                                //cerr << "switching from input" << __FILE__ << __LINE__ << endl << endl;
                                (*i)->monitor_input (false);   
                        }
@@ -1349,14 +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);
 
        if (_transport_speed) {
-               if (!punch_in) {
+               if (!Config->get_punch_in()) {
                        enable_record ();
                } 
        } else {
@@ -1367,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 
@@ -1426,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();
 
@@ -1449,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
@@ -1489,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 */
        
@@ -1500,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);
                
        }
 
@@ -1747,6 +1671,7 @@ Session::new_audio_track (int input_channels, int output_channels, TrackMode mod
        string port;
        RouteList new_routes;
        list<boost::shared_ptr<AudioTrack> > ret;
+       uint32_t control_id;
 
        /* count existing audio tracks */
 
@@ -1770,6 +1695,7 @@ Session::new_audio_track (int input_channels, int output_channels, TrackMode mod
 
        _engine.get_physical_outputs (physoutputs);
        _engine.get_physical_inputs (physinputs);
+       control_id = 0;
 
        while (how_many) {
 
@@ -1791,13 +1717,13 @@ Session::new_audio_track (int input_channels, int output_channels, TrackMode mod
                        
                } while (track_id < (UINT_MAX-1));
 
-               if (input_auto_connect & AutoConnectPhysical) {
+               if (Config->get_input_auto_connect() & AutoConnectPhysical) {
                        nphysical_in = min (n_physical_inputs, (uint32_t) physinputs.size());
                } else {
                        nphysical_in = 0;
                }
                
-               if (output_auto_connect & AutoConnectPhysical) {
+               if (Config->get_output_auto_connect() & AutoConnectPhysical) {
                        nphysical_out = min (n_physical_outputs, (uint32_t) physinputs.size());
                } else {
                        nphysical_out = 0;
@@ -1817,7 +1743,7 @@ Session::new_audio_track (int input_channels, int output_channels, TrackMode mod
                                        
                                        port = "";
                                        
-                                       if (input_auto_connect & AutoConnectPhysical) {
+                                       if (Config->get_input_auto_connect() & AutoConnectPhysical) {
                                                port = physinputs[(channels_used+x)%nphysical_in];
                                        } 
                                        
@@ -1831,9 +1757,9 @@ Session::new_audio_track (int input_channels, int output_channels, TrackMode mod
                                
                                port = "";
                                
-                               if (nphysical_out && (output_auto_connect & AutoConnectPhysical)) {
+                               if (nphysical_out && (Config->get_output_auto_connect() & AutoConnectPhysical)) {
                                        port = physoutputs[(channels_used+x)%nphysical_out];
-                               } else if (output_auto_connect & AutoConnectMaster) {
+                               } else if (Config->get_output_auto_connect() & AutoConnectMaster) {
                                        if (_master_out) {
                                                port = _master_out->input (x%_master_out->n_inputs().get(DataType::AUDIO))->name();
                                        }
@@ -1858,7 +1784,8 @@ Session::new_audio_track (int input_channels, int output_channels, TrackMode mod
                        }
                        
                        track->DiskstreamChanged.connect (mem_fun (this, &Session::resort_routes));
-                       track->set_remote_control_id (ntracks());
+                       track->set_remote_control_id (ntracks() + control_id + 1);
+                       ++control_id;
 
                        new_routes.push_back (track);
                        ret.push_back (track);
@@ -1933,12 +1860,12 @@ Session::new_audio_route (int input_channels, int output_channels, uint32_t how_
                                      << endmsg;
                        }
                        
-                       for (uint32_t x = 0; x < bus->n_inputs().get(DataType::AUDIO); ++x) {
+                       for (uint32_t x = 0; n_physical_inputs && x < bus->n_inputs().get(DataType::AUDIO); ++x) {
                                
                                port = "";
-                               
-                               if (input_auto_connect & AutoConnectPhysical) {
-                                       port = physinputs[((n+x)%n_physical_inputs)];
+
+                               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)) {
@@ -1946,13 +1873,13 @@ Session::new_audio_route (int input_channels, int output_channels, uint32_t how_
                                }
                        }
                        
-                       for (uint32_t x = 0; x < bus->n_outputs().get(DataType::AUDIO); ++x) {
+                       for (uint32_t x = 0; n_physical_outputs && x < bus->n_outputs().get(DataType::AUDIO); ++x) {
                                
                                port = "";
                                
-                               if (output_auto_connect & AutoConnectPhysical) {
+                               if (Config->get_output_auto_connect() & AutoConnectPhysical) {
                                        port = physoutputs[((n+x)%n_physical_outputs)];
-                               } else if (output_auto_connect & AutoConnectMaster) {
+                               } else if (Config->get_output_auto_connect() & AutoConnectMaster) {
                                        if (_master_out) {
                                                port = _master_out->input (x%_master_out->n_inputs().get(DataType::AUDIO))->name();
                                        }
@@ -2006,7 +1933,10 @@ Session::add_routes (RouteList& new_routes, bool save)
        }
 
        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)));
+               
+               boost::weak_ptr<Route> wpr (*x);
+
+               (*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));
@@ -2056,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 */
 
@@ -2104,14 +2035,26 @@ Session::remove_route (shared_ptr<Route> route)
        
        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 */
 
-       save_state (_current_snapshot_name);
+       /* 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 */
 
        route->drop_references ();
+
+       /* save the new state of the world */
+
+       if (save_state (_current_snapshot_name)) {
+               save_history (_current_snapshot_name);
+       }
 }      
 
 void
@@ -2121,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
@@ -2129,8 +2072,15 @@ Session::route_solo_changed (void* src, shared_ptr<Route> route)
        }
        
        bool is_track;
-       
-       is_track = (dynamic_cast<Track*>(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 ();
 
@@ -2166,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;
                                } 
                        }
@@ -2215,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 ()
 {
@@ -2384,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);
@@ -2393,16 +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; 
 
        boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
 
        for (DiskstreamList::const_iterator i = dsl->begin(); i != dsl->end(); ++i) {
-               Playlist* pl = (*i)->playlist();
+               boost::shared_ptr<Playlist> pl = (*i)->playlist();
                if ((me = pl->get_maximum_extent()) > max) {
                        max = me;
                }
@@ -2607,15 +2547,21 @@ Session::add_region (boost::shared_ptr<Region> region)
        set_dirty();
        
        if (added) {
-               region->GoingAway.connect (sigc::bind (mem_fun (*this, &Session::remove_region), region));
-               region->StateChanged.connect (sigc::bind (mem_fun (*this, &Session::region_changed), region));
+               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, boost::shared_ptr<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);
@@ -2623,17 +2569,17 @@ Session::region_changed (Change what_changed, boost::shared_ptr<Region> region)
 }
 
 void
-Session::region_renamed (boost::shared_ptr<Region> region)
-{
-       add_region (region);
-}
-
-void
-Session::remove_region (boost::shared_ptr<Region> region)
+Session::remove_region (boost::weak_ptr<Region> weak_region)
 {
        RegionList::iterator i;
+       boost::shared_ptr<Region> region (weak_region.lock ());
+
+       if (!region) {
+               return;
+       }
+
        bool removed = false;
-       
+
        { 
                Glib::Mutex::Lock lm (region_lock);
 
@@ -2655,7 +2601,7 @@ Session::remove_region (boost::shared_ptr<Region> region)
 }
 
 boost::shared_ptr<Region>
-Session::find_whole_file_parent (Region& child)
+Session::find_whole_file_parent (boost::shared_ptr<Region const> child)
 {
        RegionList::iterator i;
        boost::shared_ptr<Region> region;
@@ -2668,13 +2614,13 @@ Session::find_whole_file_parent (Region& child)
 
                if (region->whole_file()) {
 
-                       if (child.source_equivalent (region)) {
+                       if (child->source_equivalent (region)) {
                                return region;
                        }
                }
        } 
 
-       return boost::shared_ptr<AudioRegion> ((AudioRegion*) 0);
+       return boost::shared_ptr<Region> ();
 }      
 
 void
@@ -2687,32 +2633,38 @@ Session::find_equivalent_playlist_regions (boost::shared_ptr<Region> region, vec
 int
 Session::destroy_region (boost::shared_ptr<Region> region)
 {
-       boost::shared_ptr<AudioRegion> aregion;
-
-       if ((aregion = boost::dynamic_pointer_cast<AudioRegion> (region)) == 0) {
-               return 0;
-       }
-       
-       if (aregion->playlist()) {
-               aregion->playlist()->destroy_region (region);
-       }
-
        vector<boost::shared_ptr<Source> > srcs;
-       
-       for (uint32_t n = 0; n < aregion->n_channels(); ++n) {
-               srcs.push_back (aregion->source (n));
+               
+       {
+               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));
+               }
        }
 
+       region->drop_references ();
+
        for (vector<boost::shared_ptr<Source> >::iterator i = srcs.begin(); i != srcs.end(); ++i) {
-               
-               if ((*i).use_count() == 1) {
-                       boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*i);
 
+               if (!(*i)->used()) {
+                       boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*i);
+                       
                        if (afs) {
                                (afs)->mark_for_remove ();
                        }
                        
                        (*i)->drop_references ();
+                       
+                       cerr << "source was not used by any playlist\n";
                }
        }
 
@@ -2759,8 +2711,6 @@ Session::remove_region_from_region_list (boost::shared_ptr<Region> r)
 void
 Session::add_source (boost::shared_ptr<Source> source)
 {
-       cerr << "add new source " << source->name() << endl;
-
        pair<SourceMap::key_type, SourceMap::mapped_type> entry;
        pair<SourceMap::iterator,bool> result;
 
@@ -2772,14 +2722,10 @@ Session::add_source (boost::shared_ptr<Source> source)
                result = sources.insert (entry);
        }
 
-       if (!result.second) {
-               cerr << "\tNOT inserted ? " << result.second << endl;
+       if (result.second) {
+               source->GoingAway.connect (sigc::bind (mem_fun (this, &Session::remove_source), boost::weak_ptr<Source> (source)));
+               set_dirty();
        }
-
-       source->GoingAway.connect (sigc::bind (mem_fun (this, &Session::remove_source), boost::weak_ptr<Source> (source)));
-       set_dirty();
-       
-       SourceAdded (source); /* EMIT SIGNAL */
 }
 
 void
@@ -2789,9 +2735,11 @@ Session::remove_source (boost::weak_ptr<Source> src)
        boost::shared_ptr<Source> source = src.lock();
 
        if (!source) {
-               cerr << "removing a source DEAD\n";
-       } else {
-               cerr << "removing a source " << source->name () << endl;
+               return;
+       } 
+
+       { 
+               Glib::Mutex::Lock lm (source_lock);
                
                { 
                        Glib::Mutex::Lock lm (source_lock);
@@ -2800,17 +2748,15 @@ Session::remove_source (boost::weak_ptr<Source> src)
                                sources.erase (i);
                        } 
                }
+       }
+       
+       if (!_state_of_the_state & InCleanup) {
                
-               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 state so we don't end up with a session file
+                  referring to non-existent sources.
+               */
                
-               SourceRemoved(source); /* EMIT SIGNAL */
+               save_state (_current_snapshot_name);
        }
 }
 
@@ -2831,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";
 
@@ -2987,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) {
@@ -3007,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 += '/';
@@ -3027,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) {
@@ -3038,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();
                }
        }
@@ -3048,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 ('/');
        
@@ -3069,7 +3005,8 @@ 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()));
+       return boost::dynamic_pointer_cast<AudioFileSource> (
+               SourceFactory::createWritable (DataType::AUDIO, *this, spath, destructive, frame_rate()));
 }
 
 // FIXME: _terrible_ code duplication
@@ -3255,13 +3192,13 @@ Session::create_midi_source_for_session (MidiDiskstream& ds)
 {
        string spath = midi_path_from_name (ds.name());
        
-       return boost::dynamic_pointer_cast<SMFSource> (SourceFactory::createWritable (DataType::MIDI, spath, false, frame_rate()));
+       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);
@@ -3275,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;
@@ -3289,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 (sigc::bind (mem_fun (*this, &Session::remove_playlist), 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)));
                }
        }
 
@@ -3301,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);
                        
@@ -3319,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()) {
@@ -3331,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);
                }
@@ -3415,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());
                        
@@ -3504,6 +3486,12 @@ Session::graph_reordered ()
                return;
        }
        
+       /* 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 ();
 
        /* force all diskstreams to update their capture offset values to 
@@ -3581,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*/
@@ -3601,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
@@ -3662,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)
 {
@@ -3700,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 ()
 {
-       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 < 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);
+       }
 }
 
-string
-Session::next_insert_name ()
+uint32_t
+Session::next_send_id ()
+{
+       /* 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);
+       }
+}
+
+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 */
@@ -3790,12 +3840,6 @@ Session::route_name_unique (string n) const
        return true;
 }
 
-int
-Session::cleanup_audio_file_source (boost::shared_ptr<AudioFileSource> fs)
-{
-       return fs->move_to_trash (dead_sound_dir_name);
-}
-
 uint32_t
 Session::n_playlists () const
 {
@@ -3804,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;
@@ -3859,24 +3893,23 @@ Session::freeze (InterThreadInfo& itt)
 }
 
 int
-Session::write_one_audio_track (AudioTrack& track, jack_nframes_t start, jack_nframes_t len,   
+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;
-       
-       int              ret = -1;
-       Playlist*        playlist = 0;
-       uint32_t         x;
-       char             buf[PATH_MAX+1];
-       string           dir;
-       ChanCount        nchans(track.audio_diskstream()->n_channels());
-       jack_nframes_t   position;
-       jack_nframes_t   this_chunk;
-       jack_nframes_t   to_do;
-       BufferSet        buffers;
+       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);
        
@@ -3909,7 +3942,8 @@ Session::write_one_audio_track (AudioTrack& track, jack_nframes_t start, jack_nf
                }
                
                try {
-                       fsource = boost::dynamic_pointer_cast<AudioFileSource> (SourceFactory::createWritable (DataType::AUDIO, buf, false, frame_rate()));
+                       fsource = boost::dynamic_pointer_cast<AudioFileSource> (
+                               SourceFactory::createWritable (DataType::AUDIO, *this, buf, false, frame_rate()));
                }
                
                catch (failed_constructor& err) {
@@ -3978,7 +4012,12 @@ Session::write_one_audio_track (AudioTrack& track, jack_nframes_t start, jack_nf
                                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;
        }
                
@@ -4064,33 +4103,14 @@ Session::nbusses () const
 }
 
 void
-Session::set_layer_model (LayerModel lm)
-{
-       if (lm != layer_model) {
-               layer_model = lm;
-               set_dirty ();
-               ControlChanged (LayeringModel);
-       }
-}
-
-void
-Session::set_xfade_model (CrossfadeModel xm)
+Session::add_automation_list(AutomationList *al)
 {
-       if (xm != xfade_model) {
-               xfade_model = xm;
-               set_dirty ();
-               ControlChanged (CrossfadingModel);
-       }
+       automation_lists[al->id()] = al;
 }
 
-void
-Session::add_curve(Curve *curve)
+nframes_t
+Session::compute_initial_length ()
 {
-    curves[curve->id()] = curve;
+       return _engine.frame_rate() * 60 * 5;
 }
 
-void
-Session::add_automation_list(AutomationList *al)
-{
-    automation_lists[al->id()] = al;
-}