ExoPlayer icon indicating copy to clipboard operation
ExoPlayer copied to clipboard

Offline DRM protection

Open sarahachem opened this issue 11 years ago • 57 comments

Hi, Any news on offline DRM protection? Is it possible to decrypt and play a widevine protected movie that is stored on the phone with no internet access?

sarahachem avatar Nov 11 '15 15:11 sarahachem

Offline DRM Protection is Possible via Android DRM SDK, You just have to open the DRM Session on your own.

Extend your class from AbstractDrmSessionManager.

The Keypoint to guide you is in your MediaDrm.KeyRequest the keyType must be of type MediaDrm.KEY_TYPE_OFFLINE

You can find more informations about this here: http://developer.android.com/reference/android/media/MediaDrm.html#KEY_TYPE_OFFLINE

CaptnBlubber avatar Nov 12 '15 12:11 CaptnBlubber

Thank you. However, is it possible to (using exoplayer), bypass the whole server license/key acquisition step and assume licenses are stored locally? Licenses can then be retrieved offline to acquire the key and decrypt and play offline movies?

On a different note, I am testing your samples and when I select sample 4 in WIDEVINE GTS DASH (WV: secure video path required ) I get playerFailed followed by android.media.MediaCodec$CryptoException: Error decrypting data. I changed nothing in the code after downloading the zip file from Github.

sarahachem avatar Nov 15 '15 19:11 sarahachem

Please note that I only get the error on a Samsung 4 while it works on a Samsung 6.

sarahachem avatar Nov 15 '15 21:11 sarahachem

Hi, I am trying to extends the player functionality for Offline Videos.The Query is should i have to write a separate ExtractorRendererBuilder providing the OfflineDRMSessionManager object or i have to use DashRendererbuilder.

Since we are using ExtractorRendererBuilder for playing offline videos, I guess i have to rewrite the same class.

Also do i need to download .mpd file along with .mp4 or only .mp4 will work..??

Amritpal33 avatar Dec 16 '15 06:12 Amritpal33

@Amritpal33 You don't need a new ExtractorRendererBuilder, you only need to create a new DRMSessionManager.

Yes, you should. You will provide the player the mpd file not the mp4, and the mpd should point to the mp4 file.

hakemcpu avatar May 18 '16 10:05 hakemcpu

@sarahachem Regarding your question yes it is possible. But as stated above you will need to create your own DRMSessionManager.

hakemcpu avatar May 18 '16 10:05 hakemcpu

@Amritpal33 - were you able to make it work? @hakemcpu - just in case do you plan to provide any working sample for off-line playback for Widevine modular/DASH? One day it would be great to see Samples.java is extended with off-line playback code.

sergeyt22 avatar May 29 '16 13:05 sergeyt22

Are there any plan to provide off-line sample?

hotchemi avatar Jul 20 '16 09:07 hotchemi

I was able to make it work by writing my own DrmSessionManager that store keys in media drm and later restore it.

Also you can use Extractor renderer builder with this SessionManager to play your video/audio.

On Jul 20, 2016 3:25 PM, "Shintaro Katafuchi" [email protected] wrote:

Are there any plan to provide off-line sample?

— You are receiving this because you were mentioned. Reply to this email directly, view it on GitHub https://github.com/google/ExoPlayer/issues/949#issuecomment-233905132, or mute the thread https://github.com/notifications/unsubscribe-auth/ADjdjsXC5MCennn79ZEOb9T0kb9zsIkEks5qXfCOgaJpZM4GgSz7 .

Amritpal33 avatar Jul 20 '16 10:07 Amritpal33

+1 for an offline DRM sample.

bosbefok avatar Jul 22 '16 01:07 bosbefok

@Amritpal33 Thx for your info! Can you give us a sample code? And one more question, what vide format do you use?

hotchemi avatar Jul 25 '16 07:07 hotchemi

This file will help you to fetch keys and store it in mediaDrm which in turn returns keySetId.

