MediaDrm.java revision f0d4777473f25847d67fc17fc082fada08cf678d
1/*
2 * Copyright (C) 2013 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package android.media;
18
19import android.media.MediaDrmException;
20import java.lang.ref.WeakReference;
21import java.util.UUID;
22import java.util.HashMap;
23import java.util.List;
24import android.os.Handler;
25import android.os.Looper;
26import android.os.Message;
27import android.os.Bundle;
28import android.os.Parcel;
29import android.util.Log;
30
31/**
32 * MediaDrm can be used to obtain keys for decrypting protected media streams, in
33 * conjunction with {@link android.media.MediaCrypto}.  The MediaDrm APIs
34 * are designed to support the ISO/IEC 23001-7: Common Encryption standard, but
35 * may also be used to implement other encryption schemes.
36 * <p>
37 * Encrypted content is prepared using an encryption server and stored in a content
38 * library. The encrypted content is streamed or downloaded from the content library to
39 * client devices via content servers.  Licenses to view the content are obtained from
40 * a License Server.
41 * <p>
42 * <p><img src="../../../images/mediadrm_overview.png"
43 *      alt="MediaDrm Overview diagram"
44 *      border="0" /></p>
45 * <p>
46 * Keys are requested from the license server using a key request. The key
47 * response is delivered to the client app, which provides the response to the
48 * MediaDrm API.
49 * <p>
50 * A Provisioning server may be required to distribute device-unique credentials to
51 * the devices.
52 * <p>
53 * Enforcing requirements related to the number of devices that may play content
54 * simultaneously can be performed either through key renewal or using the secure
55 * stop methods.
56 * <p>
57 * The following sequence diagram shows the interactions between the objects
58 * involved while playing back encrypted content:
59 * <p>
60 * <p><img src="../../../images/mediadrm_decryption_sequence.png"
61 *         alt="MediaDrm Overview diagram"
62 *         border="0" /></p>
63 * <p>
64 * The app first constructs {@link android.media.MediaExtractor} and
65 * {@link android.media.MediaCodec} objects. It accesses the DRM-scheme-identifying UUID,
66 * typically from metadata in the content, and uses this UUID to construct an instance
67 * of a MediaDrm object that is able to support the DRM scheme required by the content.
68 * Crypto schemes are assigned 16 byte UUIDs.  The method {@link #isCryptoSchemeSupported}
69 * can be used to query if a given scheme is supported on the device.
70 * <p>
71 * The app calls {@link #openSession} to generate a sessionId that will uniquely identify
72 * the session in subsequent interactions. The app next uses the MediaDrm object to
73 * obtain a key request message and send it to the license server, then provide
74 * the server's response to the MediaDrm object.
75 * <p>
76 * Once the app has a sessionId, it can construct a MediaCrypto object from the UUID and
77 * sessionId.  The MediaCrypto object is registered with the MediaCodec in the
78 * {@link MediaCodec.#configure} method to enable the codec to decrypt content.
79 * <p>
80 * When the app has constructed {@link android.media.MediaExtractor},
81 * {@link android.media.MediaCodec} and {@link android.media.MediaCrypto} objects,
82 * it proceeds to pull samples from the extractor and queue them into the decoder.  For
83 * encrypted content, the samples returned from the extractor remain encrypted, they
84 * are only decrypted when the samples are delivered to the decoder.
85 * <p>
86 * <a name="Callbacks"></a>
87 * <h3>Callbacks</h3>
88 * <p>Applications should register for informational events in order
89 * to be informed of key state updates during playback or streaming.
90 * Registration for these events is done via a call to
91 * {@link #setOnEventListener}. In order to receive the respective
92 * callback associated with this listener, applications are required to create
93 * MediaDrm objects on a thread with its own Looper running (main UI
94 * thread by default has a Looper running).
95 */
96public final class MediaDrm {
97
98    private final static String TAG = "MediaDrm";
99
100    private EventHandler mEventHandler;
101    private OnEventListener mOnEventListener;
102
103    private int mNativeContext;
104
105    /**
106     * Query if the given scheme identified by its UUID is supported on
107     * this device.
108     * @param uuid The UUID of the crypto scheme.
109     */
110    public static final boolean isCryptoSchemeSupported(UUID uuid) {
111        return isCryptoSchemeSupportedNative(getByteArrayFromUUID(uuid));
112    }
113
114    private static final byte[] getByteArrayFromUUID(UUID uuid) {
115        long msb = uuid.getMostSignificantBits();
116        long lsb = uuid.getLeastSignificantBits();
117
118        byte[] uuidBytes = new byte[16];
119        for (int i = 0; i < 8; ++i) {
120            uuidBytes[i] = (byte)(msb >>> (8 * (7 - i)));
121            uuidBytes[8 + i] = (byte)(lsb >>> (8 * (7 - i)));
122        }
123
124        return uuidBytes;
125    }
126
127    private static final native boolean isCryptoSchemeSupportedNative(byte[] uuid);
128
129    /**
130     * Instantiate a MediaDrm object using opaque, crypto scheme specific
131     * data.
132     * @param uuid The UUID of the crypto scheme.
133     */
134    public MediaDrm(UUID uuid) throws MediaDrmException {
135        Looper looper;
136        if ((looper = Looper.myLooper()) != null) {
137            mEventHandler = new EventHandler(this, looper);
138        } else if ((looper = Looper.getMainLooper()) != null) {
139            mEventHandler = new EventHandler(this, looper);
140        } else {
141            mEventHandler = null;
142        }
143
144        /* Native setup requires a weak reference to our object.
145         * It's easier to create it here than in C++.
146         */
147        native_setup(new WeakReference<MediaDrm>(this),
148                     getByteArrayFromUUID(uuid));
149    }
150
151    /**
152     * Register a callback to be invoked when an event occurs
153     *
154     * @param listener the callback that will be run
155     */
156    public void setOnEventListener(OnEventListener listener)
157    {
158        mOnEventListener = listener;
159    }
160
161    /**
162     * Interface definition for a callback to be invoked when a drm event
163     * occurs
164     */
165    public interface OnEventListener
166    {
167        /**
168         * Called when an event occurs that requires the app to be notified
169         *
170         * @param md the MediaDrm object on which the event occurred
171         * @param sessionId the DRM session ID on which the event occurred
172         * @param event indicates the event type
173         * @param extra an secondary error code
174         * @param data optional byte array of data that may be associated with the event
175         */
176        void onEvent(MediaDrm md, byte[] sessionId, int event, int extra, byte[] data);
177    }
178
179    /**
180     * This event type indicates that the app needs to request a certificate from
181     * the provisioning server.  The request message data is obtained using
182     * {@link #getProvisionRequest}
183     */
184    public static final int EVENT_PROVISION_REQUIRED = 1;
185
186    /**
187     * This event type indicates that the app needs to request keys from a license
188     * server.  The request message data is obtained using {@link #getKeyRequest}.
189     */
190    public static final int EVENT_KEY_REQUIRED = 2;
191
192    /**
193     * This event type indicates that the licensed usage duration for keys in a session
194     * has expired.  The keys are no longer valid.
195     */
196    public static final int EVENT_KEY_EXPIRED = 3;
197
198    /**
199     * This event may indicate some specific vendor-defined condition, see your
200     * DRM provider documentation for details
201     */
202    public static final int EVENT_VENDOR_DEFINED = 4;
203
204    private static final int DRM_EVENT = 200;
205
206    private class EventHandler extends Handler
207    {
208        private MediaDrm mMediaDrm;
209
210        public EventHandler(MediaDrm md, Looper looper) {
211            super(looper);
212            mMediaDrm = md;
213        }
214
215        @Override
216        public void handleMessage(Message msg) {
217            if (mMediaDrm.mNativeContext == 0) {
218                Log.w(TAG, "MediaDrm went away with unhandled events");
219                return;
220            }
221            switch(msg.what) {
222
223            case DRM_EVENT:
224                Log.i(TAG, "Drm event (" + msg.arg1 + "," + msg.arg2 + ")");
225
226                if (mOnEventListener != null) {
227                    if (msg.obj != null && msg.obj instanceof Parcel) {
228                        Parcel parcel = (Parcel)msg.obj;
229                        byte[] sessionId = parcel.createByteArray();
230                        if (sessionId.length == 0) {
231                            sessionId = null;
232                        }
233                        byte[] data = parcel.createByteArray();
234                        if (data.length == 0) {
235                            data = null;
236                        }
237                        mOnEventListener.onEvent(mMediaDrm, sessionId, msg.arg1, msg.arg2, data);
238                    }
239                }
240                return;
241
242            default:
243                Log.e(TAG, "Unknown message type " + msg.what);
244                return;
245            }
246        }
247    }
248
249    /*
250     * This method is called from native code when an event occurs.  This method
251     * just uses the EventHandler system to post the event back to the main app thread.
252     * We use a weak reference to the original MediaPlayer object so that the native
253     * code is safe from the object disappearing from underneath it.  (This is
254     * the cookie passed to native_setup().)
255     */
256    private static void postEventFromNative(Object mediadrm_ref,
257                                            int eventType, int extra, Object obj)
258    {
259        MediaDrm md = (MediaDrm)((WeakReference)mediadrm_ref).get();
260        if (md == null) {
261            return;
262        }
263        if (md.mEventHandler != null) {
264            Message m = md.mEventHandler.obtainMessage(DRM_EVENT, eventType, extra, obj);
265            md.mEventHandler.sendMessage(m);
266        }
267    }
268
269    /**
270     * Open a new session with the MediaDrm object.  A session ID is returned.
271     */
272    public native byte[] openSession();
273
274    /**
275     * Close a session on the MediaDrm object that was previously opened
276     * with {@link #openSession}.
277     */
278    public native void closeSession(byte[] sessionId);
279
280    /**
281     * This key request type species that the keys will be for online use, they will
282     * not be saved to the device for subsequent use when the device is not connected
283     * to a network.
284     */
285    public static final int KEY_TYPE_STREAMING = 1;
286
287    /**
288     * This key request type specifies that the keys will be for offline use, they
289     * will be saved to the device for use when the device is not connected to a network.
290     */
291    public static final int KEY_TYPE_OFFLINE = 2;
292
293    /**
294     * This key request type specifies that previously saved offline keys should be released.
295     */
296    public static final int KEY_TYPE_RELEASE = 3;
297
298    /**
299     * Contains the opaque data an app uses to request keys from a license server
300     */
301    public final static class KeyRequest {
302        KeyRequest() {}
303
304        /**
305         * Get the opaque message data
306         */
307        public byte[] getData() { return mData; }
308
309        /**
310         * Get the default URL to use when sending the key request message to a
311         * server, if known.  The app may prefer to use a different license
312         * server URL from other sources.
313         */
314        public String getDefaultUrl() { return mDefaultUrl; }
315
316        private byte[] mData;
317        private String mDefaultUrl;
318    };
319
320    /**
321     * A key request/response exchange occurs between the app and a license server
322     * to obtain or release keys used to decrypt encrypted content.
323     * <p>
324     * getKeyRequest() is used to obtain an opaque key request byte array that is
325     * delivered to the license server.  The opaque key request byte array is returned
326     * in KeyRequest.data.  The recommended URL to deliver the key request to is
327     * returned in KeyRequest.defaultUrl.
328     * <p>
329     * After the app has received the key request response from the server,
330     * it should deliver to the response to the DRM engine plugin using the method
331     * {@link #provideKeyResponse}.
332     *
333     * @param scope may be a sessionId or a keySetId, depending on the specified keyType.
334     * When the keyType is KEY_TYPE_STREAMING or KEY_TYPE_OFFLINE,
335     * scope should be set to the sessionId the keys will be provided to.  When the keyType
336     * is KEY_TYPE_RELEASE, scope should be set to the keySetId of the keys
337     * being released. Releasing keys from a device invalidates them for all sessions.
338     * @param init container-specific data, its meaning is interpreted based on the
339     * mime type provided in the mimeType parameter.  It could contain, for example,
340     * the content ID, key ID or other data obtained from the content metadata that is
341     * required in generating the key request. init may be null when keyType is
342     * KEY_TYPE_RELEASE.
343     * @param mimeType identifies the mime type of the content
344     * @param keyType specifes the type of the request. The request may be to acquire
345     * keys for streaming or offline content, or to release previously acquired
346     * keys, which are identified by a keySetId.
347     * @param optionalParameters are included in the key request message to
348     * allow a client application to provide additional message parameters to the server.
349     */
350    public native KeyRequest getKeyRequest(byte[] scope, byte[] init,
351                                           String mimeType, int keyType,
352                                           HashMap<String, String> optionalParameters);
353
354
355    /**
356     * A key response is received from the license server by the app, then it is
357     * provided to the DRM engine plugin using provideKeyResponse. The byte array
358     * returned is a keySetId that can be used to later restore the keys to a new
359     * session with the method {@link #restoreKeys}, enabling offline key use.
360     *
361     * @param sessionId the session ID for the DRM session
362     * @param response the byte array response from the server
363     */
364    public native byte[] provideKeyResponse(byte[] sessionId, byte[] response);
365
366    /**
367     * Restore persisted offline keys into a new session.  keySetId identifies the
368     * keys to load, obtained from a prior call to {@link #provideKeyResponse}.
369     *
370     * @param sessionId the session ID for the DRM session
371     * @param keySetId identifies the saved key set to restore
372     */
373    public native void restoreKeys(byte[] sessionId, byte[] keySetId);
374
375    /**
376     * Remove the current keys from a session.
377     *
378     * @param sessionId the session ID for the DRM session
379     */
380    public native void removeKeys(byte[] sessionId);
381
382    /**
383     * Request an informative description of the key status for the session.  The status is
384     * in the form of {name, value} pairs.  Since DRM license policies vary by vendor,
385     * the specific status field names are determined by each DRM vendor.  Refer to your
386     * DRM provider documentation for definitions of the field names for a particular
387     * DRM engine plugin.
388     *
389     * @param sessionId the session ID for the DRM session
390     */
391    public native HashMap<String, String> queryKeyStatus(byte[] sessionId);
392
393    /**
394     * Contains the opaque data an app uses to request a certificate from a provisioning
395     * server
396     */
397    public final static class ProvisionRequest {
398        ProvisionRequest() {}
399
400        /**
401         * Get the opaque message data
402         */
403        public byte[] getData() { return mData; }
404
405        /**
406         * Get the default URL to use when sending the provision request
407         * message to a server, if known. The app may prefer to use a different
408         * provisioning server URL obtained from other sources.
409         */
410        public String getDefaultUrl() { return mDefaultUrl; }
411
412        private byte[] mData;
413        private String mDefaultUrl;
414    }
415
416    /**
417     * A provision request/response exchange occurs between the app and a provisioning
418     * server to retrieve a device certificate.  If provisionining is required, the
419     * EVENT_PROVISION_REQUIRED event will be sent to the event handler.
420     * getProvisionRequest is used to obtain the opaque provision request byte array that
421     * should be delivered to the provisioning server. The provision request byte array
422     * is returned in ProvisionRequest.data. The recommended URL to deliver the provision
423     * request to is returned in ProvisionRequest.defaultUrl.
424     */
425    public native ProvisionRequest getProvisionRequest();
426
427    /**
428     * After a provision response is received by the app, it is provided to the DRM
429     * engine plugin using this method.
430     *
431     * @param response the opaque provisioning response byte array to provide to the
432     * DRM engine plugin.
433     */
434    public native void provideProvisionResponse(byte[] response);
435
436    /**
437     * A means of enforcing limits on the number of concurrent streams per subscriber
438     * across devices is provided via SecureStop. This is achieved by securely
439     * monitoring the lifetime of sessions.
440     * <p>
441     * Information from the server related to the current playback session is written
442     * to persistent storage on the device when each MediaCrypto object is created.
443     * <p>
444     * In the normal case, playback will be completed, the session destroyed and the
445     * Secure Stops will be queried. The app queries secure stops and forwards the
446     * secure stop message to the server which verifies the signature and notifies the
447     * server side database that the session destruction has been confirmed. The persisted
448     * record on the client is only removed after positive confirmation that the server
449     * received the message using releaseSecureStops().
450     */
451    public native List<byte[]> getSecureStops();
452
453
454    /**
455     * Process the SecureStop server response message ssRelease.  After authenticating
456     * the message, remove the SecureStops identified in the response.
457     *
458     * @param ssRelease the server response indicating which secure stops to release
459     */
460    public native void releaseSecureStops(byte[] ssRelease);
461
462
463    /**
464     * String property name: identifies the maker of the DRM engine plugin
465     */
466    public static final String PROPERTY_VENDOR = "vendor";
467
468    /**
469     * String property name: identifies the version of the DRM engine plugin
470     */
471    public static final String PROPERTY_VERSION = "version";
472
473    /**
474     * String property name: describes the DRM engine plugin
475     */
476    public static final String PROPERTY_DESCRIPTION = "description";
477
478    /**
479     * String property name: a comma-separated list of cipher and mac algorithms
480     * supported by CryptoSession.  The list may be empty if the DRM engine
481     * plugin does not support CryptoSession operations.
482     */
483    public static final String PROPERTY_ALGORITHMS = "algorithms";
484
485    /**
486     * Read a DRM engine plugin String property value, given the property name string.
487     * <p>
488     * Standard fields names are:
489     * {@link #PROPERTY_VENDOR}, {@link #PROPERTY_VERSION},
490     * {@link #PROPERTY_DESCRIPTION}, {@link #PROPERTY_ALGORITHM}
491     */
492    public native String getPropertyString(String propertyName);
493
494
495    /**
496     * Byte array property name: the device unique identifier is established during
497     * device provisioning and provides a means of uniquely identifying each device.
498     */
499    public static final String PROPERTY_DEVICE_UNIQUE_ID = "deviceUniqueId";
500
501    /**
502     * Read a DRM engine plugin byte array property value, given the property name string.
503     * <p>
504     * Standard fields names are {@link #PROPERTY_DEVICE_UNIQUE_ID}
505     */
506    public native byte[] getPropertyByteArray(String propertyName);
507
508
509    /**
510     * Set a DRM engine plugin String property value.
511     */
512    public native void setPropertyString(String propertyName, String value);
513
514    /**
515     * Set a DRM engine plugin byte array property value.
516     */
517    public native void setPropertyByteArray(String propertyName, byte[] value);
518
519
520    private static final native void setCipherAlgorithmNative(MediaDrm drm, byte[] sessionId,
521                                                              String algorithm);
522
523    private static final native void setMacAlgorithmNative(MediaDrm drm, byte[] sessionId,
524                                                           String algorithm);
525
526    private static final native byte[] encryptNative(MediaDrm drm, byte[] sessionId,
527                                                     byte[] keyId, byte[] input, byte[] iv);
528
529    private static final native byte[] decryptNative(MediaDrm drm, byte[] sessionId,
530                                                     byte[] keyId, byte[] input, byte[] iv);
531
532    private static final native byte[] signNative(MediaDrm drm, byte[] sessionId,
533                                                  byte[] keyId, byte[] message);
534
535    private static final native boolean verifyNative(MediaDrm drm, byte[] sessionId,
536                                                     byte[] keyId, byte[] message,
537                                                     byte[] signature);
538
539    /**
540     * In addition to supporting decryption of DASH Common Encrypted Media, the
541     * MediaDrm APIs provide the ability to securely deliver session keys from
542     * an operator's session key server to a client device, based on the factory-installed
543     * root of trust, and then perform encrypt, decrypt, sign and verify operations
544     * with the session key on arbitrary user data.
545     * <p>
546     * The CryptoSession class implements generic encrypt/decrypt/sign/verify methods
547     * based on the established session keys.  These keys are exchanged using the
548     * getKeyRequest/provideKeyResponse methods.
549     * <p>
550     * Applications of this capability could include securing various types of
551     * purchased or private content, such as applications, books and other media,
552     * photos or media delivery protocols.
553     * <p>
554     * Operators can create session key servers that are functionally similar to a
555     * license key server, except that instead of receiving license key requests and
556     * providing encrypted content keys which are used specifically to decrypt A/V media
557     * content, the session key server receives session key requests and provides
558     * encrypted session keys which can be used for general purpose crypto operations.
559     * <p>
560     * A CryptoSession is obtained using {@link #getCryptoSession}
561     */
562    public final class CryptoSession {
563        private MediaDrm mDrm;
564        private byte[] mSessionId;
565
566        CryptoSession(MediaDrm drm, byte[] sessionId,
567                      String cipherAlgorithm, String macAlgorithm)
568        {
569            mSessionId = sessionId;
570            mDrm = drm;
571            setCipherAlgorithmNative(drm, sessionId, cipherAlgorithm);
572            setMacAlgorithmNative(drm, sessionId, macAlgorithm);
573        }
574
575        /**
576         * Encrypt data using the CryptoSession's cipher algorithm
577         *
578         * @param keyid specifies which key to use
579         * @param input the data to encrypt
580         * @param iv the initialization vector to use for the cipher
581         */
582        public byte[] encrypt(byte[] keyid, byte[] input, byte[] iv) {
583            return encryptNative(mDrm, mSessionId, keyid, input, iv);
584        }
585
586        /**
587         * Decrypt data using the CryptoSessions's cipher algorithm
588         *
589         * @param keyid specifies which key to use
590         * @param input the data to encrypt
591         * @param iv the initialization vector to use for the cipher
592         */
593        public byte[] decrypt(byte[] keyid, byte[] input, byte[] iv) {
594            return decryptNative(mDrm, mSessionId, keyid, input, iv);
595        }
596
597        /**
598         * Sign data using the CryptoSessions's mac algorithm.
599         *
600         * @param keyid specifies which key to use
601         * @param message the data for which a signature is to be computed
602         */
603        public byte[] sign(byte[] keyid, byte[] message) {
604            return signNative(mDrm, mSessionId, keyid, message);
605        }
606
607        /**
608         * Verify a signature using the CryptoSessions's mac algorithm. Return true
609         * if the signatures match, false if they do no.
610         *
611         * @param keyid specifies which key to use
612         * @param message the data to verify
613         * @param signature the reference signature which will be compared with the
614         *        computed signature
615         */
616        public boolean verify(byte[] keyid, byte[] message, byte[] signature) {
617            return verifyNative(mDrm, mSessionId, keyid, message, signature);
618        }
619    };
620
621    /**
622     * Obtain a CryptoSession object which can be used to encrypt, decrypt,
623     * sign and verify messages or data using the session keys established
624     * for the session using methods {@link #getKeyRequest} and
625     * {@link #provideKeyResponse} using a session key server.
626     *
627     * @param sessionId the session ID for the session containing keys
628     * to be used for encrypt, decrypt, sign and/or verify
629     * @param cipherAlgorithm the algorithm to use for encryption and
630     * decryption ciphers. The algorithm string conforms to JCA Standard
631     * Names for Cipher Transforms and is case insensitive.  For example
632     * "AES/CBC/NoPadding".
633     * @param macAlgorithm the algorithm to use for sign and verify
634     * The algorithm string conforms to JCA Standard Names for Mac
635     * Algorithms and is case insensitive.  For example "HmacSHA256".
636     * <p>
637     * The list of supported algorithms for a DRM engine plugin can be obtained
638     * using the method {@link #getPropertyString} with the property name
639     * "algorithms".
640     */
641    public CryptoSession getCryptoSession(byte[] sessionId,
642                                          String cipherAlgorithm,
643                                          String macAlgorithm)
644    {
645        return new CryptoSession(this, sessionId, cipherAlgorithm, macAlgorithm);
646    }
647
648    @Override
649    protected void finalize() {
650        native_finalize();
651    }
652
653    public native final void release();
654    private static native final void native_init();
655
656    private native final void native_setup(Object mediadrm_this, byte[] uuid);
657
658    private native final void native_finalize();
659
660    static {
661        System.loadLibrary("media_jni");
662        native_init();
663    }
664}
665