added L and R as possible audio file suffixes
[ardour.git] / libs / ardour / session.cc
index 1b7c3be6ddc738880cd51c9dfa73ae914fb24319..4a0245d4c6b08428b7174ac599076d14850dd78f 100644 (file)
@@ -15,7 +15,6 @@
     along with this program; if not, write to the Free Software
     Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 
-    $Id$
 */
 
 #include <algorithm>
@@ -40,6 +39,7 @@
 #include <pbd/pathscanner.h>
 #include <pbd/stl_delete.h>
 #include <pbd/basename.h>
+#include <pbd/stacktrace.h>
 
 #include <ardour/audioengine.h>
 #include <ardour/configuration.h>
@@ -53,7 +53,6 @@
 #include <ardour/midi_playlist.h>
 #include <ardour/midi_region.h>
 #include <ardour/smf_source.h>
-#include <ardour/destructive_filesource.h>
 #include <ardour/auditioner.h>
 #include <ardour/recent_sessions.h>
 #include <ardour/redirect.h>
@@ -85,6 +84,12 @@ using namespace ARDOUR;
 using namespace PBD;
 using boost::shared_ptr;
 
+#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
+
 const char* Session::_template_suffix = X_(".template");
 const char* Session::_statefile_suffix = X_(".ardour");
 const char* Session::_pending_suffix = X_(".pending");
@@ -93,11 +98,7 @@ const char* Session::sound_dir_name = X_("audiofiles");
 const char* Session::peak_dir_name = X_("peaks");
 const char* Session::dead_sound_dir_name = X_("dead_sounds");
 const char* Session::interchange_dir_name = X_("interchange");
-
-Session::compute_peak_t                                Session::compute_peak                   = 0;
-Session::apply_gain_to_buffer_t                Session::apply_gain_to_buffer   = 0;
-Session::mix_buffers_with_gain_t       Session::mix_buffers_with_gain  = 0;
-Session::mix_buffers_no_gain_t         Session::mix_buffers_no_gain    = 0;
+const char* Session::export_dir_name = X_("export");
 
 sigc::signal<int> Session::AskAboutPendingState;
 sigc::signal<void> Session::SendFeedback;
