1# DRM Media Key System Management (ArkTS)
2
3Using the **MediaKeySystem** class of the DRM module, you can manage **MediaKeySystem** instances, generate media key system requests to obtain DRM certificates, process responses to these requests, manage media key sessions, manage offline media keys, and obtain DRM statistics and device configuration information.
4
5Before using DRM Kit, check whether the device supports the DRM capabilities of a specific DRM scheme.
6
7In DRM Kit, the DRM scheme exists as a plug-in.
8
9## How to Develop
10
11Read [DRM](../../reference/apis-drm-kit/js-apis-drm.md) for the API reference.
12
131. Import the module.
14
15    ```ts
16    import { drm } from '@kit.DrmKit';
17    ```
18
192. Import the **BusinessError** module, which provides the error codes thrown by the APIs of the DRM module.
20
21    ```ts
22    import { BusinessError } from '@kit.BasicServicesKit';
23    ```
24
253. Check whether the device supports the specified DRM scheme.
26
27   > **NOTE**
28   >
29   > The value **false** means that the device does not support the specified DRM scheme.
30
31   ```ts
32   let isSupported: boolean = drm.isMediaKeySystemSupported("com.clearplay.drm", "video/avc", drm.ContentProtectionLevel.CONTENT_PROTECTION_LEVEL_SW_CRYPTO);
33   ```
34
354. (Optional) Obtain the name and ID list of the DRM schemes on the device.
36
37   > **NOTE**
38   >
39   > If the returned array is empty, no DRM scheme is supported by the device.
40
41   ```ts
42   let description: drm.MediaKeySystemDescription[] = drm.getMediaKeySystems();
43   ```
44
455. Create a **MediaKeySystem** instance.
46
47   > **NOTE**
48   >
49   > If the creation fails, **undefined** is returned, indicating that the device does not support the DRM capability.
50
51   ```ts
52   let mediaKeySystem: drm.MediaKeySystem = drm.createMediaKeySystem("com.clearplay.drm");
53   ```
54
556. (Optional) Obtain the UUID corresponding to the specified DRM scheme name.
56
57   > **NOTE**
58   >
59   > If the length of the returned UUID is 0, no DRM scheme is supported by the device.
60
61   ```ts
62   let uuid: string = drm.getMediaKeySystemUuid("com.clearplay.drm");
63   ```
64
657. (Optional) Set and obtain the configuration items supported by the DRM scheme.
66
67    ```ts
68    // If the DRM scheme supports configuration item setting, set the value of a configuration item of the string type supported by the DRM scheme.
69    mediaKeySystem.setConfigurationString("configName", "configValue");
70    // Obtain the value of a configuration item in the form of a string.
71    let configValueString : string = mediaKeySystem.getConfigurationString("version");
72    let configValueUint8ArrayA: Uint8Array = new Uint8Array([0x00, 0x00, 0x00, 0x00]);
73    // If the DRM scheme supports configuration item setting, set the value of a configuration item of the array type supported by the DRM scheme.
74    mediaKeySystem.setConfigurationByteArray("Uint8ArrayConfigName", configValueUint8ArrayA);
75    // Obtain the value of a configuration item in the form of an array.
76    let configValueUint8ArrayB: Uint8Array = mediaKeySystem.getConfigurationByteArray("Uint8ArrayConfigName");
77    ```
78
798. (Optional) Obtain the maximum content protection level supported by the device.
80
81    ```ts
82    let contentProtectionLevel: drm.ContentProtectionLevel = drm.ContentProtectionLevel.CONTENT_PROTECTION_LEVEL_UNKNOWN;
83    try {
84      contentProtectionLevel = mediaKeySystem.getMaxContentProtectionLevel();
85    } catch (err) {
86      let error = err as BusinessError;
87      console.error(`getMaxContentProtectionLevel ERROR: ${error}`);
88    }
89    ```
90
919. Start listening.
92
93    Listen for the event indicating that the application requests a DRM certificate.
94
95    Register the event **'keySystemRequired'**. This event can be listened for when a **MediaKeySystem** instance is created and is triggered when the application requests a DRM certificate.
96
97    ```ts
98    mediaKeySystem.on('keySystemRequired', (eventInfo: drm.EventInfo) => {
99      console.log('keySystemRequired' + 'extra:' + eventInfo.extraInfo + ' data:' + eventInfo.info);
100    });
101    ```
102
10310. (Optional) Obtain the status of the DRM certificate.
104
105    ```ts
106    let certificateStatus: drm.CertificateStatus = mediaKeySystem.getCertificateStatus();
107    ```
108
10911. Generate a provision request.
110
111    During the creation of a **MediaKeySession** session, if no DRM certificate is available, the **keySystemRequired** event is triggered. In this case, the DRM certificate status on the device is obtained first. If the device does not have a DRM certificate or the DRM certificate status is abnormal (not **drm.CertificateStatus.CERT_STATUS_PROVISIONED**), a provision request is generated to obtain a DRM certificate.
112
113       ```ts
114         if(certificateStatus != drm.CertificateStatus.CERT_STATUS_PROVISIONED){
115           mediaKeySystem.generateKeySystemRequest().then(async (drmRequest: drm.ProvisionRequest) => {
116             console.info("generateKeySystemRequest success", drmRequest.data, drmRequest.defaultURL);
117           }).catch((err:BusinessError) =>{
118               console.info("generateKeySystemRequest err end", err.code);
119            });
120         } else {
121           console.info("The certificate already exists.");
122         }
123       ```
124
12512. Process the provision response.
126
127    A response to the provision request is received. You need to process this response.
128
129       ```ts
130         // Send drmRequest.data returned by the provision request to the DRM certificate service through a network request to obtain a provision response and process the response.
131         let provisionResponseByte = new Uint8Array([0x00, 0x00, 0x00, 0x00]);
132         mediaKeySystem.processKeySystemResponse(provisionResponseByte).then(() => {
133           console.info("processKeySystemResponse success");
134         }).catch((err:BusinessError) =>{
135           console.info("processKeySystemResponse err end", err.code);
136         });
137       ```
138
13913. Create a **MediaKeySession** instance.
140
141    Create a **MediaKeySession** instance with the specified content protection level or a **MediaKeySession** instance with the default content protection level of the DRM scheme.
142     ```ts
143     let mediaKeySession: drm.MediaKeySession = mediaKeySystem.createMediaKeySession();
144     ```
145
14614. (Optional) Obtain the list of offline media key IDs, which are used to manage offline media keys.
147
148     ```ts
149     let offlineMediaKeyIds: Uint8Array[] = mediaKeySystem.getOfflineMediaKeyIds();
150     ```
151
15215. (Optional) Obtain the status of offline media keys.
153
154     ```ts
155     try {
156       let offlineMediaKeyStatus: drm.OfflineMediaKeyStatus = mediaKeySystem.getOfflineMediaKeyStatus(offlineMediaKeyIds[0]);
157     } catch (err) {
158       let error = err as BusinessError;
159       console.error(`getOfflineMediaKeyStatus ERROR: ${error}`);
160     }
161     ```
162
16316. (Optional) Clear offline media keys.
164
165     ```ts
166     try {
167       mediaKeySystem.clearOfflineMediaKeys(offlineMediaKeyIds[0]);
168     } catch (err) {
169       let error = err as BusinessError;
170       console.error(`clearOfflineMediaKeys ERROR: ${error}`);
171     }
172     ```
173
17417. (Optional) Obtain DRM statistical information, including the number of current sessions, decryption times, and decryption failures, as well as the plug-in version.
175
176     ```ts
177     let statisticKeyValue: drm.StatisticKeyValue[] = mediaKeySystem.getStatistics();
178     ```
179
18018. Destroy the **MediaKeySession** instance.
181
182    Destroy the **MediaKeySession** instance when the encrypted content is decrypted and the instance is no longer needed.
183
184     ```ts
185     // Release resources when the MediaKeySession instance is no longer needed.
186     mediaKeySession.destroy();
187     ```
188
18919. Destroy this **MediaKeySystem** instance.
190
191    Destroy the **MediaKeySystem** instance when it is no longer used.
192
193     ```ts
194     // Release resources when the MediaKeySystem instance is no longer needed.
195     mediaKeySystem.destroy();
196     ```