summaryrefslogtreecommitdiffstats
path: root/mobile/android/geckoview/src/main/java/org/mozilla/gecko/media/GeckoMediaDrmBridgeV21.java
blob: e5380bbb5c05f23606f48be61fea08000872e73b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

package org.mozilla.gecko.media;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.media.DeniedByServerException;
import android.media.MediaCrypto;
import android.media.MediaDrm;
import android.media.NotProvisionedException;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Handler;
import android.os.HandlerThread;
import android.util.Log;
import androidx.annotation.RequiresApi;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URLEncoder;
import java.nio.ByteBuffer;
import java.nio.charset.Charset;
import java.util.ArrayDeque;
import java.util.HashMap;
import java.util.HashSet;
import java.util.UUID;
import org.mozilla.gecko.util.ProxySelector;

@TargetApi(Build.VERSION_CODES.LOLLIPOP)
@RequiresApi(Build.VERSION_CODES.LOLLIPOP)
public class GeckoMediaDrmBridgeV21 implements GeckoMediaDrm {
  protected final String LOGTAG;
  private static final String INVALID_SESSION_ID = "Invalid";
  private static final String WIDEVINE_KEY_SYSTEM = "com.widevine.alpha";
  private static final boolean DEBUG = false;
  private static final UUID WIDEVINE_SCHEME_UUID =
      new UUID(0xedef8ba979d64aceL, 0xa3c827dcd51d21edL);
  private static final int MAX_PROMISE_ID = Integer.MAX_VALUE;
  // MediaDrm.KeyStatus information listener is supported on M+, adding a
  // dummy key id to report key status.
  private static final byte[] DUMMY_KEY_ID = new byte[] {0};

  public static final Charset UTF_8 = Charset.forName("UTF-8");

  private UUID mSchemeUUID;
  private Handler mHandler;
  PostRequestTask mProvisionTask;
  private HandlerThread mHandlerThread;
  private ByteBuffer mCryptoSessionId;

  // mProvisioningPromiseId is great than 0 only during provisioning.
  private int mProvisioningPromiseId;
  private HashSet<ByteBuffer> mSessionIds;
  private HashMap<ByteBuffer, String> mSessionMIMETypes;
  private ArrayDeque<PendingCreateSessionData> mPendingCreateSessionDataQueue;
  private PendingKeyRequest mPendingKeyRequest;
  private GeckoMediaDrm.Callbacks mCallbacks;

  private MediaCrypto mCrypto;
  protected MediaDrm mDrm;

  public static final int LICENSE_REQUEST_INITIAL = 0; /*MediaKeyMessageType::License_request*/
  public static final int LICENSE_REQUEST_RENEWAL = 1; /*MediaKeyMessageType::License_renewal*/
  public static final int LICENSE_REQUEST_RELEASE = 2; /*MediaKeyMessageType::License_release*/

  // Store session data while provisioning
  private static class PendingCreateSessionData {
    public final int mToken;
    public final int mPromiseId;
    public final byte[] mInitData;
    public final String mMimeType;

    private PendingCreateSessionData(
        final int token, final int promiseId, final byte[] initData, final String mimeType) {
      mToken = token;
      mPromiseId = promiseId;
      mInitData = initData;
      mMimeType = mimeType;
    }
  }

  private static class PendingKeyRequest {
    public final ByteBuffer mSession;
    public final byte[] mData;
    public final String mMimeType;

    private PendingKeyRequest(final ByteBuffer session, final byte[] data, final String mimeType) {
      mSession = session;
      mData = data;
      mMimeType = mimeType;
    }
  }

  public boolean isSecureDecoderComonentRequired(final String mimeType) {
    if (mCrypto != null) {
      return mCrypto.requiresSecureDecoderComponent(mimeType);
    }
    return false;
  }

  private static void assertTrue(final boolean condition) {
    if (DEBUG && !condition) {
      throw new AssertionError("Expected condition to be true");
    }
  }

