fix ordering of cut/copied regions when pasting; ctrl-click now does the right thing...
[ardour.git] / libs / ardour / session.cc
index a4def58bb43c973a01a9d2d60a8f083ac20ceb61..eba090665a173559c4a672cac964e0e160e170f7 100644 (file)
@@ -40,6 +40,7 @@
 #include <pbd/pathscanner.h>
 #include <pbd/stl_delete.h>
 #include <pbd/basename.h>
+#include <pbd/stacktrace.h>
 
 #include <ardour/audioengine.h>
 #include <ardour/configuration.h>
@@ -280,12 +281,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 ();
        }
        
@@ -345,33 +347,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 ();
        }
        
@@ -381,12 +395,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.
@@ -405,7 +427,7 @@ Session::~Session ()
 
        /* clear history so that no references to objects are held any more */
 
-       history.clear ();
+       _history.clear ();
 
        /* clear state tree so that no references to objects are held any more */
        
@@ -467,10 +489,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 audio regions\n";
@@ -615,8 +651,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());
 
@@ -681,23 +715,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
        */
@@ -835,6 +852,7 @@ Session::when_engine_running ()
                }
        }
 
+       
        _state_of_the_state = StateOfTheState (_state_of_the_state & ~(CannotSave|Dirty));
 
        /* hook us up to the engine */
@@ -861,6 +879,22 @@ Session::hookup_io ()
 
        _state_of_the_state = StateOfTheState (_state_of_the_state | InitialConnecting);
 
+       if (auditioner == 0) {
+               
+               /* we delay creating the auditioner till now because
+                  it makes its own connections to ports.
+                  the engine has to be running for this to work.
+               */
+               
+               try {
+                       auditioner.reset (new Auditioner (*this));
+               }
+               
+               catch (failed_constructor& err) {
+                       warning << _("cannot create Auditioner: no auditioning of regions possible") << endmsg;
+               }
+       }
+
        /* Tell all IO objects to create their ports */
 
        IO::enable_ports ();
@@ -912,7 +946,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,
@@ -926,10 +960,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 () */
@@ -1593,6 +1627,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 */
 
@@ -1616,6 +1651,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,7 +1740,8 @@ Session::new_audio_track (int input_channels, int output_channels, TrackMode mod
                        }
                        
                        track->DiskstreamChanged.connect (mem_fun (this, &Session::resort_routes));
-                       track->set_remote_control_id (ntracks());
+                       track->set_remote_control_id (control_id);
+                       ++control_id;
 
                        new_routes.push_back (track);
                        ret.push_back (track);
@@ -1736,6 +1773,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 */
 
@@ -1756,6 +1794,7 @@ 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) {
 
@@ -1819,6 +1858,9 @@ Session::new_audio_route (int input_channels, int output_channels, uint32_t how_
                                bus->set_control_outs (cports);
                        }
 
+                       bus->set_remote_control_id (control_id);
+                       ++control_id;
+
                        ret.push_back (bus);
                }
        
@@ -2262,7 +2304,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;
                }
@@ -2540,7 +2582,7 @@ Session::remove_region (boost::weak_ptr<Region> weak_region)
 }
 
 boost::shared_ptr<AudioRegion>
-Session::find_whole_file_parent (boost::shared_ptr<AudioRegion> child)
+Session::find_whole_file_parent (boost::shared_ptr<AudioRegion const> child)
 {
        AudioRegionList::iterator i;
        boost::shared_ptr<AudioRegion> region;
@@ -2665,17 +2707,12 @@ Session::add_source (boost::shared_ptr<Source> source)
                        result = audio_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 */
-       } else {
-               cerr << "\tNOT AUDIO FILE\n";
-       }
+       } 
 }
 
 void
@@ -2704,8 +2741,6 @@ Session::remove_source (boost::weak_ptr<Source> src)
                
                save_state (_current_snapshot_name);
        }
-       
-       SourceRemoved(source); /* EMIT SIGNAL */
 }
 
 boost::shared_ptr<Source>
@@ -2891,6 +2926,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 += '/';
@@ -2923,6 +2959,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();
                }
        }
@@ -2934,6 +2971,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 ('/');
        
@@ -2955,7 +2993,7 @@ Session::create_audio_source_for_session (AudioDiskstream& ds, uint32_t chan, bo
 
 /* Playlist management */
 
-Playlist *
+boost::shared_ptr<Playlist>
 Session::playlist_by_name (string name)
 {
        Glib::Mutex::Lock lm (playlist_lock);
@@ -2969,11 +3007,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;
@@ -2983,9 +3022,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)));
                }
        }
 
@@ -2995,7 +3033,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);
@@ -3009,15 +3047,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);
                        
@@ -3027,8 +3075,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()) {
@@ -3039,20 +3086,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);
                }
@@ -3230,6 +3281,12 @@ Session::graph_reordered ()
                return;
        }
 
+       /* every track/bus asked for this to be handled but it was deferred because
+          we were connecting. do it now.
+       */
+
+       request_input_change_handling ();
+
        resort_routes ();
 
        /* force all diskstreams to update their capture offset values to 
@@ -3307,18 +3364,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*/
@@ -3340,6 +3407,13 @@ Session::available_capture_duration ()
        case FormatInt24:
                sample_bytes_on_disk = 3;
                break;
+
+       default: 
+               /* impossible, but keep some gcc versions happy */
+               fatal << string_compose (_("programming error: %1"),
+                                        X_("illegal native file data format"))
+                     << endmsg;
+               /*NOTREACHED*/
        }
 
        double scale = 4096.0 / sample_bytes_on_disk;
@@ -3443,20 +3517,70 @@ Session::ensure_passthru_buffers (uint32_t howmany)
        allocate_pan_automation_buffers (current_block_size, howmany, false);
 }
 
-string
-Session::next_send_name ()
+uint32_t
+Session::next_insert_id ()
+{
+       /* this doesn't really loop forever. just think about it */
+
+       while (true) {
+               for (boost::dynamic_bitset<uint32_t>::size_type n = 0; n < insert_bitset.size(); ++n) {
+                       if (!insert_bitset[n]) {
+                               insert_bitset[n] = true;
+                               cerr << "Returning " << n << " as insert ID\n";
+                               return n;
+                               
+                       }
+               }
+               
+               /* none available, so resize and try again */
+
+               insert_bitset.resize (insert_bitset.size() + 16, false);
+       }
+}
+
+uint32_t
+Session::next_send_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 < send_bitset.size(); ++n) {
+                       if (!send_bitset[n]) {
+                               send_bitset[n] = true;
+                               cerr << "Returning " << n << " as send ID\n";
+                               return n;
+                               
+                       }
+               }
+               
+               /* none available, so resize and try again */
+
+               send_bitset.resize (send_bitset.size() + 16, false);
+       }
 }
 
-string
-Session::next_insert_name ()
+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 */
@@ -3481,9 +3605,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
@@ -3533,12 +3661,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
 {
@@ -3596,7 +3718,7 @@ Session::write_one_audio_track (AudioTrack& track, nframes_t start, nframes_t le
                               bool overwrite, vector<boost::shared_ptr<AudioSource> >& srcs, InterThreadInfo& itt)
 {
        int ret = -1;
-       Playlist* playlist;
+       boost::shared_ptr<Playlist> playlist;
        boost::shared_ptr<AudioFileSource> fsource;
        uint32_t x;
        char buf[PATH_MAX+1];
@@ -3724,7 +3846,7 @@ Session::write_one_audio_track (AudioTrack& track, nframes_t start, nframes_t le
                /* 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;
        }