Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CacheDataSource vs SimpleCache in exoplayer?

I am very confused with ExoPlayer and their documentation. Can anyone please explain me for what purpose and when should we use CacheDataSource and SimpleCache?

like image 829
nirazverma Avatar asked Oct 19 '25 15:10

nirazverma


1 Answers

CacheDataSource and SimpleCache fulfill two different purposes. If you take a look at their class prototype you will see that CacheDataSource implements DataSource and SimpleCache implements Cache. When you need to cache your downloaded videos you have to use CacheDataSource as your DataSource.Factory to prepare your media playback:

// Produces DataSource instances through which media data is loaded.
DataSource.Factory dataSourceFactory = new DefaultDataSourceFactory(context, Util.getUserAgent(context, "AppName"));
dataSourceFactory = new CacheDataSourceFactory(VideoCacheSingleton.getInstance(), dataSourceFactory);

And then use dataSourceFactory to create a MediaSource:

// This is the MediaSource representing the media to be played.
MediaSource mediaSource = new ProgressiveMediaSource.Factory(dataSourceFactory)
        .createMediaSource(mediaUri);
SimpleExoPlayer exoPlayerInstance = new SimpleExoPlayer.Builder(context).build();
exoPlayerInstance.prepare(mediaSource);

While SimpleCache offers you a cache implementation that maintains an in-memory representation. As you can see in the first code block a CacheDataSourceFactory constructor needs a Cache instance to work with. You can either declare your own caching mechanism or use the default SimpleCache class that ExoPlayer provides you. If you need to use the default implementation you should keep this in mind:

Only one instance of SimpleCache is allowed for a given directory at a given time

As per the documentation. So in order to use a single instance of SimpleCache for a folder we use singleton declaration pattern:

public class VideoCacheSingleton {
    private static final int MAX_VIDEO_CACHE_SIZE_IN_BYTES = 200 * 1024 * 1024;  // 200MB

    private static Cache sInstance;

    public static Cache getInstance(Context context) {
        if (sInstance != null) return sInstance;
        else return sInstance = new SimpleCache(new File(context.getCacheDir(), "video"), new LeastRecentlyUsedCacheEvictor(MAX_VIDEO_CACHE_SIZE_IN_BYTES), new ExoDatabaseProvider(context)));
    }
}

TL; DR

We use CacheDataSource to prepare a caching media playback and SimpleCache to build its DataSource.Factory instance.

like image 187
Sdghasemi Avatar answered Oct 21 '25 04:10

Sdghasemi