Search code examples
interopspotifylibspotify

Lifetime of tracks in libspotify


When using libspotify, I respond to callbacks about playlists changing by going through the playlists and getting information about the tracks.

When I get a track handle, when does that track handle become invalid? Can I assume that in a session, a given value for a track handle will always refer to the same track? Do I need to increase and decrease the ref count of tracks manually to be sure?

Thanks Tom


Solution

  • As per the docs:

    Reference counting is used for all domain objects in libspotify. Functions including the string create will return an object with a pre-incremented reference count. Thus, each create must have a corresponding release when the value is no longer needed.

    Other accessor functions (including sp_link_as_artist et al.), on the other hand, returns a reference borrowed from the object it was retrieved from. Retrieving an sp_album from an sp_link would make the album object survive until the link object is freed, unless its reference count is explicitly incremented.

    So if you get a track handle by calling sp_playlist_track – which does not contain the string create – the track reference is owned by the playlist. You can only be sure it is still valid while you are sure the playlist handle is valid, and you are sure the playlist still contains the track, unless you manually increase its reference count.

    Similarly, a playlist obtained from a playlist container can only live as long as the container, and might not live as long.

    In practice, I think you should add a reference to the track before you return from the callback or call into sp_session_process_events again. It's fine to rely on the parent object keeping it alive before that point, but after that point it's much harder to reason about, so just add a reference and later release it when you're done.