  @SuppressLint("WrongConstant")
  private void configureVendorSpecificProperty() {
    assertTrue(mDrm != null);
    if (mDrm == null) {
      return;
    }
    // Support L3 for now
    mDrm.setPropertyString("securityLevel", "L3");
    // Refer to chromium, set multi-session mode for Widevine.
    if (mSchemeUUID.equals(WIDEVINE_SCHEME_UUID)) {
      mDrm.setPropertyString("privacyMode", "enable");
      mDrm.setPropertyString("sessionSharing", "enable");
    }
  }

  GeckoMediaDrmBridgeV21(final String keySystem) throws Exception {
    LOGTAG = getClass().getSimpleName();
    if (DEBUG) Log.d(LOGTAG, "GeckoMediaDrmBridgeV21 ctor");

    mProvisioningPromiseId = 0;
    mSessionIds = new HashSet<ByteBuffer>();
    mSessionMIMETypes = new HashMap<ByteBuffer, String>();
    mPendingCreateSessionDataQueue = new ArrayDeque<PendingCreateSessionData>();

    mSchemeUUID = convertKeySystemToSchemeUUID(keySystem);
    mCryptoSessionId = null;

    if (DEBUG) Log.d(LOGTAG, "mSchemeUUID : " + mSchemeUUID.toString());

    // The caller of GeckoMediaDrmBridgeV21 ctor should handle exceptions
    // threw by the following steps.
    mDrm = new MediaDrm(mSchemeUUID);
    configureVendorSpecificProperty();
    mDrm.setOnEventListener(new MediaDrmListener());
    try {
      // ensureMediaCryptoCreated may cause NotProvisionedException for the first time use.
      // Need to start provisioning with a dummy promise id.
      ensureMediaCryptoCreated();
    } catch (final android.media.NotProvisionedException e) {
      if (DEBUG) Log.d(LOGTAG, "Device not provisioned:" + e.getMessage());
      startProvisioning(MAX_PROMISE_ID);
    }
  }

  @Override
  public void setCallbacks(final GeckoMediaDrm.Callbacks callbacks) {
    assertTrue(callbacks != null);
    mCallbacks = callbacks;
  }

  @Override
  public void createSession(
      final int createSessionToken,
      final int promiseId,
      final String initDataType,
      final byte[] initData) {
    if (DEBUG) Log.d(LOGTAG, "createSession()");
    if (mDrm == null) {
      onRejectPromise(promiseId, "MediaDrm instance doesn't exist !!");
      return;
    }

    if (mProvisioningPromiseId > 0 && mCrypto == null) {
      if (DEBUG) Log.d(LOGTAG, "Pending createSession because it's provisioning !");
      savePendingCreateSessionData(
          createSessionToken, promiseId,
          initData, initDataType);
      return;
    }

    ByteBuffer sessionId = null;
    try {
      final boolean hasMediaCrypto = ensureMediaCryptoCreated();
      if (!hasMediaCrypto) {
        onRejectPromise(promiseId, "MediaCrypto intance is not created !");
        return;
      }

      sessionId = openSession();
      if (sessionId == null) {
        onRejectPromise(promiseId, "Cannot get a session id from MediaDrm !");
        return;
      }

      final MediaDrm.KeyRequest request = getKeyRequest(sessionId, initData, initDataType);
      if (request == null) {
        mDrm.closeSession(sessionId.array());
        onRejectPromise(promiseId, "Cannot get a key request from MediaDrm !");
        return;
      }
      onSessionCreated(createSessionToken, promiseId, sessionId.array(), request.getData());
      onSessionMessage(sessionId.array(), LICENSE_REQUEST_INITIAL, request.getData());
      mSessionMIMETypes.put(sessionId, initDataType);
      mSessionIds.add(sessionId);
      if (DEBUG)
        Log.d(
            LOGTAG,
            " StringID : " + new String(sessionId.array(), UTF_8) + " is put into mSessionIds ");
    } catch (final android.media.NotProvisionedException e) {
      if (DEBUG) Log.d(LOGTAG, "Device not provisioned:" + e.getMessage());
      if (sessionId != null) {
        // The promise of this createSession will be either resolved
        // or rejected after provisioning.
        mDrm.closeSession(sessionId.array());
      }
      savePendingCreateSessionData(
          createSessionToken, promiseId,
          initData, initDataType);
      startProvisioning(promiseId);
    }
  }