###
import android.annotation.SuppressLint;
import android.content.Context;
import android.media.MediaDrm;
import android.media.NotProvisionedException;
import android.media.UnsupportedSchemeException;
import android.net.Uri;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;
import android.os.Message;
import android.util.Log;

import com.google.android.exoplayer.C;
import com.google.android.exoplayer.demo.WidevineTestMediaDrmCallback;
import com.google.android.exoplayer.drm.DrmInitData;
import com.google.android.exoplayer.extractor.DefaultExtractorInput;
import com.google.android.exoplayer.extractor.Extractor;
import com.google.android.exoplayer.extractor.ExtractorInput;
import com.google.android.exoplayer.extractor.ExtractorOutput;
import com.google.android.exoplayer.extractor.ExtractorSampleSource;
import com.google.android.exoplayer.extractor.PositionHolder;
import com.google.android.exoplayer.extractor.SeekMap;
import com.google.android.exoplayer.extractor.TrackOutput;
import com.google.android.exoplayer.extractor.mp4.PsshAtomUtil;
import com.google.android.exoplayer.upstream.DataSource;
import com.google.android.exoplayer.upstream.DataSpec;
import com.google.android.exoplayer.upstream.DefaultBandwidthMeter;
import com.google.android.exoplayer.upstream.DefaultUriDataSource;
import com.google.android.exoplayer.util.Util;
import com.jio.media.widevinesample.MainActivity;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * Created by amritpalsingh on 16/12/15.
 */
public class WidevineKeysFetcher implements ExtractorOutput
{

    PositionHolder _positionHolder;
    PostResponseHandler _postResponseHandler;

    private HandlerThread _requestHandlerThread;
    private Handler _postRequestHandler;
    private Extractor _extractor;
    private String _mimeType;
    private byte[] _schemeData;
    private byte[] _sessionId;
    private static final int MSG_KEYS = 1;
    private MediaDrm _mediaDrm;
    private static final String TAG = WidevineKeysFetcher.class.getSimpleName();
    private String _assetID;
    private Context _context;
    private static WidevineKeysFetcher _instance;
    public static final String OUTPUT_FILE_PATH="/mnt/sdcard/wv/lic.text";


    private WidevineKeysFetcher()
    {
        if (_instance != null)
        {
            throw new IllegalStateException("No two instances of this class can co-exists.");
        }
        _positionHolder = new PositionHolder();
    }

    public static WidevineKeysFetcher getInstance()
    {
        if (_instance == null)
        {
            synchronized (WidevineKeysFetcher.class)
            {
                _instance = new WidevineKeysFetcher();
            }
        }
        return _instance;
    }

