tor-browser

The Tor Browser
git clone https://git.dasho.dev/tor-browser.git
Log | Files | Refs | README | LICENSE

content_decryption_module.h (81421B)


      1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
      2 // Use of this source code is governed by a BSD-style license that can be
      3 // found in the LICENSE file.
      4 
      5 #ifndef CDM_CONTENT_DECRYPTION_MODULE_H_
      6 #define CDM_CONTENT_DECRYPTION_MODULE_H_
      7 
      8 #include <type_traits>
      9 
     10 #include "content_decryption_module_export.h"
     11 
     12 #if defined(_MSC_VER)
     13 typedef unsigned char uint8_t;
     14 typedef unsigned int uint32_t;
     15 typedef int int32_t;
     16 typedef __int64 int64_t;
     17 #else
     18 #include <stdint.h>
     19 #endif
     20 
     21 #include "mozilla/DefineEnum.h"
     22 
     23 // The version number must be rolled when the exported functions are updated!
     24 // If the CDM and the adapter use different versions of these functions, the
     25 // adapter will fail to load or crash!
     26 #define CDM_MODULE_VERSION 4
     27 
     28 // Build the versioned entrypoint name.
     29 // The extra macros are necessary to expand version to an actual value.
     30 #define INITIALIZE_CDM_MODULE \
     31  BUILD_ENTRYPOINT(InitializeCdmModule, CDM_MODULE_VERSION)
     32 #define BUILD_ENTRYPOINT(name, version) \
     33  BUILD_ENTRYPOINT_NO_EXPANSION(name, version)
     34 #define BUILD_ENTRYPOINT_NO_EXPANSION(name, version) name##_##version
     35 
     36 // Macro to check that |type| does the following:
     37 // 1. is a standard layout.
     38 // 2. is trivial.
     39 // 3. sizeof(type) matches the expected size in bytes. As some types contain
     40 //    pointers, the size is specified for both 32 and 64 bit.
     41 #define CHECK_TYPE(type, size_32, size_64)                           \
     42  static_assert(std::is_standard_layout<type>(),                     \
     43                #type " not standard_layout");                       \
     44  static_assert(std::is_trivial<type>(), #type " not trivial");      \
     45  static_assert((sizeof(void*) == 4 && sizeof(type) == size_32) ||   \
     46                    (sizeof(void*) == 8 && sizeof(type) == size_64), \
     47                #type " size mismatch")
     48 
     49 extern "C" {
     50 
     51 CDM_API void INITIALIZE_CDM_MODULE();
     52 
     53 CDM_API void DeinitializeCdmModule();
     54 
     55 // Returns a pointer to the requested CDM Host interface upon success.
     56 // Returns NULL if the requested CDM Host interface is not supported.
     57 // The caller should cast the returned pointer to the type matching
     58 // |host_interface_version|.
     59 typedef void* (*GetCdmHostFunc)(int host_interface_version, void* user_data);
     60 
     61 // Returns a pointer to the requested CDM upon success.
     62 // Returns NULL if an error occurs or the requested |cdm_interface_version| or
     63 // |key_system| is not supported or another error occurs.
     64 // The caller should cast the returned pointer to the type matching
     65 // |cdm_interface_version|.
     66 // Caller retains ownership of arguments and must call Destroy() on the returned
     67 // object.
     68 CDM_API void* CreateCdmInstance(int cdm_interface_version,
     69                                const char* key_system,
     70                                uint32_t key_system_size,
     71                                GetCdmHostFunc get_cdm_host_func,
     72                                void* user_data);
     73 
     74 CDM_API const char* GetCdmVersion();
     75 
     76 }  // extern "C"
     77 
     78 namespace cdm {
     79 
     80 MOZ_DEFINE_ENUM_WITH_BASE_AND_TOSTRING(Status, uint32_t, (
     81  kSuccess,
     82  kNeedMoreData,  // Decoder needs more data to produce a decoded frame/sample.
     83  kNoKey,         // The required decryption key is not available.
     84  kInitializationError,    // Initialization error.
     85  kDecryptError,           // Decryption failed.
     86  kDecodeError,            // Error decoding audio or video.
     87  kDeferredInitialization  // Decoder is not ready for initialization.
     88 ));
     89 CHECK_TYPE(Status, 4, 4);
     90 
     91 // Exceptions used by the CDM to reject promises.
     92 // https://w3c.github.io/encrypted-media/#exceptions
     93 enum Exception : uint32_t {
     94  kExceptionTypeError,
     95  kExceptionNotSupportedError,
     96  kExceptionInvalidStateError,
     97  kExceptionQuotaExceededError
     98 };
     99 CHECK_TYPE(Exception, 4, 4);
    100 
    101 // The encryption scheme. The definitions are from ISO/IEC 23001-7:2016.
    102 enum class EncryptionScheme : uint32_t {
    103  kUnencrypted = 0,
    104  kCenc,  // 'cenc' subsample encryption using AES-CTR mode.
    105  kCbcs   // 'cbcs' pattern encryption using AES-CBC mode.
    106 };
    107 CHECK_TYPE(EncryptionScheme, 4, 4);
    108 
    109 // The pattern used for pattern encryption. Note that ISO/IEC 23001-7:2016
    110 // defines each block to be 16-bytes.
    111 struct Pattern {
    112  uint32_t crypt_byte_block;  // Count of the encrypted blocks.
    113  uint32_t skip_byte_block;   // Count of the unencrypted blocks.
    114 };
    115 CHECK_TYPE(Pattern, 8, 8);
    116 
    117 enum class ColorRange : uint8_t {
    118  kInvalid,
    119  kLimited,  // 709 color range with RGB values ranging from 16 to 235.
    120  kFull,     // Full RGB color range with RGB values from 0 to 255.
    121  kDerived   // Range is defined by |transfer_id| and |matrix_id|.
    122 };
    123 CHECK_TYPE(ColorRange, 1, 1);
    124 
    125 // Described in ISO 23001-8:2016, section 7. All the IDs are in the range
    126 // [0, 255] so 8-bit integer is sufficient. An unspecified ColorSpace should be
    127 // {2, 2, 2, ColorRange::kInvalid}, where value 2 means "Unspecified" for all
    128 // the IDs, as defined by the spec.
    129 struct ColorSpace {
    130  uint8_t primary_id;   // 7.1 colour primaries, table 2
    131  uint8_t transfer_id;  // 7.2 transfer characteristics, table 3
    132  uint8_t matrix_id;    // 7.3 matrix coefficients, table 4
    133  ColorRange range;
    134 };
    135 CHECK_TYPE(ColorSpace, 4, 4);
    136 
    137 // Time is defined as the number of seconds since the Epoch
    138 // (00:00:00 UTC, January 1, 1970), not including any added leap second.
    139 // Also see Time definition in spec: https://w3c.github.io/encrypted-media/#time
    140 // Note that Time is defined in millisecond accuracy in the spec but in second
    141 // accuracy here.
    142 typedef double Time;
    143 
    144 // An input buffer can be split into several continuous subsamples.
    145 // A SubsampleEntry specifies the number of clear and cipher bytes in each
    146 // subsample. For example, the following buffer has three subsamples:
    147 //
    148 // |<----- subsample1 ----->|<----- subsample2 ----->|<----- subsample3 ----->|
    149 // |   clear1   |  cipher1  |  clear2  |   cipher2   | clear3 |    cipher3    |
    150 //
    151 // For decryption, all of the cipher bytes in a buffer should be concatenated
    152 // (in the subsample order) into a single logical stream. The clear bytes should
    153 // not be considered as part of decryption.
    154 //
    155 // Stream to decrypt:   |  cipher1  |   cipher2   |    cipher3    |
    156 // Decrypted stream:    | decrypted1|  decrypted2 |   decrypted3  |
    157 //
    158 // After decryption, the decrypted bytes should be copied over the position
    159 // of the corresponding cipher bytes in the original buffer to form the output
    160 // buffer. Following the above example, the decrypted buffer should be:
    161 //
    162 // |<----- subsample1 ----->|<----- subsample2 ----->|<----- subsample3 ----->|
    163 // |   clear1   | decrypted1|  clear2  |  decrypted2 | clear3 |   decrypted3  |
    164 //
    165 struct SubsampleEntry {
    166  uint32_t clear_bytes;
    167  uint32_t cipher_bytes;
    168 };
    169 CHECK_TYPE(SubsampleEntry, 8, 8);
    170 
    171 // Represents an input buffer to be decrypted (and possibly decoded). It does
    172 // not own any pointers in this struct. If |encryption_scheme| = kUnencrypted,
    173 // the data is unencrypted.
    174 // Note that this struct is organized so that sizeof(InputBuffer_2)
    175 // equals the sum of sizeof() all members in both 32-bit and 64-bit compiles.
    176 // Padding has been added to keep the fields aligned.
    177 struct InputBuffer_2 {
    178  const uint8_t* data;  // Pointer to the beginning of the input data.
    179  uint32_t data_size;   // Size (in bytes) of |data|.
    180 
    181  EncryptionScheme encryption_scheme;
    182 
    183  const uint8_t* key_id;  // Key ID to identify the decryption key.
    184  uint32_t key_id_size;   // Size (in bytes) of |key_id|.
    185  uint32_t : 32;          // Padding.
    186 
    187  const uint8_t* iv;  // Initialization vector.
    188  uint32_t iv_size;   // Size (in bytes) of |iv|.
    189  uint32_t : 32;      // Padding.
    190 
    191  const struct SubsampleEntry* subsamples;
    192  uint32_t num_subsamples;  // Number of subsamples in |subsamples|.
    193  uint32_t : 32;            // Padding.
    194 
    195  // |pattern| is required if |encryption_scheme| specifies pattern encryption.
    196  Pattern pattern;
    197 
    198  int64_t timestamp;  // Presentation timestamp in microseconds.
    199 };
    200 CHECK_TYPE(InputBuffer_2, 64, 80);
    201 
    202 enum AudioCodec : uint32_t { kUnknownAudioCodec = 0, kCodecVorbis, kCodecAac };
    203 CHECK_TYPE(AudioCodec, 4, 4);
    204 
    205 struct AudioDecoderConfig_2 {
    206  AudioCodec codec;
    207  int32_t channel_count;
    208  int32_t bits_per_channel;
    209  int32_t samples_per_second;
    210 
    211  // Optional byte data required to initialize audio decoders, such as the
    212  // vorbis setup header.
    213  uint8_t* extra_data;
    214  uint32_t extra_data_size;
    215 
    216  // Encryption scheme.
    217  EncryptionScheme encryption_scheme;
    218 };
    219 CHECK_TYPE(AudioDecoderConfig_2, 28, 32);
    220 
    221 // Supported sample formats for AudioFrames.
    222 enum AudioFormat : uint32_t {
    223  kUnknownAudioFormat = 0,  // Unknown format value. Used for error reporting.
    224  kAudioFormatU8,           // Interleaved unsigned 8-bit w/ bias of 128.
    225  kAudioFormatS16,          // Interleaved signed 16-bit.
    226  kAudioFormatS32,          // Interleaved signed 32-bit.
    227  kAudioFormatF32,          // Interleaved float 32-bit.
    228  kAudioFormatPlanarS16,    // Signed 16-bit planar.
    229  kAudioFormatPlanarF32,    // Float 32-bit planar.
    230 };
    231 CHECK_TYPE(AudioFormat, 4, 4);
    232 
    233 // Surface formats based on FOURCC labels, see: http://www.fourcc.org/yuv.php
    234 // Values are chosen to be consistent with Chromium's VideoPixelFormat values.
    235 enum VideoFormat : uint32_t {
    236  kUnknownVideoFormat = 0,  // Unknown format value. Used for error reporting.
    237  kYv12 = 1,                // 12bpp YVU planar 1x1 Y, 2x2 VU samples.
    238  kI420 = 2,                // 12bpp YUV planar 1x1 Y, 2x2 UV samples.
    239 
    240  // In the following formats, each sample uses 16-bit in storage, while the
    241  // sample value is stored in the least significant N bits where N is
    242  // specified by the number after "P". For example, for YUV420P9, each Y, U,
    243  // and V sample is stored in the least significant 9 bits in a 2-byte block.
    244  kYUV420P9 = 16,
    245  kYUV420P10 = 17,
    246  kYUV422P9 = 18,
    247  kYUV422P10 = 19,
    248  kYUV444P9 = 20,
    249  kYUV444P10 = 21,
    250  kYUV420P12 = 22,
    251  kYUV422P12 = 23,
    252  kYUV444P12 = 24,
    253 };
    254 CHECK_TYPE(VideoFormat, 4, 4);
    255 
    256 struct Size {
    257  int32_t width;
    258  int32_t height;
    259 };
    260 CHECK_TYPE(Size, 8, 8);
    261 
    262 enum VideoCodec : uint32_t {
    263  kUnknownVideoCodec = 0,
    264  kCodecVp8,
    265  kCodecH264,
    266  kCodecVp9,
    267  kCodecAv1
    268 };
    269 CHECK_TYPE(VideoCodec, 4, 4);
    270 
    271 enum VideoCodecProfile : uint32_t {
    272  kUnknownVideoCodecProfile = 0,
    273  kProfileNotNeeded,
    274  kH264ProfileBaseline,
    275  kH264ProfileMain,
    276  kH264ProfileExtended,
    277  kH264ProfileHigh,
    278  kH264ProfileHigh10,
    279  kH264ProfileHigh422,
    280  kH264ProfileHigh444Predictive,
    281  kVP9Profile0,
    282  kVP9Profile1,
    283  kVP9Profile2,
    284  kVP9Profile3,
    285  kAv1ProfileMain,
    286  kAv1ProfileHigh,
    287  kAv1ProfilePro
    288 };
    289 CHECK_TYPE(VideoCodecProfile, 4, 4);
    290 
    291 // Deprecated: New CDM implementations should use VideoDecoderConfig_3.
    292 // Note that this struct is organized so that sizeof(VideoDecoderConfig_2)
    293 // equals the sum of sizeof() all members in both 32-bit and 64-bit compiles.
    294 // Padding has been added to keep the fields aligned.
    295 struct VideoDecoderConfig_2 {
    296  VideoCodec codec;
    297  VideoCodecProfile profile;
    298  VideoFormat format;
    299  uint32_t : 32;  // Padding.
    300 
    301  // Width and height of video frame immediately post-decode. Not all pixels
    302  // in this region are valid.
    303  Size coded_size;
    304 
    305  // Optional byte data required to initialize video decoders, such as H.264
    306  // AAVC data.
    307  uint8_t* extra_data;
    308  uint32_t extra_data_size;
    309 
    310  // Encryption scheme.
    311  EncryptionScheme encryption_scheme;
    312 };
    313 CHECK_TYPE(VideoDecoderConfig_2, 36, 40);
    314 
    315 struct VideoDecoderConfig_3 {
    316  VideoCodec codec;
    317  VideoCodecProfile profile;
    318  VideoFormat format;
    319  ColorSpace color_space;
    320 
    321  // Width and height of video frame immediately post-decode. Not all pixels
    322  // in this region are valid.
    323  Size coded_size;
    324 
    325  // Optional byte data required to initialize video decoders, such as H.264
    326  // AAVC data.
    327  uint8_t* extra_data;
    328  uint32_t extra_data_size;
    329 
    330  EncryptionScheme encryption_scheme;
    331 };
    332 CHECK_TYPE(VideoDecoderConfig_3, 36, 40);
    333 
    334 enum StreamType : uint32_t { kStreamTypeAudio = 0, kStreamTypeVideo = 1 };
    335 CHECK_TYPE(StreamType, 4, 4);
    336 
    337 // Structure provided to ContentDecryptionModule::OnPlatformChallengeResponse()
    338 // after a platform challenge was initiated via Host::SendPlatformChallenge().
    339 // All values will be NULL / zero in the event of a challenge failure.
    340 struct PlatformChallengeResponse {
    341  // |challenge| provided during Host::SendPlatformChallenge() combined with
    342  // nonce data and signed with the platform's private key.
    343  const uint8_t* signed_data;
    344  uint32_t signed_data_length;
    345 
    346  // RSASSA-PKCS1-v1_5-SHA256 signature of the |signed_data| block.
    347  const uint8_t* signed_data_signature;
    348  uint32_t signed_data_signature_length;
    349 
    350  // X.509 device specific certificate for the |service_id| requested.
    351  const uint8_t* platform_key_certificate;
    352  uint32_t platform_key_certificate_length;
    353 };
    354 CHECK_TYPE(PlatformChallengeResponse, 24, 48);
    355 
    356 // The current status of the associated key. The valid types are defined in the
    357 // spec: https://w3c.github.io/encrypted-media/#dom-mediakeystatus
    358 enum KeyStatus : uint32_t {
    359  kUsable = 0,
    360  kInternalError = 1,
    361  kExpired = 2,
    362  kOutputRestricted = 3,
    363  kOutputDownscaled = 4,
    364  kStatusPending = 5,
    365  kReleased = 6
    366 };
    367 CHECK_TYPE(KeyStatus, 4, 4);
    368 
    369 // Used when passing arrays of key information. Does not own the referenced
    370 // data. |system_code| is an additional error code for unusable keys and
    371 // should be 0 when |status| == kUsable.
    372 struct KeyInformation {
    373  const uint8_t* key_id;
    374  uint32_t key_id_size;
    375  KeyStatus status;
    376  uint32_t system_code;
    377 };
    378 CHECK_TYPE(KeyInformation, 16, 24);
    379 
    380 // Supported output protection methods for use with EnableOutputProtection() and
    381 // returned by OnQueryOutputProtectionStatus().
    382 enum OutputProtectionMethods : uint32_t {
    383  kProtectionNone = 0,
    384  kProtectionHDCP = 1 << 0
    385 };
    386 CHECK_TYPE(OutputProtectionMethods, 4, 4);
    387 
    388 // Connected output link types returned by OnQueryOutputProtectionStatus().
    389 enum OutputLinkTypes : uint32_t {
    390  kLinkTypeNone = 0,
    391  kLinkTypeUnknown = 1 << 0,
    392  kLinkTypeInternal = 1 << 1,
    393  kLinkTypeVGA = 1 << 2,
    394  kLinkTypeHDMI = 1 << 3,
    395  kLinkTypeDVI = 1 << 4,
    396  kLinkTypeDisplayPort = 1 << 5,
    397  kLinkTypeNetwork = 1 << 6
    398 };
    399 CHECK_TYPE(OutputLinkTypes, 4, 4);
    400 
    401 // Result of the QueryOutputProtectionStatus() call.
    402 enum QueryResult : uint32_t { kQuerySucceeded = 0, kQueryFailed };
    403 CHECK_TYPE(QueryResult, 4, 4);
    404 
    405 // The Initialization Data Type. The valid types are defined in the spec:
    406 // https://w3c.github.io/encrypted-media/format-registry/initdata/index.html#registry
    407 enum InitDataType : uint32_t { kCenc = 0, kKeyIds = 1, kWebM = 2 };
    408 CHECK_TYPE(InitDataType, 4, 4);
    409 
    410 // The type of session to create. The valid types are defined in the spec:
    411 // https://w3c.github.io/encrypted-media/#dom-mediakeysessiontype
    412 enum SessionType : uint32_t {
    413  kTemporary = 0,
    414  kPersistentLicense = 1,
    415  kPersistentUsageRecord = 2
    416 };
    417 CHECK_TYPE(SessionType, 4, 4);
    418 
    419 // The type of the message event.  The valid types are defined in the spec:
    420 // https://w3c.github.io/encrypted-media/#dom-mediakeymessagetype
    421 enum MessageType : uint32_t {
    422  kLicenseRequest = 0,
    423  kLicenseRenewal = 1,
    424  kLicenseRelease = 2,
    425  kIndividualizationRequest = 3
    426 };
    427 CHECK_TYPE(MessageType, 4, 4);
    428 
    429 enum HdcpVersion : uint32_t {
    430  kHdcpVersionNone,
    431  kHdcpVersion1_0,
    432  kHdcpVersion1_1,
    433  kHdcpVersion1_2,
    434  kHdcpVersion1_3,
    435  kHdcpVersion1_4,
    436  kHdcpVersion2_0,
    437  kHdcpVersion2_1,
    438  kHdcpVersion2_2,
    439  kHdcpVersion2_3
    440 };
    441 CHECK_TYPE(HdcpVersion, 4, 4);
    442 
    443 struct Policy {
    444  HdcpVersion min_hdcp_version;
    445 };
    446 CHECK_TYPE(Policy, 4, 4);
    447 
    448 // Represents a buffer created by Allocator implementations.
    449 class CDM_CLASS_API Buffer {
    450 public:
    451  // Destroys the buffer in the same context as it was created.
    452  virtual void Destroy() = 0;
    453 
    454  virtual uint32_t Capacity() const = 0;
    455  virtual uint8_t* Data() = 0;
    456  virtual void SetSize(uint32_t size) = 0;
    457  virtual uint32_t Size() const = 0;
    458 
    459 protected:
    460  Buffer() {}
    461  virtual ~Buffer() {}
    462 
    463 private:
    464  Buffer(const Buffer&);
    465  void operator=(const Buffer&);
    466 };
    467 
    468 // Represents a decrypted block that has not been decoded.
    469 class CDM_CLASS_API DecryptedBlock {
    470 public:
    471  virtual void SetDecryptedBuffer(Buffer* buffer) = 0;
    472  virtual Buffer* DecryptedBuffer() = 0;
    473 
    474  // TODO(tomfinegan): Figure out if timestamp is really needed. If it is not,
    475  // we can just pass Buffer pointers around.
    476  virtual void SetTimestamp(int64_t timestamp) = 0;
    477  virtual int64_t Timestamp() const = 0;
    478 
    479 protected:
    480  DecryptedBlock() {}
    481  virtual ~DecryptedBlock() {}
    482 };
    483 
    484 // This intentionally avoids using an enum, since it will be used to do math
    485 // with other enums, which is deprecated in C++20.
    486 using VideoPlane = uint32_t;
    487 constexpr VideoPlane kYPlane = 0;
    488 constexpr VideoPlane kUPlane = 1;
    489 constexpr VideoPlane kVPlane = 2;
    490 constexpr VideoPlane kMaxPlanes = 3;
    491 CHECK_TYPE(VideoPlane, 4, 4);
    492 
    493 class CDM_CLASS_API VideoFrame {
    494 public:
    495  virtual void SetFormat(VideoFormat format) = 0;
    496  virtual VideoFormat Format() const = 0;
    497 
    498  virtual void SetSize(cdm::Size size) = 0;
    499  virtual cdm::Size Size() const = 0;
    500 
    501  virtual void SetFrameBuffer(Buffer* frame_buffer) = 0;
    502  virtual Buffer* FrameBuffer() = 0;
    503 
    504  virtual void SetPlaneOffset(VideoPlane plane, uint32_t offset) = 0;
    505  virtual uint32_t PlaneOffset(VideoPlane plane) = 0;
    506 
    507  virtual void SetStride(VideoPlane plane, uint32_t stride) = 0;
    508  virtual uint32_t Stride(VideoPlane plane) = 0;
    509 
    510  // Sets and gets the presentation timestamp which is in microseconds.
    511  virtual void SetTimestamp(int64_t timestamp) = 0;
    512  virtual int64_t Timestamp() const = 0;
    513 
    514 protected:
    515  VideoFrame() {}
    516  virtual ~VideoFrame() {}
    517 };
    518 
    519 // Represents a decoded video frame. The CDM should call the interface methods
    520 // to set the frame attributes. See DecryptAndDecodeFrame().
    521 class CDM_CLASS_API VideoFrame_2 {
    522 public:
    523  virtual void SetFormat(VideoFormat format) = 0;
    524  virtual void SetSize(cdm::Size size) = 0;
    525  virtual void SetFrameBuffer(Buffer* frame_buffer) = 0;
    526  virtual void SetPlaneOffset(VideoPlane plane, uint32_t offset) = 0;
    527  virtual void SetStride(VideoPlane plane, uint32_t stride) = 0;
    528  // Sets the presentation timestamp which is in microseconds.
    529  virtual void SetTimestamp(int64_t timestamp) = 0;
    530  virtual void SetColorSpace(ColorSpace color_space) = 0;
    531 
    532 protected:
    533  VideoFrame_2() {}
    534  virtual ~VideoFrame_2() {}
    535 };
    536 
    537 // Represents decrypted and decoded audio frames. AudioFrames can contain
    538 // multiple audio output buffers, which are serialized into this format:
    539 //
    540 // |<------------------- serialized audio buffer ------------------->|
    541 // | int64_t timestamp | int64_t length | length bytes of audio data |
    542 //
    543 // For example, with three audio output buffers, the AudioFrames will look
    544 // like this:
    545 //
    546 // |<----------------- AudioFrames ------------------>|
    547 // | audio buffer 0 | audio buffer 1 | audio buffer 2 |
    548 class CDM_CLASS_API AudioFrames {
    549 public:
    550  virtual void SetFrameBuffer(Buffer* buffer) = 0;
    551  virtual Buffer* FrameBuffer() = 0;
    552 
    553  // The CDM must call this method, providing a valid format, when providing
    554  // frame buffers. Planar data should be stored end to end; e.g.,
    555  // |ch1 sample1||ch1 sample2|....|ch1 sample_last||ch2 sample1|...
    556  virtual void SetFormat(AudioFormat format) = 0;
    557  virtual AudioFormat Format() const = 0;
    558 
    559 protected:
    560  AudioFrames() {}
    561  virtual ~AudioFrames() {}
    562 };
    563 
    564 // FileIO interface provides a way for the CDM to store data in a file in
    565 // persistent storage. This interface aims only at providing basic read/write
    566 // capabilities and should not be used as a full fledged file IO API.
    567 // Each CDM and origin (e.g. HTTPS, "foo.example.com", 443) combination has
    568 // its own persistent storage. All instances of a given CDM associated with a
    569 // given origin share the same persistent storage.
    570 // Note to implementors of this interface:
    571 // Per-origin storage and the ability for users to clear it are important.
    572 // See http://www.w3.org/TR/encrypted-media/#privacy-storedinfo.
    573 class CDM_CLASS_API FileIO {
    574 public:
    575  // Opens the file with |file_name| for read and write.
    576  // FileIOClient::OnOpenComplete() will be called after the opening
    577  // operation finishes.
    578  // - When the file is opened by a CDM instance, it will be classified as "in
    579  //   use". In this case other CDM instances in the same domain may receive
    580  //   kInUse status when trying to open it.
    581  // - |file_name| must only contain letters (A-Za-z), digits(0-9), or "._-".
    582  //   It must not start with an underscore ('_'), and must be at least 1
    583  //   character and no more than 256 characters long.
    584  virtual void Open(const char* file_name, uint32_t file_name_size) = 0;
    585 
    586  // Reads the contents of the file. FileIOClient::OnReadComplete() will be
    587  // called with the read status. Read() should not be called if a previous
    588  // Read() or Write() call is still pending; otherwise OnReadComplete() will
    589  // be called with kInUse.
    590  virtual void Read() = 0;
    591 
    592  // Writes |data_size| bytes of |data| into the file.
    593  // FileIOClient::OnWriteComplete() will be called with the write status.
    594  // All existing contents in the file will be overwritten. Calling Write() with
    595  // NULL |data| will clear all contents in the file. Write() should not be
    596  // called if a previous Write() or Read() call is still pending; otherwise
    597  // OnWriteComplete() will be called with kInUse.
    598  virtual void Write(const uint8_t* data, uint32_t data_size) = 0;
    599 
    600  // Closes the file if opened, destroys this FileIO object and releases any
    601  // resources allocated. The CDM must call this method when it finished using
    602  // this object. A FileIO object must not be used after Close() is called.
    603  virtual void Close() = 0;
    604 
    605 protected:
    606  FileIO() {}
    607  virtual ~FileIO() {}
    608 };
    609 
    610 // Responses to FileIO calls. All responses will be called asynchronously.
    611 // When kError is returned, the FileIO object could be in an error state. All
    612 // following calls (other than Close()) could return kError. The CDM should
    613 // still call Close() to destroy the FileIO object.
    614 class CDM_CLASS_API FileIOClient {
    615 public:
    616  enum class Status : uint32_t { kSuccess = 0, kInUse, kError };
    617 
    618  // Response to a FileIO::Open() call with the open |status|.
    619  virtual void OnOpenComplete(Status status) = 0;
    620 
    621  // Response to a FileIO::Read() call to provide |data_size| bytes of |data|
    622  // read from the file.
    623  // - kSuccess indicates that all contents of the file has been successfully
    624  //   read. In this case, 0 |data_size| means that the file is empty.
    625  // - kInUse indicates that there are other read/write operations pending.
    626  // - kError indicates read failure, e.g. the storage is not open or cannot be
    627  //   fully read.
    628  virtual void OnReadComplete(Status status,
    629                              const uint8_t* data,
    630                              uint32_t data_size) = 0;
    631 
    632  // Response to a FileIO::Write() call.
    633  // - kSuccess indicates that all the data has been written into the file
    634  //   successfully.
    635  // - kInUse indicates that there are other read/write operations pending.
    636  // - kError indicates write failure, e.g. the storage is not open or cannot be
    637  //   fully written. Upon write failure, the contents of the file should be
    638  //   regarded as corrupt and should not used.
    639  virtual void OnWriteComplete(Status status) = 0;
    640 
    641 protected:
    642  FileIOClient() {}
    643  virtual ~FileIOClient() {}
    644 };
    645 
    646 // Metrics that will be reported from the CDM through the ReportMetrics()
    647 // function. To add a new metric, please add it to the end of this enum list
    648 // without changing any existing enum values.
    649 // Note: For forward compatibility, Host implementations must gracefully handle
    650 // unexpected (new) enum values, e.g. no-op.
    651 enum MetricName : uint32_t {
    652  kSdkVersion,
    653  kCertificateSerialNumber,
    654  kDecoderBypassBlockCount,
    655 };
    656 CHECK_TYPE(MetricName, 4, 4);
    657 
    658 class CDM_CLASS_API Host_10;
    659 class CDM_CLASS_API Host_11;
    660 class CDM_CLASS_API Host_12;
    661 
    662 // ContentDecryptionModule interface that all CDMs need to implement.
    663 // The interface is versioned for backward compatibility.
    664 // Note: ContentDecryptionModule implementations must use the allocator
    665 // provided in CreateCdmInstance() to allocate any Buffer that needs to
    666 // be passed back to the caller. Implementations must call Buffer::Destroy()
    667 // when a Buffer is created that will never be returned to the caller.
    668 class CDM_CLASS_API ContentDecryptionModule_10 {
    669 public:
    670  static const int kVersion = 10;
    671  static const bool kIsStable = true;
    672  typedef Host_10 Host;
    673 
    674  // Initializes the CDM instance, providing information about permitted
    675  // functionalities. The CDM must respond by calling Host::OnInitialized()
    676  // with whether the initialization succeeded. No other calls will be made by
    677  // the host before Host::OnInitialized() returns.
    678  // If |allow_distinctive_identifier| is false, messages from the CDM,
    679  // such as message events, must not contain a Distinctive Identifier,
    680  // even in an encrypted form.
    681  // If |allow_persistent_state| is false, the CDM must not attempt to
    682  // persist state. Calls to CreateFileIO() will fail.
    683  // If |use_hw_secure_codecs| is true, the CDM must ensure the decryption key
    684  // and video buffers (compressed and uncompressed) are securely protected by
    685  // hardware.
    686  virtual void Initialize(bool allow_distinctive_identifier,
    687                          bool allow_persistent_state,
    688                          bool use_hw_secure_codecs) = 0;
    689 
    690  // Gets the key status if the CDM has a hypothetical key with the |policy|.
    691  // The CDM must respond by calling either Host::OnResolveKeyStatusPromise()
    692  // with the result key status or Host::OnRejectPromise() if an unexpected
    693  // error happened or this method is not supported.
    694  virtual void GetStatusForPolicy(uint32_t promise_id,
    695                                  const Policy& policy) = 0;
    696 
    697  // SetServerCertificate(), CreateSessionAndGenerateRequest(), LoadSession(),
    698  // UpdateSession(), CloseSession(), and RemoveSession() all accept a
    699  // |promise_id|, which must be passed to the completion Host method
    700  // (e.g. Host::OnResolveNewSessionPromise()).
    701 
    702  // Provides a server certificate to be used to encrypt messages to the
    703  // license server. The CDM must respond by calling either
    704  // Host::OnResolvePromise() or Host::OnRejectPromise().
    705  // If the CDM does not support server certificates, the promise should be
    706  // rejected with kExceptionNotSupportedError. If |server_certificate_data|
    707  // is empty, reject with kExceptionTypeError. Any other error should be
    708  // rejected with kExceptionInvalidStateError or kExceptionQuotaExceededError.
    709  // TODO(crbug.com/796417): Add support for the promise to return true or
    710  // false, rather than using kExceptionNotSupportedError to mean false.
    711  virtual void SetServerCertificate(uint32_t promise_id,
    712                                    const uint8_t* server_certificate_data,
    713                                    uint32_t server_certificate_data_size) = 0;
    714 
    715  // Creates a session given |session_type|, |init_data_type|, and |init_data|.
    716  // The CDM must respond by calling either Host::OnResolveNewSessionPromise()
    717  // or Host::OnRejectPromise().
    718  virtual void CreateSessionAndGenerateRequest(uint32_t promise_id,
    719                                               SessionType session_type,
    720                                               InitDataType init_data_type,
    721                                               const uint8_t* init_data,
    722                                               uint32_t init_data_size) = 0;
    723 
    724  // Loads the session of type |session_type| specified by |session_id|.
    725  // The CDM must respond by calling either Host::OnResolveNewSessionPromise()
    726  // or Host::OnRejectPromise(). If the session is not found, call
    727  // Host::OnResolveNewSessionPromise() with session_id = NULL.
    728  virtual void LoadSession(uint32_t promise_id,
    729                           SessionType session_type,
    730                           const char* session_id,
    731                           uint32_t session_id_size) = 0;
    732 
    733  // Updates the session with |response|. The CDM must respond by calling
    734  // either Host::OnResolvePromise() or Host::OnRejectPromise().
    735  virtual void UpdateSession(uint32_t promise_id,
    736                             const char* session_id,
    737                             uint32_t session_id_size,
    738                             const uint8_t* response,
    739                             uint32_t response_size) = 0;
    740 
    741  // Requests that the CDM close the session. The CDM must respond by calling
    742  // either Host::OnResolvePromise() or Host::OnRejectPromise() when the request
    743  // has been processed. This may be before the session is closed. Once the
    744  // session is closed, Host::OnSessionClosed() must also be called.
    745  virtual void CloseSession(uint32_t promise_id,
    746                            const char* session_id,
    747                            uint32_t session_id_size) = 0;
    748 
    749  // Removes any stored session data associated with this session. Will only be
    750  // called for persistent sessions. The CDM must respond by calling either
    751  // Host::OnResolvePromise() or Host::OnRejectPromise() when the request has
    752  // been processed.
    753  virtual void RemoveSession(uint32_t promise_id,
    754                             const char* session_id,
    755                             uint32_t session_id_size) = 0;
    756 
    757  // Performs scheduled operation with |context| when the timer fires.
    758  virtual void TimerExpired(void* context) = 0;
    759 
    760  // Decrypts the |encrypted_buffer|.
    761  //
    762  // Returns kSuccess if decryption succeeded, in which case the callee
    763  // should have filled the |decrypted_buffer| and passed the ownership of
    764  // |data| in |decrypted_buffer| to the caller.
    765  // Returns kNoKey if the CDM did not have the necessary decryption key
    766  // to decrypt.
    767  // Returns kDecryptError if any other error happened.
    768  // If the return value is not kSuccess, |decrypted_buffer| should be ignored
    769  // by the caller.
    770  virtual Status Decrypt(const InputBuffer_2& encrypted_buffer,
    771                         DecryptedBlock* decrypted_buffer) = 0;
    772 
    773  // Initializes the CDM audio decoder with |audio_decoder_config|. This
    774  // function must be called before DecryptAndDecodeSamples() is called.
    775  //
    776  // Returns kSuccess if the |audio_decoder_config| is supported and the CDM
    777  // audio decoder is successfully initialized.
    778  // Returns kInitializationError if |audio_decoder_config| is not supported.
    779  // The CDM may still be able to do Decrypt().
    780  // Returns kDeferredInitialization if the CDM is not ready to initialize the
    781  // decoder at this time. Must call Host::OnDeferredInitializationDone() once
    782  // initialization is complete.
    783  virtual Status InitializeAudioDecoder(
    784      const AudioDecoderConfig_2& audio_decoder_config) = 0;
    785 
    786  // Initializes the CDM video decoder with |video_decoder_config|. This
    787  // function must be called before DecryptAndDecodeFrame() is called.
    788  //
    789  // Returns kSuccess if the |video_decoder_config| is supported and the CDM
    790  // video decoder is successfully initialized.
    791  // Returns kInitializationError if |video_decoder_config| is not supported.
    792  // The CDM may still be able to do Decrypt().
    793  // Returns kDeferredInitialization if the CDM is not ready to initialize the
    794  // decoder at this time. Must call Host::OnDeferredInitializationDone() once
    795  // initialization is complete.
    796  virtual Status InitializeVideoDecoder(
    797      const VideoDecoderConfig_2& video_decoder_config) = 0;
    798 
    799  // De-initializes the CDM decoder and sets it to an uninitialized state. The
    800  // caller can initialize the decoder again after this call to re-initialize
    801  // it. This can be used to reconfigure the decoder if the configuration
    802  // changes.
    803  virtual void DeinitializeDecoder(StreamType decoder_type) = 0;
    804 
    805  // Resets the CDM decoder to an initialized clean state. All internal buffers
    806  // MUST be flushed.
    807  virtual void ResetDecoder(StreamType decoder_type) = 0;
    808 
    809  // Decrypts the |encrypted_buffer| and decodes the decrypted buffer into a
    810  // |video_frame|. Upon end-of-stream, the caller should call this function
    811  // repeatedly with empty |encrypted_buffer| (|data| == NULL) until
    812  // kNeedMoreData is returned.
    813  //
    814  // Returns kSuccess if decryption and decoding both succeeded, in which case
    815  // the callee will have filled the |video_frame| and passed the ownership of
    816  // |frame_buffer| in |video_frame| to the caller.
    817  // Returns kNoKey if the CDM did not have the necessary decryption key
    818  // to decrypt.
    819  // Returns kNeedMoreData if more data was needed by the decoder to generate
    820  // a decoded frame (e.g. during initialization and end-of-stream).
    821  // Returns kDecryptError if any decryption error happened.
    822  // Returns kDecodeError if any decoding error happened.
    823  // If the return value is not kSuccess, |video_frame| should be ignored by
    824  // the caller.
    825  virtual Status DecryptAndDecodeFrame(const InputBuffer_2& encrypted_buffer,
    826                                       VideoFrame* video_frame) = 0;
    827 
    828  // Decrypts the |encrypted_buffer| and decodes the decrypted buffer into
    829  // |audio_frames|. Upon end-of-stream, the caller should call this function
    830  // repeatedly with empty |encrypted_buffer| (|data| == NULL) until only empty
    831  // |audio_frames| is produced.
    832  //
    833  // Returns kSuccess if decryption and decoding both succeeded, in which case
    834  // the callee will have filled |audio_frames| and passed the ownership of
    835  // |data| in |audio_frames| to the caller.
    836  // Returns kNoKey if the CDM did not have the necessary decryption key
    837  // to decrypt.
    838  // Returns kNeedMoreData if more data was needed by the decoder to generate
    839  // audio samples (e.g. during initialization and end-of-stream).
    840  // Returns kDecryptError if any decryption error happened.
    841  // Returns kDecodeError if any decoding error happened.
    842  // If the return value is not kSuccess, |audio_frames| should be ignored by
    843  // the caller.
    844  virtual Status DecryptAndDecodeSamples(const InputBuffer_2& encrypted_buffer,
    845                                         AudioFrames* audio_frames) = 0;
    846 
    847  // Called by the host after a platform challenge was initiated via
    848  // Host::SendPlatformChallenge().
    849  virtual void OnPlatformChallengeResponse(
    850      const PlatformChallengeResponse& response) = 0;
    851 
    852  // Called by the host after a call to Host::QueryOutputProtectionStatus(). The
    853  // |link_mask| is a bit mask of OutputLinkTypes and |output_protection_mask|
    854  // is a bit mask of OutputProtectionMethods. If |result| is kQueryFailed,
    855  // then |link_mask| and |output_protection_mask| are undefined and should
    856  // be ignored.
    857  virtual void OnQueryOutputProtectionStatus(
    858      QueryResult result,
    859      uint32_t link_mask,
    860      uint32_t output_protection_mask) = 0;
    861 
    862  // Called by the host after a call to Host::RequestStorageId(). If the
    863  // version of the storage ID requested is available, |storage_id| and
    864  // |storage_id_size| are set appropriately. |version| will be the same as
    865  // what was requested, unless 0 (latest) was requested, in which case
    866  // |version| will be the actual version number for the |storage_id| returned.
    867  // If the requested version is not available, null/zero will be provided as
    868  // |storage_id| and |storage_id_size|, respectively, and |version| should be
    869  // ignored.
    870  virtual void OnStorageId(uint32_t version,
    871                           const uint8_t* storage_id,
    872                           uint32_t storage_id_size) = 0;
    873 
    874  // Destroys the object in the same context as it was created.
    875  virtual void Destroy() = 0;
    876 
    877 protected:
    878  ContentDecryptionModule_10() {}
    879  virtual ~ContentDecryptionModule_10() {}
    880 };
    881 
    882 // ContentDecryptionModule interface that all CDMs need to implement.
    883 // The interface is versioned for backward compatibility.
    884 // Note: ContentDecryptionModule implementations must use the allocator
    885 // provided in CreateCdmInstance() to allocate any Buffer that needs to
    886 // be passed back to the caller. Implementations must call Buffer::Destroy()
    887 // when a Buffer is created that will never be returned to the caller.
    888 class CDM_CLASS_API ContentDecryptionModule_11 {
    889 public:
    890  static const int kVersion = 11;
    891  static const bool kIsStable = true;
    892  typedef Host_11 Host;
    893 
    894  // Initializes the CDM instance, providing information about permitted
    895  // functionalities. The CDM must respond by calling Host::OnInitialized()
    896  // with whether the initialization succeeded. No other calls will be made by
    897  // the host before Host::OnInitialized() returns.
    898  // If |allow_distinctive_identifier| is false, messages from the CDM,
    899  // such as message events, must not contain a Distinctive Identifier,
    900  // even in an encrypted form.
    901  // If |allow_persistent_state| is false, the CDM must not attempt to
    902  // persist state. Calls to CreateFileIO() will fail.
    903  // If |use_hw_secure_codecs| is true, the CDM must ensure the decryption key
    904  // and video buffers (compressed and uncompressed) are securely protected by
    905  // hardware.
    906  virtual void Initialize(bool allow_distinctive_identifier,
    907                          bool allow_persistent_state,
    908                          bool use_hw_secure_codecs) = 0;
    909 
    910  // Gets the key status if the CDM has a hypothetical key with the |policy|.
    911  // The CDM must respond by calling either Host::OnResolveKeyStatusPromise()
    912  // with the result key status or Host::OnRejectPromise() if an unexpected
    913  // error happened or this method is not supported.
    914  virtual void GetStatusForPolicy(uint32_t promise_id,
    915                                  const Policy& policy) = 0;
    916 
    917  // SetServerCertificate(), CreateSessionAndGenerateRequest(), LoadSession(),
    918  // UpdateSession(), CloseSession(), and RemoveSession() all accept a
    919  // |promise_id|, which must be passed to the completion Host method
    920  // (e.g. Host::OnResolveNewSessionPromise()).
    921 
    922  // Provides a server certificate to be used to encrypt messages to the
    923  // license server. The CDM must respond by calling either
    924  // Host::OnResolvePromise() or Host::OnRejectPromise().
    925  // If the CDM does not support server certificates, the promise should be
    926  // rejected with kExceptionNotSupportedError. If |server_certificate_data|
    927  // is empty, reject with kExceptionTypeError. Any other error should be
    928  // rejected with kExceptionInvalidStateError or kExceptionQuotaExceededError.
    929  // TODO(crbug.com/796417): Add support for the promise to return true or
    930  // false, rather than using kExceptionNotSupportedError to mean false.
    931  virtual void SetServerCertificate(uint32_t promise_id,
    932                                    const uint8_t* server_certificate_data,
    933                                    uint32_t server_certificate_data_size) = 0;
    934 
    935  // Creates a session given |session_type|, |init_data_type|, and |init_data|.
    936  // The CDM must respond by calling either Host::OnResolveNewSessionPromise()
    937  // or Host::OnRejectPromise().
    938  virtual void CreateSessionAndGenerateRequest(uint32_t promise_id,
    939                                               SessionType session_type,
    940                                               InitDataType init_data_type,
    941                                               const uint8_t* init_data,
    942                                               uint32_t init_data_size) = 0;
    943 
    944  // Loads the session of type |session_type| specified by |session_id|.
    945  // The CDM must respond by calling either Host::OnResolveNewSessionPromise()
    946  // or Host::OnRejectPromise(). If the session is not found, call
    947  // Host::OnResolveNewSessionPromise() with session_id = NULL.
    948  virtual void LoadSession(uint32_t promise_id,
    949                           SessionType session_type,
    950                           const char* session_id,
    951                           uint32_t session_id_size) = 0;
    952 
    953  // Updates the session with |response|. The CDM must respond by calling
    954  // either Host::OnResolvePromise() or Host::OnRejectPromise().
    955  virtual void UpdateSession(uint32_t promise_id,
    956                             const char* session_id,
    957                             uint32_t session_id_size,
    958                             const uint8_t* response,
    959                             uint32_t response_size) = 0;
    960 
    961  // Requests that the CDM close the session. The CDM must respond by calling
    962  // either Host::OnResolvePromise() or Host::OnRejectPromise() when the request
    963  // has been processed. This may be before the session is closed. Once the
    964  // session is closed, Host::OnSessionClosed() must also be called.
    965  virtual void CloseSession(uint32_t promise_id,
    966                            const char* session_id,
    967                            uint32_t session_id_size) = 0;
    968 
    969  // Removes any stored session data associated with this session. Will only be
    970  // called for persistent sessions. The CDM must respond by calling either
    971  // Host::OnResolvePromise() or Host::OnRejectPromise() when the request has
    972  // been processed.
    973  virtual void RemoveSession(uint32_t promise_id,
    974                             const char* session_id,
    975                             uint32_t session_id_size) = 0;
    976 
    977  // Performs scheduled operation with |context| when the timer fires.
    978  virtual void TimerExpired(void* context) = 0;
    979 
    980  // Decrypts the |encrypted_buffer|.
    981  //
    982  // Returns kSuccess if decryption succeeded, in which case the callee
    983  // should have filled the |decrypted_buffer| and passed the ownership of
    984  // |data| in |decrypted_buffer| to the caller.
    985  // Returns kNoKey if the CDM did not have the necessary decryption key
    986  // to decrypt.
    987  // Returns kDecryptError if any other error happened.
    988  // If the return value is not kSuccess, |decrypted_buffer| should be ignored
    989  // by the caller.
    990  virtual Status Decrypt(const InputBuffer_2& encrypted_buffer,
    991                         DecryptedBlock* decrypted_buffer) = 0;
    992 
    993  // Initializes the CDM audio decoder with |audio_decoder_config|. This
    994  // function must be called before DecryptAndDecodeSamples() is called.
    995  //
    996  // Returns kSuccess if the |audio_decoder_config| is supported and the CDM
    997  // audio decoder is successfully initialized.
    998  // Returns kInitializationError if |audio_decoder_config| is not supported.
    999  // The CDM may still be able to do Decrypt().
   1000  // Returns kDeferredInitialization if the CDM is not ready to initialize the
   1001  // decoder at this time. Must call Host::OnDeferredInitializationDone() once
   1002  // initialization is complete.
   1003  virtual Status InitializeAudioDecoder(
   1004      const AudioDecoderConfig_2& audio_decoder_config) = 0;
   1005 
   1006  // Initializes the CDM video decoder with |video_decoder_config|. This
   1007  // function must be called before DecryptAndDecodeFrame() is called.
   1008  //
   1009  // Returns kSuccess if the |video_decoder_config| is supported and the CDM
   1010  // video decoder is successfully initialized.
   1011  // Returns kInitializationError if |video_decoder_config| is not supported.
   1012  // The CDM may still be able to do Decrypt().
   1013  // Returns kDeferredInitialization if the CDM is not ready to initialize the
   1014  // decoder at this time. Must call Host::OnDeferredInitializationDone() once
   1015  // initialization is complete.
   1016  virtual Status InitializeVideoDecoder(
   1017      const VideoDecoderConfig_2& video_decoder_config) = 0;
   1018 
   1019  // De-initializes the CDM decoder and sets it to an uninitialized state. The
   1020  // caller can initialize the decoder again after this call to re-initialize
   1021  // it. This can be used to reconfigure the decoder if the configuration
   1022  // changes.
   1023  virtual void DeinitializeDecoder(StreamType decoder_type) = 0;
   1024 
   1025  // Resets the CDM decoder to an initialized clean state. All internal buffers
   1026  // MUST be flushed.
   1027  virtual void ResetDecoder(StreamType decoder_type) = 0;
   1028 
   1029  // Decrypts the |encrypted_buffer| and decodes the decrypted buffer into a
   1030  // |video_frame|. Upon end-of-stream, the caller should call this function
   1031  // repeatedly with empty |encrypted_buffer| (|data| == NULL) until
   1032  // kNeedMoreData is returned.
   1033  //
   1034  // Returns kSuccess if decryption and decoding both succeeded, in which case
   1035  // the callee will have filled the |video_frame| and passed the ownership of
   1036  // |frame_buffer| in |video_frame| to the caller.
   1037  // Returns kNoKey if the CDM did not have the necessary decryption key
   1038  // to decrypt.
   1039  // Returns kNeedMoreData if more data was needed by the decoder to generate
   1040  // a decoded frame (e.g. during initialization and end-of-stream).
   1041  // Returns kDecryptError if any decryption error happened.
   1042  // Returns kDecodeError if any decoding error happened.
   1043  // If the return value is not kSuccess, |video_frame| should be ignored by
   1044  // the caller.
   1045  virtual Status DecryptAndDecodeFrame(const InputBuffer_2& encrypted_buffer,
   1046                                       VideoFrame* video_frame) = 0;
   1047 
   1048  // Decrypts the |encrypted_buffer| and decodes the decrypted buffer into
   1049  // |audio_frames|. Upon end-of-stream, the caller should call this function
   1050  // repeatedly with empty |encrypted_buffer| (|data| == NULL) until only empty
   1051  // |audio_frames| is produced.
   1052  //
   1053  // Returns kSuccess if decryption and decoding both succeeded, in which case
   1054  // the callee will have filled |audio_frames| and passed the ownership of
   1055  // |data| in |audio_frames| to the caller.
   1056  // Returns kNoKey if the CDM did not have the necessary decryption key
   1057  // to decrypt.
   1058  // Returns kNeedMoreData if more data was needed by the decoder to generate
   1059  // audio samples (e.g. during initialization and end-of-stream).
   1060  // Returns kDecryptError if any decryption error happened.
   1061  // Returns kDecodeError if any decoding error happened.
   1062  // If the return value is not kSuccess, |audio_frames| should be ignored by
   1063  // the caller.
   1064  virtual Status DecryptAndDecodeSamples(const InputBuffer_2& encrypted_buffer,
   1065                                         AudioFrames* audio_frames) = 0;
   1066 
   1067  // Called by the host after a platform challenge was initiated via
   1068  // Host::SendPlatformChallenge().
   1069  virtual void OnPlatformChallengeResponse(
   1070      const PlatformChallengeResponse& response) = 0;
   1071 
   1072  // Called by the host after a call to Host::QueryOutputProtectionStatus(). The
   1073  // |link_mask| is a bit mask of OutputLinkTypes and |output_protection_mask|
   1074  // is a bit mask of OutputProtectionMethods. If |result| is kQueryFailed,
   1075  // then |link_mask| and |output_protection_mask| are undefined and should
   1076  // be ignored.
   1077  virtual void OnQueryOutputProtectionStatus(
   1078      QueryResult result,
   1079      uint32_t link_mask,
   1080      uint32_t output_protection_mask) = 0;
   1081 
   1082  // Called by the host after a call to Host::RequestStorageId(). If the
   1083  // version of the storage ID requested is available, |storage_id| and
   1084  // |storage_id_size| are set appropriately. |version| will be the same as
   1085  // what was requested, unless 0 (latest) was requested, in which case
   1086  // |version| will be the actual version number for the |storage_id| returned.
   1087  // If the requested version is not available, null/zero will be provided as
   1088  // |storage_id| and |storage_id_size|, respectively, and |version| should be
   1089  // ignored.
   1090  virtual void OnStorageId(uint32_t version,
   1091                           const uint8_t* storage_id,
   1092                           uint32_t storage_id_size) = 0;
   1093 
   1094  // Destroys the object in the same context as it was created.
   1095  virtual void Destroy() = 0;
   1096 
   1097 protected:
   1098  ContentDecryptionModule_11() {}
   1099  virtual ~ContentDecryptionModule_11() {}
   1100 };
   1101 
   1102 // ----- Note: CDM interface(s) below still in development and not stable! -----
   1103 
   1104 // ContentDecryptionModule interface that all CDMs need to implement.
   1105 // The interface is versioned for backward compatibility.
   1106 // Note: ContentDecryptionModule implementations must use the allocator
   1107 // provided in CreateCdmInstance() to allocate any Buffer that needs to
   1108 // be passed back to the caller. Implementations must call Buffer::Destroy()
   1109 // when a Buffer is created that will never be returned to the caller.
   1110 class CDM_CLASS_API ContentDecryptionModule_12 {
   1111 public:
   1112  static const int kVersion = 12;
   1113  static const bool kIsStable = false;
   1114  typedef Host_12 Host;
   1115 
   1116  // Initializes the CDM instance, providing information about permitted
   1117  // functionalities. The CDM must respond by calling Host::OnInitialized()
   1118  // with whether the initialization succeeded. No other calls will be made by
   1119  // the host before Host::OnInitialized() returns.
   1120  // If |allow_distinctive_identifier| is false, messages from the CDM,
   1121  // such as message events, must not contain a Distinctive Identifier,
   1122  // even in an encrypted form.
   1123  // If |allow_persistent_state| is false, the CDM must not attempt to
   1124  // persist state. Calls to CreateFileIO() will fail.
   1125  // If |use_hw_secure_codecs| is true, the CDM must ensure the decryption key
   1126  // and video buffers (compressed and uncompressed) are securely protected by
   1127  // hardware.
   1128  virtual void Initialize(bool allow_distinctive_identifier,
   1129                          bool allow_persistent_state,
   1130                          bool use_hw_secure_codecs) = 0;
   1131 
   1132  // Gets the key status if the CDM has a hypothetical key with the |policy|.
   1133  // The CDM must respond by calling either Host::OnResolveKeyStatusPromise()
   1134  // with the result key status or Host::OnRejectPromise() if an unexpected
   1135  // error happened or this method is not supported.
   1136  virtual void GetStatusForPolicy(uint32_t promise_id,
   1137                                  const Policy& policy) = 0;
   1138 
   1139  // SetServerCertificate(), CreateSessionAndGenerateRequest(), LoadSession(),
   1140  // UpdateSession(), CloseSession(), and RemoveSession() all accept a
   1141  // |promise_id|, which must be passed to the completion Host method
   1142  // (e.g. Host::OnResolveNewSessionPromise()).
   1143 
   1144  // Provides a server certificate to be used to encrypt messages to the
   1145  // license server. The CDM must respond by calling either
   1146  // Host::OnResolvePromise() or Host::OnRejectPromise().
   1147  // If the CDM does not support server certificates, the promise should be
   1148  // rejected with kExceptionNotSupportedError. If |server_certificate_data|
   1149  // is empty, reject with kExceptionTypeError. Any other error should be
   1150  // rejected with kExceptionInvalidStateError or kExceptionQuotaExceededError.
   1151  // TODO(crbug.com/796417): Add support for the promise to return true or
   1152  // false, rather than using kExceptionNotSupportedError to mean false.
   1153  virtual void SetServerCertificate(uint32_t promise_id,
   1154                                    const uint8_t* server_certificate_data,
   1155                                    uint32_t server_certificate_data_size) = 0;
   1156 
   1157  // Creates a session given |session_type|, |init_data_type|, and |init_data|.
   1158  // The CDM must respond by calling either Host::OnResolveNewSessionPromise()
   1159  // or Host::OnRejectPromise().
   1160  virtual void CreateSessionAndGenerateRequest(uint32_t promise_id,
   1161                                               SessionType session_type,
   1162                                               InitDataType init_data_type,
   1163                                               const uint8_t* init_data,
   1164                                               uint32_t init_data_size) = 0;
   1165 
   1166  // Loads the session of type |session_type| specified by |session_id|.
   1167  // The CDM must respond by calling either Host::OnResolveNewSessionPromise()
   1168  // or Host::OnRejectPromise(). If the session is not found, call
   1169  // Host::OnResolveNewSessionPromise() with session_id = NULL.
   1170  virtual void LoadSession(uint32_t promise_id,
   1171                           SessionType session_type,
   1172                           const char* session_id,
   1173                           uint32_t session_id_size) = 0;
   1174 
   1175  // Updates the session with |response|. The CDM must respond by calling
   1176  // either Host::OnResolvePromise() or Host::OnRejectPromise().
   1177  virtual void UpdateSession(uint32_t promise_id,
   1178                             const char* session_id,
   1179                             uint32_t session_id_size,
   1180                             const uint8_t* response,
   1181                             uint32_t response_size) = 0;
   1182 
   1183  // Requests that the CDM close the session. The CDM must respond by calling
   1184  // either Host::OnResolvePromise() or Host::OnRejectPromise() when the request
   1185  // has been processed. This may be before the session is closed. Once the
   1186  // session is closed, Host::OnSessionClosed() must also be called.
   1187  virtual void CloseSession(uint32_t promise_id,
   1188                            const char* session_id,
   1189                            uint32_t session_id_size) = 0;
   1190 
   1191  // Removes any stored session data associated with this session. Removes all
   1192  // license(s) and key(s) associated with the session, whether they are in
   1193  // memory, persistent store, or both. For persistent session types, other
   1194  // session data (e.g. record of license destruction) will be cleared as
   1195  // defined for each session type once a release message acknowledgment is
   1196  // processed by UpdateSession(). The CDM must respond by calling either
   1197  // Host::OnResolvePromise() or Host::OnRejectPromise() when the request has
   1198  // been processed.
   1199  virtual void RemoveSession(uint32_t promise_id,
   1200                             const char* session_id,
   1201                             uint32_t session_id_size) = 0;
   1202 
   1203  // Performs scheduled operation with |context| when the timer fires.
   1204  virtual void TimerExpired(void* context) = 0;
   1205 
   1206  // Decrypts the |encrypted_buffer|.
   1207  //
   1208  // Returns kSuccess if decryption succeeded, in which case the callee
   1209  // should have filled the |decrypted_buffer| and passed the ownership of
   1210  // |data| in |decrypted_buffer| to the caller.
   1211  // Returns kNoKey if the CDM did not have the necessary decryption key
   1212  // to decrypt.
   1213  // Returns kDecryptError if any other error happened.
   1214  // If the return value is not kSuccess, |decrypted_buffer| should be ignored
   1215  // by the caller.
   1216  virtual Status Decrypt(const InputBuffer_2& encrypted_buffer,
   1217                         DecryptedBlock* decrypted_buffer) = 0;
   1218 
   1219  // Initializes the CDM audio decoder with |audio_decoder_config|. This
   1220  // function must be called before DecryptAndDecodeSamples() is called.
   1221  //
   1222  // Returns kSuccess if the |audio_decoder_config| is supported and the CDM
   1223  // audio decoder is successfully initialized.
   1224  // Returns kInitializationError if |audio_decoder_config| is not supported.
   1225  // The CDM may still be able to do Decrypt().
   1226  // Returns kDeferredInitialization if the CDM is not ready to initialize the
   1227  // decoder at this time. Must call Host::OnDeferredInitializationDone() once
   1228  // initialization is complete.
   1229  virtual Status InitializeAudioDecoder(
   1230      const AudioDecoderConfig_2& audio_decoder_config) = 0;
   1231 
   1232  // Initializes the CDM video decoder with |video_decoder_config|. This
   1233  // function must be called before DecryptAndDecodeFrame() is called.
   1234  //
   1235  // Returns kSuccess if the |video_decoder_config| is supported and the CDM
   1236  // video decoder is successfully initialized.
   1237  // Returns kInitializationError if |video_decoder_config| is not supported.
   1238  // The CDM may still be able to do Decrypt().
   1239  // Returns kDeferredInitialization if the CDM is not ready to initialize the
   1240  // decoder at this time. Must call Host::OnDeferredInitializationDone() once
   1241  // initialization is complete.
   1242  virtual Status InitializeVideoDecoder(
   1243      const VideoDecoderConfig_3& video_decoder_config) = 0;
   1244 
   1245  // De-initializes the CDM decoder and sets it to an uninitialized state. The
   1246  // caller can initialize the decoder again after this call to re-initialize
   1247  // it. This can be used to reconfigure the decoder if the configuration
   1248  // changes.
   1249  virtual void DeinitializeDecoder(StreamType decoder_type) = 0;
   1250 
   1251  // Resets the CDM decoder to an initialized clean state. All internal buffers
   1252  // MUST be flushed.
   1253  virtual void ResetDecoder(StreamType decoder_type) = 0;
   1254 
   1255  // Decrypts the |encrypted_buffer| and decodes the decrypted buffer into a
   1256  // |video_frame|. Upon end-of-stream, the caller should call this function
   1257  // repeatedly with empty |encrypted_buffer| (|data| == NULL) until
   1258  // kNeedMoreData is returned.
   1259  //
   1260  // Returns kSuccess if decryption and decoding both succeeded, in which case
   1261  // the callee will have filled the |video_frame| and passed the ownership of
   1262  // |frame_buffer| in |video_frame| to the caller.
   1263  // Returns kNoKey if the CDM did not have the necessary decryption key
   1264  // to decrypt.
   1265  // Returns kNeedMoreData if more data was needed by the decoder to generate
   1266  // a decoded frame (e.g. during initialization and end-of-stream).
   1267  // Returns kDecryptError if any decryption error happened.
   1268  // Returns kDecodeError if any decoding error happened.
   1269  // If the return value is not kSuccess, |video_frame| should be ignored by
   1270  // the caller.
   1271  virtual Status DecryptAndDecodeFrame(const InputBuffer_2& encrypted_buffer,
   1272                                       VideoFrame_2* video_frame) = 0;
   1273 
   1274  // Decrypts the |encrypted_buffer| and decodes the decrypted buffer into
   1275  // |audio_frames|. Upon end-of-stream, the caller should call this function
   1276  // repeatedly with empty |encrypted_buffer| (|data| == NULL) until only empty
   1277  // |audio_frames| is produced.
   1278  //
   1279  // Returns kSuccess if decryption and decoding both succeeded, in which case
   1280  // the callee will have filled |audio_frames| and passed the ownership of
   1281  // |data| in |audio_frames| to the caller.
   1282  // Returns kNoKey if the CDM did not have the necessary decryption key
   1283  // to decrypt.
   1284  // Returns kNeedMoreData if more data was needed by the decoder to generate
   1285  // audio samples (e.g. during initialization and end-of-stream).
   1286  // Returns kDecryptError if any decryption error happened.
   1287  // Returns kDecodeError if any decoding error happened.
   1288  // If the return value is not kSuccess, |audio_frames| should be ignored by
   1289  // the caller.
   1290  virtual Status DecryptAndDecodeSamples(const InputBuffer_2& encrypted_buffer,
   1291                                         AudioFrames* audio_frames) = 0;
   1292 
   1293  // Called by the host after a platform challenge was initiated via
   1294  // Host::SendPlatformChallenge().
   1295  virtual void OnPlatformChallengeResponse(
   1296      const PlatformChallengeResponse& response) = 0;
   1297 
   1298  // Called by the host after a call to Host::QueryOutputProtectionStatus(). The
   1299  // |link_mask| is a bit mask of OutputLinkTypes and |output_protection_mask|
   1300  // is a bit mask of OutputProtectionMethods. If |result| is kQueryFailed,
   1301  // then |link_mask| and |output_protection_mask| are undefined and should
   1302  // be ignored.
   1303  virtual void OnQueryOutputProtectionStatus(
   1304      QueryResult result,
   1305      uint32_t link_mask,
   1306      uint32_t output_protection_mask) = 0;
   1307 
   1308  // Called by the host after a call to Host::RequestStorageId(). If the
   1309  // version of the storage ID requested is available, |storage_id| and
   1310  // |storage_id_size| are set appropriately. |version| will be the same as
   1311  // what was requested, unless 0 (latest) was requested, in which case
   1312  // |version| will be the actual version number for the |storage_id| returned.
   1313  // If the requested version is not available, null/zero will be provided as
   1314  // |storage_id| and |storage_id_size|, respectively, and |version| should be
   1315  // ignored.
   1316  virtual void OnStorageId(uint32_t version,
   1317                           const uint8_t* storage_id,
   1318                           uint32_t storage_id_size) = 0;
   1319 
   1320  // Destroys the object in the same context as it was created.
   1321  virtual void Destroy() = 0;
   1322 
   1323 protected:
   1324  ContentDecryptionModule_12() {}
   1325  virtual ~ContentDecryptionModule_12() {}
   1326 };
   1327 
   1328 class CDM_CLASS_API Host_10 {
   1329 public:
   1330  static const int kVersion = 10;
   1331 
   1332  // Returns a Buffer* containing non-zero members upon success, or NULL on
   1333  // failure. The caller owns the Buffer* after this call. The buffer is not
   1334  // guaranteed to be zero initialized. The capacity of the allocated Buffer
   1335  // is guaranteed to be not less than |capacity|.
   1336  virtual Buffer* Allocate(uint32_t capacity) = 0;
   1337 
   1338  // Requests the host to call ContentDecryptionModule::TimerFired() |delay_ms|
   1339  // from now with |context|.
   1340  virtual void SetTimer(int64_t delay_ms, void* context) = 0;
   1341 
   1342  // Returns the current wall time.
   1343  virtual Time GetCurrentWallTime() = 0;
   1344 
   1345  // Called by the CDM with the result after the CDM instance was initialized.
   1346  virtual void OnInitialized(bool success) = 0;
   1347 
   1348  // Called by the CDM when a key status is available in response to
   1349  // GetStatusForPolicy().
   1350  virtual void OnResolveKeyStatusPromise(uint32_t promise_id,
   1351                                         KeyStatus key_status) = 0;
   1352 
   1353  // Called by the CDM when a session is created or loaded and the value for the
   1354  // MediaKeySession's sessionId attribute is available (|session_id|).
   1355  // This must be called before OnSessionMessage() or
   1356  // OnSessionKeysChange() is called for the same session. |session_id_size|
   1357  // should not include null termination.
   1358  // When called in response to LoadSession(), the |session_id| must be the
   1359  // same as the |session_id| passed in LoadSession(), or NULL if the
   1360  // session could not be loaded.
   1361  virtual void OnResolveNewSessionPromise(uint32_t promise_id,
   1362                                          const char* session_id,
   1363                                          uint32_t session_id_size) = 0;
   1364 
   1365  // Called by the CDM when a session is updated or released.
   1366  virtual void OnResolvePromise(uint32_t promise_id) = 0;
   1367 
   1368  // Called by the CDM when an error occurs as a result of one of the
   1369  // ContentDecryptionModule calls that accept a |promise_id|.
   1370  // |exception| must be specified. |error_message| and |system_code|
   1371  // are optional. |error_message_size| should not include null termination.
   1372  virtual void OnRejectPromise(uint32_t promise_id,
   1373                               Exception exception,
   1374                               uint32_t system_code,
   1375                               const char* error_message,
   1376                               uint32_t error_message_size) = 0;
   1377 
   1378  // Called by the CDM when it has a message for session |session_id|.
   1379  // Size parameters should not include null termination.
   1380  virtual void OnSessionMessage(const char* session_id,
   1381                                uint32_t session_id_size,
   1382                                MessageType message_type,
   1383                                const char* message,
   1384                                uint32_t message_size) = 0;
   1385 
   1386  // Called by the CDM when there has been a change in keys or their status for
   1387  // session |session_id|. |has_additional_usable_key| should be set if a
   1388  // key is newly usable (e.g. new key available, previously expired key has
   1389  // been renewed, etc.) and the browser should attempt to resume playback.
   1390  // |keys_info| is the list of key IDs for this session along with their
   1391  // current status. |keys_info_count| is the number of entries in |keys_info|.
   1392  // Size parameter for |session_id| should not include null termination.
   1393  virtual void OnSessionKeysChange(const char* session_id,
   1394                                   uint32_t session_id_size,
   1395                                   bool has_additional_usable_key,
   1396                                   const KeyInformation* keys_info,
   1397                                   uint32_t keys_info_count) = 0;
   1398 
   1399  // Called by the CDM when there has been a change in the expiration time for
   1400  // session |session_id|. This can happen as the result of an Update() call
   1401  // or some other event. If this happens as a result of a call to Update(),
   1402  // it must be called before resolving the Update() promise. |new_expiry_time|
   1403  // represents the time after which the key(s) in the session will no longer
   1404  // be usable for decryption. It can be 0 if no such time exists or if the
   1405  // license explicitly never expires. Size parameter should not include null
   1406  // termination.
   1407  virtual void OnExpirationChange(const char* session_id,
   1408                                  uint32_t session_id_size,
   1409                                  Time new_expiry_time) = 0;
   1410 
   1411  // Called by the CDM when session |session_id| is closed. Size
   1412  // parameter should not include null termination.
   1413  virtual void OnSessionClosed(const char* session_id,
   1414                               uint32_t session_id_size) = 0;
   1415 
   1416  // The following are optional methods that may not be implemented on all
   1417  // platforms.
   1418 
   1419  // Sends a platform challenge for the given |service_id|. |challenge| is at
   1420  // most 256 bits of data to be signed. Once the challenge has been completed,
   1421  // the host will call ContentDecryptionModule::OnPlatformChallengeResponse()
   1422  // with the signed challenge response and platform certificate. Size
   1423  // parameters should not include null termination.
   1424  virtual void SendPlatformChallenge(const char* service_id,
   1425                                     uint32_t service_id_size,
   1426                                     const char* challenge,
   1427                                     uint32_t challenge_size) = 0;
   1428 
   1429  // Attempts to enable output protection (e.g. HDCP) on the display link. The
   1430  // |desired_protection_mask| is a bit mask of OutputProtectionMethods. No
   1431  // status callback is issued, the CDM must call QueryOutputProtectionStatus()
   1432  // periodically to ensure the desired protections are applied.
   1433  virtual void EnableOutputProtection(uint32_t desired_protection_mask) = 0;
   1434 
   1435  // Requests the current output protection status. Once the host has the status
   1436  // it will call ContentDecryptionModule::OnQueryOutputProtectionStatus().
   1437  virtual void QueryOutputProtectionStatus() = 0;
   1438 
   1439  // Must be called by the CDM if it returned kDeferredInitialization during
   1440  // InitializeAudioDecoder() or InitializeVideoDecoder().
   1441  virtual void OnDeferredInitializationDone(StreamType stream_type,
   1442                                            Status decoder_status) = 0;
   1443 
   1444  // Creates a FileIO object from the host to do file IO operation. Returns NULL
   1445  // if a FileIO object cannot be obtained. Once a valid FileIO object is
   1446  // returned, |client| must be valid until FileIO::Close() is called. The
   1447  // CDM can call this method multiple times to operate on different files.
   1448  virtual FileIO* CreateFileIO(FileIOClient* client) = 0;
   1449 
   1450  // Requests a specific version of the storage ID. A storage ID is a stable,
   1451  // device specific ID used by the CDM to securely store persistent data. The
   1452  // ID will be returned by the host via ContentDecryptionModule::OnStorageId().
   1453  // If |version| is 0, the latest version will be returned. All |version|s
   1454  // that are greater than or equal to 0x80000000 are reserved for the CDM and
   1455  // should not be supported or returned by the host. The CDM must not expose
   1456  // the ID outside the client device, even in encrypted form.
   1457  virtual void RequestStorageId(uint32_t version) = 0;
   1458 
   1459 protected:
   1460  Host_10() {}
   1461  virtual ~Host_10() {}
   1462 };
   1463 
   1464 class CDM_CLASS_API Host_11 {
   1465 public:
   1466  static const int kVersion = 11;
   1467 
   1468  // Returns a Buffer* containing non-zero members upon success, or NULL on
   1469  // failure. The caller owns the Buffer* after this call. The buffer is not
   1470  // guaranteed to be zero initialized. The capacity of the allocated Buffer
   1471  // is guaranteed to be not less than |capacity|.
   1472  virtual Buffer* Allocate(uint32_t capacity) = 0;
   1473 
   1474  // Requests the host to call ContentDecryptionModule::TimerFired() |delay_ms|
   1475  // from now with |context|.
   1476  virtual void SetTimer(int64_t delay_ms, void* context) = 0;
   1477 
   1478  // Returns the current wall time.
   1479  virtual Time GetCurrentWallTime() = 0;
   1480 
   1481  // Called by the CDM with the result after the CDM instance was initialized.
   1482  virtual void OnInitialized(bool success) = 0;
   1483 
   1484  // Called by the CDM when a key status is available in response to
   1485  // GetStatusForPolicy().
   1486  virtual void OnResolveKeyStatusPromise(uint32_t promise_id,
   1487                                         KeyStatus key_status) = 0;
   1488 
   1489  // Called by the CDM when a session is created or loaded and the value for the
   1490  // MediaKeySession's sessionId attribute is available (|session_id|).
   1491  // This must be called before OnSessionMessage() or
   1492  // OnSessionKeysChange() is called for the same session. |session_id_size|
   1493  // should not include null termination.
   1494  // When called in response to LoadSession(), the |session_id| must be the
   1495  // same as the |session_id| passed in LoadSession(), or NULL if the
   1496  // session could not be loaded.
   1497  virtual void OnResolveNewSessionPromise(uint32_t promise_id,
   1498                                          const char* session_id,
   1499                                          uint32_t session_id_size) = 0;
   1500 
   1501  // Called by the CDM when a session is updated or released.
   1502  virtual void OnResolvePromise(uint32_t promise_id) = 0;
   1503 
   1504  // Called by the CDM when an error occurs as a result of one of the
   1505  // ContentDecryptionModule calls that accept a |promise_id|.
   1506  // |exception| must be specified. |error_message| and |system_code|
   1507  // are optional. |error_message_size| should not include null termination.
   1508  virtual void OnRejectPromise(uint32_t promise_id,
   1509                               Exception exception,
   1510                               uint32_t system_code,
   1511                               const char* error_message,
   1512                               uint32_t error_message_size) = 0;
   1513 
   1514  // Called by the CDM when it has a message for session |session_id|.
   1515  // Size parameters should not include null termination.
   1516  virtual void OnSessionMessage(const char* session_id,
   1517                                uint32_t session_id_size,
   1518                                MessageType message_type,
   1519                                const char* message,
   1520                                uint32_t message_size) = 0;
   1521 
   1522  // Called by the CDM when there has been a change in keys or their status for
   1523  // session |session_id|. |has_additional_usable_key| should be set if a
   1524  // key is newly usable (e.g. new key available, previously expired key has
   1525  // been renewed, etc.) and the browser should attempt to resume playback.
   1526  // |keys_info| is the list of key IDs for this session along with their
   1527  // current status. |keys_info_count| is the number of entries in |keys_info|.
   1528  // Size parameter for |session_id| should not include null termination.
   1529  virtual void OnSessionKeysChange(const char* session_id,
   1530                                   uint32_t session_id_size,
   1531                                   bool has_additional_usable_key,
   1532                                   const KeyInformation* keys_info,
   1533                                   uint32_t keys_info_count) = 0;
   1534 
   1535  // Called by the CDM when there has been a change in the expiration time for
   1536  // session |session_id|. This can happen as the result of an Update() call
   1537  // or some other event. If this happens as a result of a call to Update(),
   1538  // it must be called before resolving the Update() promise. |new_expiry_time|
   1539  // represents the time after which the key(s) in the session will no longer
   1540  // be usable for decryption. It can be 0 if no such time exists or if the
   1541  // license explicitly never expires. Size parameter should not include null
   1542  // termination.
   1543  virtual void OnExpirationChange(const char* session_id,
   1544                                  uint32_t session_id_size,
   1545                                  Time new_expiry_time) = 0;
   1546 
   1547  // Called by the CDM when session |session_id| is closed. Size
   1548  // parameter should not include null termination.
   1549  virtual void OnSessionClosed(const char* session_id,
   1550                               uint32_t session_id_size) = 0;
   1551 
   1552  // The following are optional methods that may not be implemented on all
   1553  // platforms.
   1554 
   1555  // Sends a platform challenge for the given |service_id|. |challenge| is at
   1556  // most 256 bits of data to be signed. Once the challenge has been completed,
   1557  // the host will call ContentDecryptionModule::OnPlatformChallengeResponse()
   1558  // with the signed challenge response and platform certificate. Size
   1559  // parameters should not include null termination.
   1560  virtual void SendPlatformChallenge(const char* service_id,
   1561                                     uint32_t service_id_size,
   1562                                     const char* challenge,
   1563                                     uint32_t challenge_size) = 0;
   1564 
   1565  // Attempts to enable output protection (e.g. HDCP) on the display link. The
   1566  // |desired_protection_mask| is a bit mask of OutputProtectionMethods. No
   1567  // status callback is issued, the CDM must call QueryOutputProtectionStatus()
   1568  // periodically to ensure the desired protections are applied.
   1569  virtual void EnableOutputProtection(uint32_t desired_protection_mask) = 0;
   1570 
   1571  // Requests the current output protection status. Once the host has the status
   1572  // it will call ContentDecryptionModule::OnQueryOutputProtectionStatus().
   1573  virtual void QueryOutputProtectionStatus() = 0;
   1574 
   1575  // Must be called by the CDM if it returned kDeferredInitialization during
   1576  // InitializeAudioDecoder() or InitializeVideoDecoder().
   1577  virtual void OnDeferredInitializationDone(StreamType stream_type,
   1578                                            Status decoder_status) = 0;
   1579 
   1580  // Creates a FileIO object from the host to do file IO operation. Returns NULL
   1581  // if a FileIO object cannot be obtained. Once a valid FileIO object is
   1582  // returned, |client| must be valid until FileIO::Close() is called. The
   1583  // CDM can call this method multiple times to operate on different files.
   1584  virtual FileIO* CreateFileIO(FileIOClient* client) = 0;
   1585 
   1586  // Requests a specific version of the storage ID. A storage ID is a stable,
   1587  // device specific ID used by the CDM to securely store persistent data. The
   1588  // ID will be returned by the host via ContentDecryptionModule::OnStorageId().
   1589  // If |version| is 0, the latest version will be returned. All |version|s
   1590  // that are greater than or equal to 0x80000000 are reserved for the CDM and
   1591  // should not be supported or returned by the host. The CDM must not expose
   1592  // the ID outside the client device, even in encrypted form.
   1593  virtual void RequestStorageId(uint32_t version) = 0;
   1594 
   1595  // Reports the metric |metric_name| with value |value| to the host. Can be
   1596  // called by the CDM at any time. May report the same metric multiple times
   1597  // during the lifetime of the CDM.
   1598  virtual void ReportMetrics(MetricName metric_name, uint64_t value) = 0;
   1599 
   1600 protected:
   1601  Host_11() {}
   1602  virtual ~Host_11() {}
   1603 };
   1604 
   1605 class CDM_CLASS_API Host_12 {
   1606 public:
   1607  static const int kVersion = 12;
   1608 
   1609  // Returns a Buffer* containing non-zero members upon success, or NULL on
   1610  // failure. The caller owns the Buffer* after this call. The buffer is not
   1611  // guaranteed to be zero initialized. The capacity of the allocated Buffer
   1612  // is guaranteed to be not less than |capacity|.
   1613  virtual Buffer* Allocate(uint32_t capacity) = 0;
   1614 
   1615  // Requests the host to call ContentDecryptionModule::TimerFired() |delay_ms|
   1616  // from now with |context|.
   1617  virtual void SetTimer(int64_t delay_ms, void* context) = 0;
   1618 
   1619  // Returns the current wall time.
   1620  virtual Time GetCurrentWallTime() = 0;
   1621 
   1622  // Called by the CDM with the result after the CDM instance was initialized.
   1623  virtual void OnInitialized(bool success) = 0;
   1624 
   1625  // Called by the CDM when a key status is available in response to
   1626  // GetStatusForPolicy().
   1627  virtual void OnResolveKeyStatusPromise(uint32_t promise_id,
   1628                                         KeyStatus key_status) = 0;
   1629 
   1630  // Called by the CDM when a session is created or loaded and the value for the
   1631  // MediaKeySession's sessionId attribute is available (|session_id|).
   1632  // This must be called before OnSessionMessage() or
   1633  // OnSessionKeysChange() is called for the same session. |session_id_size|
   1634  // should not include null termination.
   1635  // When called in response to LoadSession(), the |session_id| must be the
   1636  // same as the |session_id| passed in LoadSession(), or NULL if the
   1637  // session could not be loaded.
   1638  virtual void OnResolveNewSessionPromise(uint32_t promise_id,
   1639                                          const char* session_id,
   1640                                          uint32_t session_id_size) = 0;
   1641 
   1642  // Called by the CDM when a session is updated or released.
   1643  virtual void OnResolvePromise(uint32_t promise_id) = 0;
   1644 
   1645  // Called by the CDM when an error occurs as a result of one of the
   1646  // ContentDecryptionModule calls that accept a |promise_id|.
   1647  // |exception| must be specified. |error_message| and |system_code|
   1648  // are optional. |error_message_size| should not include null termination.
   1649  virtual void OnRejectPromise(uint32_t promise_id,
   1650                               Exception exception,
   1651                               uint32_t system_code,
   1652                               const char* error_message,
   1653                               uint32_t error_message_size) = 0;
   1654 
   1655  // Called by the CDM when it has a message for session |session_id|.
   1656  // Size parameters should not include null termination.
   1657  virtual void OnSessionMessage(const char* session_id,
   1658                                uint32_t session_id_size,
   1659                                MessageType message_type,
   1660                                const char* message,
   1661                                uint32_t message_size) = 0;
   1662 
   1663  // Called by the CDM when there has been a change in keys or their status for
   1664  // session |session_id|. |has_additional_usable_key| should be set if a
   1665  // key is newly usable (e.g. new key available, previously expired key has
   1666  // been renewed, etc.) and the browser should attempt to resume playback.
   1667  // |keys_info| is the list of key IDs for this session along with their
   1668  // current status. |keys_info_count| is the number of entries in |keys_info|.
   1669  // Size parameter for |session_id| should not include null termination.
   1670  virtual void OnSessionKeysChange(const char* session_id,
   1671                                   uint32_t session_id_size,
   1672                                   bool has_additional_usable_key,
   1673                                   const KeyInformation* keys_info,
   1674                                   uint32_t keys_info_count) = 0;
   1675 
   1676  // Called by the CDM when there has been a change in the expiration time for
   1677  // session |session_id|. This can happen as the result of an Update() call
   1678  // or some other event. If this happens as a result of a call to Update(),
   1679  // it must be called before resolving the Update() promise. |new_expiry_time|
   1680  // represents the time after which the key(s) in the session will no longer
   1681  // be usable for decryption. It can be 0 if no such time exists or if the
   1682  // license explicitly never expires. Size parameter should not include null
   1683  // termination.
   1684  virtual void OnExpirationChange(const char* session_id,
   1685                                  uint32_t session_id_size,
   1686                                  Time new_expiry_time) = 0;
   1687 
   1688  // Called by the CDM when session |session_id| is closed. Size
   1689  // parameter should not include null termination.
   1690  virtual void OnSessionClosed(const char* session_id,
   1691                               uint32_t session_id_size) = 0;
   1692 
   1693  // The following are optional methods that may not be implemented on all
   1694  // platforms.
   1695 
   1696  // Sends a platform challenge for the given |service_id|. |challenge| is at
   1697  // most 256 bits of data to be signed. Once the challenge has been completed,
   1698  // the host will call ContentDecryptionModule::OnPlatformChallengeResponse()
   1699  // with the signed challenge response and platform certificate. Size
   1700  // parameters should not include null termination.
   1701  virtual void SendPlatformChallenge(const char* service_id,
   1702                                     uint32_t service_id_size,
   1703                                     const char* challenge,
   1704                                     uint32_t challenge_size) = 0;
   1705 
   1706  // Attempts to enable output protection (e.g. HDCP) on the display link. The
   1707  // |desired_protection_mask| is a bit mask of OutputProtectionMethods. No
   1708  // status callback is issued, the CDM must call QueryOutputProtectionStatus()
   1709  // periodically to ensure the desired protections are applied.
   1710  virtual void EnableOutputProtection(uint32_t desired_protection_mask) = 0;
   1711 
   1712  // Requests the current output protection status. Once the host has the status
   1713  // it will call ContentDecryptionModule::OnQueryOutputProtectionStatus().
   1714  virtual void QueryOutputProtectionStatus() = 0;
   1715 
   1716  // Must be called by the CDM if it returned kDeferredInitialization during
   1717  // InitializeAudioDecoder() or InitializeVideoDecoder().
   1718  virtual void OnDeferredInitializationDone(StreamType stream_type,
   1719                                            Status decoder_status) = 0;
   1720 
   1721  // Creates a FileIO object from the host to do file IO operation. Returns NULL
   1722  // if a FileIO object cannot be obtained. Once a valid FileIO object is
   1723  // returned, |client| must be valid until FileIO::Close() is called. The
   1724  // CDM can call this method multiple times to operate on different files.
   1725  virtual FileIO* CreateFileIO(FileIOClient* client) = 0;
   1726 
   1727  // Requests a specific version of the storage ID. A storage ID is a stable,
   1728  // device specific ID used by the CDM to securely store persistent data. The
   1729  // ID will be returned by the host via ContentDecryptionModule::OnStorageId().
   1730  // If |version| is 0, the latest version will be returned. All |version|s
   1731  // that are greater than or equal to 0x80000000 are reserved for the CDM and
   1732  // should not be supported or returned by the host. The CDM must not expose
   1733  // the ID outside the client device, even in encrypted form.
   1734  virtual void RequestStorageId(uint32_t version) = 0;
   1735 
   1736  // Reports the metric |metric_name| with value |value| to the host. Can be
   1737  // called by the CDM at any time. May report the same metric multiple times
   1738  // during the lifetime of the CDM.
   1739  virtual void ReportMetrics(MetricName metric_name, uint64_t value) = 0;
   1740 
   1741 protected:
   1742  Host_12() {}
   1743  virtual ~Host_12() {}
   1744 };
   1745 
   1746 }  // namespace cdm
   1747 
   1748 #endif  // CDM_CONTENT_DECRYPTION_MODULE_H_