Offline downloads using the VdoCipher Android SDK
#
OverviewThe VdoCipher Android SDK offers capability to download videos to local storage for offline playback on Android devices running Lollipop and above (API level 20+).
It includes APIs to :
- Fetch available download options for a video in your dashboard
- Download media assets to local storage
- Track download progress
- Manage downloads (query or delete downloads)
We'll explore a typical download workflow in this document. The Sample App on Github provides code examples for a typical use case.
#
Generating OTP for Offline PlaybackTo initialize video playback on website or app, your backend has to generate
an OTP
+playbackInfo
using the VdoCipher API. The regular OTP does
not have permission to be persisted offline. To enable offline playback you
will need to send additional parameters while making the API call for the OTP.
You can specify the time period for which the offline download will be available for playback. The time period of validity is called the rental duration. Beyond the rental duration the license will expire, and the downloaded file will no longer play.
How to generate offline OTP »
You can find more details on the OTP-based playback mechanism at the API page.
#
Get the available options for a mediaA video in your VdoCipher dashboard may be encoded in multiple bitrates (for adaptive streaming) or has multiple audio tracks for different languages. Hence, there are some options regarding what exactly needs to be downloaded. For offline playback, adaptive doesn't make sense, and also the user typically has a preferred language. So, you must specify exactly one video track and exactly one audio track for download.
The first step is to get the available options for the media. We'll use the OptionsDownloader
class for this. We'll need a playbackInfo
and otp
or signature
corresponding to the video to fetch the options.
OptionsDownloader optionsDownloader = new OptionsDownloader(); // assuming we have otp and playbackInfo optionsDownloader().downloadOptionsWithOtp( otp, playbackInfo, new OptionsDownloader.Callback() { @Override public void onOptionsReceived(DownloadOptions options) { // we have received the available download options Log.i("Success", "onOptionsReceived"); // ... }
@Override public void onOptionsNotReceived(ErrorDescription errDesc) { // there was an error downloading the available options String errMsg = "onOptionsNotReceived : " + errDesc.toString(); Log.e("Error", errMsg); } } );
The available options are received in the OptionsDownloader.Callback#onOptionsReceived()
callback in the form of a DownloadOptions
instance. A DownloadOptions
object contains a MediaInfo
object (with general details of the media, such as title, description as set in your VdoCipher dashboard, etc.) and an array of Track
objects corresponding to the available audio and video track options. Each Track
object in the array corresponds to a audio or video track (specified by Track#type
) and contains relevant information such as bitrate, resolution, language, etc.
Once we've obtained the available options, the next step is to make a selection of which tracks to download.
#
Select the tracks to downloadAs mentioned earlier in this document, we need to select exactly one audio track and one video track.
Once we have the download options, we may make selections automatically based on user preferences etc. (e.g. select the highest quality/bitrate) or present the options to the user to choose.
Once a selection has been made (automatically or by the user), make a DownloadSelections
object using the options we received in the previous step and the indices of the tracks we want to download in the Track
array in the DownloadOptions
.
// selections must include exactly one audio track (Track#TYPE_AUDIO) and one video track (Track#TYPE_VIDEO)
// track indices are the index of the track in the Track array in received DownloadOptionsint[] selectionIndices = new int[]{audioTrackIndex, videoTrackIndex};DownloadSelections downloadSelections = new DownloadSelections(downloadOptions, selectionIndices);
Now we have made the selctions specifying which tracks to download. Next step is to specify some more options such as download location on local storage and create a DownloadRequest
.
#
Specify more optionsWe need to specify a storage location for the media files to be downloaded. This location must be a folder on external storage. External storage does not necessarily mean a removable media such as a SD card. Specifically, the location should be inside the directory tree returned by Context#getExternalFilesDir(). This will also ensure the media files are deleted when the app in uninstalled.
We'll store all downloads to a dedicated folder on the external storage.
// ensure external storage is in read-write modeif (!isExternalStorageWritable()) { // External storage is not available; can't proceed Log.e("error", "external storage not available"); Toast.makeText(this, "external storage not available", Toast.LENGTH_LONG).show(); return;}
// we'll download all videos to directory "offlineVideos" on the primary external storageString downloadLocation;try { downloadLocation = getExternalFilesDir(null).getPath() + File.separator + "offlineVideos";} catch (NullPointerException npe) { Log.e("error", "external storage not available: " + Log.getStackTraceString(npe)); Toast.makeText(this, "external storage not available", Toast.LENGTH_LONG).show(); return;}
// ensure download directory is createdFile dlLocation = new File(downloadLocation);if (!(dlLocation.exists() && dlLocation.isDirectory())) { // directory not created yet; let's create it if (!dlLocation.mkdir()) { Log.e("error", "failed to create storage directory"); Toast.makeText(this, "failed to create storage directory", Toast.LENGTH_LONG).show(); return; }}
Now we'll create a new DownloadRequest
.
// build a DownloadRequestDownloadRequest request = new DownloadRequest.Builder(downloadSelections, downloadLocation).build();
Now we have a DownloadRequest
that can be enqueued for download right away. We'll do this in the next step.
#
Enqueue request for downloadThe VdoDownloadManager
class handles enqueuing requests for download. This class a familiar API somewhat similar to the DownloadManager
in Android sdk.
VdoDownloadManager vdoDownloadManager = VdoDownloadManager.getInstance(activityContext);
// enqueue request to VdoDownloadManager for downloadtry { vdoDownloadManager.enqueue(request);} catch (IllegalArgumentException | IllegalStateException e) { Log.e("error", "error enqueuing download request"); Toast.makeText(this, "error enqueuing download request", Toast.LENGTH_LONG).show();}
This will add the request to the download queue and start download when all requests enqueued before have completed.
#
Monitoring download progressWe can monitor the progress of the download queue by registering a EventListener
with the VdoDownloadManager
.
// register a listener for download events; recommended to do this in Activity's onStart()VdoDownloadManager vdoDownloadManager = VdoDownloadManager.getInstance(activityContext);vdoDownloadManager.addEventListener(eventListener);
// don't forget to de-register the listener in Activity's onStop() to avoid memory leaksvdoDownloadManager.removeEventListener(eventListener);
#
Query for downloadsVdoDownloadManager
allows querying for all downloads managed by it or only specific downloads specified by filters.
Queries provide status of all downloads that are queued or downloding or completed. Make a Query
object and specify any filters you want.
Query query = new Query();
// set mediaId filters if these are the only videos for which you want the statusquery.setFilterByMediaId(mediaId1, mediaId2);
// set filters by status// here we filter for downloads which are queued and downloadingquery.setFilterByStatus(VdoDownloadManager.STATUS_PENDING, VdoDownloadManager.STATUS_DOWNLOADING);
Now we can use this query object to query status for the specified downloads. A query result is provided as a list of DownloadStatus
objects which provides information such as the MediaInfo
, status, any errors if they occured while downloading, etc.
The query results are provided asynchronously to a QueryResultListener
provided as an argument to the query method.
vdoDownloadManager.query(query, new VdoDownloadManager.QueryResultListener() { @Override public void onQueryResult(List statusList) { int size = statusList.size(); Log.i(TAG, size + " results found"); }});
#
Delete a downloadTo delete a media download use the VdoDownloadManager#remove()
method. This will cancel the download if it is still downloading or pending and remove any downloaded media files. You will also receive a EventListener#onDeleted()
callback if you have an EventListener
registered with the VdoDownloadManager
.
VdoDownloadManager vdoDownloadManager = VdoDownloadManager.getInstance(activityContext);vdoDownloadManager.remove(mediaIdtoDelete);