    public void fetchKeys(Context context, String assetID, String userAgent, String filePath, Extractor... extractors)
    {

        _assetID = assetID;
        _context = context;

        int result = Extractor.RESULT_CONTINUE;
        DefaultBandwidthMeter bandwidthMeter = new DefaultBandwidthMeter(null, null);
        DataSource dataSource = new DefaultUriDataSource(_context, bandwidthMeter, userAgent);

        ExtractorInput input = null;
        try
        {
            long position = _positionHolder.position;
            long length = 0;

            length = dataSource.open(new DataSpec(Uri.parse(filePath), position, C.LENGTH_UNBOUNDED, null));

            if (length != C.LENGTH_UNBOUNDED)
            {
                length += position;
            }
            input = new DefaultExtractorInput(dataSource, position, length);
            if (extractors == null || extractors.length == 0)
            {
                extractors = new Extractor[ExtractorSampleSource.DEFAULT_EXTRACTOR_CLASSES.size()];
                for (int i = 0; i < extractors.length; i++)
                {
                    try
                    {
                        extractors[i] = ExtractorSampleSource.DEFAULT_EXTRACTOR_CLASSES.get(i).newInstance();
                    }
                    catch (InstantiationException e)
                    {
                        throw new IllegalStateException("Unexpected error creating default extractor", e);
                    }
                    catch (IllegalAccessException e)
                    {
                        throw new IllegalStateException("Unexpected error creating default extractor", e);
                    }
                }
            }

            ExtractorSampleSource.ExtractorHolder extractorHolder = new ExtractorSampleSource.ExtractorHolder(extractors, this);
            _extractor = extractorHolder.selectExtractor(input);

            while (result == Extractor.RESULT_CONTINUE)
            {
                result = _extractor.read(input, _positionHolder);
            }
        }

        catch (IOException e)
        {
            e.printStackTrace();
        }
        catch (InterruptedException e)
        {
            e.printStackTrace();
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        finally
        {
            if (result == Extractor.RESULT_SEEK)
            {
                result = Extractor.RESULT_CONTINUE;
            }
            else if (input != null)
            {
                _positionHolder.position = input.getPosition();
            }

            try
            {
                dataSource.close();
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
        }
    }

    /**
     * Invoked when the {@link Extractor} identifies the existence of a track in the stream.
     * <p/>
     * Returns a {@link TrackOutput} that will receive track level data belonging to the track.
     *
     * @param trackId A track identifier.
     * @return The {@link TrackOutput} that should receive track level data belonging to the track.
     */
    @Override
    public TrackOutput track(int trackId)
    {
        return null;
    }

    /**
     * Invoked when all tracks have been identified, meaning that {@link #track(int)} will not be
     * invoked again.
     */
    @Override
    public void endTracks()
    {

    }

    /**
     * Invoked when a {@link SeekMap} has been extracted from the stream.
     *
     * @param seekMap The extracted {@link SeekMap}.
     */
    @Override
    public void seekMap(SeekMap seekMap)
    {

    }

    /**
     * Invoked when {@link DrmInitData} has been extracted from the stream.
     *
     * @param drmInitData The extracted {@link DrmInitData}.
     */
    @Override
    public void drmInitData(DrmInitData drmInitData)
    {
        createFetchKeyRequest(drmInitData);
    }

    private void initDRM()
    {
        try
        {
            _mediaDrm = new MediaDrm(OfflineDRMSessionManager.WIDEVINE_UUID);
            _sessionId = _mediaDrm.openSession();
            postKeyRequest();
        }
        catch (UnsupportedSchemeException e)
        {
            e.printStackTrace();
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }


    private void postKeyRequest()
    {
        MediaDrm.KeyRequest keyRequest;
        try
        {
            keyRequest = _mediaDrm.getKeyRequest(_sessionId, _schemeData, _mimeType,
                    MediaDrm.KEY_TYPE_OFFLINE, null);
            _postRequestHandler.obtainMessage(MSG_KEYS, keyRequest).sendToTarget();
        }
        catch (NotProvisionedException e)
        {
            // onKeysError(e);
        }
    }


    private void createFetchKeyRequest(DrmInitData drmInitData)
    {
        if (_postRequestHandler == null)
        {
            _postResponseHandler = new PostResponseHandler(_context.getMainLooper());
        }
        if (_postRequestHandler == null)
        {
            _requestHandlerThread = new HandlerThread("DrmRequestHandler");
            _requestHandlerThread.start();
            _postRequestHandler = new PostRequestHandler(_requestHandlerThread.getLooper());
        }
        if (_schemeData == null)
        {
            _mimeType = drmInitData.mimeType;
            _schemeData = drmInitData.get(OfflineDRMSessionManager.WIDEVINE_UUID);
            if (_schemeData == null)
            {
                return;
            }
            if (Util.SDK_INT < 21)
            {
                Log.i(TAG, "+++Android version<21, Reading pssh header");
                // Prior to L the Widevine CDM required data to be extracted from the PSSH atom.
                byte[] psshData = PsshAtomUtil.parseSchemeSpecificData(_schemeData, OfflineDRMSessionManager.WIDEVINE_UUID);
                if (psshData == null)
                {
                    // Extraction failed. _schemeData isn't a Widevine PSSH atom, so leave it unchanged.
                }
                else
                {
                    _schemeData = psshData;
                }
            }
        }
        initDRM();
    }

    @SuppressLint("HandlerLeak")
    private class PostRequestHandler extends Handler
    {

        public PostRequestHandler(Looper backgroundLooper)
        {
            super(backgroundLooper);
        }

        @Override
        public void handleMessage(Message msg)
        {
            Object response;
            try
            {
                switch (msg.what)
                {
                    case MSG_KEYS:
                        response = new WidevineTestMediaDrmCallback(_assetID).executeKeyRequest(OfflineDRMSessionManager.WIDEVINE_UUID, (MediaDrm.KeyRequest) msg.obj);
                        break;
                    default:
                        throw new RuntimeException();
                }
            }
            catch (Exception e)
            {
                response = e;
            }
            _postResponseHandler.obtainMessage(msg.what, response).sendToTarget();
        }

    }

    @SuppressLint("HandlerLeak")
    private class PostResponseHandler extends Handler
    {

        public PostResponseHandler(Looper looper)
        {
            super(looper);
        }

        @Override
        public void handleMessage(Message msg)
        {
            switch (msg.what)
            {
                case MSG_KEYS:
                    onKeyResponse(msg.obj);
                    return;
            }
        }

    }

    private void onKeyResponse(Object response)
    {
        if (response instanceof Exception)
        {
            return;
        }

        try
        {
            byte[] keySetID = _mediaDrm.provideKeyResponse(_sessionId, (byte[]) response);
            File outputFile=new File(OUTPUT_FILE_PATH);
            if(!outputFile.exists())
            {
                outputFile.createNewFile();
            }

            FileOutputStream outputStream=new FileOutputStream(outputFile);
            outputStream.write(keySetID,0,keySetID.length);
            outputStream.flush();
            outputStream.close();

            //MainActivity.TEMP_KEYSET_ID = keySetID;
            Log.d(TAG, "++++++key set id after response" + keySetID);
        }

        catch (Exception e)
        {
            e.printStackTrace();
        }
    }

}

Here is the same Offline DRMSessionManager implementation that restore keys using keySetId which you have store somewhere in your db.

Once you get the keys

package com.google.android.exoplayer.demo.offline;

import android.annotation.SuppressLint;
import android.media.MediaCrypto;
import android.media.MediaDrm;
import android.media.NotProvisionedException;
import android.media.UnsupportedSchemeException;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;
import android.os.Message;
import android.util.Log;

import com.google.android.exoplayer.drm.DrmInitData;
import com.google.android.exoplayer.drm.DrmSessionManager;
import com.google.android.exoplayer.drm.KeysExpiredException;
import com.google.android.exoplayer.drm.MediaDrmCallback;
import com.google.android.exoplayer.drm.UnsupportedDrmException;

import java.util.HashMap;
import java.util.UUID;

/**
 * Created by amritpalsingh on 16/12/15.
 */
public class OfflineDRMSessionManager implements DrmSessionManager
{

    /**
     * UUID for the Widevine DRM scheme.
     */
    public static final UUID WIDEVINE_UUID = UUID.fromString("edef8ba9-79d6-4ace-a3c8-27dcd51d21ed");

    private final Handler eventHandler;
    private final EventListener eventListener;
    private final MediaDrm mediaDrm;
    private final HashMap<String, String> optionalKeyRequestParameters;

    /* package */ final MediaDrmHandler mediaDrmHandler;
    /* package */ final MediaDrmCallback callback;
    /* package */ final UUID uuid;

    private int openCount;
    private int state;
    private MediaCrypto mediaCrypto;
    private Exception lastException;
    private byte[] sessionId;
    private byte[] keySetID;
    private static final String TAG = OfflineDRMSessionManager.class.getSimpleName();


    /**
     * Interface definition for a callback to be notified of {@link OfflineDRMSessionManager}
     * events.
     */
    public interface EventListener
    {
        /**
         * Invoked when a drm error occurs.
         *
         * @param e The corresponding exception.
         */
        void onDrmSessionManagerError(Exception e);

    }

    /**
     * Instantiates a new instance using the Widevine scheme.
     *
     * @param playbackLooper               The looper associated with the media playback thread. Should usually be
     *                                     obtained using {@link com.google.android.exoplayer.ExoPlayer#getPlaybackLooper()}.
     * @param callback                     Performs key and provisioning requests.
     * @param optionalKeyRequestParameters An optional map of parameters to pass as the last argument
     *                                     to {@link MediaDrm#getKeyRequest(byte[], byte[], String, int, HashMap)}. May be null.
     * @param eventHandler                 A handler to use when delivering events to {@code eventListener}. May be
     *                                     null if delivery of events is not required.
     * @param eventListener                A listener of events. May be null if delivery of events is not required.
     * @throws UnsupportedDrmException If the specified DRM scheme is not supported.
     */
    public static OfflineDRMSessionManager newWidevineInstance(Looper playbackLooper,
                                                               MediaDrmCallback callback, HashMap<String, String> optionalKeyRequestParameters,
                                                               Handler eventHandler, EventListener eventListener,byte[] keySetId) throws UnsupportedDrmException
    {
        return new OfflineDRMSessionManager(WIDEVINE_UUID, playbackLooper, callback,
                optionalKeyRequestParameters, eventHandler, eventListener,keySetId);
    }

    /**
     * @param uuid                         The UUID of the drm scheme.
     * @param playbackLooper               The looper associated with the media playback thread. Should usually be
     *                                     obtained using {@link com.google.android.exoplayer.ExoPlayer#getPlaybackLooper()}.
     * @param callback                     Performs key and provisioning requests.
     * @param optionalKeyRequestParameters An optional map of parameters to pass as the last argument
     *                                     to {@link MediaDrm#getKeyRequest(byte[], byte[], String, int, HashMap)}. May be null.
     * @param eventHandler                 A handler to use when delivering events to {@code eventListener}. May be
     *                                     null if delivery of events is not required.
     * @param eventListener                A listener of events. May be null if delivery of events is not required.
     * @throws UnsupportedDrmException If the specified DRM scheme is not supported.
     */
    private OfflineDRMSessionManager(UUID uuid, Looper playbackLooper, MediaDrmCallback callback,
                                    HashMap<String, String> optionalKeyRequestParameters, Handler eventHandler,
                                    EventListener eventListener,byte[] keySetId) throws UnsupportedDrmException
    {
        this.uuid = uuid;
        this.callback = callback;
        this.optionalKeyRequestParameters = optionalKeyRequestParameters;
        this.eventHandler = eventHandler;
        this.eventListener = eventListener;
        this.keySetID =keySetId;
        try
        {
            mediaDrm = new MediaDrm(uuid);
        }
        catch (UnsupportedSchemeException e)
        {
            throw new UnsupportedDrmException(UnsupportedDrmException.REASON_UNSUPPORTED_SCHEME, e);
        }
        catch (Exception e)
        {
            throw new UnsupportedDrmException(UnsupportedDrmException.REASON_INSTANTIATION_ERROR, e);
        }
        mediaDrm.setOnEventListener(new MediaDrmEventListener());
        mediaDrmHandler = new MediaDrmHandler(playbackLooper);
        state = STATE_CLOSED;
    }


    /**
     * Opens the session, possibly asynchronously.
     *
     * @param drmInitData DRM initialization data.
     */
    @Override
    public void open(DrmInitData drmInitData)
    {
        if (++openCount != 1)
        {
            return;
        }
        state = STATE_OPENING;
        openInternal(true);
    }


    private void openInternal(boolean allowProvisioning)
    {
        try
        {
            sessionId = mediaDrm.openSession();
            Log.i(TAG, "+++Creating MediaCrypto");
            mediaCrypto = new MediaCrypto(uuid, sessionId);
            state = STATE_OPENED;
            restoreKeys();
        }
        catch (NotProvisionedException e)
        {
            if (allowProvisioning)
            {
                //postProvisionRequest();
            }
            else
            {
                onError(e);
            }
        }
        catch (Exception e)
        {
            onError(e);
        }
    }

    /**
     * Closes the session.
     */
    @Override
    public void close()
    {
        if (--openCount != 0)
        {
            return;
        }
        state = STATE_CLOSED;
        mediaDrmHandler.removeCallbacksAndMessages(null);
        mediaCrypto = null;
        lastException = null;
        if (sessionId != null)
        {
            mediaDrm.closeSession(sessionId);
            sessionId = null;
        }
    }

    /**
     * Gets the current state of the session.
     *
     * @return One of {@link #STATE_ERROR}, {@link #STATE_CLOSED}, {@link #STATE_OPENING},
     * {@link #STATE_OPENED} and {@link #STATE_OPENED_WITH_KEYS}.
     */
    @Override
    public int getState()
    {
        return state;
    }

    /**
     * Gets a {@link MediaCrypto} for the open session.
     * <p/>
     * This method may be called when the manager is in the following states:
     * {@link #STATE_OPENED}, {@link #STATE_OPENED_WITH_KEYS}
     *
     * @return A {@link MediaCrypto} for the open session.
     * @throws IllegalStateException If called when a session isn't opened.
     */
    @Override
    public MediaCrypto getMediaCrypto()
    {
        if (state != STATE_OPENED && state != STATE_OPENED_WITH_KEYS)
        {
            throw new IllegalStateException();
        }
        return mediaCrypto;
    }

    /**
     * Whether the session requires a secure decoder for the specified mime type.
     * <p/>
     * Normally this method should return {@link MediaCrypto#requiresSecureDecoderComponent(String)},
     * however in some cases implementations  may wish to modify the return value (i.e. to force a
     * secure decoder even when one is not required).
     * <p/>
     * This method may be called when the manager is in the following states:
     * {@link #STATE_OPENED}, {@link #STATE_OPENED_WITH_KEYS}
     *
     * @param mimeType
     * @return Whether the open session requires a secure decoder for the specified mime type.
     * @throws IllegalStateException If called when a session isn't opened.
     */
    @Override
    public boolean requiresSecureDecoderComponent(String mimeType)
    {
        if (state != STATE_OPENED && state != STATE_OPENED_WITH_KEYS)
        {
            throw new IllegalStateException();
        }
        return mediaCrypto.requiresSecureDecoderComponent(mimeType);
    }

    /**
     * Gets the cause of the error state.
     * <p/>
     * This method may be called when the manager is in any state.
     *
     * @return An exception if the state is {@link #STATE_ERROR}. Null otherwise.
     */
    @Override
    public Exception getError()
    {
        return state == STATE_ERROR ? lastException : null;
    }


    @SuppressLint("HandlerLeak")
    private class MediaDrmHandler extends Handler
    {

        public MediaDrmHandler(Looper looper)
        {
            super(looper);
        }

        @Override
        public void handleMessage(Message msg)
        {
            if (openCount == 0 || (state != STATE_OPENED && state != STATE_OPENED_WITH_KEYS))
            {
                return;
            }
            switch (msg.what)
            {
                case MediaDrm.EVENT_KEY_REQUIRED:
                    restoreKeys();
                    return;
                case MediaDrm.EVENT_KEY_EXPIRED:
                    state = STATE_OPENED;
                    onError(new KeysExpiredException());
                    return;
            }
        }

    }

    private class MediaDrmEventListener implements MediaDrm.OnEventListener
    {

        @Override
        public void onEvent(MediaDrm md, byte[] sessionId, int event, int extra, byte[] data)
        {
            mediaDrmHandler.sendEmptyMessage(event);
        }

    }

    private void onError(final Exception e)
    {
        lastException = e;
        if (eventHandler != null && eventListener != null)
        {
            eventHandler.post(new Runnable()
            {
                @Override
                public void run()
                {
                    eventListener.onDrmSessionManagerError(e);
                }
            });
        }
        if (state != STATE_OPENED_WITH_KEYS)
        {
            state = STATE_ERROR;
        }
    }

    private void restoreKeys()
    {
        if(keySetID ==null)
        {
            return;
        }

        mediaDrm.restoreKeys(sessionId, keySetID);
        state = STATE_OPENED_WITH_KEYS;
    }

}

Amritpal33 avatar Jul 25 '16 16:07 Amritpal33

@Amritpal33 awesome! Thanks for the code samples, this really helped me get going with offline DRM. As mentioned above, I would also like an official code sample/implementation in the Exoplayer project to achieve this.

jonhan avatar Aug 22 '16 12:08 jonhan

Does anyone interested in the same implementation for the ExoPlayer v2 ?

ChernyshovYuriy avatar Sep 25 '16 22:09 ChernyshovYuriy

@ChernyshovYuriy we are interested in the same implementation in Exoplayer. Is it possible to download DRM protected DASH stream to be downloaded using exoplayer to playback offline without Internet?

techguy2 avatar Sep 26 '16 14:09 techguy2

Hi @techguy2 . The intention of my question was: "does any one else tried to implement solution provided by Amritpal33 commented on Jul 25 with Exo Player v2". Sorry if I confused someone, I do not have solution so far and as well.

ChernyshovYuriy avatar Sep 26 '16 16:09 ChernyshovYuriy

Hello @ChernyshovYuriy and all

I have implemented it for an offline player reading dash encrypted videos (using mpd descriptor)

Here is how i made it work :

A. Use the two classes from @Amritpal33 (WidevineKeysFetcher and OfflineDRMSessionManager) I've modified WidevineKeysFetcher because using it as a singleton causes issues when using it multiple times. Please see https://github.com/papaanoel/exoplayer-dash-offline/tree/master/app/src/main/java/fr/artestudio/offlinedrm/helper/widewine for modified versions.

B. Then use WidevineKeysFetcher to retrieve licence when needed (I personnaly call it before downloading the video segments)

WidevineKeysFetcher fetcher = new WidevineKeysFetcher(); fetcher.fetchKeys(context, null, "fakeuseragent", dashUrl, new FragmentedMp4Extractor());

Important note here, dashUrl is the url of the "initialisation" parameter in the mpd for example :

<SegmentTemplate timescale="48000" initialization="video50-$RepresentationID$.dash" media="video50-$RepresentationID$-$Number$.m4s" startNumber="1" duration="144000"> </SegmentTemplate>

WidevineKeysFetcher has a callback method private void onKeyResponse(Object response) which gives you the licence key that you will have to store somewhere (database, filesystem) for future use.

C. Once you have called and stored your licence somewhere in your app, you will be able to use it like this

Call the exoplayer activity playerActivity with an extra key PlayerActivity.KEY_SET_ID containing the licence that you have stored :

Intent mpdIntent = new Intent(v.getContext(), PlayerActivity.class) .setData(Uri.parse(le.getUrl())) .putExtra(PlayerActivity.CONTENT_ID_EXTRA, "") .putExtra(PlayerActivity.CONTENT_TYPE_EXTRA, Util.TYPE_DASH) .putExtra(PlayerActivity.PROVIDER_EXTRA, "") .putExtra(PlayerActivity.KEY_SET_ID, "your_licence_key"); v.getContext().startActivity(mpdIntent);

and modify the private Player.RendererBuilder getRendererBuilder() in playerActivity so that the DashRendererBuilder uses the licence you have stored :

// Internal methods
    private Player.RendererBuilder getRendererBuilder() {
        String userAgent = Util.getUserAgent(this, "ExoPlayerDemo");
        switch (contentType) {
            case Util.TYPE_SS:
                return new SmoothStreamingRendererBuilder(this, userAgent, contentUri.toString(),
                        new SmoothStreamingTestMediaDrmCallback());
            case Util.TYPE_DASH:
                return new DashRendererBuilder(this, userAgent, contentUri.toString(),
                        new WidevineMediaDrmCallback(true), keySetId);
            case Util.TYPE_HLS:
                return new HlsRendererBuilder(this, userAgent, contentUri.toString());
            case Util.TYPE_OTHER:
                return new ExtractorRendererBuilder(this, userAgent, contentUri);
            default:
                throw new IllegalStateException("Unsupported type: " + contentType);
        }
    }

Last, in DashRendererBuilder, in buildRenderers() method, instead of using

 drmSessionManager = StreamingDrmSessionManager.newWidevineInstance(
                                player.getPlaybackLooper(), drmCallback, null, player.getMainHandler(), player);

use

drmSessionManager = OfflineDRMSessionManager.newWidevineInstance(player.getPlaybackLooper(), drmCallback, null, player.getMainHandler(), player, keySetId.getBytes());

This worked for me, hope this will help.

papaanoel avatar Oct 04 '16 10:10 papaanoel

We have just finished our offline Dash+Widevine implementation now and we chose a slightly different method to fetch the init segment. Instead of using a class like the proposed WidevineKeysFetcher we basically just created a separate DashRenderBuilder that uses a configuration of the OfflineDRMSessionManager for storing the DRM keys.

Then we are using an Android Service that sets up a headless instance of Exoplayer using this RenderBuilder and just calls prepare() on the player. This leads to that Exoplayer internally calls all logic for fetching the init-segment and passing it to the OfflineDRMSessionManager.

Don't know if this is a slightly unorthodox way of solving it but it's an easy setup and seems to work fine for us so far.

jonhan avatar Oct 04 '16 11:10 jonhan

I tried the logic provided by @papaanoel and @Amritpal33 but I am getting exceptions in WidevineKeysFetcher class. what is the "dashUrl" point to in the method signature fetchKeys. and is there any sample app available where I get the implemetation logic (even a crude is ok).

ram992 avatar Oct 19 '16 09:10 ram992

Hello @ram992,

dashUrl in the method signature fetchKeys(...) is the url of the initialization segment of the video stream. For example, if you're using a mpd container, considering the following piece of mpd :

<AdaptationSet group="2" contentType="video" par="16:9" minBandwidth="2356000" maxBandwidth="2356000" segmentAlignment="true" width="1280" height="720" mimeType="video/mp4" codecs="avc1.640028" startWithSAP="1">
<!--  Common Encryption  -->
<ContentProtection schemeIdUri="urn:mpeg:dash:mp4" value="cenc" cenc:default_KID=""></ContentProtection>
<!--  PlayReady  -->
<ContentProtection schemeIdUri="" value="MSPR 2.0"></ContentProtection>
<!--  Widevine  -->
<ContentProtection schemeIdUri=""></ContentProtection>
<!--  Marlin  -->
<ContentProtection schemeIdUri="">
<mas:MarlinContentIds>
<mas:MarlinContentId></mas:MarlinContentId>
</mas:MarlinContentIds>
</ContentProtection>
<SegmentTemplate timescale="12800" initialization="init/initSegment-$RepresentationID$.dash" media="video-$RepresentationID$-$Number$.m4s" startNumber="1" duration="38400"></SegmentTemplate>
<Representation id="video=2356000" bandwidth="2356000" scanType="progressive"></Representation>
</AdaptationSet>

the initialization segment is located in <segmentTemplate>

<SegmentTemplate timescale="12800" initialization="init/initSegment-$RepresentationID$.dash" media="video-$RepresentationID$-$Number$.m4s" startNumber="1" duration="38400"></SegmentTemplate>

and thus the initialization segment in this case is init/initSegment-video=2356000.dash

Consequently, dashUrl should be http://<absolute_path_to_your_cdn>/init/initSegment-ideo=2356000.dash and that's what should be passed in the fetchKeys method.

Hope this will help,

papaanoel avatar Oct 19 '16 14:10 papaanoel