Merge with 2.0-ongoing R2883.
[ardour.git] / libs / ardour / session.cc
index 1170685b6cee6d50c556a4be3265fb9316c3670d..cef5c7df485fddd9becf38585663d1a3872b8330 100644 (file)
 #include <pbd/stl_delete.h>
 #include <pbd/basename.h>
 #include <pbd/stacktrace.h>
+#include <pbd/file_utils.h>
 
 #include <ardour/audioengine.h>
 #include <ardour/configuration.h>
 #include <ardour/session.h>
-#include <ardour/audio_diskstream.h>
+#include <ardour/session_directory.h>
 #include <ardour/utils.h>
+#include <ardour/audio_diskstream.h>
 #include <ardour/audioplaylist.h>
 #include <ardour/audioregion.h>
 #include <ardour/audiofilesource.h>
+#include <ardour/midi_diskstream.h>
+#include <ardour/midi_playlist.h>
+#include <ardour/midi_region.h>
+#include <ardour/smf_source.h>
 #include <ardour/auditioner.h>
 #include <ardour/recent_sessions.h>
-#include <ardour/redirect.h>
+#include <ardour/io_processor.h>
 #include <ardour/send.h>
-#include <ardour/insert.h>
-#include <ardour/connection.h>
+#include <ardour/processor.h>
+#include <ardour/plugin_insert.h>
+#include <ardour/port_insert.h>
+#include <ardour/auto_bundle.h>
 #include <ardour/slave.h>
 #include <ardour/tempo.h>
 #include <ardour/audio_track.h>
+#include <ardour/midi_track.h>
 #include <ardour/cycle_timer.h>
 #include <ardour/named_selection.h>
 #include <ardour/crossfade.h>
 #include <ardour/playlist.h>
 #include <ardour/click.h>
 #include <ardour/data_type.h>
+#include <ardour/buffer_set.h>
 #include <ardour/source_factory.h>
 #include <ardour/region_factory.h>
+#include <ardour/filename_extensions.h>
+#include <ardour/session_directory.h>
+#include <ardour/tape_file_matcher.h>
 
 #ifdef HAVE_LIBLO
 #include <ardour/osc.h>
@@ -78,20 +91,19 @@ using namespace ARDOUR;
 using namespace PBD;
 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::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");
-const char* Session::export_dir_name = X_("export");
-
-Session::compute_peak_t                                Session::compute_peak                   = 0;
-Session::apply_gain_to_buffer_t                Session::apply_gain_to_buffer   = 0;
-Session::mix_buffers_with_gain_t       Session::mix_buffers_with_gain  = 0;
-Session::mix_buffers_no_gain_t         Session::mix_buffers_no_gain    = 0;
+#ifdef __x86_64__
+static const int CPU_CACHE_ALIGN = 64;
+#else
+static const int CPU_CACHE_ALIGN = 16; /* arguably 32 on most arches, but it matters less */
+#endif
+
+bool Session::_disable_all_loaded_plugins = false;
+
+Session::compute_peak_t          Session::compute_peak          = 0;
+Session::find_peaks_t            Session::find_peaks            = 0;
+Session::apply_gain_to_buffer_t  Session::apply_gain_to_buffer  = 0;
+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::SendFeedback;
@@ -100,186 +112,45 @@ 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)
-{
-       struct stat statbuf;
-       char buf[PATH_MAX+1];
-
-       isnew = false;
-
-       if (!realpath (str.c_str(), buf) && (errno != ENOENT && errno != ENOTDIR)) {
-               error << string_compose (_("Could not resolve path: %1 (%2)"), buf, strerror(errno)) << endmsg;
-               return -1;
-       }
-
-       str = buf;
-       
-       /* check to see if it exists, and what it is */
-
-       if (stat (str.c_str(), &statbuf)) {
-               if (errno == ENOENT) {
-                       isnew = true;
-               } else {
-                       error << string_compose (_("cannot check session path %1 (%2)"), str, strerror (errno))
-                             << endmsg;
-                       return -1;
-               }
-       }
-
-       if (!isnew) {
-
-               /* it exists, so it must either be the name
-                  of the directory, or the name of the statefile
-                  within it.
-               */
-
-               if (S_ISDIR (statbuf.st_mode)) {
-
-                       string::size_type slash = str.find_last_of ('/');
-               
-                       if (slash == string::npos) {
-                               
-                               /* a subdirectory of cwd, so statefile should be ... */
-
-                               string tmp;
-                               tmp = str;
-                               tmp += '/';
-                               tmp += str;
-                               tmp += _statefile_suffix;
-
-                               /* is it there ? */
-                               
-                               if (stat (tmp.c_str(), &statbuf)) {
-                                       error << string_compose (_("cannot check statefile %1 (%2)"), tmp, strerror (errno))
-                                             << endmsg;
-                                       return -1;
-                               }
-
-                               path = str;
-                               snapshot = str;
-
-                       } else {
-
-                               /* some directory someplace in the filesystem.
-                                  the snapshot name is the directory name
-                                  itself.
-                               */
-
-                               path = str;
-                               snapshot = str.substr (slash+1);
-                                       
-                       }
-
-               } else if (S_ISREG (statbuf.st_mode)) {
-                       
-                       string::size_type slash = str.find_last_of ('/');
-                       string::size_type suffix;
-
-                       /* remove the suffix */
-                       
-                       if (slash != string::npos) {
-                               snapshot = str.substr (slash+1);
-                       } else {
-                               snapshot = str;
-                       }
-
-                       suffix = snapshot.find (_statefile_suffix);
-                       
-                       if (suffix == string::npos) {
-                               error << string_compose (_("%1 is not an Ardour snapshot file"), str) << endmsg;
-                               return -1;
-                       }
-
-                       /* remove suffix */
-
-                       snapshot = snapshot.substr (0, suffix);
-                       
-                       if (slash == string::npos) {
-                               
-                               /* we must be in the directory where the 
-                                  statefile lives. get it using cwd().
-                               */
-
-                               char cwd[PATH_MAX+1];
-
-                               if (getcwd (cwd, sizeof (cwd)) == 0) {
-                                       error << string_compose (_("cannot determine current working directory (%1)"), strerror (errno))
-                                             << endmsg;
-                                       return -1;
-                               }
-
-                               path = cwd;
-
-                       } else {
-
-                               /* full path to the statefile */
-
-                               path = str.substr (0, slash);
-                       }
-                               
-               } else {
-
-                       /* what type of file is it? */
-                       error << string_compose (_("unknown file type for session %1"), str) << endmsg;
-                       return -1;
-               }
-
-       } else {
-
-               /* its the name of a new directory. get the name
-                  as "dirname" does.
-               */
-
-               string::size_type slash = str.find_last_of ('/');
-
-               if (slash == string::npos) {
-                       
-                       /* no slash, just use the name, but clean it up */
-                       
-                       path = legalize_for_path (str);
-                       snapshot = path;
-                       
-               } else {
-                       
-                       path = str;
-                       snapshot = str.substr (slash+1);
-               }
-       }
-
-       return 0;
-}
-
 Session::Session (AudioEngine &eng,
-                 string fullpath,
-                 string snapshot_name,
-                 string* mix_template)
+                 const string& fullpath,
+                 const string& snapshot_name,
+                 string mix_template)
 
        : _engine (eng),
+         _scratch_buffers(new BufferSet()),
+         _silent_buffers(new BufferSet()),
+         _mix_buffers(new BufferSet()),
          _mmc_port (default_mmc_port),
          _mtc_port (default_mtc_port),
          _midi_port (default_midi_port),
+         _session_dir (new SessionDirectory(fullpath)),
          pending_events (2048),
-         midi_requests (128), // the size of this should match the midi request pool size
+         //midi_requests (128), // the size of this should match the midi request pool size
+         _send_smpte_update (false),
          diskstreams (new DiskstreamList),
          routes (new RouteList),
          auditioner ((Auditioner*) 0),
+         _bundle_xml_node (0),
          _click_io ((IO*) 0),
          main_outs (0)
 {
        bool new_session;
 
+       if (!eng.connected()) {
+               throw failed_constructor();
+       }
+       
        cerr << "Loading session " << fullpath << " using snapshot " << snapshot_name << " (1)" << endl;
 
        n_physical_outputs = _engine.n_physical_outputs();
        n_physical_inputs =  _engine.n_physical_inputs();
 
        first_stage_init (fullpath, snapshot_name);
-       
+
        new_session = !g_file_test (_path.c_str(), GFileTest (G_FILE_TEST_EXISTS | G_FILE_TEST_IS_DIR));
        if (new_session) {
                if (create (new_session, mix_template, compute_initial_length())) {
-                       cerr << "create failed\n";
                        destroy ();
                        throw failed_constructor ();
                }
@@ -315,18 +186,28 @@ Session::Session (AudioEngine &eng,
                  nframes_t initial_length)
 
        : _engine (eng),
+         _scratch_buffers(new BufferSet()),
+         _silent_buffers(new BufferSet()),
+         _mix_buffers(new BufferSet()),
          _mmc_port (default_mmc_port),
          _mtc_port (default_mtc_port),
          _midi_port (default_midi_port),
+         _session_dir ( new SessionDirectory(fullpath)),
          pending_events (2048),
-         midi_requests (16),
+         //midi_requests (16),
+         _send_smpte_update (false),
          diskstreams (new DiskstreamList),
          routes (new RouteList),
+         _bundle_xml_node (0),
          main_outs (0)
 
 {
        bool new_session;
 
+       if (!eng.connected()) {
+               throw failed_constructor();
+       }
+
        cerr << "Loading session " << fullpath << " using snapshot " << snapshot_name << " (2)" << endl;
 
        n_physical_outputs = _engine.n_physical_outputs();
@@ -345,7 +226,7 @@ Session::Session (AudioEngine &eng,
        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)) {
+               if (create (new_session, string(), initial_length)) {
                        destroy ();
                        throw failed_constructor ();
                }
@@ -375,7 +256,7 @@ Session::Session (AudioEngine &eng,
                }
                
                if (!rl.empty()) {
-                       add_routes (rl);
+                       add_routes (rl, false);
                }
                
        }
@@ -388,17 +269,12 @@ Session::Session (AudioEngine &eng,
                throw failed_constructor ();
        }
        
-       store_recent_sessions(_name, _path);
+       store_recent_sessions (_name, _path);
        
-       bool was_dirty = dirty ();
-
        _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 */
-       }
+       Config->ParameterChanged.connect (mem_fun (*this, &Session::config_changed));
 }
 
 Session::~Session ()
@@ -416,6 +292,7 @@ Session::destroy ()
        remove_pending_capture_state ();
 
        _state_of_the_state = StateOfTheState (CannotSave|Deletion);
+
        _engine.remove_session ();
 
        GoingAway (); /* EMIT SIGNAL */
@@ -435,7 +312,7 @@ Session::destroy ()
        }
 
        terminate_butler_thread ();
