Skip to content Skip to sidebar Skip to footer

Cachedatasource Vs Simplecache In Exoplayer?

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

Solution 1:

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.FactorydataSourceFactory=newDefaultDataSourceFactory(context, Util.getUserAgent(context, "AppName"));
dataSourceFactory = newCacheDataSourceFactory(VideoCacheSingleton.getInstance(), dataSourceFactory);

And then use dataSourceFactory to create a MediaSource:

// This is the MediaSource representing the media to be played.MediaSourcemediaSource=newProgressiveMediaSource.Factory(dataSourceFactory)
        .createMediaSource(mediaUri);
SimpleExoPlayerexoPlayerInstance=newSimpleExoPlayer.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:

publicclassVideoCacheSingleton {
    privatestaticfinalintMAX_VIDEO_CACHE_SIZE_IN_BYTES=200 * 1024 * 1024;  // 200MBprivatestatic Cache sInstance;

    publicstatic Cache getInstance(Context context) {
        if (sInstance != null) return sInstance;
        elsereturnsInstance=newSimpleCache(newFile(context.getCacheDir(), "video"), newLeastRecentlyUsedCacheEvictor(MAX_VIDEO_CACHE_SIZE_IN_BYTES), newExoDatabaseProvider(context)));
    }
}

TL; DR

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

Post a Comment for "Cachedatasource Vs Simplecache In Exoplayer?"