  @Override
  public void updateSession(final int promiseId, final String sessionId, final byte[] response) {
    if (DEBUG) Log.d(LOGTAG, "updateSession(), sessionId = " + sessionId);
    if (mDrm == null) {
      onRejectPromise(promiseId, "MediaDrm instance doesn't exist !!");
      return;
    }

    final ByteBuffer session = ByteBuffer.wrap(sessionId.getBytes(UTF_8));
    if (!sessionExists(session)) {
      onRejectPromise(promiseId, "Invalid session during updateSession.");
      return;
    }

    try {
      final byte[] keySetId = mDrm.provideKeyResponse(session.array(), response);
      if (DEBUG) {
        final HashMap<String, String> infoMap = mDrm.queryKeyStatus(session.array());
        for (final String strKey : infoMap.keySet()) {
          final String strValue = infoMap.get(strKey);
          Log.d(LOGTAG, "InfoMap : key(" + strKey + ")/value(" + strValue + ")");
        }
      }
      HandleKeyStatusChangeByDummyKey(sessionId);
      onSessionUpdated(promiseId, session.array());
      return;
    } catch (final NotProvisionedException | DeniedByServerException | IllegalStateException e) {
      if (DEBUG) Log.d(LOGTAG, "Failed to provide key response:", e);
      onSessionError(session.array(), "Got exception during updateSession.");
      onRejectPromise(promiseId, "Got exception during updateSession.");
    }
    release();
    return;
  }

  @Override
  public void closeSession(final int promiseId, final String sessionId) {
    if (DEBUG) Log.d(LOGTAG, "closeSession()");
    if (mDrm == null) {
      onRejectPromise(promiseId, "MediaDrm instance doesn't exist !!");
      return;
    }

    final ByteBuffer session = ByteBuffer.wrap(sessionId.getBytes(UTF_8));
    mSessionIds.remove(session);
    mDrm.closeSession(session.array());
    onSessionClosed(promiseId, session.array());
  }

  @Override
  public void release() {
    if (DEBUG) Log.d(LOGTAG, "release()");
    if (mProvisionTask != null) {
      mProvisionTask.cancel(true);
      mProvisionTask = null;
    }
    if (mProvisioningPromiseId > 0) {
      onRejectPromise(mProvisioningPromiseId, "Releasing ... reject provisioning session.");
      mProvisioningPromiseId = 0;
    }
    if (mPendingKeyRequest != null) {
      mPendingKeyRequest = null;
    }
    while (!mPendingCreateSessionDataQueue.isEmpty()) {
      final PendingCreateSessionData pendingData = mPendingCreateSessionDataQueue.poll();
      if (pendingData != null) {
        onRejectPromise(pendingData.mPromiseId, "Releasing ... reject all pending sessions.");
      }
    }
    mPendingCreateSessionDataQueue = null;

    if (mDrm != null) {
      for (final ByteBuffer session : mSessionIds) {
        mDrm.closeSession(session.array());
      }
      mDrm.release();
      mDrm = null;
    }
    mSessionIds.clear();
    mSessionIds = null;
    mSessionMIMETypes.clear();
    mSessionMIMETypes = null;

    mCryptoSessionId = null;
    if (mCrypto != null) {
      mCrypto.release();
      mCrypto = null;
    }
    if (mHandlerThread != null) {
      mHandlerThread.quitSafely();
      mHandlerThread = null;
    }
    mHandler = null;
  }

  @Override
  public MediaCrypto getMediaCrypto() {
    if (DEBUG) Log.d(LOGTAG, "getMediaCrypto()");
    return mCrypto;
  }

  @SuppressLint("WrongConstant")
  @Override
  public void setServerCertificate(final byte[] cert) {
    if (DEBUG) Log.d(LOGTAG, "setServerCertificate()");
    if (mDrm == null) {
      throw new IllegalStateException("MediaDrm instance doesn't exist !!");
    }
    mDrm.setPropertyByteArray("serviceCertificate", cert);
    return;
  }

