Dela Agbenyegah

Dela Agbenyegah

Welcome to my personal space.

03 Jun 2023

Hacking ExoPlayer Download Service

Canvas 1Layer 1DownloadServiceApplicationcodeHttpDataSourceCacheDownloadIndexDownloadManagercommandsreadwriteload / store

Introduction

Android ExoPlayer has an in-built functionality for downloading media files. This is intended to be used by ExoPlayer for offline playback, as indicated in the documentation.

Note: It’s important that you do not try and read files directly from the download directory. Instead, use ExoPlayer library classes as described below.

Recently, I was working on a task that required downloading and processing of video files. I explored how to leverage the download service and manager that came with ExoPlayer.

Downloading your media

Most of ExoPlayer’s default components can be replaced with our own custom implementations. We’ll make changes to the default components to achieve what we want.

Custom downloader

Downloader is responsible for downloading and removing content. ExoPlayer is bundled with some default implementations of the downloader. ProgressiveDownloader is the closest to what we want, except we need to make a simple change to make it work for us.

ProgressiveDownloader fragments the downloaded data into multiple cache files, that is useful when playing the media whiles downloading it. In our situation, we want the data in a single cache file. Unfortunately, we can’t extend the ProgressiveDownloader, so we can copy the code and make that single change.

You can read through the code here

Custom download factory

To use our downloader, we need to inject into a DownloaderFactory.

Downloader manager

Finally, we can create our DownloadManager that will use our custom components.

Rewriting downloaded file

ExoPlayer downloader uses .exo file extension to persist the cached media. We will add a download listener that listens to the download completed state and then change the format of the file. In the code snippet below, we are expecting an .mp4 file.