@@ -279,6 +280,10 @@ Session::Session (AudioEngine &eng,
 {
        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();
@@ -290,12 +295,13 @@ Session::Session (AudioEngine &eng,
        if (new_session) {
                if (create (new_session, mix_template, compute_initial_length())) {
                        cerr << "create failed\n";
+                       destroy ();
                        throw failed_constructor ();
                }
        }
        
        if (second_stage_init (new_session)) {
-               cerr << "2nd state failed\n";
+               destroy ();
                throw failed_constructor ();
        }
        
@@ -340,6 +346,10 @@ Session::Session (AudioEngine &eng,
 {
        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();
@@ -359,33 +369,45 @@ Session::Session (AudioEngine &eng,
 
        if (new_session) {
                if (create (new_session, 0, initial_length)) {
+                       destroy ();
                        throw failed_constructor ();
                }
        }
 
-       if (control_out_channels) {
-               shared_ptr<Route> r (new Route (*this, _("monitor"), -1, control_out_channels, -1, control_out_channels, Route::ControlOut));
-               RouteList rl;
-               rl.push_back (r);
-               add_routes (rl);
-               _control_out = r;
-       }
-
-       if (master_out_channels) {
-               shared_ptr<Route> r (new Route (*this, _("master"), -1, master_out_channels, -1, master_out_channels, Route::MasterOut));
+       {
+               /* set up Master Out and Control Out if necessary */
+               
                RouteList rl;
-               rl.push_back (r);
-               add_routes (rl);
-               _master_out = r;
-       } else {
-               /* prohibit auto-connect to master, because there isn't one */
-               output_ac = AutoConnectOption (output_ac & ~AutoConnectMaster);
+               int control_id = 1;
+               
+               if (control_out_channels) {
+                       shared_ptr<Route> r (new Route (*this, _("monitor"), -1, control_out_channels, -1, control_out_channels, Route::ControlOut));
+                       r->set_remote_control_id (control_id++);
+                       
+                       rl.push_back (r);
+               }
+               
+               if (master_out_channels) {
+                       shared_ptr<Route> r (new Route (*this, _("master"), -1, master_out_channels, -1, master_out_channels, Route::MasterOut));
+                       r->set_remote_control_id (control_id);
+                        
+                       rl.push_back (r);
+               } else {
+                       /* prohibit auto-connect to master, because there isn't one */
+                       output_ac = AutoConnectOption (output_ac & ~AutoConnectMaster);
+               }
+               
+               if (!rl.empty()) {
+                       add_routes (rl);
+               }
+               
        }
 
        Config->set_input_auto_connect (input_ac);
        Config->set_output_auto_connect (output_ac);
 
        if (second_stage_init (new_session)) {
+               destroy ();
                throw failed_constructor ();
        }
        
@@ -395,12 +417,20 @@ Session::Session (AudioEngine &eng,
 
        _state_of_the_state = StateOfTheState (_state_of_the_state & ~Dirty);
 
+       Config->ParameterChanged.connect (mem_fun (*this, &Session::config_changed));
+
        if (was_dirty) {
                DirtyChanged (); /* EMIT SIGNAL */
        }
 }
 
 Session::~Session ()
+{
+       destroy ();
+}
+
+void
+Session::destroy ()
 {
        /* if we got to here, leaving pending capture state around
           is a mistake.
@@ -469,10 +499,24 @@ Session::~Session ()
                tmp = i;
                ++tmp;
 
-               delete *i;
+               (*i)->drop_references ();
                
                i = tmp;
        }
+       
+       for (PlaylistList::iterator i = unused_playlists.begin(); i != unused_playlists.end(); ) {
+               PlaylistList::iterator tmp;
+
+               tmp = i;
+               ++tmp;
+
+               (*i)->drop_references ();
+               
+               i = tmp;
+       }
+       
+       playlists.clear ();
+       unused_playlists.clear ();
 
 #ifdef TRACK_DESTRUCTION
        cerr << "delete regions\n";
@@ -484,9 +528,7 @@ Session::~Session ()
                tmp = i;
                ++tmp;
 
-               cerr << "dropping refs on a region (" << i->second->name() << " @ " << i->second << ") with UC = " << i->second.use_count() << endl;
                i->second->drop_references ();
-               cerr << "AFTER: UC = " << i->second.use_count() << endl;
 
                i = tmp;
        }
@@ -619,8 +661,6 @@ Session::when_engine_running ()
 
        /* we don't want to run execute this again */
 
-       first_time_running.disconnect ();
-
        set_block_size (_engine.frames_per_cycle());
        set_frame_rate (_engine.frame_rate());
 
@@ -685,23 +725,6 @@ Session::when_engine_running ()
                // XXX HOW TO ALERT UI TO THIS ? DO WE NEED TO?
        }
 
-       if (auditioner == 0) {
-
-               /* we delay creating the auditioner till now because
-                  it makes its own connections to ports named
-                  in the ARDOUR_RC config file. the engine has
-                  to be running for this to work.
-               */
-
-               try {
-                       auditioner.reset (new Auditioner (*this));
-               }
-
-               catch (failed_constructor& err) {
-                       warning << _("cannot create Auditioner: no auditioning of regions possible") << endmsg;
-               }
-       }
-
        /* Create a set of Connection objects that map
           to the physical outputs currently available
        */
@@ -781,8 +804,8 @@ Session::when_engine_running ()
                        
                        _master_out->defer_pan_reset ();
                        
-                       while (_master_out->n_inputs().get(DataType::AUDIO)
-                                       < _master_out->input_maximum().get(DataType::AUDIO)) {
+                       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;
@@ -790,8 +813,8 @@ Session::when_engine_running ()
                                }
                        }
                        n = 0;
-                       while (_master_out->n_outputs().get(DataType::AUDIO)
-                                       < _master_out->output_maximum().get(DataType::AUDIO)) {
+                       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;
@@ -841,6 +864,7 @@ Session::when_engine_running ()
                }
        }
 
+       
        _state_of_the_state = StateOfTheState (_state_of_the_state & ~(CannotSave|Dirty));
 
        /* hook us up to the engine */
@@ -867,14 +891,31 @@ Session::hookup_io ()
 
        _state_of_the_state = StateOfTheState (_state_of_the_state | InitialConnecting);
 
+       if (auditioner == 0) {
+               
+               /* we delay creating the auditioner till now because
+                  it makes its own connections to ports.
+                  the engine has to be running for this to work.
+               */
+               
+               try {
+                       auditioner.reset (new Auditioner (*this));
+               }
+               
+               catch (failed_constructor& err) {
+                       warning << _("cannot create Auditioner: no auditioning of regions possible") << endmsg;
+               }
+       }
+
        /* Tell all IO objects to create their ports */
 
        IO::enable_ports ();
 
        if (_control_out) {
                uint32_t n;
+               vector<string> cports;
 
-               while (_control_out->n_inputs().get(DataType::AUDIO) < _control_out->input_maximum().get(DataType::AUDIO)) {
+               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;
@@ -882,7 +923,7 @@ Session::hookup_io ()
                        }
                }
                n = 0;
-               while (_control_out->n_outputs().get(DataType::AUDIO) < _control_out->output_maximum().get(DataType::AUDIO)) {
+               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;
@@ -890,7 +931,20 @@ Session::hookup_io ()
                        }
                        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);
+               }
+       } 
 
        /* Tell all IO objects to connect themselves together */
 
@@ -918,7 +972,7 @@ Session::hookup_io ()
 }
 
 void
-Session::playlist_length_changed (Playlist* pl)
+Session::playlist_length_changed ()
 {
        /* we can't just increase end_location->end() if pl->get_maximum_extent() 
           if larger. if the playlist used to be the longest playlist,
@@ -932,10 +986,10 @@ Session::playlist_length_changed (Playlist* pl)
 void
 Session::diskstream_playlist_changed (boost::shared_ptr<Diskstream> dstream)
 {
-       Playlist *playlist;
+       boost::shared_ptr<Playlist> playlist;
 
        if ((playlist = dstream->playlist()) != 0) {
-         playlist->LengthChanged.connect (sigc::bind (mem_fun (this, &Session::playlist_length_changed), playlist));
+               playlist->LengthChanged.connect (mem_fun (this, &Session::playlist_length_changed));
        }
        
        /* see comment in playlist_length_changed () */
@@ -1340,7 +1394,7 @@ 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));
+       Route::set_automation_interval ((nframes_t) ceil ((double) frames_per_second * 0.25));
 
        // XXX we need some equivalent to this, somehow
        // SndFileSource::setup_standard_crossfades (frames_per_second);