  protected void HandleKeyStatusChangeByDummyKey(final String sessionId) {
    final SessionKeyInfo[] keyInfos = new SessionKeyInfo[1];
    keyInfos[0] = new SessionKeyInfo(DUMMY_KEY_ID, MediaDrm.KeyStatus.STATUS_USABLE);
    onSessionBatchedKeyChanged(sessionId.getBytes(), keyInfos);
    if (DEBUG) Log.d(LOGTAG, "Key successfully added for session " + sessionId);
  }

  protected void onSessionCreated(
      final int createSessionToken,
      final int promiseId,
      final byte[] sessionId,
      final byte[] request) {
    assertTrue(mCallbacks != null);
    if (mCallbacks != null) {
      mCallbacks.onSessionCreated(createSessionToken, promiseId, sessionId, request);
    }
  }

  protected void onSessionUpdated(final int promiseId, final byte[] sessionId) {
    assertTrue(mCallbacks != null);
    if (mCallbacks != null) {
      mCallbacks.onSessionUpdated(promiseId, sessionId);
    }
  }

  protected void onSessionClosed(final int promiseId, final byte[] sessionId) {
    assertTrue(mCallbacks != null);
    if (mCallbacks != null) {
      mCallbacks.onSessionClosed(promiseId, sessionId);
    }
  }

  protected void onSessionMessage(
      final byte[] sessionId, final int sessionMessageType, final byte[] request) {
    assertTrue(mCallbacks != null);
    if (mCallbacks != null) {
      mCallbacks.onSessionMessage(sessionId, sessionMessageType, request);
    }
  }

  protected void onSessionError(final byte[] sessionId, final String message) {
    assertTrue(mCallbacks != null);
    if (mCallbacks != null) {
      mCallbacks.onSessionError(sessionId, message);
    }
  }

  protected void onSessionBatchedKeyChanged(
      final byte[] sessionId, final SessionKeyInfo[] keyInfos) {
    assertTrue(mCallbacks != null);
    if (mCallbacks != null) {
      mCallbacks.onSessionBatchedKeyChanged(sessionId, keyInfos);
    }
  }

  protected void onRejectPromise(final int promiseId, final String message) {
    assertTrue(mCallbacks != null);
    if (mCallbacks != null) {
      mCallbacks.onRejectPromise(promiseId, message);
    }
  }

  private MediaDrm.KeyRequest getKeyRequest(
      final ByteBuffer aSession, final byte[] data, final String mimeType)
      throws android.media.NotProvisionedException {
    if (mProvisioningPromiseId > 0) {
      if (DEBUG) Log.d(LOGTAG, "Now provisioning");
      return null;
    }

    try {
      final HashMap<String, String> optionalParameters = new HashMap<String, String>();
      return mDrm.getKeyRequest(
          aSession.array(), data, mimeType, MediaDrm.KEY_TYPE_STREAMING, optionalParameters);
    } catch (final Exception e) {
      Log.e(LOGTAG, "Got excpetion during MediaDrm.getKeyRequest", e);
    }
    return null;
  }

