id_t becomes a fully-fledged object, UUID's used for IDs, generic MIDI now owns bindi...
[ardour.git] / libs / ardour / session.cc
index 726d3070bb9b67833d265ad5c50bd029c7e1ee07..3f400b0b2b3edad3a9f49ffd12e8ab4d877fe754 100644 (file)
 #include <sigc++/bind.h>
 #include <sigc++/retype.h>
 
+#include <glibmm/thread.h>
+#include <glibmm/miscutils.h>
+
 #include <pbd/error.h>
-#include <pbd/lockmonitor.h>
+#include <glibmm/thread.h>
 #include <pbd/pathscanner.h>
 #include <pbd/stl_delete.h>
 #include <pbd/basename.h>
-#include <pbd/dirname.h>
 
 #include <ardour/audioengine.h>
 #include <ardour/configuration.h>
 #include <ardour/session.h>
-#include <ardour/diskstream.h>
+#include <ardour/audio_diskstream.h>
 #include <ardour/utils.h>
 #include <ardour/audioplaylist.h>
 #include <ardour/audioregion.h>
-#include <ardour/source.h>
-#include <ardour/filesource.h>
-#include <ardour/sndfilesource.h>
+#include <ardour/audiofilesource.h>
+#include <ardour/destructive_filesource.h>
 #include <ardour/auditioner.h>
 #include <ardour/recent_sessions.h>
 #include <ardour/redirect.h>
 #include <ardour/crossfade.h>
 #include <ardour/playlist.h>
 #include <ardour/click.h>
-#include <ardour/timestamps.h>
+
+#ifdef HAVE_LIBLO
+#include <ardour/osc.h>
+#endif
 
 #include "i18n.h"
 
 using namespace std;
 using namespace ARDOUR;
-//using namespace sigc;
+using namespace PBD;
 
 const char* Session::_template_suffix = X_(".template");
 const char* Session::_statefile_suffix = X_(".ardour");
 const char* Session::_pending_suffix = X_(".pending");
 const char* Session::sound_dir_name = X_("sounds");
+const char* Session::tape_dir_name = X_("tapes");
 const char* Session::peak_dir_name = X_("peaks");
 const char* Session::dead_sound_dir_name = X_("dead_sounds");
 
@@ -84,6 +89,9 @@ Session::mix_buffers_with_gain_t      Session::mix_buffers_with_gain  = 0;
 Session::mix_buffers_no_gain_t         Session::mix_buffers_no_gain    = 0;
 
 sigc::signal<int> Session::AskAboutPendingState;
+sigc::signal<void> Session::SMPTEOffsetChanged;
+sigc::signal<void> Session::SendFeedback;
+
 
 int
 Session::find_session (string str, string& path, string& snapshot, bool& isnew)
@@ -359,7 +367,6 @@ Session::~Session ()
        
        terminate_butler_thread ();
        terminate_midi_thread ();
-       terminate_feedback ();
        
        if (click_data && click_data != default_click) {
                delete [] click_data;
@@ -388,6 +395,14 @@ Session::~Session ()
                free(*i);
        }
 
+       for (vector<Sample*>::iterator i = _send_buffers.begin(); i != _send_buffers.end(); ++i) {
+               free(*i);
+       }
+
+       for (map<RunContext,char*>::iterator i = _conversion_buffers.begin(); i != _conversion_buffers.end(); ++i) {
+               delete [] (i->second);
+       }
+       
 #undef TRACK_DESTRUCTION
 #ifdef TRACK_DESTRUCTION
        cerr << "delete named selections\n";
@@ -425,7 +440,7 @@ Session::~Session ()
                tmp =i;
                ++tmp;
 
-               delete (*i).second;
+               delete i->second;
 
                i = tmp;
        }
@@ -442,10 +457,10 @@ Session::~Session ()
        }
 
 #ifdef TRACK_DESTRUCTION
-       cerr << "delete diskstreams\n";
+       cerr << "delete audio_diskstreams\n";
 #endif /* TRACK_DESTRUCTION */
-       for (DiskStreamList::iterator i = diskstreams.begin(); i != diskstreams.end(); ) {
-               DiskStreamList::iterator tmp;
+       for (AudioDiskstreamList::iterator i = audio_diskstreams.begin(); i != audio_diskstreams.end(); ) {
+               AudioDiskstreamList::iterator tmp;
 
                tmp = i;
                ++tmp;
@@ -456,15 +471,15 @@ Session::~Session ()
        }
 
 #ifdef TRACK_DESTRUCTION
-       cerr << "delete sources\n";
+       cerr << "delete audio sources\n";
 #endif /* TRACK_DESTRUCTION */
-       for (SourceList::iterator i = sources.begin(); i != sources.end(); ) {
-               SourceList::iterator tmp;
+       for (AudioSourceList::iterator i = audio_sources.begin(); i != audio_sources.end(); ) {
+               AudioSourceList::iterator tmp;
 
                tmp = i;
                ++tmp;
 
-               delete (*i).second;
+               delete i->second;
 
                i = tmp;
        }
@@ -541,7 +556,7 @@ Session::set_worst_io_latencies (bool take_lock)
        }
 
        if (take_lock) {
-               route_lock.read_lock ();
+               route_lock.reader_lock ();
        }
        
        for (RouteList::iterator i = routes.begin(); i != routes.end(); ++i) {
@@ -550,7 +565,7 @@ Session::set_worst_io_latencies (bool take_lock)
        }
 
        if (take_lock) {
-               route_lock.unlock ();
+               route_lock.reader_unlock ();
        }
 }
 
@@ -757,7 +772,7 @@ Session::when_engine_running ()
 
        insert_cnt = 0;
        
