fixes for destructive track offsets of various kinds; move from jack_nframes_t -...
[ardour.git] / libs / ardour / session.cc
index 21b0cf5fa7cf3769227663630c19a6b88256ad2e..2cf86434d7cbcab1941dd70cf4494ab2b81124e7 100644 (file)
@@ -65,6 +65,7 @@
 #include <ardour/playlist.h>
 #include <ardour/click.h>
 #include <ardour/data_type.h>
+#include <ardour/source_factory.h>
 
 #ifdef HAVE_LIBLO
 #include <ardour/osc.h>
@@ -80,10 +81,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;
@@ -91,9 +93,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)
@@ -271,11 +275,16 @@ Session::Session (AudioEngine &eng,
 
        first_stage_init (fullpath, snapshot_name);
        
-       if (create (new_session, mix_template, _engine.frame_rate() * 60 * 5)) {
-               throw failed_constructor ();
+       new_session = !g_file_test (_path.c_str(), GFileTest (G_FILE_TEST_EXISTS | G_FILE_TEST_IS_DIR));
+       if (new_session) {
+               if (create (new_session, mix_template, _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 ();
        }
        
@@ -285,6 +294,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 */
        }
@@ -299,7 +310,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),
          _mmc_port (default_mmc_port),
@@ -320,9 +331,12 @@ Session::Session (AudioEngine &eng,
        n_physical_inputs = max (requested_physical_in, _engine.n_physical_inputs());
 
        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)) {
+                       throw failed_constructor ();
+               }
        }
 
        if (control_out_channels) {
@@ -475,15 +489,8 @@ Session::~Session ()
        {
               RCUWriter<DiskstreamList> dwriter (diskstreams);
               boost::shared_ptr<DiskstreamList> dsl = dwriter.get_copy();
-              for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ) {
-                      DiskstreamList::iterator tmp;
-                      
-                      tmp = i;
-                      ++tmp;
-                      
+              for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
                       (*i)->drop_references ();
-                      
-                      i = tmp;
               }
               dsl->clear ();
        }
@@ -498,11 +505,13 @@ Session::~Session ()
                tmp = i;
                ++tmp;
 
-               delete i->second;
+               i->second->drop_references ();
 
                i = tmp;
        }
 
+       audio_sources.clear ();
+
 #ifdef TRACK_DESTRUCTION
        cerr << "delete mix groups\n";
 #endif /* TRACK_DESTRUCTION */
@@ -590,6 +599,8 @@ Session::when_engine_running ()
        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));
@@ -615,7 +626,7 @@ Session::when_engine_running ()
                        
                        if (_click_io->set_state (*child->children().front()) == 0) {
                                
-                               _clicking = click_requested;
+                               _clicking = Config->get_clicking ();
 
                        } else {
 
@@ -633,7 +644,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 ();
                                }
                        }
                }
@@ -646,7 +657,7 @@ Session::when_engine_running ()
        set_worst_io_latencies ();
 
        if (_clicking) {
-                ControlChanged (Clicking); /* EMIT SIGNAL */
+               // XXX HOW TO ALERT UI TO THIS ? DO WE NEED TO?
        }
 
        if (auditioner == 0) {
@@ -912,76 +923,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 ()
 {
@@ -992,7 +939,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_use_hardware_monitoring() && !Config->get_auto_input());
                        }
                }
        } else {
@@ -1000,44 +947,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;
+                               //cerr << "switching to input = " << !Config->get_auto_input() << __FILE__ << __LINE__ << endl << endl;
                                (*i)->monitor_input (Config->get_use_hardware_monitoring());
                        }
                }
        }
 }
 
-
-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);
        }
@@ -1046,7 +968,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);
 }      
@@ -1054,7 +976,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;
@@ -1066,7 +988,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()) {
 
@@ -1077,7 +999,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
@@ -1134,48 +1056,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)
 {
@@ -1269,7 +1149,7 @@ Session::enable_record ()
                _last_record_location = _transport_frame;
                send_mmc_in_another_thread (MIDI::MachineControl::cmdRecordStrobe);
 
-               if (Config->get_use_hardware_monitoring() && auto_input) {
+               if (Config->get_use_hardware_monitoring() && 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 ()) {
@@ -1299,7 +1179,7 @@ Session::disable_record (bool rt_context, bool force)
 
                send_mmc_in_another_thread (MIDI::MachineControl::cmdRecordExit);
 
-               if (Config->get_use_hardware_monitoring() && auto_input) {
+               if (Config->get_use_hardware_monitoring() && Config->get_auto_input()) {
                        boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
                        
                        for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
@@ -1326,7 +1206,7 @@ Session::step_back_from_record ()
                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);   
                        }
@@ -1346,7 +1226,7 @@ Session::maybe_enable_record ()
        save_state ("", true);
 
        if (_transport_speed) {
-               if (!punch_in) {
+               if (!Config->get_punch_in()) {
                        enable_record ();
                } 
        } else {
@@ -1357,12 +1237,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 
@@ -1416,19 +1296,20 @@ 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));
+       Route::set_automation_interval ((nframes_t) ceil ((double) frames_per_second * 0.25));
 
        // XXX we need some equivalent to this, somehow
        // DestructiveFileSource::setup_standard_crossfades (frames_per_second);
@@ -1439,7 +1320,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
@@ -1507,7 +1388,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 */
        
@@ -1518,7 +1399,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);
                
        }
 
@@ -2105,7 +1986,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;
                                } 
                        }