-       terminate_midi_thread ();
+       //terminate_midi_thread ();
        
        if (click_data && click_data != default_click) {
                delete [] click_data;
@@ -447,23 +324,11 @@ Session::destroy ()
 
        clear_clicks ();
 
-       for (vector<Sample*>::iterator i = _passthru_buffers.begin(); i != _passthru_buffers.end(); ++i) {
-               free(*i);
-       }
-
-       for (vector<Sample*>::iterator i = _silent_buffers.begin(); i != _silent_buffers.end(); ++i) {
-               free(*i);
-       }
-
-       for (vector<Sample*>::iterator i = _send_buffers.begin(); i != _send_buffers.end(); ++i) {
-               free(*i);
-       }
+       delete _scratch_buffers;
+       delete _silent_buffers;
+       delete _mix_buffers;
 
        AudioDiskstream::free_working_buffers();
-
-       /* this should cause deletion of the auditioner */
-
-       // auditioner.reset ();
        
 #undef TRACK_DESTRUCTION
 #ifdef TRACK_DESTRUCTION
@@ -508,11 +373,11 @@ Session::destroy ()
        unused_playlists.clear ();
 
 #ifdef TRACK_DESTRUCTION
-       cerr << "delete audio regions\n";
+       cerr << "delete regions\n";
 #endif /* TRACK_DESTRUCTION */
        
-       for (AudioRegionList::iterator i = audio_regions.begin(); i != audio_regions.end(); ) {
-               AudioRegionList::iterator tmp;
+       for (RegionList::iterator i = regions.begin(); i != regions.end(); ) {
+               RegionList::iterator tmp;
 
                tmp = i;
                ++tmp;
@@ -522,8 +387,8 @@ Session::destroy ()
                i = tmp;
        }
 
-       audio_regions.clear ();
-       
+       regions.clear ();
+
 #ifdef TRACK_DESTRUCTION
        cerr << "delete routes\n";
 #endif /* TRACK_DESTRUCTION */
@@ -555,8 +420,8 @@ Session::destroy ()
 #ifdef TRACK_DESTRUCTION
        cerr << "delete audio sources\n";
 #endif /* TRACK_DESTRUCTION */
-       for (AudioSourceList::iterator i = audio_sources.begin(); i != audio_sources.end(); ) {
-               AudioSourceList::iterator tmp;
+       for (SourceMap::iterator i = sources.begin(); i != sources.end(); ) {
+               SourceMap::iterator tmp;
 
                tmp = i;
                ++tmp;
@@ -566,7 +431,7 @@ Session::destroy ()
                i = tmp;
        }
 
-       audio_sources.clear ();
+       sources.clear ();
 
 #ifdef TRACK_DESTRUCTION
        cerr << "delete mix groups\n";
@@ -596,20 +461,6 @@ Session::destroy ()
                i = tmp;
        }
        
-#ifdef TRACK_DESTRUCTION
-       cerr << "delete connections\n";
-#endif /* TRACK_DESTRUCTION */
-       for (ConnectionList::iterator i = _connections.begin(); i != _connections.end(); ) {
-               ConnectionList::iterator tmp;
-
-               tmp = i;
-               ++tmp;
-
-               delete *i;
-
-               i = tmp;
-       }
-
        if (butler_mixdown_buffer) {
                delete [] butler_mixdown_buffer;
        }
@@ -692,8 +543,8 @@ Session::when_engine_running ()
                        
                        /* default state for Click */
 
-                       first_physical_output = _engine.get_nth_physical_output (0);
-                       
+                       first_physical_output = _engine.get_nth_physical_output (DataType::AUDIO, 0);
+
                        if (first_physical_output.length()) {
                                if (_click_io->add_output_port (first_physical_output, this)) {
                                        // relax, even though its an error
@@ -714,7 +565,7 @@ Session::when_engine_running ()
                // XXX HOW TO ALERT UI TO THIS ? DO WE NEED TO?
        }
 
-       /* Create a set of Connection objects that map
+       /* Create a set of Bundle objects that map
           to the physical outputs currently available
        */
 
@@ -724,24 +575,22 @@ Session::when_engine_running ()
                char buf[32];
                snprintf (buf, sizeof (buf), _("out %" PRIu32), np+1);
 
-               Connection* c = new OutputConnection (buf, true);
+               shared_ptr<AutoBundle> c (new AutoBundle (buf, true));
+               c->set_channels (1);
+               c->set_port (0, _engine.get_nth_physical_output (DataType::AUDIO, np));
 
-               c->add_port ();
-               c->add_connection (0, _engine.get_nth_physical_output (np));
-
-               add_connection (c);
+               add_bundle (c);
        }
 
        for (uint32_t np = 0; np < n_physical_inputs; ++np) {
                char buf[32];
                snprintf (buf, sizeof (buf), _("in %" PRIu32), np+1);
 
-               Connection* c = new InputConnection (buf, true);
-
-               c->add_port ();
-               c->add_connection (0, _engine.get_nth_physical_input (np));
+               shared_ptr<AutoBundle> c (new AutoBundle (buf, false));
+               c->set_channels (1);
+               c->set_port (0, _engine.get_nth_physical_input (DataType::AUDIO, np));
 
-               add_connection (c);
+               add_bundle (c);
        }
 
        /* TWO: STEREO */
@@ -750,28 +599,24 @@ Session::when_engine_running ()
                char buf[32];
                snprintf (buf, sizeof (buf), _("out %" PRIu32 "+%" PRIu32), np+1, np+2);
 
-               Connection* c = new OutputConnection (buf, true);
+               shared_ptr<AutoBundle> c (new AutoBundle (buf, true));
+               c->set_channels (2);
+               c->set_port (0, _engine.get_nth_physical_output (DataType::AUDIO, np));
+               c->set_port (1, _engine.get_nth_physical_output (DataType::AUDIO, np + 1));
 
-               c->add_port ();
-               c->add_port ();
-               c->add_connection (0, _engine.get_nth_physical_output (np));
-               c->add_connection (1, _engine.get_nth_physical_output (np+1));
-
-               add_connection (c);
+               add_bundle (c);
        }
 
        for (uint32_t np = 0; np < n_physical_inputs; np +=2) {
                char buf[32];
                snprintf (buf, sizeof (buf), _("in %" PRIu32 "+%" PRIu32), np+1, np+2);
 
-               Connection* c = new InputConnection (buf, true);
-
-               c->add_port ();
-               c->add_port ();
-               c->add_connection (0, _engine.get_nth_physical_input (np));
-               c->add_connection (1, _engine.get_nth_physical_input (np+1));
+               shared_ptr<AutoBundle> c (new AutoBundle (buf, false));
+               c->set_channels (2);
+               c->set_port (0, _engine.get_nth_physical_input (DataType::AUDIO, np));
+               c->set_port (1, _engine.get_nth_physical_input (DataType::AUDIO, np + 1));
 
-               add_connection (c);
+               add_bundle (c);
        }
 
        /* THREE MASTER */
@@ -793,16 +638,18 @@ Session::when_engine_running ()
                        
                        _master_out->defer_pan_reset ();
                        
-                       while ((int) _master_out->n_inputs() < _master_out->input_maximum()) {
-                               if (_master_out->add_input_port ("", this)) {
+                       while (_master_out->n_inputs().n_audio()
+                                       < _master_out->input_maximum().n_audio()) {
+                               if (_master_out->add_input_port ("", this, DataType::AUDIO)) {
                                        error << _("cannot setup master inputs") 
                                              << endmsg;
                                        break;
                                }
                        }
                        n = 0;
-                       while ((int) _master_out->n_outputs() < _master_out->output_maximum()) {
-                               if (_master_out->add_output_port (_engine.get_nth_physical_output (n), this)) {
+                       while (_master_out->n_outputs().n_audio()
+                                       < _master_out->output_maximum().n_audio()) {
+                               if (_master_out->add_output_port (_engine.get_nth_physical_output (DataType::AUDIO, n), this, DataType::AUDIO)) {
                                        error << _("cannot setup master outputs")
                                              << endmsg;
                                        break;
@@ -814,13 +661,13 @@ Session::when_engine_running ()
                        
                }
 
-               Connection* c = new OutputConnection (_("Master Out"), true);
+               shared_ptr<AutoBundle> c (new AutoBundle (_("Master Out"), true));
 
-               for (uint32_t n = 0; n < _master_out->n_inputs (); ++n) {
-                       c->add_port ();
-                       c->add_connection ((int) n, _master_out->input(n)->name());
-               }
-               add_connection (c);
+               c->set_channels (_master_out->n_inputs().n_total());
+               for (uint32_t n = 0; n < _master_out->n_inputs ().n_total(); ++n) {
+                       c->set_port (n, _master_out->input(n)->name());
+               }
+               add_bundle (c);
        } 
 
        hookup_io ();
@@ -854,6 +701,7 @@ Session::when_engine_running ()
        
        _state_of_the_state = StateOfTheState (_state_of_the_state & ~(CannotSave|Dirty));
 
+
        /* hook us up to the engine */
 
        _engine.set_session (this);
@@ -863,10 +711,7 @@ Session::when_engine_running ()
 
        osc->set_session (*this);
 #endif
-    
-       _state_of_the_state = Clean;
 
-       DirtyChanged (); /* EMIT SIGNAL */
 }
 
 void
@@ -878,6 +723,7 @@ Session::hookup_io ()
 
        _state_of_the_state = StateOfTheState (_state_of_the_state | InitialConnecting);
 
+
        if (auditioner == 0) {
                
                /* we delay creating the auditioner till now because
@@ -900,8 +746,9 @@ Session::hookup_io ()
 
        if (_control_out) {
                uint32_t n;
+               vector<string> cports;
 
-               while ((int) _control_out->n_inputs() < _control_out->input_maximum()) {
+               while (_control_out->n_inputs().n_audio() < _control_out->input_maximum().n_audio()) {
                        if (_control_out->add_input_port ("", this)) {
                                error << _("cannot setup control inputs")
                                      << endmsg;
@@ -909,16 +756,35 @@ Session::hookup_io ()
                        }
                }
                n = 0;
-               while ((int) _control_out->n_outputs() < _control_out->output_maximum()) {
-                       if (_control_out->add_output_port (_engine.get_nth_physical_output (n), this)) {
+               while (_control_out->n_outputs().n_audio() < _control_out->output_maximum().n_audio()) {
+                       if (_control_out->add_output_port (_engine.get_nth_physical_output (DataType::AUDIO, n), this)) {
                                error << _("cannot set up master outputs")
                                      << endmsg;
                                break;
                        }
                        n++;
                }
+
+
+               uint32_t ni = _control_out->n_inputs().get (DataType::AUDIO);
+
+               for (n = 0; n < ni; ++n) {
+                       cports.push_back (_control_out->input(n)->name());
+               }
+
+               boost::shared_ptr<RouteList> r = routes.reader ();              
+
+               for (RouteList::iterator x = r->begin(); x != r->end(); ++x) {
+                       (*x)->set_control_outs (cports);
+               }
        }
 
+       /* load bundles, which we may have postponed earlier on */
+       if (_bundle_xml_node) {
+               load_bundles (*_bundle_xml_node);
+               delete _bundle_xml_node;
+       }       
+
        /* Tell all IO objects to connect themselves together */
 
        IO::enable_connecting ();
@@ -933,6 +799,7 @@ Session::hookup_io ()
 
        _state_of_the_state = StateOfTheState (_state_of_the_state & ~InitialConnecting);
 
+
        /* now handle the whole enchilada as if it was one
           graph reorder event.
        */
@@ -1201,7 +1068,7 @@ Session::enable_record ()
        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);
+               deliver_mmc(MIDI::MachineControl::cmdRecordStrobe, _last_record_location);
 
                if (Config->get_monitoring_model() == HardwareMonitoring && Config->get_auto_input()) {
                        boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
@@ -1223,7 +1090,7 @@ Session::disable_record (bool rt_context, bool force)
 
        if ((rs = (RecordState) g_atomic_int_get (&_record_status)) != Disabled) {
 
-               if (!Config->get_latched_record_enable () || force) {
+               if ((!Config->get_latched_record_enable () && !play_loop) || force) {
                        g_atomic_int_set (&_record_status, Disabled);
                } else {
                        if (rs == Recording) {
@@ -1231,7 +1098,11 @@ Session::disable_record (bool rt_context, bool force)
                        }
                }
 
-               send_mmc_in_another_thread (MIDI::MachineControl::cmdRecordExit);
+               // FIXME: timestamp correct? [DR]
+               // FIXME FIXME FIXME: rt_context?  this must be called in the process thread.
+               // does this /need/ to be sent in all cases?
+               if (rt_context)
+                       deliver_mmc (MIDI::MachineControl::cmdRecordExit, _transport_frame);
 
                if (Config->get_monitoring_model() == HardwareMonitoring && Config->get_auto_input()) {
                        boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
@@ -1254,15 +1125,18 @@ Session::disable_record (bool rt_context, bool force)
 void
 Session::step_back_from_record ()
 {
-       g_atomic_int_set (&_record_status, Enabled);
+       /* XXX really atomic compare+swap here */
+       if (g_atomic_int_get (&_record_status) == Recording) {
+               g_atomic_int_set (&_record_status, Enabled);
 
-       if (Config->get_monitoring_model() == HardwareMonitoring) {
-               boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
-               
-               for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
-                       if (Config->get_auto_input() && (*i)->record_enabled ()) {
-                               //cerr << "switching from input" << __FILE__ << __LINE__ << endl << endl;
-                               (*i)->monitor_input (false);   
+               if (Config->get_monitoring_model() == HardwareMonitoring) {
+                       boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
+                       
+                       for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
+                               if (Config->get_auto_input() && (*i)->record_enabled ()) {
+                                       //cerr << "switching from input" << __FILE__ << __LINE__ << endl << endl;
+                                       (*i)->monitor_input (false);   
+                               }
                        }
                }
        }
@@ -1284,7 +1158,7 @@ Session::maybe_enable_record ()
                        enable_record ();
                } 
        } else {
-               send_mmc_in_another_thread (MIDI::MachineControl::cmdRecordPause);
+               deliver_mmc (MIDI::MachineControl::cmdRecordPause, _transport_frame);
                RecordStateChanged (); /* EMIT SIGNAL */
        }
 
@@ -1363,8 +1237,10 @@ Session::set_frame_rate (nframes_t frames_per_second)
 
        sync_time_vars();
 
-       Route::set_automation_interval ((jack_nframes_t) ceil ((double) frames_per_second * 0.25));
+       Automatable::set_automation_interval ((jack_nframes_t) ceil ((double) frames_per_second * (0.001 * Config->get_automation_interval())));
 
+       clear_clicks ();
+       
        // XXX we need some equivalent to this, somehow
        // SndFileSource::setup_standard_crossfades (frames_per_second);
 
@@ -1383,39 +1259,11 @@ Session::set_block_size (nframes_t nframes)
        */
 
        { 
-               vector<Sample*>::iterator i;
-               uint32_t np;
                        
                current_block_size = nframes;
-               
-               for (np = 0, i = _passthru_buffers.begin(); i != _passthru_buffers.end(); ++i, ++np) {
-                       free (*i);
-               }
-
-               for (vector<Sample*>::iterator i = _silent_buffers.begin(); i != _silent_buffers.end(); ++i) {
-                       free (*i);
-               }
-
-               _passthru_buffers.clear ();
-               _silent_buffers.clear ();
-
-               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);
-               }
+               ensure_buffers(_scratch_buffers->available());
 
-               
                if (_gain_automation_buffer) {
                        delete [] _gain_automation_buffer;
                }
@@ -1594,17 +1442,11 @@ Session::resort_routes_using (shared_ptr<RouteList> r)
        
        for (i = r->begin(); i != r->end(); ++i) {
                trace_terminal (*i, *i);
-       }       
-
+       }
+       
        RouteSorter cmp;
        r->sort (cmp);
        
-       /* don't leave dangling references to routes in Route::fed_by */
-
-       for (i = r->begin(); i != r->end(); ++i) {
-               (*i)->fed_by.clear ();
-       }
-
 #if 0
        cerr << "finished route resort\n";
        
@@ -1616,33 +1458,35 @@ Session::resort_routes_using (shared_ptr<RouteList> r)
        
 }
 
-list<boost::shared_ptr<AudioTrack> >
-Session::new_audio_track (int input_channels, int output_channels, TrackMode mode, uint32_t how_many)
+list<boost::shared_ptr<MidiTrack> >
+Session::new_midi_track (TrackMode mode, uint32_t how_many)
 {
        char track_name[32];
        uint32_t track_id = 0;
        uint32_t n = 0;
-       uint32_t channels_used = 0;
        string port;
        RouteList new_routes;
-       list<boost::shared_ptr<AudioTrack> > ret;
-       uint32_t control_id;
+       list<boost::shared_ptr<MidiTrack> > ret;
+       //uint32_t control_id;
 
-       /* count existing audio tracks */
+       // FIXME: need physical I/O and autoconnect stuff for MIDI
+       
+       /* count existing midi tracks */
 
        {
                shared_ptr<RouteList> r = routes.reader ();
 
                for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
-                       if (dynamic_cast<AudioTrack*>((*i).get()) != 0) {
-                               if (!(*i)->hidden()) {
+                       if (dynamic_cast<MidiTrack*>((*i).get()) != 0) {
+                               if (!(*i)->is_hidden()) {
                                        n++;
-                                       channels_used += (*i)->n_inputs();
+                                       //channels_used += (*i)->n_inputs().n_midi();
                                }
                        }
                }
        }
 
+       /*
        vector<string> physinputs;
        vector<string> physoutputs;
        uint32_t nphysical_in;
@@ -1651,6 +1495,7 @@ Session::new_audio_track (int input_channels, int output_channels, TrackMode mod
        _engine.get_physical_outputs (physoutputs);
        _engine.get_physical_inputs (physinputs);
        control_id = ntracks() + nbusses() + 1;
+       */
 
        while (how_many) {
 
@@ -1664,7 +1509,7 @@ Session::new_audio_track (int input_channels, int output_channels, TrackMode mod
                do {
                        ++track_id;
 
-                       snprintf (track_name, sizeof(track_name), "Audio %" PRIu32, track_id);
+                       snprintf (track_name, sizeof(track_name), "Midi %" PRIu32, track_id);
 
                        if (route_by_name (track_name) == 0) {
                                break;
@@ -1672,6 +1517,7 @@ Session::new_audio_track (int input_channels, int output_channels, TrackMode mod
                        
                } while (track_id < (UINT_MAX-1));
 
+               /*
                if (Config->get_input_auto_connect() & AutoConnectPhysical) {
                        nphysical_in = min (n_physical_inputs, (uint32_t) physinputs.size());
                } else {
@@ -1683,18 +1529,21 @@ Session::new_audio_track (int input_channels, int output_channels, TrackMode mod
                } else {
                        nphysical_out = 0;
                }
+               */
+
+               shared_ptr<MidiTrack> track;
                
                try {
-                       shared_ptr<AudioTrack> track (new AudioTrack (*this, track_name, Route::Flag (0), mode));
+                       track = boost::shared_ptr<MidiTrack>((new MidiTrack (*this, track_name, Route::Flag (0), mode)));
                        
-                       if (track->ensure_io (input_channels, output_channels, false, this)) {
-                               error << string_compose (_("cannot configure %1 in/%2 out configuration for new audio track"),
-                                                        input_channels, output_channels)
-                                     << endmsg;
+                       if (track->ensure_io (ChanCount(DataType::MIDI, 1), ChanCount(DataType::AUDIO, 1), false, this)) {
+                               error << "cannot configure 1 in/1 out configuration for new midi track" << endmsg;
+                               goto failed;
                        }
-                       
+
+                       /*
                        if (nphysical_in) {
-                               for (uint32_t x = 0; x < track->n_inputs() && x < nphysical_in; ++x) {
+                               for (uint32_t x = 0; x < track->n_inputs().n_midi() && x < nphysical_in; ++x) {
                                        
                                        port = "";
                                        
@@ -1708,7 +1557,7 @@ Session::new_audio_track (int input_channels, int output_channels, TrackMode mod
                                }
                        }
                        
-                       for (uint32_t x = 0; x < track->n_outputs(); ++x) {
+                       for (uint32_t x = 0; x < track->n_outputs().n_midi(); ++x) {
                                
                                port = "";
                                
@@ -1716,7 +1565,7 @@ Session::new_audio_track (int input_channels, int output_channels, TrackMode mod
                                        port = physoutputs[(channels_used+x)%nphysical_out];
                                } else if (Config->get_output_auto_connect() & AutoConnectMaster) {
                                        if (_master_out) {
-                                               port = _master_out->input (x%_master_out->n_inputs())->name();
+                                               port = _master_out->input (x%_master_out->n_inputs().n_midi())->name();
                                        }
                                }
                                
@@ -1725,41 +1574,58 @@ Session::new_audio_track (int input_channels, int output_channels, TrackMode mod
                                }
                        }
                        
-                       channels_used += track->n_inputs ();
+                       channels_used += track->n_inputs ().n_midi();
 
-                       if (_control_out) {
-                               vector<string> cports;
-                               uint32_t ni = _control_out->n_inputs();
-                               
-                               for (n = 0; n < ni; ++n) {
-                                       cports.push_back (_control_out->input(n)->name());
-                               }
-                               
-                               track->set_control_outs (cports);
-                       }
+                       */
 
-                       // assert (current_thread != RT_thread)
-                       
-                       track->audio_diskstream()->non_realtime_input_change();
+                       track->midi_diskstream()->non_realtime_input_change();
                        
                        track->DiskstreamChanged.connect (mem_fun (this, &Session::resort_routes));
-                       track->set_remote_control_id (control_id);
-                       ++control_id;
+                       //track->set_remote_control_id (control_id);
 
                        new_routes.push_back (track);
                        ret.push_back (track);
                }
 
                catch (failed_constructor &err) {
-                       error << _("Session: could not create new audio track.") << endmsg;
-                       // XXX should we delete the tracks already created? 
-                       ret.clear ();
-                       return ret;
+                       error << _("Session: could not create new midi track.") << endmsg;
+
+                       if (track) {
+                               /* we need to get rid of this, since the track failed to be created */
+                               /* XXX arguably, AudioTrack::AudioTrack should not do the Session::add_diskstream() */
+
+                               { 
+                                       RCUWriter<DiskstreamList> writer (diskstreams);
+                                       boost::shared_ptr<DiskstreamList> ds = writer.get_copy();
+                                       ds->remove (track->midi_diskstream());
+                               }
+                       }
+
+                       goto failed;
                }
-               
+
+               catch (AudioEngine::PortRegistrationFailure& pfe) {
+
+                       error << _("No more JACK ports are available. You will need to stop Ardour and restart JACK with ports if you need this many tracks.") << endmsg;
+
+                       if (track) {
+                               /* we need to get rid of this, since the track failed to be created */
+                               /* XXX arguably, MidiTrack::MidiTrack should not do the Session::add_diskstream() */
+
+                               { 
+                                       RCUWriter<DiskstreamList> writer (diskstreams);
+                                       boost::shared_ptr<DiskstreamList> ds = writer.get_copy();
+                                       ds->remove (track->midi_diskstream());
+                               }
+                       }
+
+                       goto failed;
+               }
+
                --how_many;
        }
 
+  failed:
        if (!new_routes.empty()) {
                add_routes (new_routes, false);
                save_state (_current_snapshot_name);
@@ -1768,46 +1634,28 @@ Session::new_audio_track (int input_channels, int output_channels, TrackMode mod
        return ret;
 }
 
-void
-Session::set_remote_control_ids ()
-{
-       RemoteModel m = Config->get_remote_model();
-
-       shared_ptr<RouteList> r = routes.reader ();
-
-       for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
-               if ( MixerOrdered == m) {                       
-                       long order = (*i)->order_key(N_("signal"));
-                       (*i)->set_remote_control_id( order+1 );
-               } else if ( EditorOrdered == m) {
-                       long order = (*i)->order_key(N_("editor"));
-                       (*i)->set_remote_control_id( order+1 );
-               } else if ( UserOrdered == m) {
-                       //do nothing ... only changes to remote id's are initiated by user 
-               }
-       }
-}
-
-
-Session::RouteList
-Session::new_audio_route (int input_channels, int output_channels, uint32_t how_many)
+list<boost::shared_ptr<AudioTrack> >
+Session::new_audio_track (int input_channels, int output_channels, TrackMode mode, uint32_t how_many)
 {
-       char bus_name[32];
-       uint32_t bus_id = 1;
+       char track_name[32];
+       uint32_t track_id = 0;
        uint32_t n = 0;
+       uint32_t channels_used = 0;
        string port;
-       RouteList ret;
+       RouteList new_routes;
+       list<boost::shared_ptr<AudioTrack> > ret;
        uint32_t control_id;
 
-       /* count existing audio busses */
+       /* count existing audio tracks */
 
        {
                shared_ptr<RouteList> r = routes.reader ();
 
                for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
-                       if (dynamic_cast<AudioTrack*>((*i).get()) == 0) {
-                               if (!(*i)->hidden()) {
-                                       bus_id++;
+                       if (dynamic_cast<AudioTrack*>((*i).get()) != 0) {
+                               if (!(*i)->is_hidden()) {
+                                       n++;
+                                       channels_used += (*i)->n_inputs().n_audio();
                                }
                        }
                }
@@ -1815,6 +1663,8 @@ Session::new_audio_route (int input_channels, int output_channels, uint32_t how_
 
        vector<string> physinputs;
        vector<string> physoutputs;
+       uint32_t nphysical_in;
+       uint32_t nphysical_out;
 
        _engine.get_physical_outputs (physoutputs);
        _engine.get_physical_inputs (physinputs);
@@ -1822,11 +1672,197 @@ Session::new_audio_route (int input_channels, int output_channels, uint32_t how_
 
        while (how_many) {
 
-               do {
-                       ++bus_id;
-
-                       snprintf (bus_name, sizeof(bus_name), "Bus %" PRIu32, bus_id);
-
+               /* check for duplicate route names, since we might have pre-existing
+                  routes with this name (e.g. create Audio1, Audio2, delete Audio1,
+                  save, close,restart,add new route - first named route is now
+                  Audio2)
+               */
+               
+
+               do {
+                       ++track_id;
+
+                       snprintf (track_name, sizeof(track_name), "Audio %" PRIu32, track_id);
+
+                       if (route_by_name (track_name) == 0) {
+                               break;
+                       }
+                       
+               } while (track_id < (UINT_MAX-1));
+
+               if (Config->get_input_auto_connect() & AutoConnectPhysical) {
+                       nphysical_in = min (n_physical_inputs, (uint32_t) physinputs.size());
+               } else {
+                       nphysical_in = 0;
+               }
+               
+               if (Config->get_output_auto_connect() & AutoConnectPhysical) {
+                       nphysical_out = min (n_physical_outputs, (uint32_t) physinputs.size());
+               } else {
+                       nphysical_out = 0;
+               }
+
+               shared_ptr<AudioTrack> track;
+               
+               try {
+                       track = boost::shared_ptr<AudioTrack>((new AudioTrack (*this, track_name, Route::Flag (0), mode)));
+                       
+                       if (track->ensure_io (ChanCount(DataType::AUDIO, input_channels), ChanCount(DataType::AUDIO, output_channels), false, this)) {
+                               error << string_compose (_("cannot configure %1 in/%2 out configuration for new audio track"),
+                                                        input_channels, output_channels)
+                                     << endmsg;
+                               goto failed;
+                       }
+
+                       if (nphysical_in) {
+                               for (uint32_t x = 0; x < track->n_inputs().n_audio() && x < nphysical_in; ++x) {
+                                       
+                                       port = "";
+                                       
+                                       if (Config->get_input_auto_connect() & AutoConnectPhysical) {
+                                               port = physinputs[(channels_used+x)%nphysical_in];
+                                       } 
+                                       
+                                       if (port.length() && track->connect_input (track->input (x), port, this)) {
+                                               break;
+                                       }
+                               }
+                       }
+                       
+                       for (uint32_t x = 0; x < track->n_outputs().n_midi(); ++x) {
+                               
+                               port = "";
+                               
+                               if (nphysical_out && (Config->get_output_auto_connect() & AutoConnectPhysical)) {
+                                       port = physoutputs[(channels_used+x)%nphysical_out];
+                               } else if (Config->get_output_auto_connect() & AutoConnectMaster) {
+                                       if (_master_out) {
+                                               port = _master_out->input (x%_master_out->n_inputs().n_audio())->name();
+                                       }
+                               }
+                               
+                               if (port.length() && track->connect_output (track->output (x), port, this)) {
+                                       break;
+                               }
+                       }
+                       
+                       channels_used += track->n_inputs ().n_audio();
+
+                       track->audio_diskstream()->non_realtime_input_change();
+                       
+                       track->DiskstreamChanged.connect (mem_fun (this, &Session::resort_routes));
+                       track->set_remote_control_id (control_id);
+                       ++control_id;
+
+                       new_routes.push_back (track);
+                       ret.push_back (track);
+               }
+
+               catch (failed_constructor &err) {
+                       error << _("Session: could not create new audio track.") << endmsg;
+
+                       if (track) {
+                               /* we need to get rid of this, since the track failed to be created */
+                               /* XXX arguably, AudioTrack::AudioTrack should not do the Session::add_diskstream() */
+
+                               { 
+                                       RCUWriter<DiskstreamList> writer (diskstreams);
+                                       boost::shared_ptr<DiskstreamList> ds = writer.get_copy();
+                                       ds->remove (track->audio_diskstream());
+                               }
+                       }
+
+                       goto failed;
+               }
+
+               catch (AudioEngine::PortRegistrationFailure& pfe) {
+
+                       error << _("No more JACK ports are available. You will need to stop Ardour and restart JACK with ports if you need this many tracks.") << endmsg;
+
+                       if (track) {
+                               /* we need to get rid of this, since the track failed to be created */
+                               /* XXX arguably, AudioTrack::AudioTrack should not do the Session::add_diskstream() */
+
+                               { 
+                                       RCUWriter<DiskstreamList> writer (diskstreams);
+                                       boost::shared_ptr<DiskstreamList> ds = writer.get_copy();
+                                       ds->remove (track->audio_diskstream());
+                               }
+                       }
+
+                       goto failed;
+               }
+
+               --how_many;
+       }
+
+  failed:
+       if (!new_routes.empty()) {
+               add_routes (new_routes, true);
+       }
+
+       return ret;
+}
+
+void
+Session::set_remote_control_ids ()
+{
+       RemoteModel m = Config->get_remote_model();
+
+       shared_ptr<RouteList> r = routes.reader ();
+
+       for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
+               if ( MixerOrdered == m) {                       
+                       long order = (*i)->order_key(N_("signal"));
+                       (*i)->set_remote_control_id( order+1 );
+               } else if ( EditorOrdered == m) {
+                       long order = (*i)->order_key(N_("editor"));
+                       (*i)->set_remote_control_id( order+1 );
+               } else if ( UserOrdered == m) {
+                       //do nothing ... only changes to remote id's are initiated by user 
+               }
+       }
+}
+
+
+Session::RouteList
+Session::new_audio_route (int input_channels, int output_channels, uint32_t how_many)
+{
+       char bus_name[32];
+       uint32_t bus_id = 1;
+       uint32_t n = 0;
+       string port;
+       RouteList ret;
+       uint32_t control_id;
+
+       /* count existing audio busses */
+
+       {
+               shared_ptr<RouteList> r = routes.reader ();
+
+               for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
+                       if (dynamic_cast<AudioTrack*>((*i).get()) == 0) {
+                               if (!(*i)->is_hidden() && (*i)->name() != _("master")) {
+                                       bus_id++;
+                               }
+                       }
+               }
+       }
+
+       vector<string> physinputs;
+       vector<string> physoutputs;
+
+       _engine.get_physical_outputs (physoutputs);
+       _engine.get_physical_inputs (physinputs);
+       control_id = ntracks() + nbusses() + 1;
+
+       while (how_many) {
+
+               do {
+                       snprintf (bus_name, sizeof(bus_name), "Bus %" PRIu32, bus_id);
+
+                       bus_id++;
+
                        if (route_by_name (bus_name) == 0) {
                                break;
                        }
@@ -1836,13 +1872,14 @@ Session::new_audio_route (int input_channels, int output_channels, uint32_t how_
                try {
                        shared_ptr<Route> bus (new Route (*this, bus_name, -1, -1, -1, -1, Route::Flag(0), DataType::AUDIO));
                        
-                       if (bus->ensure_io (input_channels, output_channels, false, this)) {
+                       if (bus->ensure_io (ChanCount(DataType::AUDIO, input_channels), ChanCount(DataType::AUDIO, output_channels), false, this)) {
                                error << string_compose (_("cannot configure %1 in/%2 out configuration for new audio track"),
                                                         input_channels, output_channels)
                                      << endmsg;
+                               goto failure;
                        }
                        
-                       for (uint32_t x = 0; n_physical_inputs && x < bus->n_inputs(); ++x) {
+                       for (uint32_t x = 0; n_physical_inputs && x < bus->n_inputs().n_audio(); ++x) {
                                
                                port = "";
 
@@ -1855,7 +1892,7 @@ Session::new_audio_route (int input_channels, int output_channels, uint32_t how_
                                }
                        }
                        
-                       for (uint32_t x = 0; n_physical_outputs && x < bus->n_outputs(); ++x) {
+                       for (uint32_t x = 0; n_physical_outputs && x < bus->n_outputs().n_audio(); ++x) {
                                
                                port = "";
                                
@@ -1863,7 +1900,7 @@ Session::new_audio_route (int input_channels, int output_channels, uint32_t how_
                                        port = physoutputs[((n+x)%n_physical_outputs)];
                                } else if (Config->get_output_auto_connect() & AutoConnectMaster) {
                                        if (_master_out) {
-                                               port = _master_out->input (x%_master_out->n_inputs())->name();
+                                               port = _master_out->input (x%_master_out->n_inputs().n_audio())->name();
                                        }
                                }
                                
@@ -1872,16 +1909,6 @@ Session::new_audio_route (int input_channels, int output_channels, uint32_t how_
                                }
                        }
                        
-                       if (_control_out) {
-                               vector<string> cports;
-                               uint32_t ni = _control_out->n_inputs();
-                               
-                               for (uint32_t n = 0; n < ni; ++n) {
-                                       cports.push_back (_control_out->input(n)->name());
-                               }
-                               bus->set_control_outs (cports);
-                       }
-
                        bus->set_remote_control_id (control_id);
                        ++control_id;
 
@@ -1891,16 +1918,21 @@ Session::new_audio_route (int input_channels, int output_channels, uint32_t how_
 
                catch (failed_constructor &err) {
                        error << _("Session: could not create new audio route.") << endmsg;
-                       ret.clear ();
-                       return ret;
+                       goto failure;
+               }
+
+               catch (AudioEngine::PortRegistrationFailure& pfe) {
+                       error << _("No more JACK ports are available. You will need to stop Ardour and restart JACK with ports if you need this many tracks.") << endmsg;
+                       goto failure;
                }
 
+
                --how_many;
        }
 
+  failure:
        if (!ret.empty()) {
-               add_routes (ret, false);
-               save_state (_current_snapshot_name);
+               add_routes (ret, true);
        }
 
        return ret;
@@ -1924,17 +1956,34 @@ Session::add_routes (RouteList& new_routes, bool save)
                (*x)->solo_changed.connect (sigc::bind (mem_fun (*this, &Session::route_solo_changed), wpr));
                (*x)->mute_changed.connect (mem_fun (*this, &Session::route_mute_changed));
                (*x)->output_changed.connect (mem_fun (*this, &Session::set_worst_io_latencies_x));
-               (*x)->redirects_changed.connect (mem_fun (*this, &Session::update_latency_compensation_proxy));
+               (*x)->processors_changed.connect (bind (mem_fun (*this, &Session::update_latency_compensation), false, false));
                
-               if ((*x)->master()) {
+               if ((*x)->is_master()) {
                        _master_out = (*x);
                }
                
-               if ((*x)->control()) {
+               if ((*x)->is_control()) {
                        _control_out = (*x);
                }
+
+               add_bundle ((*x)->bundle_for_inputs());
+               add_bundle ((*x)->bundle_for_outputs());
        }
 
+       if (_control_out && IO::connecting_legal) {
+
+               vector<string> cports;
+               uint32_t ni = _control_out->n_inputs().n_audio();
+
+               for (uint32_t n = 0; n < ni; ++n) {
+                       cports.push_back (_control_out->input(n)->name());
+               }
+
+               for (RouteList::iterator x = new_routes.begin(); x != new_routes.end(); ++x) {
+                       (*x)->set_control_outs (cports);
+               }
+       } 
+
        set_dirty();
 
        if (save) {
@@ -1948,21 +1997,23 @@ void
 Session::add_diskstream (boost::shared_ptr<Diskstream> dstream)
 {
        /* need to do this in case we're rolling at the time, to prevent false underruns */
-       dstream->do_refill_with_alloc();
+       dstream->do_refill_with_alloc ();
        
-       { 
+       dstream->set_block_size (current_block_size);
+
+       {
                RCUWriter<DiskstreamList> writer (diskstreams);
                boost::shared_ptr<DiskstreamList> ds = writer.get_copy();
                ds->push_back (dstream);
-       }
-
-       dstream->set_block_size (current_block_size);
+               /* writer goes out of scope, copies ds back to main */
+       } 
 
        dstream->PlaylistChanged.connect (sigc::bind (mem_fun (*this, &Session::diskstream_playlist_changed), dstream));
        /* this will connect to future changes, and check the current length */
        diskstream_playlist_changed (dstream);
 
        dstream->prepare ();
+
 }
 
 void
@@ -2000,12 +2051,11 @@ Session::remove_route (shared_ptr<Route> route)
                /* writer goes out of scope, forces route list update */
        }
 
-       // FIXME: audio specific
-       AudioTrack* at;
-       boost::shared_ptr<AudioDiskstream> ds;
+       Track* t;
+       boost::shared_ptr<Diskstream> ds;
        
-       if ((at = dynamic_cast<AudioTrack*>(route.get())) != 0) {
-               ds = at->audio_diskstream();
+       if ((t = dynamic_cast<Track*>(route.get())) != 0) {
+               ds = t->diskstream();
        }
        
        if (ds) {
@@ -2019,13 +2069,14 @@ Session::remove_route (shared_ptr<Route> route)
 
        find_current_end ();
        
+       // We need to disconnect the routes inputs and outputs 
+
+       route->disconnect_inputs (0);
+       route->disconnect_outputs (0);
+       
        update_latency_compensation (false, false);
        set_dirty();
 
-       // We need to disconnect the routes inputs and outputs 
-       route->disconnect_inputs(NULL);
-       route->disconnect_outputs(NULL);
-       
        /* get rid of it from the dead wood collection in the route list manager */
 
        /* XXX i think this is unsafe as it currently stands, but i am not sure. (pd, october 2nd, 2006) */
@@ -2078,7 +2129,7 @@ Session::route_solo_changed (void* src, boost::weak_ptr<Route> wpr)
                        
                        /* don't mess with busses */
                        
-                       if (dynamic_cast<AudioTrack*>((*i).get()) == 0) {
+                       if (dynamic_cast<Track*>((*i).get()) == 0) {
                                continue;
                        }
                        
@@ -2086,7 +2137,7 @@ Session::route_solo_changed (void* src, boost::weak_ptr<Route> wpr)
                        
                        /* don't mess with tracks */
                        
-                       if (dynamic_cast<AudioTrack*>((*i).get()) != 0) {
+                       if (dynamic_cast<Track*>((*i).get()) != 0) {
                                continue;
                        }
                }
@@ -2122,7 +2173,7 @@ Session::route_solo_changed (void* src, boost::weak_ptr<Route> wpr)
         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
                if ((*i)->soloed()) {
                        something_soloed = true;
-                       if (dynamic_cast<AudioTrack*>((*i).get())) {
+                       if (dynamic_cast<Track*>((*i).get())) {
                                if (is_track) {
                                        same_thing_soloed = true;
                                        break;
@@ -2168,10 +2219,10 @@ Session::update_route_solo_state ()
        
        shared_ptr<RouteList> r = routes.reader ();
 
-        for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
+       for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
                if ((*i)->soloed()) {
                        mute = true;
-                       if (dynamic_cast<AudioTrack*>((*i).get())) {
+                       if (dynamic_cast<Track*>((*i).get())) {
                                is_track = true;
                        }
                        break;
@@ -2216,7 +2267,7 @@ Session::modify_solo_mute (bool is_track, bool mute)
                        
                        /* only alter track solo mute */
                        
-                       if (dynamic_cast<AudioTrack*>((*i).get())) {
+                       if (dynamic_cast<Track*>((*i).get())) {
                                if ((*i)->soloed()) {
                                        (*i)->set_solo_mute (!mute);
                                } else {
@@ -2228,7 +2279,7 @@ Session::modify_solo_mute (bool is_track, bool mute)
 
                        /* only alter bus solo mute */
 
-                       if (!dynamic_cast<AudioTrack*>((*i).get())) {
+                       if (!dynamic_cast<Track*>((*i).get())) {
 
                                if ((*i)->soloed()) {
 
@@ -2367,7 +2418,7 @@ Session::diskstream_by_id (const PBD::ID& id)
        return boost::shared_ptr<Diskstream>((Diskstream*) 0);
 }
 
-/* AudioRegion management */
+/* Region management */
 
 string
 Session::new_region_name (string old)
@@ -2393,7 +2444,7 @@ Session::new_region_name (string old)
 
        while (number < (UINT_MAX-1)) {
 
-               AudioRegionList::const_iterator i;
+               RegionList::const_iterator i;
                string sbuf;
 
                number++;
@@ -2401,13 +2452,13 @@ Session::new_region_name (string old)
                snprintf (buf, len, "%s%" PRIu32, old.substr (0, last_period + 1).c_str(), number);
                sbuf = buf;
 
-               for (i = audio_regions.begin(); i != audio_regions.end(); ++i) {
+               for (i = regions.begin(); i != regions.end(); ++i) {
                        if (i->second->name() == sbuf) {
                                break;
                        }
                }
                
-               if (i == audio_regions.end()) {
+               if (i == regions.end()) {
                        break;
                }
        }
@@ -2426,11 +2477,13 @@ Session::region_name (string& result, string base, bool newlevel) const
        char buf[16];
        string subbase;
 
+       assert(base.find("/") == string::npos);
+
        if (base == "") {
                
                Glib::Mutex::Lock lm (region_lock);
 
-               snprintf (buf, sizeof (buf), "%d", (int)audio_regions.size() + 1);
+               snprintf (buf, sizeof (buf), "%d", (int)regions.size() + 1);
 
                
                result = "region.";
@@ -2466,7 +2519,7 @@ Session::region_name (string& result, string base, bool newlevel) const
                                
                                name_taken = false;
                                
-                               for (AudioRegionList::const_iterator i = audio_regions.begin(); i != audio_regions.end(); ++i) {
+                               for (RegionList::const_iterator i = regions.begin(); i != regions.end(); ++i) {
                                        if (i->second->name() == result) {
                                                name_taken = true;
                                                break;
@@ -2490,51 +2543,40 @@ Session::region_name (string& result, string base, bool newlevel) const
 void
 Session::add_region (boost::shared_ptr<Region> region)
 {
-       boost::shared_ptr<AudioRegion> ar;
-       boost::shared_ptr<AudioRegion> oar;
+       boost::shared_ptr<Region> other;
        bool added = false;
 
        { 
                Glib::Mutex::Lock lm (region_lock);
 
-               if ((ar = boost::dynamic_pointer_cast<AudioRegion> (region)) != 0) {
-
-                       AudioRegionList::iterator x;
+               RegionList::iterator x;
 
-                       for (x = audio_regions.begin(); x != audio_regions.end(); ++x) {
+               for (x = regions.begin(); x != regions.end(); ++x) {
 
-                               oar = boost::dynamic_pointer_cast<AudioRegion> (x->second);
+                       other = x->second;
 
-                               if (ar->region_list_equivalent (oar)) {
-                                       break;
-                               }
+                       if (region->region_list_equivalent (other)) {
+                               break;
                        }
+               }
 
-                       if (x == audio_regions.end()) {
-
-                               pair<AudioRegionList::key_type,AudioRegionList::mapped_type> entry;
+               if (x == regions.end()) {
 
-                               entry.first = region->id();
-                               entry.second = ar;
+                       pair<RegionList::key_type,RegionList::mapped_type> entry;
 
-                               pair<AudioRegionList::iterator,bool> x = audio_regions.insert (entry);
+                       entry.first = region->id();
+                       entry.second = region;
 
-                               
-                               if (!x.second) {
-                                       return;
-                               }
+                       pair<RegionList::iterator,bool> x = regions.insert (entry);
 
-                               added = true;
-                       } 
 
-               } else {
+                       if (!x.second) {
+                               return;
+                       }
 
-                       fatal << _("programming error: ")
-                             << X_("unknown region type passed to Session::add_region()")
-                             << endmsg;
-                       /*NOTREACHED*/
+                       added = true;
+               } 
 
-               }
        }
 
        /* mark dirty because something has changed even if we didn't
@@ -2546,7 +2588,7 @@ Session::add_region (boost::shared_ptr<Region> region)
        if (added) {
                region->GoingAway.connect (sigc::bind (mem_fun (*this, &Session::remove_region), boost::weak_ptr<Region>(region)));
                region->StateChanged.connect (sigc::bind (mem_fun (*this, &Session::region_changed), boost::weak_ptr<Region>(region)));
-               AudioRegionAdded (ar); /* EMIT SIGNAL */
+               RegionAdded (region); /* EMIT SIGNAL */
        }
 }
 
@@ -2568,31 +2610,21 @@ Session::region_changed (Change what_changed, boost::weak_ptr<Region> weak_regio
 void
 Session::remove_region (boost::weak_ptr<Region> weak_region)
 {
-       AudioRegionList::iterator i;
+       RegionList::iterator i;
        boost::shared_ptr<Region> region (weak_region.lock ());
 
        if (!region) {
                return;
        }
 
-       boost::shared_ptr<AudioRegion> ar;
        bool removed = false;
 
        { 
                Glib::Mutex::Lock lm (region_lock);
 
-               if ((ar = boost::dynamic_pointer_cast<AudioRegion> (region)) != 0) {
-                       if ((i = audio_regions.find (region->id())) != audio_regions.end()) {
-                               audio_regions.erase (i);
-                               removed = true;
-                       }
-
-               } else {
-
-                       fatal << _("programming error: ") 
-                             << X_("unknown region type passed to Session::remove_region()")
-                             << endmsg;
-                       /*NOTREACHED*/
+               if ((i = regions.find (region->id())) != regions.end()) {
+                       regions.erase (i);
+                       removed = true;
                }
        }
 
@@ -2603,18 +2635,19 @@ Session::remove_region (boost::weak_ptr<Region> weak_region)
        set_dirty();
 
        if (removed) {
-               AudioRegionRemoved (ar); /* EMIT SIGNAL */
+                RegionRemoved(region); /* EMIT SIGNAL */
        }
 }
 
-boost::shared_ptr<AudioRegion>
-Session::find_whole_file_parent (boost::shared_ptr<AudioRegion const> child)
+boost::shared_ptr<Region>
+Session::find_whole_file_parent (boost::shared_ptr<Region const> child)
 {
-       AudioRegionList::iterator i;
-       boost::shared_ptr<AudioRegion> region;
+       RegionList::iterator i;
+       boost::shared_ptr<Region> region;
+       
        Glib::Mutex::Lock lm (region_lock);
 
-       for (i = audio_regions.begin(); i != audio_regions.end(); ++i) {
+       for (i = regions.begin(); i != regions.end(); ++i) {
 
                region = i->second;
 
@@ -2626,7 +2659,7 @@ Session::find_whole_file_parent (boost::shared_ptr<AudioRegion const> child)
                }
        } 
 
-       return boost::shared_ptr<AudioRegion> ();
+       return boost::shared_ptr<Region> ();
 }      
 
 void
@@ -2703,6 +2736,9 @@ Session::remove_last_capture ()
        }
 
        destroy_regions (r);
+
+       save_state (_current_snapshot_name);
+
        return 0;
 }
 
@@ -2714,37 +2750,30 @@ Session::remove_region_from_region_list (boost::shared_ptr<Region> r)
 }
 
 /* Source Management */
-
 void
 Session::add_source (boost::shared_ptr<Source> source)
 {
-       boost::shared_ptr<AudioFileSource> afs;
-
-       if ((afs = boost::dynamic_pointer_cast<AudioFileSource>(source)) != 0) {
+       pair<SourceMap::key_type, SourceMap::mapped_type> entry;
+       pair<SourceMap::iterator,bool> result;
 
-               pair<AudioSourceList::key_type, AudioSourceList::mapped_type> entry;
-               pair<AudioSourceList::iterator,bool> result;
-
-               entry.first = source->id();
-               entry.second = afs;
-               
-               {
-                       Glib::Mutex::Lock lm (audio_source_lock);
-                       result = audio_sources.insert (entry);
-               }
-
-               if (result.second) {
-                       source->GoingAway.connect (sigc::bind (mem_fun (this, &Session::remove_source), boost::weak_ptr<Source> (source)));
-                       set_dirty();
-               }
+       entry.first = source->id();
+       entry.second = source;
+       
+       {
+               Glib::Mutex::Lock lm (source_lock);
+               result = sources.insert (entry);
+       }
 
-       } 
+       if (result.second) {
+               source->GoingAway.connect (sigc::bind (mem_fun (this, &Session::remove_source), boost::weak_ptr<Source> (source)));
+               set_dirty();
+       }
 }
 
 void
 Session::remove_source (boost::weak_ptr<Source> src)
 {
-       AudioSourceList::iterator i;
+       SourceMap::iterator i;
        boost::shared_ptr<Source> source = src.lock();
 
        if (!source) {
@@ -2752,10 +2781,10 @@ Session::remove_source (boost::weak_ptr<Source> src)
        } 
 
        { 
-               Glib::Mutex::Lock lm (audio_source_lock);
-               
-               if ((i = audio_sources.find (source->id())) != audio_sources.end()) {
-                       audio_sources.erase (i);
+               Glib::Mutex::Lock lm (source_lock);
+
+               if ((i = sources.find (source->id())) != sources.end()) {
+                       sources.erase (i);
                } 
        }
        
@@ -2772,29 +2801,41 @@ Session::remove_source (boost::weak_ptr<Source> src)
 boost::shared_ptr<Source>
 Session::source_by_id (const PBD::ID& id)
 {
-       Glib::Mutex::Lock lm (audio_source_lock);
-       AudioSourceList::iterator i;
+       Glib::Mutex::Lock lm (source_lock);
+       SourceMap::iterator i;
        boost::shared_ptr<Source> source;
 
-       if ((i = audio_sources.find (id)) != audio_sources.end()) {
+       if ((i = sources.find (id)) != sources.end()) {
                source = i->second;
        }
 
-       /* XXX search MIDI or other searches here */
-       
        return source;
 }
 
-string
-Session::peak_path_from_audio_path (string audio_path) const
+
+boost::shared_ptr<Source>
+Session::source_by_path_and_channel (const Glib::ustring& path, uint16_t chn)
 {
-       string res;
+       Glib::Mutex::Lock lm (source_lock);
+
+       for (SourceMap::iterator i = sources.begin(); i != sources.end(); ++i) {
+               cerr << "comparing " << path << " with " << i->second->name() << endl;
+               boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(i->second);
 
-       res = peak_dir ();
-       res += PBD::basename_nosuffix (audio_path);
-       res += ".peak";
+               if (afs && afs->path() == path && chn == afs->channel()) {
+                       return afs;
+               } 
+                      
+       }
+       return boost::shared_ptr<Source>();
+}
 
-       return res;
+Glib::ustring
+Session::peak_path (Glib::ustring base) const
+{
+       sys::path peakfile_path(_session_dir->peak_path());
+       peakfile_path /= basename_nosuffix (base) + peakfile_suffix;
+       return peakfile_path.to_string();
 }
 
 string
@@ -2934,9 +2975,9 @@ Session::audio_path_from_name (string name, uint32_t nchan, uint32_t chan, bool
 
                for (i = session_dirs.begin(); i != session_dirs.end(); ++i) {
 
-                       spath = (*i).path;
+                       SessionDirectory sdir((*i).path);
 
-                       spath += sound_dir (false);
+                       spath = sdir.sound_path().to_string();
 
                        if (destructive) {
                                if (nchan < 2) {
@@ -2973,7 +3014,7 @@ Session::audio_path_from_name (string name, uint32_t nchan, uint32_t chan, bool
                                }
                        }
 
-                       if (g_file_test (buf, G_FILE_TEST_EXISTS)) {
+                       if (sys::exists(buf)) {
                                existing++;
                        } 
 
@@ -2996,7 +3037,9 @@ Session::audio_path_from_name (string name, uint32_t nchan, uint32_t chan, bool
 
        string foo = buf;
 
-       spath = discover_best_sound_dir ();
+       SessionDirectory sdir(get_best_session_directory_for_new_source ());
+
+       spath = sdir.sound_path().to_string();
        spath += '/';
 
        string::size_type pos = foo.find_last_of ('/');
@@ -3013,10 +3056,205 @@ Session::audio_path_from_name (string name, uint32_t nchan, uint32_t chan, bool
 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);
-       return boost::dynamic_pointer_cast<AudioFileSource> (SourceFactory::createWritable (*this, spath, destructive, frame_rate()));
+       string spath = audio_path_from_name (ds.name(), ds.n_channels().n_audio(), chan, destructive);
+       return boost::dynamic_pointer_cast<AudioFileSource> (
+               SourceFactory::createWritable (DataType::AUDIO, *this, spath, destructive, frame_rate()));
+}
+
+// FIXME: _terrible_ code duplication
+string
+Session::change_midi_path_by_name (string path, string oldname, string newname, bool destructive)
+{
+       string look_for;
+       string old_basename = PBD::basename_nosuffix (oldname);
+       string new_legalized = legalize_for_path (newname);
+
+       /* note: we know (or assume) the old path is already valid */
+
+       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 += ".mid";  /* 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.
+               */
+               
+               string dir;
+               string suffix;
+               string::size_type slash;
+               string::size_type dash;
+               string::size_type postfix;
+
+               /* find last slash */
+
+               if ((slash = path.find_last_of ('/')) == string::npos) {
+                       return "";
+               }
+
+               dir = path.substr (0, slash+1);
+
+               /* '-' is not a legal character for the NAME part of the path */
+
+               if ((dash = path.find_last_of ('-')) == string::npos) {
+                       return "";
+               }
+
+               suffix = path.substr (dash+1);
+               
+               // Suffix is now everything after the dash. Now we need to eliminate
+               // the nnnnn part, which is done by either finding a '%' or a '.'
+
+               postfix = suffix.find_last_of ("%");
+               if (postfix == string::npos) {
+                       postfix = suffix.find_last_of ('.');
+               }
+
+               if (postfix != string::npos) {
+                       suffix = suffix.substr (postfix);
+               } else {
+                       error << "Logic error in Session::change_midi_path_by_name(), please report to the developers" << endl;
+                       return "";
+               }
+
+               const uint32_t limit = 10000;
+               char buf[PATH_MAX+1];
+
+               for (uint32_t cnt = 1; cnt <= limit; ++cnt) {
+
+                       snprintf (buf, sizeof(buf), "%s%s-%u%s", dir.c_str(), newname.c_str(), cnt, suffix.c_str());
+
+                       if (access (buf, F_OK) != 0) {
+                               path = buf;
+                               break;
+                       }
+                       path = "";
+               }
+
+               if (path == "") {
+                       error << "FATAL ERROR! Could not find a " << endl;
+               }
+
+       }
+
+       return path;
+}
+
+string
+Session::midi_path_from_name (string name)
+{
+       string spath;
+       uint32_t cnt;
+       char buf[PATH_MAX+1];
+       const uint32_t limit = 10000;
+       string legalized;
+
+       buf[0] = '\0';
+       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) {
+
+               vector<space_and_path>::iterator i;
+               uint32_t existing = 0;
+
+               for (i = session_dirs.begin(); i != session_dirs.end(); ++i) {
+
+                       SessionDirectory sdir((*i).path);
+               
+                       sys::path p = sdir.midi_path();
+
+                       p /= legalized;
+
+                       spath = p.to_string();
+
+                       snprintf (buf, sizeof(buf), "%s-%u.mid", spath.c_str(), cnt);
+
+                       if (sys::exists (buf)) {
+                               existing++;
+                       } 
+               }
+
+               if (existing == 0) {
+                       break;
+               }
+
+               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
+          actually put it.
+       */
+
+       string foo = buf;
+
+       SessionDirectory sdir(get_best_session_directory_for_new_source ());
+
+       spath = sdir.midi_path().to_string();
+       spath += '/';
+
+       string::size_type pos = foo.find_last_of ('/');
+       
+       if (pos == string::npos) {
+               spath += foo;
+       } else {
+               spath += foo.substr (pos + 1);
+       }
+
+       return spath;
+}
+       
+boost::shared_ptr<MidiSource>
+Session::create_midi_source_for_session (MidiDiskstream& ds)
+{
+       string mpath = midi_path_from_name (ds.name());
+       
+       return boost::dynamic_pointer_cast<SMFSource> (SourceFactory::createWritable (DataType::MIDI, *this, mpath, false, frame_rate()));
 }
 
+
 /* Playlist management */
 
 boost::shared_ptr<Playlist>
@@ -3200,46 +3438,37 @@ Session::RoutePublicOrderSorter::operator() (boost::shared_ptr<Route> a, boost::
 void
 Session::remove_empty_sounds ()
 {
-       PathScanner scanner;
+       vector<string> audio_filenames;
 
-       vector<string *>* possible_audiofiles = scanner (sound_dir(), "\\.(wav|aiff|caf|w64)$", false, true);
+       get_files_in_directory (_session_dir->sound_path(), audio_filenames);
        
-       Glib::Mutex::Lock lm (audio_source_lock);
-       
-       regex_t compiled_tape_track_pattern;
-       int err;
+       Glib::Mutex::Lock lm (source_lock);
 
-       if ((err = regcomp (&compiled_tape_track_pattern, "/T[0-9][0-9][0-9][0-9]-", REG_EXTENDED|REG_NOSUB))) {
+       TapeFileMatcher tape_file_matcher;
 
-               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;
-       }
+       remove_if (audio_filenames.begin(), audio_filenames.end(),
+                       sigc::mem_fun (tape_file_matcher, &TapeFileMatcher::matches));
 
-       for (vector<string *>::iterator i = possible_audiofiles->begin(); i != possible_audiofiles->end(); ++i) {
-               
-               /* never remove files that appear to be a tape track */
+       for (vector<string>::iterator i = audio_filenames.begin(); i != audio_filenames.end(); ++i) {
 
-               if (regexec (&compiled_tape_track_pattern, (*i)->c_str(), 0, 0, 0) == 0) {
-                       delete *i;
-                       continue;
-               }
-                       
-               if (AudioFileSource::is_empty (*this, *(*i))) {
+               sys::path audio_file_path (_session_dir->sound_path());
 
-                       unlink ((*i)->c_str());
+               audio_file_path /= *i;
                        
-                       string peak_path = peak_path_from_audio_path (**i);
-                       unlink (peak_path.c_str());
-               }
+               if (AudioFileSource::is_empty (*this, audio_file_path.to_string())) {
 
-               delete* i;
+                       try
+                       {
+                               sys::remove (audio_file_path);
+                               const string peakfile = peak_path (audio_file_path.to_string());
+                               sys::remove (peakfile);
+                       }
+                       catch (const sys::filesystem_error& err)
+                       {
+                               error << err.what() << endmsg; 
+                       }
+               }
        }
-
-       delete possible_audiofiles;
 }
 
 bool
@@ -3259,7 +3488,7 @@ Session::set_all_solo (bool yn)
        shared_ptr<RouteList> r = routes.reader ();
        
        for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
-               if (!(*i)->hidden()) {
+               if (!(*i)->is_hidden()) {
                        (*i)->set_solo (yn, this);
                }
        }
@@ -3273,7 +3502,7 @@ Session::set_all_mute (bool yn)
        shared_ptr<RouteList> r = routes.reader ();
        
        for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
-               if (!(*i)->hidden()) {
+               if (!(*i)->is_hidden()) {
                        (*i)->set_mute (yn, this);
                }
        }
@@ -3300,13 +3529,13 @@ void
 Session::graph_reordered ()
 {
        /* don't do this stuff if we are setting up connections
-          from a set_state() call.
+          from a set_state() call or creating new tracks.
        */
 
        if (_state_of_the_state & InitialConnecting) {
                return;
        }
-
+       
        /* every track/bus asked for this to be handled but it was deferred because
           we were connecting. do it now.
        */
@@ -3344,9 +3573,9 @@ Session::record_enable_change_all (bool yn)
        shared_ptr<RouteList> r = routes.reader ();
        
        for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
-               AudioTrack* at;
+               Track* at;
 
-               if ((at = dynamic_cast<AudioTrack*>((*i).get())) != 0) {
+               if ((at = dynamic_cast<Track*>((*i).get())) != 0) {
                        at->set_record_enable (yn, this);
                }
        }
@@ -3355,65 +3584,51 @@ Session::record_enable_change_all (bool yn)
 }
 
 void
-Session::add_redirect (Redirect* redirect)
+Session::add_processor (Processor* processor)
 {
        Send* send;
-       Insert* insert;
        PortInsert* port_insert;
        PluginInsert* plugin_insert;
 
-       if ((insert = dynamic_cast<Insert *> (redirect)) != 0) {
-               if ((port_insert = dynamic_cast<PortInsert *> (insert)) != 0) {
-                       _port_inserts.insert (_port_inserts.begin(), port_insert);
-               } else if ((plugin_insert = dynamic_cast<PluginInsert *> (insert)) != 0) {
-                       _plugin_inserts.insert (_plugin_inserts.begin(), plugin_insert);
-               } else {
-                       fatal << _("programming error: unknown type of Insert created!") << endmsg;
-                       /*NOTREACHED*/
-               }
-       } else if ((send = dynamic_cast<Send *> (redirect)) != 0) {
+       if ((port_insert = dynamic_cast<PortInsert *> (processor)) != 0) {
+               _port_inserts.insert (_port_inserts.begin(), port_insert);
+       } else if ((plugin_insert = dynamic_cast<PluginInsert *> (processor)) != 0) {
+               _plugin_inserts.insert (_plugin_inserts.begin(), plugin_insert);
+       } else if ((send = dynamic_cast<Send *> (processor)) != 0) {
                _sends.insert (_sends.begin(), send);
        } else {
-               fatal << _("programming error: unknown type of Redirect created!") << endmsg;
+               fatal << _("programming error: unknown type of Insert created!") << endmsg;
                /*NOTREACHED*/
        }
 
-       redirect->GoingAway.connect (sigc::bind (mem_fun (*this, &Session::remove_redirect), redirect));
+       processor->GoingAway.connect (sigc::bind (mem_fun (*this, &Session::remove_processor), processor));
 
        set_dirty();
 }
 
 void
-Session::remove_redirect (Redirect* redirect)
+Session::remove_processor (Processor* processor)
 {
        Send* send;
-       Insert* insert;
        PortInsert* port_insert;
        PluginInsert* plugin_insert;
        
-       if ((insert = dynamic_cast<Insert *> (redirect)) != 0) {
-               if ((port_insert = dynamic_cast<PortInsert *> (insert)) != 0) {
-                       list<PortInsert*>::iterator x = find (_port_inserts.begin(), _port_inserts.end(), port_insert);
-                       if (x != _port_inserts.end()) {
-                               insert_bitset[port_insert->bit_slot()] = false;
-                               _port_inserts.erase (x);
-                       }
-               } else if ((plugin_insert = dynamic_cast<PluginInsert *> (insert)) != 0) {
-                       _plugin_inserts.remove (plugin_insert);
-               } else {
-                       fatal << string_compose (_("programming error: %1"),
-                                                X_("unknown type of Insert deleted!")) 
-                             << endmsg;
-                       /*NOTREACHED*/
+       if ((port_insert = dynamic_cast<PortInsert *> (processor)) != 0) {
+               list<PortInsert*>::iterator x = find (_port_inserts.begin(), _port_inserts.end(), port_insert);
+               if (x != _port_inserts.end()) {
+                       insert_bitset[port_insert->bit_slot()] = false;
+                       _port_inserts.erase (x);
                }
-       } else if ((send = dynamic_cast<Send *> (redirect)) != 0) {
+       } else if ((plugin_insert = dynamic_cast<PluginInsert *> (processor)) != 0) {
+               _plugin_inserts.remove (plugin_insert);
+       } else if ((send = dynamic_cast<Send *> (processor)) != 0) {
                list<Send*>::iterator x = find (_sends.begin(), _sends.end(), send);
                if (x != _sends.end()) {
                        send_bitset[send->bit_slot()] = false;
                        _sends.erase (x);
                }
        } else {
-               fatal << _("programming error: unknown type of Redirect deleted!") << endmsg;
+               fatal << _("programming error: unknown type of Insert deleted!") << endmsg;
                /*NOTREACHED*/
        }
 
@@ -3434,6 +3649,10 @@ Session::available_capture_duration ()
                sample_bytes_on_disk = 3.0;
                break;
 
+       case FormatInt16:
+               sample_bytes_on_disk = 2.0;
+               break;
+
        default: 
                /* impossible, but keep some gcc versions happy */
                fatal << string_compose (_("programming error: %1"),
@@ -3452,52 +3671,52 @@ Session::available_capture_duration ()
 }
 
 void
-Session::add_connection (ARDOUR::Connection* connection)
+Session::add_bundle (shared_ptr<Bundle> bundle)
 {
        {
-               Glib::Mutex::Lock guard (connection_lock);
-               _connections.push_back (connection);
+               Glib::Mutex::Lock guard (bundle_lock);
+               _bundles.push_back (bundle);
        }
        
-       ConnectionAdded (connection); /* EMIT SIGNAL */
+       BundleAdded (bundle); /* EMIT SIGNAL */
 
        set_dirty();
 }
 
 void
-Session::remove_connection (ARDOUR::Connection* connection)
+Session::remove_bundle (shared_ptr<Bundle> bundle)
 {
        bool removed = false;
 
        {
-               Glib::Mutex::Lock guard (connection_lock);
-               ConnectionList::iterator i = find (_connections.begin(), _connections.end(), connection);
+               Glib::Mutex::Lock guard (bundle_lock);
+               BundleList::iterator i = find (_bundles.begin(), _bundles.end(), bundle);
                
-               if (i != _connections.end()) {
-                       _connections.erase (i);
+               if (i != _bundles.end()) {
+                       _bundles.erase (i);
                        removed = true;
                }
        }
 
        if (removed) {
-                ConnectionRemoved (connection); /* EMIT SIGNAL */
+                BundleRemoved (bundle); /* EMIT SIGNAL */
        }
 
        set_dirty();
 }
 
-ARDOUR::Connection *
-Session::connection_by_name (string name) const
+shared_ptr<Bundle>
+Session::bundle_by_name (string name) const
 {
-       Glib::Mutex::Lock lm (connection_lock);
+       Glib::Mutex::Lock lm (bundle_lock);
 
-       for (ConnectionList::const_iterator i = _connections.begin(); i != _connections.end(); ++i) {
+       for (BundleList::const_iterator i = _bundles.begin(); i != _bundles.end(); ++i) {
                if ((*i)->name() == name) {
                        return* i;
                }
        }
 
-       return 0;
+       return boost::shared_ptr<Bundle> ();
 }
 
 void
@@ -3507,40 +3726,26 @@ Session::tempo_map_changed (Change ignored)
        set_dirty ();
 }
 
+/** Ensures that all buffers (scratch, send, silent, etc) are allocated for
+ * the given count with the current block size.
+ */
 void
-Session::ensure_passthru_buffers (uint32_t howmany)
+Session::ensure_buffers (ChanCount howmany)
 {
-       while (howmany > _passthru_buffers.size()) {
-               Sample *p;
-#ifdef NO_POSIX_MEMALIGN
-               p =  (Sample *) malloc(current_block_size * sizeof(Sample));
-#else
-               posix_memalign((void **)&p,16,current_block_size * 4);
-#endif                 
-               _passthru_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);
-               _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);
+       if (current_block_size == 0)
+               return; // too early? (is this ok?)
+
+       // We need at least 2 MIDI scratch buffers to mix/merge
+       if (howmany.n_midi() < 2)
+               howmany.set_midi(2);
+
+       // FIXME: JACK needs to tell us maximum MIDI buffer size
+       // Using nasty assumption (max # events == nframes) for now
+       _scratch_buffers->ensure_buffers(howmany, current_block_size);
+       _mix_buffers->ensure_buffers(howmany, current_block_size);
+       _silent_buffers->ensure_buffers(howmany, current_block_size);
+       
+       allocate_pan_automation_buffers (current_block_size, howmany.n_audio(), false);
 }
 
 uint32_t
@@ -3552,7 +3757,6 @@ Session::next_insert_id ()
                for (boost::dynamic_bitset<uint32_t>::size_type n = 0; n < insert_bitset.size(); ++n) {
                        if (!insert_bitset[n]) {
                                insert_bitset[n] = true;
-                               cerr << "Returning " << n << " as insert ID\n";
                                return n;
                                
                        }
@@ -3573,7 +3777,6 @@ Session::next_send_id ()
                for (boost::dynamic_bitset<uint32_t>::size_type n = 0; n < send_bitset.size(); ++n) {
                        if (!send_bitset[n]) {
                                send_bitset[n] = true;
-                               cerr << "Returning " << n << " as send ID\n";
                                return n;
                                
                        }
@@ -3726,9 +3929,9 @@ Session::freeze (InterThreadInfo& itt)
 
        for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
 
-               AudioTrack *at;
+               Track *at;
 
-               if ((at = dynamic_cast<AudioTrack*>((*i).get())) != 0) {
+               if ((at = dynamic_cast<Track*>((*i).get())) != 0) {
                        /* XXX this is wrong because itt.progress will keep returning to zero at the start
                           of every track.
                        */
@@ -3741,19 +3944,20 @@ Session::freeze (InterThreadInfo& itt)
 
 int
 Session::write_one_audio_track (AudioTrack& track, nframes_t start, nframes_t len,     
-                              bool overwrite, vector<boost::shared_ptr<AudioSource> >& srcs, InterThreadInfo& itt)
+                              bool overwrite, vector<boost::shared_ptr<Source> >& srcs, InterThreadInfo& itt)
 {
        int ret = -1;
        boost::shared_ptr<Playlist> playlist;
        boost::shared_ptr<AudioFileSource> fsource;
        uint32_t x;
        char buf[PATH_MAX+1];
-       string dir;
-       uint32_t nchans;
+       ChanCount nchans(track.audio_diskstream()->n_channels());
        nframes_t position;
        nframes_t this_chunk;
        nframes_t to_do;
-       vector<Sample*> buffers;
+       BufferSet buffers;
+       SessionDirectory sdir(get_best_session_directory_for_new_source ());
+       const string sound_dir = sdir.sound_path().to_string();
 
        // any bigger than this seems to cause stack overflows in called functions
        const nframes_t chunk_size = (128 * 1024)/4;
@@ -3772,14 +3976,10 @@ Session::write_one_audio_track (AudioTrack& track, nframes_t start, nframes_t le
                goto out;
        }
 
-       nchans = track.audio_diskstream()->n_channels();
-       
-       dir = discover_best_sound_dir ();
-
-       for (uint32_t chan_n=0; chan_n < nchans; ++chan_n) {
+       for (uint32_t chan_n=0; chan_n < nchans.n_audio(); ++chan_n) {
 
                for (x = 0; x < 99999; ++x) {
-                       snprintf (buf, sizeof(buf), "%s/%s-%d-bounce-%" PRIu32 ".wav", dir.c_str(), playlist->name().c_str(), chan_n, x+1);
+                       snprintf (buf, sizeof(buf), "%s/%s-%d-bounce-%" PRIu32 ".wav", sound_dir.c_str(), playlist->name().c_str(), chan_n, x+1);
                        if (access (buf, F_OK) != 0) {
                                break;
                        }
@@ -3791,7 +3991,8 @@ Session::write_one_audio_track (AudioTrack& track, nframes_t start, nframes_t le
                }
                
                try {
-                       fsource = boost::dynamic_pointer_cast<AudioFileSource> (SourceFactory::createWritable (*this, buf, false, frame_rate()));
+                       fsource = boost::dynamic_pointer_cast<AudioFileSource> (
+                               SourceFactory::createWritable (DataType::AUDIO, *this, buf, false, frame_rate()));
                }
                
                catch (failed_constructor& err) {
@@ -3808,31 +4009,29 @@ Session::write_one_audio_track (AudioTrack& track, nframes_t start, nframes_t le
        to_do = len;
 
        /* create a set of reasonably-sized buffers */
+       buffers.ensure_buffers(nchans, chunk_size);
+       buffers.set_count(nchans);
 
-       for (vector<Sample*>::iterator i = _passthru_buffers.begin(); i != _passthru_buffers.end(); ++i) {
-               Sample* b;
-#ifdef NO_POSIX_MEMALIGN
-               b =  (Sample *) malloc(chunk_size * sizeof(Sample));
-#else
-               posix_memalign((void **)&b,16,chunk_size * 4);
-#endif                 
-               buffers.push_back (b);
+       for (vector<boost::shared_ptr<Source> >::iterator src=srcs.begin(); src != srcs.end(); ++src) {
+               boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
+               if (afs)
+                       afs->prepare_for_peakfile_writes ();
        }
-
+                       
        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, start, this_chunk)) {
                        goto out;
                }
 
                uint32_t n = 0;
-               for (vector<boost::shared_ptr<AudioSource> >::iterator src=srcs.begin(); src != srcs.end(); ++src, ++n) {
+               for (vector<boost::shared_ptr<Source> >::iterator src=srcs.begin(); src != srcs.end(); ++src, ++n) {
                        boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
                        
                        if (afs) {
-                               if (afs->write (buffers[n], this_chunk) != this_chunk) {
+                               if (afs->write (buffers.get_audio(n).data(), this_chunk) != this_chunk) {
                                        goto out;
                                }
                        }
@@ -3852,23 +4051,15 @@ Session::write_one_audio_track (AudioTrack& track, nframes_t start, nframes_t le
                time (&now);
                xnow = localtime (&now);
                
-               for (vector<boost::shared_ptr<AudioSource> >::iterator src=srcs.begin(); src != srcs.end(); ++src) {
+               for (vector<boost::shared_ptr<Source> >::iterator src=srcs.begin(); src != srcs.end(); ++src) {
                        boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
-
+                       
                        if (afs) {
                                afs->update_header (position, *xnow, now);
+                               afs->flush_header ();
                        }
                }
                
-               /* build peakfile for new source */
-               
-               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 ();
-                       }
-               }
-
                /* construct a region to represent the bounced material */
 
                boost::shared_ptr<Region> aregion = RegionFactory::create (srcs, 0, srcs.front()->length(), 
@@ -3879,7 +4070,7 @@ Session::write_one_audio_track (AudioTrack& track, nframes_t start, nframes_t le
                
   out:
        if (ret) {
-               for (vector<boost::shared_ptr<AudioSource> >::iterator src = srcs.begin(); src != srcs.end(); ++src) {
+               for (vector<boost::shared_ptr<Source> >::iterator src = srcs.begin(); src != srcs.end(); ++src) {
                        boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
 
                        if (afs) {
@@ -3888,26 +4079,50 @@ Session::write_one_audio_track (AudioTrack& track, nframes_t start, nframes_t le
 
                        (*src)->drop_references ();
                }
-       }
 
-       for (vector<Sample*>::iterator i = buffers.begin(); i != buffers.end(); ++i) {
-               free(*i);
+       } else {
+               for (vector<boost::shared_ptr<Source> >::iterator src = srcs.begin(); src != srcs.end(); ++src) {
+                       boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
+                       
+                       if (afs)
+                               afs->done_with_peakfile_writes ();
+               }
        }
 
        g_atomic_int_set (&processing_prohibited, 0);
 
-       itt.done = true;
-
        return ret;
 }
 
-vector<Sample*>&
-Session::get_silent_buffers (uint32_t howmany)
+BufferSet&
+Session::get_silent_buffers (ChanCount count)
 {
-       for (uint32_t i = 0; i < howmany; ++i) {
-               memset (_silent_buffers[i], 0, sizeof (Sample) * current_block_size);
+       assert(_silent_buffers->available() >= count);
+       _silent_buffers->set_count(count);
+
+       for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
+               for (size_t i=0; i < count.get(*t); ++i) {
+                       _silent_buffers->get(*t, i).clear();
+               }
        }
-       return _silent_buffers;
+       
+       return *_silent_buffers;
+}
+
+BufferSet&
+Session::get_scratch_buffers (ChanCount count)
+{
+       assert(_scratch_buffers->available() >= count);
+       _scratch_buffers->set_count(count);
+       return *_scratch_buffers;
+}
+
+BufferSet&
+Session::get_mix_buffers (ChanCount count)
+{
+       assert(_mix_buffers->available() >= count);
+       _mix_buffers->set_count(count);
+       return *_mix_buffers;
 }
 
 uint32_t 
@@ -3917,7 +4132,7 @@ Session::ntracks () const
        shared_ptr<RouteList> r = routes.reader ();
 
        for (RouteList::const_iterator i = r->begin(); i != r->end(); ++i) {
-               if (dynamic_cast<AudioTrack*> ((*i).get())) {
+               if (dynamic_cast<Track*> ((*i).get())) {
                        ++n;
                }
        }
@@ -3932,7 +4147,7 @@ Session::nbusses () const
        shared_ptr<RouteList> r = routes.reader ();
 
        for (RouteList::const_iterator i = r->begin(); i != r->end(); ++i) {
-               if (dynamic_cast<AudioTrack*> ((*i).get()) == 0) {
+               if (dynamic_cast<Track*> ((*i).get()) == 0) {
                        ++n;
                }
        }
@@ -3952,3 +4167,29 @@ Session::compute_initial_length ()
        return _engine.frame_rate() * 60 * 5;
 }
 
+void
+Session::sync_order_keys ()
+{
+       if (!Config->get_sync_all_route_ordering()) {
+               /* leave order keys as they are */
+               return;
+       }
+
+       boost::shared_ptr<RouteList> r = routes.reader ();
+
+       for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
+               (*i)->sync_order_keys ();
+       }
+
+       Route::SyncOrderKeys (); // EMIT SIGNAL
+}
+
+void
+Session::foreach_bundle (sigc::slot<void, boost::shared_ptr<Bundle> > sl)
+{
+       Glib::Mutex::Lock lm (bundle_lock);
+       for (BundleList::iterator i = _bundles.begin(); i != _bundles.end(); ++i) {
+               sl (*i);
+       }
+}
+