  private class MediaDrmListener implements MediaDrm.OnEventListener {
    @Override
    public void onEvent(
        final MediaDrm mediaDrm,
        final byte[] sessionArray,
        final int event,
        final int extra,
        final byte[] data) {
      if (DEBUG) Log.d(LOGTAG, "MediaDrmListener.onEvent()");
      if (sessionArray == null) {
        if (DEBUG) Log.d(LOGTAG, "MediaDrmListener: Null session.");
        return;
      }
      final ByteBuffer session = ByteBuffer.wrap(sessionArray);
      if (!sessionExists(session)) {
        if (DEBUG) Log.d(LOGTAG, "MediaDrmListener: Invalid session.");
        return;
      }
      // On L, these events are treated as exceptions and handled correspondingly.
      // Leaving this code block for logging message.
      switch (event) {
        case MediaDrm.EVENT_PROVISION_REQUIRED:
          if (DEBUG) Log.d(LOGTAG, "MediaDrm.EVENT_PROVISION_REQUIRED");
          break;
        case MediaDrm.EVENT_KEY_REQUIRED:
          if (DEBUG)
            Log.d(
                LOGTAG,
                "MediaDrm.EVENT_KEY_REQUIRED, sessionId=" + new String(session.array(), UTF_8));
          final String mimeType = mSessionMIMETypes.get(session);
          MediaDrm.KeyRequest request = null;
          try {
            request = getKeyRequest(session, data, mimeType);
          } catch (final android.media.NotProvisionedException e) {
            Log.w(LOGTAG, "MediaDrm.EVENT_KEY_REQUIRED, Device not provisioned.", e);
            startProvisioning(MAX_PROMISE_ID);
            mPendingKeyRequest = new PendingKeyRequest(session, data, mimeType);
            return;
          }
          requestLicense(sessionArray, request);
          break;
        case MediaDrm.EVENT_KEY_EXPIRED:
          if (DEBUG)
            Log.d(
                LOGTAG,
                "MediaDrm.EVENT_KEY_EXPIRED, sessionId=" + new String(session.array(), UTF_8));
          break;
        case MediaDrm.EVENT_VENDOR_DEFINED:
          if (DEBUG)
            Log.d(
                LOGTAG,
                "MediaDrm.EVENT_VENDOR_DEFINED, sessionId=" + new String(session.array(), UTF_8));
          break;
        case MediaDrm.EVENT_SESSION_RECLAIMED:
          if (DEBUG)
            Log.d(
                LOGTAG,
                "MediaDrm.EVENT_SESSION_RECLAIMED, sessionId="
                    + new String(session.array(), UTF_8));
          break;
        default:
          if (DEBUG) Log.d(LOGTAG, "Invalid DRM event " + event);
          return;
      }
    }
  }

  private ByteBuffer openSession() throws android.media.NotProvisionedException {
    try {
      final byte[] sessionId = mDrm.openSession();
      // ByteBuffer.wrap() is backed by the byte[]. Make a clone here in
      // case the underlying byte[] is modified.
      return ByteBuffer.wrap(sessionId.clone());
    } catch (final android.media.NotProvisionedException e) {
      // Throw NotProvisionedException so that we can startProvisioning().
      throw e;
    } catch (final java.lang.RuntimeException e) {
      if (DEBUG) Log.d(LOGTAG, "Cannot open a new session:" + e.getMessage());
      release();
      return null;
    } catch (final android.media.MediaDrmException e) {
      // Other MediaDrmExceptions (e.g. ResourceBusyException) are not
      // recoverable.
      release();
      return null;
    }
  }

  protected boolean sessionExists(final ByteBuffer session) {
    if (mCryptoSessionId == null) {
      if (DEBUG)
        Log.d(LOGTAG, "Session doesn't exist because media crypto session is not created.");
      return false;
    }
    if (session == null) {
      if (DEBUG) Log.d(LOGTAG, "Session is null, not in map !");
      return false;
    }
    return !session.equals(mCryptoSessionId) && mSessionIds.contains(session);
  }

  private class PostRequestTask extends AsyncTask<Void, Void, Void> {
    private static final String LOGTAG = "PostRequestTask";

    private int mPromiseId;
    private String mURL;
    private byte[] mDrmRequest;
    private byte[] mResponseBody;

    PostRequestTask(final int promiseId, final String url, final byte[] drmRequest) {
      this.mPromiseId = promiseId;
      this.mURL = url;
      this.mDrmRequest = drmRequest;
    }