-       for (slist<PortInsert*>::iterator i = _port_inserts.begin(); i != _port_inserts.end(); ++i) {
+       for (list<PortInsert*>::iterator i = _port_inserts.begin(); i != _port_inserts.end(); ++i) {
                uint32_t id;
 
                if (sscanf ((*i)->name().c_str(), "%*s %u", &id) == 1) {
@@ -769,7 +784,7 @@ Session::when_engine_running ()
 
        send_cnt = 0;
 
-       for (slist<Send*>::iterator i = _sends.begin(); i != _sends.end(); ++i) {
+       for (list<Send*>::iterator i = _sends.begin(); i != _sends.end(); ++i) {
                uint32_t id;
                
                if (sscanf ((*i)->name().c_str(), "%*s %u", &id) == 1) {
@@ -785,6 +800,12 @@ Session::when_engine_running ()
 
        _engine.set_session (this);
 
+#ifdef HAVE_LIBLO
+       /* and to OSC */
+
+       osc->set_session (*this);
+#endif
+    
        _state_of_the_state = Clean;
 
        DirtyChanged (); /* EMIT SIGNAL */
@@ -862,7 +883,7 @@ Session::playlist_length_changed (Playlist* pl)
 }
 
 void
-Session::diskstream_playlist_changed (DiskStream* dstream)
+Session::diskstream_playlist_changed (AudioDiskstream* dstream)
 {
        Playlist *playlist;
 
@@ -919,10 +940,10 @@ Session::set_crossfades_active (bool yn)
 }
 
 void
-Session::set_recording_plugins (bool yn)
+Session::set_do_not_record_plugins (bool yn)
 {
-       if (recording_plugins != yn) {
-               recording_plugins = yn; 
+       if (do_not_record_plugins != yn) {
+               do_not_record_plugins = yn; 
                set_dirty ();
                ControlChanged (RecordingPlugins); 
        }
@@ -941,8 +962,8 @@ Session::set_auto_input (bool yn)
                           a non-tentative rwlock here,  because the action must occur.
                           The rarity and short potential lock duration makes this "OK"
                        */
-                       RWLockMonitor dsm (diskstream_lock, false, __LINE__, __FILE__);
-                       for (DiskStreamList::iterator i = diskstreams.begin(); i != diskstreams.end(); ++i) {
+                       Glib::RWLock::ReaderLock dsm (diskstream_lock);
+                       for (AudioDiskstreamList::iterator i = audio_diskstreams.begin(); i != audio_diskstreams.end(); ++i) {
                                if ((*i)->record_enabled ()) {
                                        //cerr << "switching to input = " << !auto_input << __FILE__ << __LINE__ << endl << endl;
                                        (*i)->monitor_input (!auto_input);   
@@ -959,16 +980,16 @@ void
 Session::reset_input_monitor_state ()
 {
        if (transport_rolling()) {
-               RWLockMonitor dsm (diskstream_lock, false, __LINE__, __FILE__);
-               for (DiskStreamList::iterator i = diskstreams.begin(); i != diskstreams.end(); ++i) {
+               Glib::RWLock::ReaderLock dsm (diskstream_lock);
+               for (AudioDiskstreamList::iterator i = audio_diskstreams.begin(); i != audio_diskstreams.end(); ++i) {
                        if ((*i)->record_enabled ()) {
                                //cerr << "switching to input = " << !auto_input << __FILE__ << __LINE__ << endl << endl;
                                (*i)->monitor_input (Config->get_use_hardware_monitoring() && !auto_input);
                        }
                }
        } else {
-               RWLockMonitor dsm (diskstream_lock, false, __LINE__, __FILE__);
-               for (DiskStreamList::iterator i = diskstreams.begin(); i != diskstreams.end(); ++i) {
+               Glib::RWLock::ReaderLock dsm (diskstream_lock);
+               for (AudioDiskstreamList::iterator i = audio_diskstreams.begin(); i != audio_diskstreams.end(); ++i) {
                        if ((*i)->record_enabled ()) {
                                //cerr << "switching to input = " << !auto_input << __FILE__ << __LINE__ << endl << endl;
                                (*i)->monitor_input (Config->get_use_hardware_monitoring());
@@ -1049,7 +1070,7 @@ Session::auto_loop_changed (Location* location)
                }
                else if (seamless_loop && !loop_changing) {
                        
-                       // schedule a locate-roll to refill the diskstreams at the
+                       // schedule a locate-roll to refill the audio_diskstreams at the
                        // previous loop end
                        loop_changing = true;
 
@@ -1234,8 +1255,8 @@ void
 Session::enable_record ()
 {
        /* XXX really atomic compare+swap here */
-       if (atomic_read (&_record_status) != Recording) {
-               atomic_set (&_record_status, Recording);
+       if (g_atomic_int_get (&_record_status) != Recording) {
+               g_atomic_int_set (&_record_status, Recording);
                _last_record_location = _transport_frame;
                send_mmc_in_another_thread (MIDI::MachineControl::cmdRecordStrobe);
 
@@ -1244,25 +1265,34 @@ Session::enable_record ()
                           a non-tentative rwlock here,  because the action must occur.
                           The rarity and short potential lock duration makes this "OK"
                        */
-                       RWLockMonitor dsm (diskstream_lock, false, __LINE__, __FILE__);
+                       Glib::RWLock::ReaderLock dsm (diskstream_lock);
                        
-                       for (DiskStreamList::iterator i = diskstreams.begin(); i != diskstreams.end(); ++i) {
+                       for (AudioDiskstreamList::iterator i = audio_diskstreams.begin(); i != audio_diskstreams.end(); ++i) {
                                if ((*i)->record_enabled ()) {
-                                       //cerr << "switching to input" << __FILE__ << __LINE__ << endl << endl;
                                        (*i)->monitor_input (true);   
                                }
                        }
                }
 
-               RecordEnabled ();
+               RecordStateChanged ();
        }
 }
 
 void
-Session::disable_record ()
+Session::disable_record (bool rt_context, bool force)
 {
-       if (atomic_read (&_record_status) != Disabled) {
-               atomic_set (&_record_status, Disabled);
+       RecordState rs;
+
+       if ((rs = (RecordState) g_atomic_int_get (&_record_status)) != Disabled) {
+
+               if (!Config->get_latched_record_enable () || force) {
+                       g_atomic_int_set (&_record_status, Disabled);
+               } else {
+                       if (rs == Recording) {
+                               g_atomic_int_set (&_record_status, Enabled);
+                       }
+               }
+
                send_mmc_in_another_thread (MIDI::MachineControl::cmdRecordExit);
 
                if (Config->get_use_hardware_monitoring() && auto_input) {
@@ -1270,35 +1300,36 @@ Session::disable_record ()
                           a non-tentative rwlock here,  because the action must occur.
                           The rarity and short potential lock duration makes this "OK"
                        */
-                       RWLockMonitor dsm (diskstream_lock, false, __LINE__, __FILE__);
+                       Glib::RWLock::ReaderLock dsm (diskstream_lock);
                        
-                       for (DiskStreamList::iterator i = diskstreams.begin(); i != diskstreams.end(); ++i) {
+                       for (AudioDiskstreamList::iterator i = audio_diskstreams.begin(); i != audio_diskstreams.end(); ++i) {
                                if ((*i)->record_enabled ()) {
-                                       //cerr << "switching from input" << __FILE__ << __LINE__ << endl << endl;
                                        (*i)->monitor_input (false);   
                                }
                        }
                }
                
-               RecordDisabled ();
-               remove_pending_capture_state ();
+               RecordStateChanged (); /* emit signal */
 
+               if (!rt_context) {
+                       remove_pending_capture_state ();
+               }
        }
 }
 
 void
 Session::step_back_from_record ()
 {
-       atomic_set (&_record_status, Enabled);
+       g_atomic_int_set (&_record_status, Enabled);
 
        if (Config->get_use_hardware_monitoring()) {
                /* Even though this can be called from RT context we are using
                   a non-tentative rwlock here,  because the action must occur.
                   The rarity and short potential lock duration makes this "OK"
                */
-               RWLockMonitor dsm (diskstream_lock, false, __LINE__, __FILE__);
+               Glib::RWLock::ReaderLock dsm (diskstream_lock);
                
-               for (DiskStreamList::iterator i = diskstreams.begin(); i != diskstreams.end(); ++i) {
+               for (AudioDiskstreamList::iterator i = audio_diskstreams.begin(); i != audio_diskstreams.end(); ++i) {
                        if (auto_input && (*i)->record_enabled ()) {
                                //cerr << "switching from input" << __FILE__ << __LINE__ << endl << endl;
                                (*i)->monitor_input (false);   
@@ -1310,7 +1341,11 @@ Session::step_back_from_record ()
 void
 Session::maybe_enable_record ()
 {
-       atomic_set (&_record_status, Enabled);
+       g_atomic_int_set (&_record_status, Enabled);
+
+       /* XXX this save should really happen in another thread. its needed so that
+          pending capture state can be recovered if we crash.
+       */
 
        save_state ("", true);
 
@@ -1320,7 +1355,7 @@ Session::maybe_enable_record ()
                } 
        } else {
                send_mmc_in_another_thread (MIDI::MachineControl::cmdRecordPause);
-               RecordEnabled (); /* EMIT SIGNAL */
+               RecordStateChanged (); /* EMIT SIGNAL */
        }
 
        set_dirty();
@@ -1399,6 +1434,9 @@ Session::set_frame_rate (jack_nframes_t frames_per_second)
 
        Route::set_automation_interval ((jack_nframes_t) ceil ((double) frames_per_second * 0.25));
 
+       // XXX we need some equivalent to this, somehow
+       // DestructiveFileSource::setup_standard_crossfades (frames_per_second);
+
        set_dirty();
 
        /* XXX need to reset/reinstantiate all LADSPA plugins */
@@ -1414,8 +1452,8 @@ Session::set_block_size (jack_nframes_t nframes)
        */
 
        { 
-               RWLockMonitor lm (route_lock, false, __LINE__, __FILE__);
-               RWLockMonitor dsm (diskstream_lock, false, __LINE__, __FILE__);
+               Glib::RWLock::ReaderLock lm (route_lock);
+               Glib::RWLock::ReaderLock dsm (diskstream_lock);
                vector<Sample*>::iterator i;
                uint32_t np;
                        
@@ -1434,6 +1472,21 @@ Session::set_block_size (jack_nframes_t nframes)
 
                ensure_passthru_buffers (np);
 
+               for (vector<Sample*>::iterator i = _send_buffers.begin(); i != _send_buffers.end(); ++i) {
+                       free(*i);
+
+                       Sample *buf;
+#ifdef NO_POSIX_MEMALIGN
+                       buf = (Sample *) malloc(current_block_size * sizeof(Sample));
+#else
+                       posix_memalign((void **)&buf,16,current_block_size * 4);
+#endif                 
+                       *i = buf;
+
+                       memset (*i, 0, sizeof (Sample) * current_block_size);
+               }
+
+               
                if (_gain_automation_buffer) {
                        delete [] _gain_automation_buffer;
                }
@@ -1445,7 +1498,7 @@ Session::set_block_size (jack_nframes_t nframes)
                        (*i)->set_block_size (nframes);
                }
                
-               for (DiskStreamList::iterator i = diskstreams.begin(); i != diskstreams.end(); ++i) {
+               for (AudioDiskstreamList::iterator i = audio_diskstreams.begin(); i != audio_diskstreams.end(); ++i) {
                        (*i)->set_block_size (nframes);
                }
 
@@ -1477,7 +1530,7 @@ Session::set_default_fade (float steepness, float fade_msecs)
 
        {
                // jlc, WTF is this!
-               RWLockMonitor lm (route_lock, false, __LINE__, __FILE__);
+               Glib::RWLock::ReaderLock lm (route_lock);
                AudioRegion::set_default_fade (steepness, fade_frames);
        }
 
@@ -1615,7 +1668,7 @@ Session::resort_routes (void* src)
 }
 
 AudioTrack*
-Session::new_audio_track (int input_channels, int output_channels)
+Session::new_audio_track (int input_channels, int output_channels, TrackMode mode)
 {
        AudioTrack *track;
        char track_name[32];
@@ -1628,7 +1681,7 @@ Session::new_audio_track (int input_channels, int output_channels)
        /* count existing audio tracks */
 
        {
-               RWLockMonitor lm (route_lock, false, __LINE__, __FILE__);
+               Glib::RWLock::ReaderLock lm (route_lock);
                for (RouteList::iterator i = routes.begin(); i != routes.end(); ++i) {
                        if (dynamic_cast<AudioTrack*>(*i) != 0) {
                                if (!(*i)->hidden()) {
@@ -1667,7 +1720,7 @@ Session::new_audio_track (int input_channels, int output_channels)
        }
 
        try {
-               track = new AudioTrack (*this, track_name);
+               track = new AudioTrack (*this, track_name, Route::Flag (0), mode);
 
                if (track->ensure_io (input_channels, output_channels, false, this)) {
                        error << string_compose (_("cannot configure %1 in/%2 out configuration for new audio track"),
@@ -1744,7 +1797,7 @@ Session::new_audio_route (int input_channels, int output_channels)
        /* count existing audio busses */
 
        {
-               RWLockMonitor lm (route_lock, false, __LINE__, __FILE__);
+               Glib::RWLock::ReaderLock lm (route_lock);
                for (RouteList::iterator i = routes.begin(); i != routes.end(); ++i) {
                        if (dynamic_cast<AudioTrack*>(*i) == 0) {
                                if (!(*i)->hidden()) {
@@ -1827,7 +1880,7 @@ void
 Session::add_route (Route* route)
 {
        { 
-               RWLockMonitor lm (route_lock, true, __LINE__, __FILE__);
+               Glib::RWLock::WriterLock lm (route_lock);
                routes.push_front (route);
                resort_routes(0);
        }
@@ -1852,14 +1905,14 @@ Session::add_route (Route* route)
 }
 
 void
-Session::add_diskstream (DiskStream* dstream)
+Session::add_diskstream (AudioDiskstream* dstream)
 {
        /* need to do this in case we're rolling at the time, to prevent false underruns */
-       dstream->do_refill(0, 0);
+       dstream->do_refill(0, 0, 0);
        
        { 
-               RWLockMonitor lm (diskstream_lock, true, __LINE__, __FILE__);
-               diskstreams.push_back (dstream);
+               Glib::RWLock::WriterLock lm (diskstream_lock);
+               audio_diskstreams.push_back (dstream);
        }
 
        /* take a reference to the diskstream, preventing it from
@@ -1879,14 +1932,14 @@ Session::add_diskstream (DiskStream* dstream)
        set_dirty();
        save_state (_current_snapshot_name);
 
-       DiskStreamAdded (dstream); /* EMIT SIGNAL */
+       AudioDiskstreamAdded (dstream); /* EMIT SIGNAL */
 }
 
 void
 Session::remove_route (Route& route)
 {
        {       
-               RWLockMonitor lm (route_lock, true, __LINE__, __FILE__);
+               Glib::RWLock::WriterLock lm (route_lock);
                routes.remove (&route);
                
                /* deleting the master out seems like a dumb
@@ -1913,18 +1966,24 @@ Session::remove_route (Route& route)
                update_route_solo_state ();
        }
 
-       {
-               RWLockMonitor lm (diskstream_lock, true, __LINE__, __FILE__);
-
-               AudioTrack* at;
+       AudioTrack* at;
+       AudioDiskstream* ds = 0;
+       
+       if ((at = dynamic_cast<AudioTrack*>(&route)) != 0) {
+               ds = &at->disk_stream();
+       }
+       
+       if (ds) {
 
-               if ((at = dynamic_cast<AudioTrack*>(&route)) != 0) {
-                       diskstreams.remove (&at->disk_stream());
-                       at->disk_stream().unref ();
+               {
+                       Glib::RWLock::WriterLock lm (diskstream_lock);
+                       audio_diskstreams.remove (ds);
                }
 
-               find_current_end ();
+               ds->unref ();
        }
+
+       find_current_end ();
        
        update_latency_compensation (false, false);
        set_dirty();
@@ -1950,7 +2009,7 @@ Session::route_solo_changed (void* src, Route* route)
                return;
        }
        
-       RWLockMonitor lm (route_lock, false, __LINE__, __FILE__);
+       Glib::RWLock::ReaderLock lm (route_lock);
        bool is_track;
        
        is_track = (dynamic_cast<AudioTrack*>(route) != 0);
@@ -2149,14 +2208,14 @@ Session::catch_up_on_solo ()
           basis, but needs the global overview that only the session
           has.
        */
-        RWLockMonitor lm (route_lock, false, __LINE__, __FILE__);
+        Glib::RWLock::ReaderLock lm (route_lock);
        update_route_solo_state();
 }      
                
 Route *
 Session::route_by_name (string name)
 {
-       RWLockMonitor lm (route_lock, false, __LINE__, __FILE__);
+       Glib::RWLock::ReaderLock lm (route_lock);
 
        for (RouteList::iterator i = routes.begin(); i != routes.end(); ++i) {
                if ((*i)->name() == name) {
@@ -2167,40 +2226,62 @@ Session::route_by_name (string name)
        return 0;
 }
 
+Route *
+Session::route_by_remote_id (uint32_t id)
+{
+       Glib::RWLock::ReaderLock lm (route_lock);
+
+       for (RouteList::iterator i = routes.begin(); i != routes.end(); ++i) {
+               if ((*i)->remote_control_id() == id) {
+                       return* i;
+               }
+       }
+
+       return 0;
+}
+
 void
 Session::find_current_end ()
 {
-       jack_nframes_t max = 0;
-       jack_nframes_t me; 
-
        if (_state_of_the_state & Loading) {
                return;
        }
 
+       jack_nframes_t max = get_maximum_extent ();
+
+       if (max > end_location->end()) {
+               end_location->set_end (max);
+               set_dirty();
+               DurationChanged(); /* EMIT SIGNAL */
+       }
+}
+
+jack_nframes_t
+Session::get_maximum_extent () const
+{
+       jack_nframes_t max = 0;
+       jack_nframes_t me; 
+
        /* Don't take the diskstream lock. Caller must have other ways to
           ensure atomicity.
        */
 
-       for (DiskStreamList::iterator i = diskstreams.begin(); i != diskstreams.end(); ++i) {
+       for (AudioDiskstreamList::const_iterator i = audio_diskstreams.begin(); i != audio_diskstreams.end(); ++i) {
                Playlist* pl = (*i)->playlist();
                if ((me = pl->get_maximum_extent()) > max) {
                        max = me;
                }
        }
-       
-       if (max > end_location->end()) {
-               end_location->set_end (max);
-               set_dirty();
-               DurationChanged(); /* EMIT SIGNAL */
-       }
+
+       return max;
 }
 
-DiskStream *
+AudioDiskstream *
 Session::diskstream_by_name (string name)
 {
-       RWLockMonitor lm (diskstream_lock, false, __LINE__, __FILE__);
+       Glib::RWLock::ReaderLock lm (diskstream_lock);
 
-       for (DiskStreamList::iterator i = diskstreams.begin(); i != diskstreams.end(); ++i) {
+       for (AudioDiskstreamList::iterator i = audio_diskstreams.begin(); i != audio_diskstreams.end(); ++i) {
                if ((*i)->name() == name) {
                        return* i;
                }
@@ -2209,12 +2290,12 @@ Session::diskstream_by_name (string name)
        return 0;
 }
 
-DiskStream *
-Session::diskstream_by_id (id_t id)
+AudioDiskstream *
+Session::diskstream_by_id (const PBD::ID& id)
 {
-       RWLockMonitor lm (diskstream_lock, false, __LINE__, __FILE__);
+       Glib::RWLock::ReaderLock lm (diskstream_lock);
 
-       for (DiskStreamList::iterator i = diskstreams.begin(); i != diskstreams.end(); ++i) {
+       for (AudioDiskstreamList::iterator i = audio_diskstreams.begin(); i != audio_diskstreams.end(); ++i) {
                if ((*i)->id() == id) {
                        return *i;
                }
@@ -2258,7 +2339,7 @@ Session::new_region_name (string old)
                sbuf = buf;
 
                for (i = audio_regions.begin(); i != audio_regions.end(); ++i) {
-                       if ((*i).second->name() == sbuf) {
+                       if (i->second->name() == sbuf) {
                                break;
                        }
                }
@@ -2284,7 +2365,7 @@ Session::region_name (string& result, string base, bool newlevel) const
 
        if (base == "") {
                
-               LockMonitor lm (region_lock, __LINE__, __FILE__);
+               Glib::Mutex::Lock lm (region_lock);
 
                snprintf (buf, sizeof (buf), "%d", (int)audio_regions.size() + 1);
 
@@ -2301,19 +2382,18 @@ Session::region_name (string& result, string base, bool newlevel) const
                } else {
                        string::size_type pos;
 
-                       if ((pos = base.find_last_of ('-')) == string::npos) {
-                               pos = base.find_last_of ('.');
-                       }
+                       pos = base.find_last_of ('.');
 
                        /* pos may be npos, but then we just use entire base */
 
                        subbase = base.substr (0, pos);
+
                }
-               
+
                bool name_taken = true;
                
                {
-                       LockMonitor lm (region_lock, __LINE__, __FILE__);
+                       Glib::Mutex::Lock lm (region_lock);
                        
                        for (int n = 1; n < 5000; ++n) {
                                
@@ -2324,7 +2404,7 @@ Session::region_name (string& result, string base, bool newlevel) const
                                name_taken = false;
                                
                                for (AudioRegionList::const_iterator i = audio_regions.begin(); i != audio_regions.end(); ++i) {
-                                       if ((*i).second->name() == result) {
+                                       if (i->second->name() == result) {
                                                name_taken = true;
                                                break;
                                        }
@@ -2341,7 +2421,6 @@ Session::region_name (string& result, string base, bool newlevel) const
                        /*NOTREACHED*/
                }
        }
-
        return 0;
 }      
 
@@ -2353,7 +2432,7 @@ Session::add_region (Region* region)
        bool added = false;
 
        { 
-               LockMonitor lm (region_lock, __LINE__, __FILE__);
+               Glib::Mutex::Lock lm (region_lock);
 
                if ((ar = dynamic_cast<AudioRegion*> (region)) != 0) {
 
@@ -2370,8 +2449,8 @@ Session::add_region (Region* region)
 
                        if (x == audio_regions.end()) {
 
-                               pair<AudioRegionList::key_type, AudioRegionList::mapped_type> entry;
-       
+                               pair<AudioRegionList::key_type,AudioRegionList::mapped_type> entry;
+
                                entry.first = region->id();
                                entry.second = ar;
 
@@ -2428,16 +2507,18 @@ Session::remove_region (Region* region)
        AudioRegionList::iterator i;
        AudioRegion* ar = 0;
        bool removed = false;
-
+       
        { 
-               LockMonitor lm (region_lock, __LINE__, __FILE__);
+               Glib::Mutex::Lock lm (region_lock);
 
-               if ((ar = dynamic_cast<AudioRegion*> (region)) != 0) {
+               if ((ar = dynamic_cast<AudioRegion*> (region)) != 0) {
                        if ((i = audio_regions.find (region->id())) != audio_regions.end()) {
                                audio_regions.erase (i);
                                removed = true;
-                       } 
+                       }
+
                } else {
+
                        fatal << _("programming error: ") 
                              << X_("unknown region type passed to Session::remove_region()")
                              << endmsg;
@@ -2461,11 +2542,11 @@ Session::find_whole_file_parent (AudioRegion& child)
 {
        AudioRegionList::iterator i;
        AudioRegion* region;
-       LockMonitor lm (region_lock, __LINE__, __FILE__);
+       Glib::Mutex::Lock lm (region_lock);
 
        for (i = audio_regions.begin(); i != audio_regions.end(); ++i) {
 
-               region = (*i).second;
+               region = i->second;
 
                if (region->whole_file()) {
 
@@ -2515,7 +2596,10 @@ Session::destroy_region (Region* region)
        for (vector<Source*>::iterator i = srcs.begin(); i != srcs.end(); ++i) {
                
                if ((*i)->use_cnt() == 0) {
-                       (*i)->mark_for_remove ();
+                       AudioFileSource* afs = dynamic_cast<AudioFileSource*>(*i);
+                       if (afs) {
+                               (afs)->mark_for_remove ();
+                       }
                        delete *i;
                }
        }
@@ -2537,9 +2621,9 @@ Session::remove_last_capture ()
 {
        list<Region*> r;
 
-       RWLockMonitor lm (diskstream_lock, false, __LINE__, __FILE__);
+       Glib::RWLock::ReaderLock lm (diskstream_lock);
        
-       for (DiskStreamList::iterator i = diskstreams.begin(); i != diskstreams.end(); ++i) {
+       for (AudioDiskstreamList::iterator i = audio_diskstreams.begin(); i != audio_diskstreams.end(); ++i) {
                list<Region*>& l = (*i)->last_capture_regions();
                
                if (!l.empty()) {
@@ -2562,16 +2646,16 @@ Session::remove_region_from_region_list (Region& r)
 /* Source Management */
 
 void
-Session::add_source (Source* source)
+Session::add_audio_source (AudioSource* source)
 {
-       pair<SourceList::key_type, SourceList::mapped_type> entry;
-       
-       {
-               LockMonitor lm (source_lock, __LINE__, __FILE__);
+       pair<AudioSourceList::key_type, AudioSourceList::mapped_type> entry;
+
+       {
+               Glib::Mutex::Lock lm (audio_source_lock);
                entry.first = source->id();
                entry.second = source;
-               sources.insert (entry);
-       }
+               audio_sources.insert (entry);
+       }
        
        source->GoingAway.connect (mem_fun (this, &Session::remove_source));
        set_dirty();
@@ -2582,14 +2666,14 @@ Session::add_source (Source* source)
 void
 Session::remove_source (Source* source)
 {
-       SourceList::iterator i;
+       AudioSourceList::iterator i;
 
        { 
-               LockMonitor lm (source_lock, __LINE__, __FILE__);
+               Glib::Mutex::Lock lm (audio_source_lock);
 
-               if ((i = sources.find (source->id())) != sources.end()) {
-                       sources.erase (i);
-               }
+               if ((i = audio_sources.find (source->id())) != audio_sources.end()) {
+                       audio_sources.erase (i);
+               } 
        }
 
        if (!_state_of_the_state & InCleanup) {
@@ -2605,21 +2689,124 @@ Session::remove_source (Source* source)
 }
 
 Source *
-Session::get_source (ARDOUR::id_t id)
+Session::source_by_id (const PBD::ID& id)
 {
-       LockMonitor lm (source_lock, __LINE__, __FILE__);
-       SourceList::iterator i;
+       Glib::Mutex::Lock lm (audio_source_lock);
+       AudioSourceList::iterator i;
        Source* source = 0;
 
-       if ((i = sources.find (id)) != sources.end()) {
-               source = (*i).second;
+       if ((i = audio_sources.find (id)) != audio_sources.end()) {
+               source = i->second;
        }
 
+       /* XXX search MIDI or other searches here */
+       
        return source;
 }
 
-FileSource *
-Session::create_file_source (DiskStream& ds, int32_t chan)
+string
+Session::peak_path_from_audio_path (string audio_path)
+{
+       /* XXX hardly bombproof! fix me */
+
+       string res;
+
+       res = Glib::path_get_dirname (audio_path);
+       res = Glib::path_get_dirname (res);
+       res += '/';
+       res += peak_dir_name;
+       res += '/';
+       res += PBD::basename_nosuffix (audio_path);
+       res += ".peak";
+
+       return res;
+}
+
+string
+Session::change_audio_path_by_name (string path, string oldname, string newname, bool destructive)
+{
+       string look_for;
+       string old_basename = PBD::basename_nosuffix (oldname);
+       string new_legalized = legalize_for_path (newname);
+
+       /* note: we know (or assume) the old path is already valid */
+
+       if (destructive) {
+               
+               /* destructive file sources have a name of the form:
+
+                   /path/to/Tnnnn-NAME(%[LR])?.wav
+                 
+                   the task here is to replace NAME with the new name.
+               */
+               
+               /* find last slash */
+
+               string dir;
+               string prefix;
+               string::size_type slash;
+               string::size_type dash;
+
+               if ((slash = path.find_last_of ('/')) == string::npos) {
+                       return "";
+               }
+
+               dir = path.substr (0, slash+1);
+
+               /* '-' is not a legal character for the NAME part of the path */
+
+               if ((dash = path.find_last_of ('-')) == string::npos) {
+                       return "";
+               }
+
+               prefix = path.substr (slash+1, dash-(slash+1));
+
+               path = dir;
+               path += prefix;
+               path += '-';
+               path += new_legalized;
+               path += ".wav";  /* XXX gag me with a spoon */
+               
+       } else {
+               
+               /* non-destructive file sources have a name of the form:
+
+                   /path/to/NAME-nnnnn(%[LR])?.wav
+                 
+                   the task here is to replace NAME with the new name.
+               */
+               
+               /* find last slash */
+
+               string dir;
+               string suffix;
+               string::size_type slash;
+               string::size_type dash;
+
+               if ((slash = path.find_last_of ('/')) == string::npos) {
+                       return "";
+               }
+
+               dir = path.substr (0, slash+1);
+
+               /* '-' is not a legal character for the NAME part of the path */
+
+               if ((dash = path.find_last_of ('-')) == string::npos) {
+                       return "";
+               }
+
+               suffix = path.substr (dash);
+
+               path = dir;
+               path += new_legalized;
+               path += suffix;
+       }
+
+       return path;
+}
+
+string
+Session::audio_path_from_name (string name, uint32_t nchan, uint32_t chan, bool destructive)
 {
        string spath;
        uint32_t cnt;
@@ -2628,51 +2815,74 @@ Session::create_file_source (DiskStream& ds, int32_t chan)
        string legalized;
 
        buf[0] = '\0';
-       legalized = legalize_for_path (ds.name());
+       legalized = legalize_for_path (name);
 
        /* find a "version" of the file name that doesn't exist in
           any of the possible directories.
        */
-       
-       for (cnt = 1; cnt <= limit; ++cnt) {
 
+       for (cnt = (destructive ? ++destructive_index : 1); cnt <= limit; ++cnt) {
+               
                vector<space_and_path>::iterator i;
                uint32_t existing = 0;
-
+               
                for (i = session_dirs.begin(); i != session_dirs.end(); ++i) {
-
+                       
                        spath = (*i).path;
-                       spath += sound_dir_name;
-                       spath += '/';
-                       spath += legalized;
-
-                       if (ds.n_channels() < 2) {
-                               snprintf (buf, sizeof(buf), "%s-%u.wav", spath.c_str(), cnt);
-                       } else if (ds.n_channels() == 2) {
-                               if (chan == 0) {
-                                       snprintf (buf, sizeof(buf), "%s-%u%%L.wav", spath.c_str(), cnt);
+                       
+                       if (destructive) {
+                               spath += tape_dir_name;
+                       } else {
+                               spath += sound_dir_name;
+                       }
+                       
+                       if (destructive) {
+                               if (nchan < 2) {
+                                       snprintf (buf, sizeof(buf), "%s/T%04d-%s.wav", spath.c_str(), cnt, legalized.c_str());
+                               } else if (nchan == 2) {
+                                       if (chan == 0) {
+                                               snprintf (buf, sizeof(buf), "%s/T%04d-%s%%L.wav", spath.c_str(), cnt, legalized.c_str());
+                                       } else {
+                                               snprintf (buf, sizeof(buf), "%s/T%04d-%s%%R.wav", spath.c_str(), cnt, legalized.c_str());
+                                       }
+                               } else if (nchan < 26) {
+                                       snprintf (buf, sizeof(buf), "%s/T%04d-%s%%%c.wav", spath.c_str(), cnt, legalized.c_str(), 'a' + chan);
                                } else {
-                                       snprintf (buf, sizeof(buf), "%s-%u%%R.wav", spath.c_str(), cnt);
+                                       snprintf (buf, sizeof(buf), "%s/T%04d-%s.wav", spath.c_str(), cnt, legalized.c_str());
                                }
-                       } else if (ds.n_channels() < 26) {
-                               snprintf (buf, sizeof(buf), "%s-%u%%%c.wav", spath.c_str(), cnt, 'a' + chan);
                        } else {
-                               snprintf (buf, sizeof(buf), "%s-%u.wav", spath.c_str(), cnt);
+                               
+                               spath += '/';
+                               spath += legalized;
+                                       
+                               if (nchan < 2) {
+                                       snprintf (buf, sizeof(buf), "%s-%u.wav", spath.c_str(), cnt);
+                               } else if (nchan == 2) {
+                                       if (chan == 0) {
+                                               snprintf (buf, sizeof(buf), "%s-%u%%L.wav", spath.c_str(), cnt);
+                                       } else {
+                                               snprintf (buf, sizeof(buf), "%s-%u%%R.wav", spath.c_str(), cnt);
+                                       }
+                               } else if (nchan < 26) {
+                                       snprintf (buf, sizeof(buf), "%s-%u%%%c.wav", spath.c_str(), cnt, 'a' + chan);
+                               } else {
+                                       snprintf (buf, sizeof(buf), "%s-%u.wav", spath.c_str(), cnt);
+                               }
                        }
 
                        if (access (buf, F_OK) == 0) {
                                existing++;
                        }
                }
-
+                       
                if (existing == 0) {
                        break;
                }
-       }
 
-       if (cnt > limit) {
-               error << string_compose(_("There are already %1 recordings for %2, which I consider too many."), limit, ds.name()) << endmsg;
-               throw failed_constructor();
+               if (cnt > limit) {
+                       error << string_compose(_("There are already %1 recordings for %2, which I consider too many."), limit, name) << endmsg;
+                       throw failed_constructor();
+               }
        }
 
        /* we now have a unique name for the file, but figure out where to
@@ -2681,7 +2891,11 @@ Session::create_file_source (DiskStream& ds, int32_t chan)
 
        string foo = buf;
 
-       spath = discover_best_sound_dir ();
+       if (destructive) {
+               spath = tape_dir ();
+       } else {
+               spath = discover_best_sound_dir ();
+       }
 
        string::size_type pos = foo.find_last_of ('/');
        
@@ -2691,9 +2905,27 @@ Session::create_file_source (DiskStream& ds, int32_t chan)
                spath += foo.substr (pos + 1);
        }
 
-       /* this might throw failed_constructor(), which is OK */
+       return spath;
+}
+
+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);
 
-       return new FileSource (spath, frame_rate());
+       /* 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());
+       }
 }
 
 /* Playlist management */
@@ -2713,7 +2945,7 @@ Session::get_playlist (string name)
 Playlist *
 Session::playlist_by_name (string name)
 {
-       LockMonitor lm (playlist_lock, __LINE__, __FILE__);
+       Glib::Mutex::Lock lm (playlist_lock);
        for (PlaylistList::iterator i = playlists.begin(); i != playlists.end(); ++i) {
                if ((*i)->name() == name) {
                        return* i;
@@ -2735,7 +2967,7 @@ Session::add_playlist (Playlist* playlist)
        }
 
        { 
-               LockMonitor lm (playlist_lock, __LINE__, __FILE__);
+               Glib::Mutex::Lock lm (playlist_lock);
                if (find (playlists.begin(), playlists.end(), playlist) == playlists.end()) {
                        playlists.insert (playlists.begin(), playlist);
                        // playlist->ref();
@@ -2755,7 +2987,7 @@ Session::track_playlist (Playlist* pl, bool inuse)
        PlaylistList::iterator x;
 
        { 
-               LockMonitor lm (playlist_lock, __LINE__, __FILE__);
+               Glib::Mutex::Lock lm (playlist_lock);
 
                if (!inuse) {
                        //cerr << "shifting playlist to unused: " << pl->name() << endl;
@@ -2787,7 +3019,7 @@ Session::remove_playlist (Playlist* playlist)
        }
 
        { 
-               LockMonitor lm (playlist_lock, __LINE__, __FILE__);
+               Glib::Mutex::Lock lm (playlist_lock);
                // cerr << "removing playlist: " << playlist->name() << endl;
 
                PlaylistList::iterator i;
@@ -2874,7 +3106,7 @@ Session::remove_empty_sounds ()
        
        for (vector<string *>::iterator i = possible_audiofiles->begin(); i != possible_audiofiles->end(); ++i) {
 
-               if (FileSource::is_empty (*(*i))) {
+               if (AudioFileSource::is_empty (*(*i))) {
 
                        unlink ((*i)->c_str());
                        
@@ -2899,45 +3131,11 @@ Session::is_auditioning () const
        }
 }
 
-
-string
-Session::peak_path_from_audio_path (string audio_path)
-{
-       /* XXX hardly bombproof! fix me */
-
-       string res;
-
-       res = PBD::dirname (audio_path);
-       res = PBD::dirname (res);
-       res += '/';
-       res += peak_dir_name;
-       res += '/';
-       res += PBD::basename_nosuffix (audio_path);
-       res += ".peak";
-
-       return res;
-}
-
-string
-Session::old_peak_path_from_audio_path (string audio_path)
-{
-       /* This is a hangover from when audio and peak files
-          lived in the same directory. We need it to to 
-          be able to open old sessions.
-       */
-
-       /* XXX hardly bombproof! fix me */
-
-       string res = audio_path.substr (0, audio_path.find_last_of ('.'));
-       res += ".peak";
-       return res;
-}
-
 void
 Session::set_all_solo (bool yn)
 {
        {
-               RWLockMonitor lm (route_lock, false, __LINE__, __FILE__);
+               Glib::RWLock::ReaderLock lm (route_lock);
                
                for (RouteList::iterator i = routes.begin(); i != routes.end(); ++i) {
                        if (!(*i)->hidden()) {
@@ -2953,7 +3151,7 @@ void
 Session::set_all_mute (bool yn)
 {
        {
-               RWLockMonitor lm (route_lock, false, __LINE__, __FILE__);
+               Glib::RWLock::ReaderLock lm (route_lock);
                
                for (RouteList::iterator i = routes.begin(); i != routes.end(); ++i) {
                        if (!(*i)->hidden()) {
@@ -2966,12 +3164,12 @@ Session::set_all_mute (bool yn)
 }
                
 uint32_t
-Session::n_diskstreams () const
+Session::n_audio_diskstreams () const
 {
-       RWLockMonitor lm (diskstream_lock, false, __LINE__, __FILE__);
+       Glib::RWLock::ReaderLock lm (diskstream_lock);
        uint32_t n = 0;
 
-       for (DiskStreamList::const_iterator i = diskstreams.begin(); i != diskstreams.end(); ++i) {
+       for (AudioDiskstreamList::const_iterator i = audio_diskstreams.begin(); i != audio_diskstreams.end(); ++i) {
                if (!(*i)->hidden()) {
                        n++;
                }
@@ -2980,10 +3178,10 @@ Session::n_diskstreams () const
 }
 
 void 
-Session::foreach_diskstream (void (DiskStream::*func)(void)) 
+Session::foreach_audio_diskstream (void (AudioDiskstream::*func)(void)) 
 {
-       RWLockMonitor lm (diskstream_lock, false, __LINE__, __FILE__);
-       for (DiskStreamList::iterator i = diskstreams.begin(); i != diskstreams.end(); ++i) {
+       Glib::RWLock::ReaderLock lm (diskstream_lock);
+       for (AudioDiskstreamList::iterator i = audio_diskstreams.begin(); i != audio_diskstreams.end(); ++i) {
                if (!(*i)->hidden()) {
                        ((*i)->*func)();
                }
@@ -3001,8 +3199,8 @@ Session::graph_reordered ()
                return;
        }
 
-       RWLockMonitor lm1 (route_lock, true, __LINE__, __FILE__);
-       RWLockMonitor lm2 (diskstream_lock, false, __LINE__, __FILE__);
+       Glib::RWLock::WriterLock lm1 (route_lock);
+       Glib::RWLock::ReaderLock lm2 (diskstream_lock);
 
        resort_routes (0);
 
@@ -3010,7 +3208,7 @@ Session::graph_reordered ()
           reflect any changes in latencies within the graph.
        */
        
-       for (DiskStreamList::iterator i = diskstreams.begin(); i != diskstreams.end(); ++i) {
+       for (AudioDiskstreamList::iterator i = audio_diskstreams.begin(); i != audio_diskstreams.end(); ++i) {
                (*i)->set_capture_offset ();
        }
 }
@@ -3030,7 +3228,7 @@ Session::record_enable_all ()
 void
 Session::record_enable_change_all (bool yn)
 {
-       RWLockMonitor lm1 (route_lock, false, __LINE__, __FILE__);
+       Glib::RWLock::ReaderLock lm1 (route_lock);
        
        for (RouteList::iterator i = routes.begin(); i != routes.end(); ++i) {
                AudioTrack* at;
@@ -3115,7 +3313,7 @@ void
 Session::add_connection (ARDOUR::Connection* connection)
 {
        {
-               LockMonitor (connection_lock, __LINE__, __FILE__);
+               Glib::Mutex::Lock guard (connection_lock);
                _connections.push_back (connection);
        }
        
@@ -3130,7 +3328,7 @@ Session::remove_connection (ARDOUR::Connection* connection)
        bool removed = false;
 
        {
-               LockMonitor (connection_lock, __LINE__, __FILE__);
+               Glib::Mutex::Lock guard (connection_lock);
                ConnectionList::iterator i = find (_connections.begin(), _connections.end(), connection);
                
                if (i != _connections.end()) {
@@ -3149,7 +3347,7 @@ Session::remove_connection (ARDOUR::Connection* connection)
 ARDOUR::Connection *
 Session::connection_by_name (string name) const
 {
-       LockMonitor lm (connection_lock, __LINE__, __FILE__);
+       Glib::Mutex::Lock lm (connection_lock);
 
        for (ConnectionList::const_iterator i = _connections.begin(); i != _connections.end(); ++i) {
                if ((*i)->name() == name) {
@@ -3166,7 +3364,7 @@ Session::set_edit_mode (EditMode mode)
        _edit_mode = mode;
        
        { 
-               LockMonitor lm (playlist_lock, __LINE__, __FILE__);
+               Glib::Mutex::Lock lm (playlist_lock);
                
                for (PlaylistList::iterator i = playlists.begin(); i != playlists.end(); ++i) {
                        (*i)->set_edit_mode (mode);
@@ -3206,6 +3404,16 @@ Session::ensure_passthru_buffers (uint32_t howmany)
                memset (p, 0, sizeof (Sample) * current_block_size);
                _silent_buffers.push_back (p);
 
+               *p = 0;
+               
+#ifdef NO_POSIX_MEMALIGN
+               p =  (Sample *) malloc(current_block_size * sizeof(Sample));
+#else
+               posix_memalign((void **)&p,16,current_block_size * 4);
+#endif                 
+               memset (p, 0, sizeof (Sample) * current_block_size);
+               _send_buffers.push_back (p);
+               
        }
        allocate_pan_automation_buffers (current_block_size, howmany, false);
 }
@@ -3231,7 +3439,7 @@ Session::next_insert_name ()
 NamedSelection *
 Session::named_selection_by_name (string name)
 {
-       LockMonitor lm (named_selection_lock, __LINE__, __FILE__);
+       Glib::Mutex::Lock lm (named_selection_lock);
        for (NamedSelectionList::iterator i = named_selections.begin(); i != named_selections.end(); ++i) {
                if ((*i)->name == name) {
                        return* i;
@@ -3244,7 +3452,7 @@ void
 Session::add_named_selection (NamedSelection* named_selection)
 {
        { 
-               LockMonitor lm (named_selection_lock, __LINE__, __FILE__);
+               Glib::Mutex::Lock lm (named_selection_lock);
                named_selections.insert (named_selections.begin(), named_selection);
        }
 
@@ -3259,7 +3467,7 @@ Session::remove_named_selection (NamedSelection* named_selection)
        bool removed = false;
 
        { 
-               LockMonitor lm (named_selection_lock, __LINE__, __FILE__);
+               Glib::Mutex::Lock lm (named_selection_lock);
 
                NamedSelectionList::iterator i = find (named_selections.begin(), named_selections.end(), named_selection);
 
@@ -3281,9 +3489,9 @@ Session::reset_native_file_format ()
 {
        // jlc - WHY take routelock?
        //RWLockMonitor lm1 (route_lock, true, __LINE__, __FILE__);
-       RWLockMonitor lm2 (diskstream_lock, false, __LINE__, __FILE__);
+       Glib::RWLock::ReaderLock lm2 (diskstream_lock);
 
-       for (DiskStreamList::iterator i = diskstreams.begin(); i != diskstreams.end(); ++i) {
+       for (AudioDiskstreamList::iterator i = audio_diskstreams.begin(); i != audio_diskstreams.end(); ++i) {
                (*i)->reset_write_sources (false);
        }
 }
@@ -3291,7 +3499,7 @@ Session::reset_native_file_format ()
 bool
 Session::route_name_unique (string n) const
 {
-       RWLockMonitor lm (route_lock, false, __LINE__, __FILE__);
+       Glib::RWLock::ReaderLock lm (route_lock);
        
        for (RouteList::const_iterator i = routes.begin(); i != routes.end(); ++i) {
                if ((*i)->name() == n) {
@@ -3303,7 +3511,7 @@ Session::route_name_unique (string n) const
 }
 
 int
-Session::remove_file_source (FileSource& fs)
+Session::cleanup_audio_file_source (AudioFileSource& fs)
 {
        return fs.move_to_trash (dead_sound_dir_name);
 }
@@ -3311,7 +3519,7 @@ Session::remove_file_source (FileSource& fs)
 uint32_t
 Session::n_playlists () const
 {
-       LockMonitor lm (playlist_lock, __LINE__, __FILE__);
+       Glib::Mutex::Lock lm (playlist_lock);
        return playlists.size();
 }
 
@@ -3354,13 +3562,13 @@ void
 Session::add_instant_xml (XMLNode& node, const std::string& dir)
 {
        Stateful::add_instant_xml (node, dir);
-       Config->add_instant_xml (node, Config->get_user_ardour_path());
+       Config->add_instant_xml (node, get_user_ardour_path());
 }
 
 int
 Session::freeze (InterThreadInfo& itt)
 {
-       RWLockMonitor lm (route_lock, false, __LINE__, __FILE__);
+       Glib::RWLock::ReaderLock lm (route_lock);
 
        for (RouteList::iterator i = routes.begin(); i != routes.end(); ++i) {
 
@@ -3378,12 +3586,12 @@ Session::freeze (InterThreadInfo& itt)
 }
 
 int
-Session::write_one_track (AudioTrack& track, jack_nframes_t start, jack_nframes_t len,         bool overwrite, vector<Source*>& srcs,
-                         InterThreadInfo& itt)
+Session::write_one_audio_track (AudioTrack& track, jack_nframes_t start, jack_nframes_t len,   
+                              bool overwrite, vector<AudioSource*>& srcs, InterThreadInfo& itt)
 {
        int ret = -1;
        Playlist* playlist;
-       FileSource* fsource;
+       AudioFileSource* fsource;
        uint32_t x;
        char buf[PATH_MAX+1];
        string dir;
@@ -3392,9 +3600,12 @@ Session::write_one_track (AudioTrack& track, jack_nframes_t start, jack_nframes_
        jack_nframes_t this_chunk;
        jack_nframes_t to_do;
        vector<Sample*> buffers;
-       const jack_nframes_t chunk_size = (256 * 1024)/4;
+       char *  workbuf = 0;
 
-       atomic_set (&processing_prohibited, 1);
+       // any bigger than this seems to cause stack overflows in called functions
+       const jack_nframes_t chunk_size = (128 * 1024)/4;
+
+       g_atomic_int_set (&processing_prohibited, 1);
        
        /* call tree *MUST* hold route_lock */
        
@@ -3427,7 +3638,11 @@ Session::write_one_track (AudioTrack& track, jack_nframes_t start, jack_nframes_
                }
                
                try {
-                       fsource = new FileSource (buf, frame_rate());
+                       fsource =  new SndFileSource (buf, 
+                                                     Config->get_native_file_data_format(),
+                                                     Config->get_native_file_header_format(),
+                                                     frame_rate());
+                                                           
                }
                
                catch (failed_constructor& err) {
@@ -3454,19 +3669,25 @@ Session::write_one_track (AudioTrack& track, jack_nframes_t start, jack_nframes_
 #endif                 
                buffers.push_back (b);
        }
+
+       workbuf = new char[chunk_size * 4];
        
        while (to_do && !itt.cancel) {
                
                this_chunk = min (to_do, chunk_size);
                
-               if (track.export_stuff (buffers, nchans, start, this_chunk)) {
+               if (track.export_stuff (buffers, workbuf, nchans, start, this_chunk)) {
                        goto out;
                }
 
                uint32_t n = 0;
-               for (vector<Source*>::iterator src=srcs.begin(); src != srcs.end(); ++src, ++n) {
-                       if ((*src)->write (buffers[n], this_chunk) != this_chunk) {
-                               goto out;
+               for (vector<AudioSource*>::iterator src=srcs.begin(); src != srcs.end(); ++src, ++n) {
+                       AudioFileSource* afs = dynamic_cast<AudioFileSource*>(*src);
+
+                       if (afs) {
+                               if (afs->write (buffers[n], this_chunk, workbuf) != this_chunk) {
+                                       goto out;
+                               }
                        }
                }
                
@@ -3484,14 +3705,20 @@ Session::write_one_track (AudioTrack& track, jack_nframes_t start, jack_nframes_
                time (&now);
                xnow = localtime (&now);
                
-               for (vector<Source*>::iterator src=srcs.begin(); src != srcs.end(); ++src) {
-                       dynamic_cast<FileSource*>((*src))->update_header (position, *xnow, now);
+               for (vector<AudioSource*>::iterator src=srcs.begin(); src != srcs.end(); ++src) {
+                       AudioFileSource* afs = dynamic_cast<AudioFileSource*>(*src);
+                       if (afs) {
+                               afs->update_header (position, *xnow, now);
+                       }
                }
                
                /* build peakfile for new source */
                
-               for (vector<Source*>::iterator src=srcs.begin(); src != srcs.end(); ++src) {
-                       dynamic_cast<FileSource*>(*src)->build_peaks ();
+               for (vector<AudioSource*>::iterator src=srcs.begin(); src != srcs.end(); ++src) {
+                       AudioFileSource* afs = dynamic_cast<AudioFileSource*>(*src);
+                       if (afs) {
+                               afs->build_peaks ();
+                       }
                }
                
                ret = 0;
@@ -3499,8 +3726,11 @@ Session::write_one_track (AudioTrack& track, jack_nframes_t start, jack_nframes_
                
   out:
        if (ret) {
-               for (vector<Source*>::iterator src=srcs.begin(); src != srcs.end(); ++src) {
-                       dynamic_cast<FileSource*>(*src)->mark_for_remove ();
+               for (vector<AudioSource*>::iterator src=srcs.begin(); src != srcs.end(); ++src) {
+                       AudioFileSource* afs = dynamic_cast<AudioFileSource*>(*src);
+                       if (afs) {
+                               afs->mark_for_remove ();
+                       }
                        delete *src;
                }
        }
@@ -3509,7 +3739,11 @@ Session::write_one_track (AudioTrack& track, jack_nframes_t start, jack_nframes_
                free(*i);
        }
 
-       atomic_set (&processing_prohibited, 0);
+       if (workbuf) {
+               delete [] workbuf;
+       }
+       
+       g_atomic_int_set (&processing_prohibited, 0);
 
        itt.done = true;
 
@@ -3529,7 +3763,7 @@ uint32_t
 Session::ntracks () const
 {
        uint32_t n = 0;
-       RWLockMonitor lm (route_lock, false, __LINE__, __FILE__);
+       Glib::RWLock::ReaderLock lm (route_lock);
 
        for (RouteList::const_iterator i = routes.begin(); i != routes.end(); ++i) {
                if (dynamic_cast<AudioTrack*> (*i)) {
@@ -3544,7 +3778,7 @@ uint32_t
 Session::nbusses () const
 {
        uint32_t n = 0;
-       RWLockMonitor lm (route_lock, false, __LINE__, __FILE__);
+       Glib::RWLock::ReaderLock lm (route_lock);
 
        for (RouteList::const_iterator i = routes.begin(); i != routes.end(); ++i) {
                if (dynamic_cast<AudioTrack*> (*i) == 0) {