@@ -2154,16 +2035,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 ()
 {
@@ -2323,7 +2194,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);
@@ -2332,11 +2203,11 @@ 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();
 
@@ -2649,25 +2520,27 @@ Session::destroy_region (boost::shared_ptr<Region> region)
        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 ();
                }
        }
 
@@ -2713,54 +2586,74 @@ Session::remove_region_from_region_list (boost::shared_ptr<Region> r)
 /* Source Management */
 
 void
-Session::add_audio_source (AudioSource* source)
+Session::add_source (boost::shared_ptr<Source> source)
 {
-       pair<AudioSourceList::key_type, AudioSourceList::mapped_type> entry;
+       boost::shared_ptr<AudioFileSource> afs;
+
+       if ((afs = boost::dynamic_pointer_cast<AudioFileSource>(source)) != 0) {
+
+               pair<AudioSourceList::key_type, AudioSourceList::mapped_type> entry;
+               pair<AudioSourceList::iterator,bool> result;
 
-       {
-               Glib::Mutex::Lock lm (audio_source_lock);
                entry.first = source->id();
-               entry.second = source;
-               audio_sources.insert (entry);
-       }
-       
-       source->GoingAway.connect (sigc::bind (mem_fun (this, &Session::remove_source), source));
-       set_dirty();
-       
-       SourceAdded (source); /* EMIT SIGNAL */
+               entry.second = afs;
+               
+               {
+                       Glib::Mutex::Lock lm (audio_source_lock);
+                       result = audio_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 */
+       } else {
+               cerr << "\tNOT AUDIO FILE\n";
+       }
 }
 
 void
-Session::remove_source (Source* source)
+Session::remove_source (boost::weak_ptr<Source> src)
 {
        AudioSourceList::iterator i;
+       boost::shared_ptr<Source> source = src.lock();
 
-       { 
-               Glib::Mutex::Lock lm (audio_source_lock);
-
-               if ((i = audio_sources.find (source->id())) != audio_sources.end()) {
-                       audio_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);
+               { 
+                       Glib::Mutex::Lock lm (audio_source_lock);
+                       
+                       if ((i = audio_sources.find (source->id())) != audio_sources.end()) {
+                               audio_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 (audio_source_lock);
        AudioSourceList::iterator i;
-       Source* source = 0;
+       boost::shared_ptr<Source> source;
 
        if ((i = audio_sources.find (id)) != audio_sources.end()) {
                source = i->second;
@@ -2772,17 +2665,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";
 
@@ -2928,11 +2815,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) {
@@ -2968,9 +2851,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) {
@@ -2989,11 +2873,7 @@ 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 ();
 
        string::size_type pos = foo.find_last_of ('/');
        
@@ -3006,24 +2886,11 @@ 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(), chan, destructive);
-
-       /* 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());
-       } else {
-               return new SndFileSource (spath, 
-                                         Config->get_native_file_data_format(),
-                                         Config->get_native_file_header_format(),
-                                         frame_rate());
-       }
+       return boost::dynamic_pointer_cast<AudioFileSource> (SourceFactory::createWritable (*this, spath, destructive, frame_rate()));
 }
 
 /* Playlist management */
@@ -3129,50 +2996,47 @@ Session::remove_playlist (Playlist* playlist)
 }
 
 void 
-Session::set_audition (boost::shared_ptr<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.get() == (AudioRegion*) 0xfeedface) {
+       if (!pending_audition_region) {
                auditioner->audition_current_playlist ();
-       } else if (pending_audition_region) {
+       } else {
                auditioner->audition_region (pending_audition_region);
+               pending_audition_region.reset ();
        }
-       pending_audition_region.reset ((AudioRegion*) 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 (boost::shared_ptr<Region> r)
-{
-       boost::shared_ptr<AudioRegion> ar = boost::dynamic_pointer_cast<AudioRegion>(r);
-       if (ar) {
-               Event* ev = new Event (Event::Audition, Event::Add, Event::Immediate, 0, 0.0);
-               // ev->set_ptr (ar); // AUDFIX
-               queue_event (ev);
-       }
-}
-
 void
 Session::cancel_audition ()
 {
        if (auditioner->active()) {
                auditioner->cancel_audition ();
-                AuditionActive (false); /* EMIT SIGNAL */
+               AuditionActive (false); /* EMIT SIGNAL */
        }
 }
 
@@ -3185,17 +3049,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 (audio_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());
                        
@@ -3371,16 +3253,16 @@ Session::remove_redirect (Redirect* redirect)
        set_dirty();
 }
 
-jack_nframes_t
+nframes_t
 Session::available_capture_duration ()
 {
        const double scale = 4096.0 / sizeof (Sample);
-       
+
        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
@@ -3432,23 +3314,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)
 {
@@ -3583,9 +3448,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
@@ -3596,17 +3461,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;
@@ -3651,23 +3506,23 @@ Session::freeze (InterThreadInfo& itt)
 }
 
 int
-Session::write_one_audio_track (AudioTrack& track, jack_nframes_t start, jack_nframes_t len,   
-                              bool overwrite, vector<AudioSource*>& srcs, InterThreadInfo& itt)
+Session::write_one_audio_track (AudioTrack& track, nframes_t start, nframes_t len,     
+                              bool overwrite, vector<boost::shared_ptr<AudioSource> >& srcs, InterThreadInfo& itt)
 {
        int ret = -1;
        Playlist* playlist;
-       AudioFileSource* fsource;
+       boost::shared_ptr<AudioFileSource> fsource;
        uint32_t x;
        char buf[PATH_MAX+1];
        string dir;
        uint32_t nchans;
-       jack_nframes_t position;
-       jack_nframes_t this_chunk;
-       jack_nframes_t to_do;
+       nframes_t position;
+       nframes_t this_chunk;
+       nframes_t to_do;
        vector<Sample*> 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);
        
@@ -3702,11 +3557,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 (*this, buf, false, frame_rate()));
                }
                
                catch (failed_constructor& err) {
@@ -3714,7 +3565,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 */
@@ -3743,9 +3594,9 @@ Session::write_one_audio_track (AudioTrack& track, jack_nframes_t start, jack_nf
                }
 
                uint32_t n = 0;
-               for (vector<AudioSource*>::iterator src=srcs.begin(); src != srcs.end(); ++src, ++n) {
-                       AudioFileSource* afs = dynamic_cast<AudioFileSource*>(*src);
-
+               for (vector<boost::shared_ptr<AudioSource> >::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[n], this_chunk) != this_chunk) {
                                        goto out;
@@ -3767,8 +3618,9 @@ Session::write_one_audio_track (AudioTrack& track, jack_nframes_t start, jack_nf
                time (&now);
                xnow = localtime (&now);
                
-               for (vector<AudioSource*>::iterator src=srcs.begin(); src != srcs.end(); ++src) {
-                       AudioFileSource* afs = dynamic_cast<AudioFileSource*>(*src);
+               for (vector<boost::shared_ptr<AudioSource> >::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);
                        }
@@ -3776,8 +3628,8 @@ Session::write_one_audio_track (AudioTrack& track, jack_nframes_t start, jack_nf
                
                /* build peakfile for new source */
                
-               for (vector<AudioSource*>::iterator src=srcs.begin(); src != srcs.end(); ++src) {
-                       AudioFileSource* afs = dynamic_cast<AudioFileSource*>(*src);
+               for (vector<boost::shared_ptr<AudioSource> >::iterator src=srcs.begin(); src != srcs.end(); ++src) {
+                       boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
                        if (afs) {
                                afs->build_peaks ();
                        }
@@ -3788,12 +3640,14 @@ Session::write_one_audio_track (AudioTrack& track, jack_nframes_t start, jack_nf
                
   out:
        if (ret) {
-               for (vector<AudioSource*>::iterator src=srcs.begin(); src != srcs.end(); ++src) {
-                       AudioFileSource* afs = dynamic_cast<AudioFileSource*>(*src);
+               for (vector<boost::shared_ptr<AudioSource> >::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 ();
                }
        }
 
@@ -3847,26 +3701,6 @@ Session::nbusses () const
        return n;
 }
 
-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)
-{
-       if (xm != xfade_model) {
-               xfade_model = xm;
-               set_dirty ();
-               ControlChanged (CrossfadingModel);
-       }
-}
-
 void
 Session::add_curve(Curve *curve)
 {