@@ -1362,7 +1416,7 @@ Session::set_block_size (nframes_t nframes)
        { 
                        
                current_block_size = nframes;
-               
+
                ensure_buffers(_scratch_buffers->available());
 
                if (_gain_automation_buffer) {
@@ -1579,7 +1633,7 @@ Session::new_midi_track (TrackMode mode, uint32_t how_many)
                        if (dynamic_cast<MidiTrack*>((*i).get()) != 0) {
                                if (!(*i)->hidden()) {
                                        n++;
-                                       channels_used += (*i)->n_inputs().get(DataType::MIDI);
+                                       channels_used += (*i)->n_inputs().n_midi();
                                }
                        }
                }
@@ -1612,7 +1666,7 @@ Session::new_midi_track (TrackMode mode, uint32_t how_many)
                                error << "cannot configure 1 in/1 out configuration for new midi track" << endmsg;
                        }
                        
-                       channels_used += track->n_inputs ().get(DataType::MIDI);
+                       channels_used += track->n_inputs ().n_midi();
 
                        track->DiskstreamChanged.connect (mem_fun (this, &Session::resort_routes));
                        track->set_remote_control_id (ntracks());
@@ -1649,6 +1703,7 @@ Session::new_audio_track (int input_channels, int output_channels, TrackMode mod
        string port;
        RouteList new_routes;
        list<boost::shared_ptr<AudioTrack> > ret;
+       uint32_t control_id;
 
        /* count existing audio tracks */
 
@@ -1659,7 +1714,7 @@ Session::new_audio_track (int input_channels, int output_channels, TrackMode mod
                        if (dynamic_cast<AudioTrack*>((*i).get()) != 0) {
                                if (!(*i)->hidden()) {
                                        n++;
-                                       channels_used += (*i)->n_inputs().get(DataType::AUDIO);
+                                       channels_used += (*i)->n_inputs().n_audio();
                                }
                        }
                }
@@ -1672,6 +1727,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) {
 
@@ -1704,18 +1760,21 @@ Session::new_audio_track (int input_channels, int output_channels, TrackMode mod
                } else {
                        nphysical_out = 0;
                }
+
+               shared_ptr<AudioTrack> track;
                
                try {
-                       shared_ptr<AudioTrack> track (new AudioTrack (*this, track_name, Route::Flag (0), mode));
+                       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().get(DataType::AUDIO) && x < nphysical_in; ++x) {
+                               for (uint32_t x = 0; x < track->n_inputs().n_audio() && x < nphysical_in; ++x) {
                                        
                                        port = "";
                                        
@@ -1729,7 +1788,7 @@ Session::new_audio_track (int input_channels, int output_channels, TrackMode mod
                                }
                        }
                        
-                       for (uint32_t x = 0; x < track->n_outputs().get(DataType::MIDI); ++x) {
+                       for (uint32_t x = 0; x < track->n_outputs().n_midi(); ++x) {
                                
                                port = "";
                                
@@ -1737,7 +1796,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().get(DataType::AUDIO))->name();
+                                               port = _master_out->input (x%_master_out->n_inputs().n_audio())->name();
                                        }
                                }
                                
@@ -1746,21 +1805,13 @@ Session::new_audio_track (int input_channels, int output_channels, TrackMode mod
                                }
                        }
                        