    @Override
    protected Void doInBackground(final Void... params) {
      HttpURLConnection urlConnection = null;
      BufferedReader in = null;
      try {
        final URI finalURI =
            new URI(mURL + "&signedRequest=" + URLEncoder.encode(new String(mDrmRequest), "UTF-8"));
        urlConnection = (HttpURLConnection) ProxySelector.openConnectionWithProxy(finalURI);
        urlConnection.setRequestMethod("POST");
        if (DEBUG) Log.d(LOGTAG, "Provisioning, posting url =" + finalURI.toString());

        // Add data
        urlConnection.setRequestProperty("Accept", "*/*");
        urlConnection.setRequestProperty("User-Agent", getCDMUserAgent());
        urlConnection.setRequestProperty("Content-Type", "application/json");

        // Execute HTTP Post Request
        urlConnection.connect();

        final int responseCode = urlConnection.getResponseCode();
        if (responseCode == HttpURLConnection.HTTP_OK) {
          in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream(), UTF_8));
          String inputLine;
          final StringBuffer response = new StringBuffer();

          while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
          }
          in.close();
          mResponseBody = String.valueOf(response).getBytes(UTF_8);
          if (DEBUG) Log.d(LOGTAG, "Provisioning, response received.");
          if (mResponseBody != null) Log.d(LOGTAG, "response length=" + mResponseBody.length);
        } else {
          Log.d(LOGTAG, "Provisioning, server returned HTTP error code :" + responseCode);
        }
      } catch (final IOException e) {
        Log.e(LOGTAG, "Got exception during posting provisioning request ...", e);
      } catch (final URISyntaxException e) {
        Log.e(LOGTAG, "Got exception during creating uri ...", e);
      } finally {
        if (urlConnection != null) {
          urlConnection.disconnect();
        }
        try {
          if (in != null) {
            in.close();
          }
        } catch (final IOException e) {
          Log.e(LOGTAG, "Exception during closing in ...", e);
        }
      }
      return null;
    }

    @Override
    protected void onPostExecute(final Void v) {
      onProvisionResponse(mPromiseId, mResponseBody);
    }
  }

  private boolean provideProvisionResponse(final byte[] response) {
    if (response == null || response.length == 0) {
      if (DEBUG) Log.d(LOGTAG, "Invalid provision response.");
      return false;
    }

    try {
      mDrm.provideProvisionResponse(response);
      return true;
    } catch (final android.media.DeniedByServerException e) {
      if (DEBUG) Log.d(LOGTAG, "Failed to provide provision response:" + e.getMessage());
    } catch (final java.lang.IllegalStateException e) {
      if (DEBUG) Log.d(LOGTAG, "Failed to provide provision response:" + e.getMessage());
    }
    return false;
  }

  private void savePendingCreateSessionData(
      final int token, final int promiseId, final byte[] initData, final String mime) {
    if (DEBUG) Log.d(LOGTAG, "savePendingCreateSessionData, promiseId : " + promiseId);
    mPendingCreateSessionDataQueue.offer(
        new PendingCreateSessionData(token, promiseId, initData, mime));
  }

  private void processPendingCreateSessionData() {
    if (DEBUG) Log.d(LOGTAG, "processPendingCreateSessionData ... ");

    assertTrue(mProvisioningPromiseId == 0);
    try {
      while (!mPendingCreateSessionDataQueue.isEmpty()) {
        final PendingCreateSessionData pendingData = mPendingCreateSessionDataQueue.poll();
        if (pendingData == null) {
          return;
        }
        if (DEBUG)
          Log.d(LOGTAG, "processPendingCreateSessionData, promiseId : " + pendingData.mPromiseId);

        createSession(
            pendingData.mToken,
            pendingData.mPromiseId,
            pendingData.mMimeType,
            pendingData.mInitData);
      }
    } catch (final Exception e) {
      Log.e(LOGTAG, "Got excpetion during processPendingCreateSessionData ...", e);
    }
  }

  private void resumePendingOperations() {
    if (mHandlerThread == null) {
      mHandlerThread = new HandlerThread("PendingSessionOpsThread");
      mHandlerThread.start();
    }
    if (mHandler == null) {
      mHandler = new Handler(mHandlerThread.getLooper());
    }
    mHandler.post(
        new Runnable() {
          @Override
          public void run() {
            if (mPendingKeyRequest != null) {
              MediaDrm.KeyRequest request = null;
              try {
                request =
                    getKeyRequest(
                        mPendingKeyRequest.mSession,
                        mPendingKeyRequest.mData,
                        mPendingKeyRequest.mMimeType);
              } catch (final NotProvisionedException e) {
                Log.e(LOGTAG, "Cannot get key request after provisioning!");
                return;
              } finally {
                mPendingKeyRequest = null;
              }
              requestLicense(mPendingKeyRequest.mSession.array(), request);
            } else {
              processPendingCreateSessionData();
            }
          }
        });
  }

  private void requestLicense(final byte[] session, final MediaDrm.KeyRequest request) {
    if (request == null) {
      Log.e(LOGTAG, "null key request when requesting license");
      return;
    }
    // The EME spec says the messageType is only for optimization and optional.
    // Send 'License_request' as default when it's not available.
    int requestType = LICENSE_REQUEST_INITIAL;
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
      requestType = request.getRequestType();
    }
    onSessionMessage(session, requestType, request.getData());
  }

  // Only triggered when failed on {openSession, getKeyRequest}
  private void startProvisioning(final int promiseId) {
    if (DEBUG) Log.d(LOGTAG, "startProvisioning()");
    if (mProvisioningPromiseId > 0) {
      // Already in provisioning.
      return;
    }
    try {
      mProvisioningPromiseId = promiseId;
      final MediaDrm.ProvisionRequest request = mDrm.getProvisionRequest();
      mProvisionTask = new PostRequestTask(promiseId, request.getDefaultUrl(), request.getData());
      mProvisionTask.execute();
    } catch (final Exception e) {
      onRejectPromise(promiseId, "Exception happened in startProvisioning !");
      mProvisioningPromiseId = 0;
    }
  }

  private void onProvisionResponse(final int promiseId, final byte[] response) {
    if (DEBUG) Log.d(LOGTAG, "onProvisionResponse()");
    mProvisionTask = null;
    mProvisioningPromiseId = 0;
    final boolean success = provideProvisionResponse(response);
    if (success) {
      // Promise will either be resovled / rejected in createSession during
      // resuming operations.
      resumePendingOperations();
    } else {
      onRejectPromise(promiseId, "Failed to provide provision response.");
    }
  }

  private boolean ensureMediaCryptoCreated() throws android.media.NotProvisionedException {
    if (mCrypto != null) {
      return true;
    }
    try {
      mCryptoSessionId = openSession();
      if (mCryptoSessionId == null) {
        if (DEBUG) Log.d(LOGTAG, "Cannot open session for MediaCrypto");
        return false;
      }

      if (MediaCrypto.isCryptoSchemeSupported(mSchemeUUID)) {
        final byte[] cryptoSessionId = mCryptoSessionId.array();
        mCrypto = new MediaCrypto(mSchemeUUID, cryptoSessionId);
        mSessionIds.add(mCryptoSessionId);
        if (DEBUG)
          Log.d(
              LOGTAG,
              "MediaCrypto successfully created! - SId "
                  + INVALID_SESSION_ID
                  + ", "
                  + new String(cryptoSessionId, UTF_8));
        return true;
      } else {
        if (DEBUG) Log.d(LOGTAG, "Cannot create MediaCrypto for unsupported scheme.");
        return false;
      }
    } catch (final android.media.MediaCryptoException e) {
      if (DEBUG) Log.d(LOGTAG, "Cannot create MediaCrypto:" + e.getMessage());
      release();
      return false;
    } catch (final android.media.NotProvisionedException e) {
      if (DEBUG)
        Log.d(LOGTAG, "ensureMediaCryptoCreated::Device not provisioned:" + e.getMessage());
      throw e;
    }
  }

  private UUID convertKeySystemToSchemeUUID(final String keySystem) {
    if (WIDEVINE_KEY_SYSTEM.equals(keySystem)) {
      return WIDEVINE_SCHEME_UUID;
    }
    if (DEBUG) Log.d(LOGTAG, "Cannot convert unsupported key system : " + keySystem);
    return new UUID(0L, 0L);
  }

  private String getCDMUserAgent() {
    // This user agent is found and hard-coded in Android(L) source code and
    // Chromium project. Not sure if it's gonna change in the future.
    final String ua = "Widevine CDM v1.0";
    return ua;
  }
}