-                       channels_used += track->n_inputs ().get(DataType::AUDIO);
+                       channels_used += track->n_inputs ().n_audio();
 
-                       if (_control_out) {
-                               vector<string> cports;
-                               uint32_t ni = _control_out->n_inputs().get(DataType::AUDIO);
-                               
-                               for (n = 0; n < ni; ++n) {
-                                       cports.push_back (_control_out->input(n)->name());
-                               }
-                               
-                               track->set_control_outs (cports);
-                       }
+                       track->audio_diskstream()->non_realtime_input_change();
                        
                        track->DiskstreamChanged.connect (mem_fun (this, &Session::resort_routes));
-                       track->set_remote_control_id (ntracks());
+                       track->set_remote_control_id (control_id);
+                       ++control_id;
 
                        new_routes.push_back (track);
                        ret.push_back (track);
@@ -1768,14 +1819,43 @@ Session::new_audio_track (int input_channels, int output_channels, TrackMode mod
 
                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;
+
+                       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, false);
                save_state (_current_snapshot_name);
@@ -1784,6 +1864,27 @@ 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)
 {
@@ -1792,6 +1893,7 @@ Session::new_audio_route (int input_channels, int output_channels, uint32_t how_
        uint32_t n = 0;
        string port;
        RouteList ret;
+       uint32_t control_id;
 
        /* count existing audio busses */
 
@@ -1800,7 +1902,7 @@ Session::new_audio_route (int input_channels, int output_channels, uint32_t how_
 
                for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
                        if (dynamic_cast<AudioTrack*>((*i).get()) == 0) {
-                               if (!(*i)->hidden()) {
+                               if (!(*i)->hidden() && (*i)->name() != _("master")) {
                                        bus_id++;
                                }
                        }
@@ -1812,14 +1914,15 @@ Session::new_audio_route (int input_channels, int output_channels, uint32_t how_
 
        _engine.get_physical_outputs (physoutputs);
        _engine.get_physical_inputs (physinputs);
+       control_id = ntracks() + nbusses() + 1;
 
        while (how_many) {
 
                do {
-                       ++bus_id;
-
                        snprintf (bus_name, sizeof(bus_name), "Bus %" PRIu32, bus_id);
 
+                       bus_id++;
+
                        if (route_by_name (bus_name) == 0) {
                                break;
                        }
@@ -1833,9 +1936,10 @@ Session::new_audio_route (int input_channels, int output_channels, uint32_t how_
                                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().get(DataType::AUDIO); ++x) {
+                       for (uint32_t x = 0; n_physical_inputs && x < bus->n_inputs().n_audio(); ++x) {
                                
                                port = "";
 
@@ -1848,7 +1952,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().get(DataType::AUDIO); ++x) {
+                       for (uint32_t x = 0; n_physical_outputs && x < bus->n_outputs().n_audio(); ++x) {
                                
                                port = "";
                                
@@ -1856,7 +1960,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().get(DataType::AUDIO))->name();
+                                               port = _master_out->input (x%_master_out->n_inputs().n_audio())->name();
                                        }
                                }
                                
@@ -1865,15 +1969,8 @@ 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().get(DataType::AUDIO);
-                               
-                               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;
 
                        ret.push_back (bus);
                }
@@ -1881,13 +1978,19 @@ 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);
@@ -1922,9 +2025,23 @@ Session::add_routes (RouteList& new_routes, bool save)
                
                if ((*x)->control()) {
                        _control_out = (*x);
-               }
+               } 
        }
 
+       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) {
@@ -1938,21 +2055,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
@@ -2134,9 +2253,11 @@ Session::route_solo_changed (void* src, boost::weak_ptr<Route> wpr)
        modify_solo_mute (is_track, same_thing_soloed);
 
        if (signal) {
-               SoloActive (currently_soloing);
+               SoloActive (currently_soloing); /* EMIT SIGNAL */
        }
 
+       SoloChanged (); /* EMIT SIGNAL */
+
        set_dirty();
 }
 
@@ -2317,7 +2438,7 @@ Session::get_maximum_extent () const
        boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
 
        for (DiskstreamList::const_iterator i = dsl->begin(); i != dsl->end(); ++i) {
-               Playlist* pl = (*i)->playlist();
+               boost::shared_ptr<Playlist> pl = (*i)->playlist();
                if ((me = pl->get_maximum_extent()) > max) {
                        max = me;
                }
@@ -2672,6 +2793,9 @@ Session::remove_last_capture ()
        }
 
        destroy_regions (r);
+
+       save_state (_current_snapshot_name);
+
        return 0;
 }
 
@@ -2697,14 +2821,10 @@ Session::add_source (boost::shared_ptr<Source> source)
                result = sources.insert (entry);
        }
 
-       if (!result.second) {
-               cerr << "\tNOT inserted ? " << result.second << endl;
+       if (result.second) {
+               source->GoingAway.connect (sigc::bind (mem_fun (this, &Session::remove_source), boost::weak_ptr<Source> (source)));
+               set_dirty();
        }
-
-       source->GoingAway.connect (sigc::bind (mem_fun (this, &Session::remove_source), boost::weak_ptr<Source> (source)));
-       set_dirty();
-       
-       SourceAdded (source); /* EMIT SIGNAL */
 }
 
 void
@@ -2737,8 +2857,6 @@ Session::remove_source (boost::weak_ptr<Source> src)
                
                save_state (_current_snapshot_name);
        }
-       
-       SourceRemoved(source); /* EMIT SIGNAL */
 }
 
 boost::shared_ptr<Source>
@@ -2757,6 +2875,24 @@ Session::source_by_id (const PBD::ID& id)
        return source;
 }
 
+
+boost::shared_ptr<Source>
+Session::source_by_path_and_channel (const Glib::ustring& path, uint16_t chn)
+{
+       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);
+
+               if (afs && afs->path() == path && chn == afs->channel()) {
+                       return afs;
+               } 
+                      
+       }
+       return boost::shared_ptr<Source>();
+}
+
 string
 Session::peak_path_from_audio_path (string audio_path) const
 {
@@ -2924,6 +3060,7 @@ Session::audio_path_from_name (string name, uint32_t nchan, uint32_t chan, bool
                                } else {
                                        snprintf (buf, sizeof(buf), "%s/T%04d-%s.wav", spath.c_str(), cnt, legalized.c_str());
                                }
+
                        } else {
 
                                spath += '/';
@@ -2956,6 +3093,7 @@ Session::audio_path_from_name (string name, uint32_t nchan, uint32_t chan, bool
 
                if (cnt > limit) {
                        error << string_compose(_("There are already %1 recordings for %2, which I consider too many."), limit, name) << endmsg;
+                       destroy ();
                        throw failed_constructor();
                }
        }
@@ -2967,6 +3105,7 @@ Session::audio_path_from_name (string name, uint32_t nchan, uint32_t chan, bool
        string foo = buf;
 
        spath = discover_best_sound_dir ();
+       spath += '/';
 
        string::size_type pos = foo.find_last_of ('/');
        
@@ -2982,7 +3121,7 @@ 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().get(DataType::AUDIO), chan, destructive);
+       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()));
 }
@@ -3125,14 +3264,16 @@ Session::midi_path_from_name (string name)
 
                for (i = session_dirs.begin(); i != session_dirs.end(); ++i) {
 
+                       spath = (*i).path;
+
                        // FIXME: different directory from audio?
-                       spath = (*i).path + sound_dir_name + "/" + legalized;
+                       spath += sound_dir(false) + "/" + legalized;
 
                        snprintf (buf, sizeof(buf), "%s-%u.mid", spath.c_str(), cnt);
 
-                       if (access (buf, F_OK) == 0) {
+                       if (g_file_test (buf, G_FILE_TEST_EXISTS)) {
                                existing++;
-                       }
+                       } 
                }
 
                if (existing == 0) {
@@ -3153,6 +3294,7 @@ Session::midi_path_from_name (string name)
 
        // FIXME: different directory than audio?
        spath = discover_best_sound_dir ();
+       spath += '/';
 
        string::size_type pos = foo.find_last_of ('/');
        
@@ -3176,7 +3318,7 @@ Session::create_midi_source_for_session (MidiDiskstream& ds)
 
 /* Playlist management */
 
-Playlist *
+boost::shared_ptr<Playlist>
 Session::playlist_by_name (string name)
 {
        Glib::Mutex::Lock lm (playlist_lock);
@@ -3190,11 +3332,12 @@ Session::playlist_by_name (string name)
                        return* i;
                }
        }
-       return 0;
+
+       return boost::shared_ptr<Playlist>();
 }
 
 void
-Session::add_playlist (Playlist* playlist)
+Session::add_playlist (boost::shared_ptr<Playlist> playlist)
 {
        if (playlist->hidden()) {
                return;
@@ -3204,9 +3347,8 @@ Session::add_playlist (Playlist* playlist)
                Glib::Mutex::Lock lm (playlist_lock);
                if (find (playlists.begin(), playlists.end(), playlist) == playlists.end()) {
                        playlists.insert (playlists.begin(), playlist);
-                       // playlist->ref();
-                       playlist->InUse.connect (mem_fun (*this, &Session::track_playlist));
-                       playlist->GoingAway.connect (sigc::bind (mem_fun (*this, &Session::remove_playlist), playlist));
+                       playlist->InUse.connect (sigc::bind (mem_fun (*this, &Session::track_playlist), boost::weak_ptr<Playlist>(playlist)));
+                       playlist->GoingAway.connect (sigc::bind (mem_fun (*this, &Session::remove_playlist), boost::weak_ptr<Playlist>(playlist)));
                }
        }
 
@@ -3216,7 +3358,7 @@ Session::add_playlist (Playlist* playlist)
 }
 
 void
-Session::get_playlists (vector<Playlist*>& s)
+Session::get_playlists (vector<boost::shared_ptr<Playlist> >& s)
 {
        { 
                Glib::Mutex::Lock lm (playlist_lock);
@@ -3230,15 +3372,25 @@ Session::get_playlists (vector<Playlist*>& s)
 }
 
 void
-Session::track_playlist (Playlist* pl, bool inuse)
+Session::track_playlist (bool inuse, boost::weak_ptr<Playlist> wpl)
 {
+       boost::shared_ptr<Playlist> pl(wpl.lock());
+
+       if (!pl) {
+               return;
+       }
+
        PlaylistList::iterator x;
 
+       if (pl->hidden()) {
+               /* its not supposed to be visible */
+               return;
+       }
+
        { 
                Glib::Mutex::Lock lm (playlist_lock);
 
                if (!inuse) {
-                       //cerr << "shifting playlist to unused: " << pl->name() << endl;
 
                        unused_playlists.insert (pl);
                        
@@ -3248,8 +3400,7 @@ Session::track_playlist (Playlist* pl, bool inuse)
 
                        
                } else {
-                       //cerr << "shifting playlist to used: " << pl->name() << endl;
-                       
+
                        playlists.insert (pl);
                        
                        if ((x = unused_playlists.find (pl)) != unused_playlists.end()) {
@@ -3260,20 +3411,24 @@ Session::track_playlist (Playlist* pl, bool inuse)
 }
 
 void
-Session::remove_playlist (Playlist* playlist)
+Session::remove_playlist (boost::weak_ptr<Playlist> weak_playlist)
 {
        if (_state_of_the_state & Deletion) {
                return;
        }
 
+       boost::shared_ptr<Playlist> playlist (weak_playlist.lock());
+
+       if (!playlist) {
+               return;
+       }
+
        { 
                Glib::Mutex::Lock lm (playlist_lock);
-               // cerr << "removing playlist: " << playlist->name() << endl;
 
                PlaylistList::iterator i;
 
                i = find (playlists.begin(), playlists.end(), playlist);
-
                if (i != playlists.end()) {
                        playlists.erase (i);
                }
@@ -3346,7 +3501,7 @@ Session::remove_empty_sounds ()
 {
        PathScanner scanner;
 
-       vector<string *>* possible_audiofiles = scanner (sound_dir(), "\\.(wav|aiff|caf|w64)$", false, true);
+       vector<string *>* possible_audiofiles = scanner (sound_dir(), "\\.(wav|aiff|caf|w64|L|R)$", false, true);
        
        Glib::Mutex::Lock lm (source_lock);
        
@@ -3444,13 +3599,19 @@ 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.
+       */
+
+       request_input_change_handling ();
+
        resort_routes ();
 
        /* force all diskstreams to update their capture offset values to 
@@ -3528,18 +3689,28 @@ Session::remove_redirect (Redirect* redirect)
        Insert* insert;
        PortInsert* port_insert;
        PluginInsert* plugin_insert;
-
+       
        if ((insert = dynamic_cast<Insert *> (redirect)) != 0) {
                if ((port_insert = dynamic_cast<PortInsert *> (insert)) != 0) {
-                       _port_inserts.remove (port_insert);
+                       list<PortInsert*>::iterator x = find (_port_inserts.begin(), _port_inserts.end(), port_insert);
+                       if (x != _port_inserts.end()) {
+                               insert_bitset[port_insert->bit_slot()] = false;
+                               _port_inserts.erase (x);
+                       }
                } else if ((plugin_insert = dynamic_cast<PluginInsert *> (insert)) != 0) {
                        _plugin_inserts.remove (plugin_insert);
                } else {
-                       fatal << _("programming error: unknown type of Insert deleted!") << endmsg;
+                       fatal << string_compose (_("programming error: %1"),
+                                                X_("unknown type of Insert deleted!")) 
+                             << endmsg;
                        /*NOTREACHED*/
                }
        } else if ((send = dynamic_cast<Send *> (redirect)) != 0) {
-               _sends.remove (send);
+               list<Send*>::iterator x = find (_sends.begin(), _sends.end(), send);
+               if (x != _sends.end()) {
+                       send_bitset[send->bit_slot()] = false;
+                       _sends.erase (x);
+               }
        } else {
                fatal << _("programming error: unknown type of Redirect deleted!") << endmsg;
                /*NOTREACHED*/
@@ -3551,16 +3722,23 @@ Session::remove_redirect (Redirect* redirect)
 nframes_t
 Session::available_capture_duration ()
 {
-       float sample_bytes_on_disk;
+       float sample_bytes_on_disk = 4.0; // keep gcc happy
 
        switch (Config->get_native_file_data_format()) {
        case FormatFloat:
-               sample_bytes_on_disk = 4;
+               sample_bytes_on_disk = 4.0;
                break;
 
        case FormatInt24:
-               sample_bytes_on_disk = 3;
+               sample_bytes_on_disk = 3.0;
                break;
+
+       default: 
+               /* impossible, but keep some gcc versions happy */
+               fatal << string_compose (_("programming error: %1"),
+                                        X_("illegal native file data format"))
+                     << endmsg;
+               /*NOTREACHED*/
        }
 
        double scale = 4096.0 / sample_bytes_on_disk;
@@ -3639,23 +3817,71 @@ Session::ensure_buffers (ChanCount howmany)
        _send_buffers->ensure_buffers(howmany, current_block_size);
        _silent_buffers->ensure_buffers(howmany, current_block_size);
        
-       allocate_pan_automation_buffers (current_block_size, howmany.get(DataType::AUDIO), false);
+       allocate_pan_automation_buffers (current_block_size, howmany.n_audio(), false);
 }
 
-string
-Session::next_send_name ()
+uint32_t
+Session::next_insert_id ()
 {
-       char buf[32];
-       snprintf (buf, sizeof (buf), "send %" PRIu32, ++send_cnt);
-       return buf;
+       /* this doesn't really loop forever. just think about it */
+
+       while (true) {
+               for (boost::dynamic_bitset<uint32_t>::size_type n = 0; n < insert_bitset.size(); ++n) {
+                       if (!insert_bitset[n]) {
+                               insert_bitset[n] = true;
+                               return n;
+                               
+                       }
+               }
+               
+               /* none available, so resize and try again */
+
+               insert_bitset.resize (insert_bitset.size() + 16, false);
+       }
 }
 
-string
-Session::next_insert_name ()
+uint32_t
+Session::next_send_id ()
+{
+       /* this doesn't really loop forever. just think about it */
+
+       while (true) {
+               for (boost::dynamic_bitset<uint32_t>::size_type n = 0; n < send_bitset.size(); ++n) {
+                       if (!send_bitset[n]) {
+                               send_bitset[n] = true;
+                               return n;
+                               
+                       }
+               }
+               
+               /* none available, so resize and try again */
+
+               send_bitset.resize (send_bitset.size() + 16, false);
+       }
+}
+
+void
+Session::mark_send_id (uint32_t id)
+{
+       if (id >= send_bitset.size()) {
+               send_bitset.resize (id+16, false);
+       }
+       if (send_bitset[id]) {
+               warning << string_compose (_("send ID %1 appears to be in use already"), id) << endmsg;
+       }
+       send_bitset[id] = true;
+}
+
+void
+Session::mark_insert_id (uint32_t id)
 {
-       char buf[32];
-       snprintf (buf, sizeof (buf), "insert %" PRIu32, ++insert_cnt);
-       return buf;
+       if (id >= insert_bitset.size()) {
+               insert_bitset.resize (id+16, false);
+       }
+       if (insert_bitset[id]) {
+               warning << string_compose (_("insert ID %1 appears to be in use already"), id) << endmsg;
+       }
+       insert_bitset[id] = true;
 }
 
 /* Named Selection management */
@@ -3680,9 +3906,13 @@ Session::add_named_selection (NamedSelection* named_selection)
                named_selections.insert (named_selections.begin(), named_selection);
        }
 
+       for (list<boost::shared_ptr<Playlist> >::iterator i = named_selection->playlists.begin(); i != named_selection->playlists.end(); ++i) {
+               add_playlist (*i);
+       }
+
        set_dirty();
 
-        NamedSelectionAdded (); /* EMIT SIGNAL */
+       NamedSelectionAdded (); /* EMIT SIGNAL */
 }
 
 void
@@ -3732,12 +3962,6 @@ Session::route_name_unique (string n) const
        return true;
 }
 
-int
-Session::cleanup_audio_file_source (boost::shared_ptr<AudioFileSource> fs)
-{
-       return fs->move_to_trash (dead_sound_dir_name);
-}
-
 uint32_t
 Session::n_playlists () const
 {
@@ -3794,18 +4018,17 @@ int
 Session::write_one_audio_track (AudioTrack& track, nframes_t start, nframes_t len,     
                               bool overwrite, vector<boost::shared_ptr<Source> >& srcs, InterThreadInfo& itt)
 {
+       int ret = -1;
+       boost::shared_ptr<Playlist> playlist;
        boost::shared_ptr<AudioFileSource> fsource;
-       
-       int              ret = -1;
-       Playlist*        playlist = 0;
-       uint32_t         x;
-       char             buf[PATH_MAX+1];
-       string           dir;
-       ChanCount        nchans(track.audio_diskstream()->n_channels());
-       jack_nframes_t   position;
-       jack_nframes_t   this_chunk;
-       jack_nframes_t   to_do;
-       BufferSet        buffers;
+       uint32_t x;
+       char buf[PATH_MAX+1];
+       string dir;
+       ChanCount nchans(track.audio_diskstream()->n_channels());
+       nframes_t position;
+       nframes_t this_chunk;
+       nframes_t to_do;
+       BufferSet buffers;
 
        // any bigger than this seems to cause stack overflows in called functions
        const nframes_t chunk_size = (128 * 1024)/4;
@@ -3826,7 +4049,7 @@ Session::write_one_audio_track (AudioTrack& track, nframes_t start, nframes_t le
        
        dir = discover_best_sound_dir ();
 
-       for (uint32_t chan_n=0; chan_n < nchans.get(DataType::AUDIO); ++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);
@@ -3862,6 +4085,12 @@ Session::write_one_audio_track (AudioTrack& track, nframes_t start, nframes_t le
        buffers.ensure_buffers(nchans, chunk_size);
        buffers.set_count(nchans);
 
+       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);
@@ -3875,7 +4104,7 @@ Session::write_one_audio_track (AudioTrack& track, nframes_t start, nframes_t le
                        boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
                        
                        if (afs) {
-                               if (afs->write (buffers.get_audio(n).data(this_chunk), this_chunk) != this_chunk) {
+                               if (afs->write (buffers.get_audio(n).data(), this_chunk) != this_chunk) {
                                        goto out;
                                }
                        }
@@ -3900,22 +4129,14 @@ Session::write_one_audio_track (AudioTrack& track, nframes_t start, nframes_t le
                        
                        if (afs) {
                                afs->update_header (position, *xnow, now);
+                               afs->flush_header ();
                        }
                }
                
-               /* build peakfile for new source */
-               
-               for (vector<boost::shared_ptr<Source> >::iterator src=srcs.begin(); src != srcs.end(); ++src) {
-                       boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
-                       if (afs) {
-                               afs->build_peaks ();
-                       }
-               }
-
                /* construct a region to represent the bounced material */
 
                boost::shared_ptr<Region> aregion = RegionFactory::create (srcs, 0, srcs.front()->length(), 
-                                                                          region_name_from_path (srcs.front()->name()));
+                                                                          region_name_from_path (srcs.front()->name(), true));
 
                ret = 0;
        }
@@ -3931,12 +4152,18 @@ Session::write_one_audio_track (AudioTrack& track, nframes_t start, nframes_t le
 
                        (*src)->drop_references ();
                }
+
+       } 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;
 }