@bitmovin/player-web-integration-cmcd 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md ADDED
@@ -0,0 +1,31 @@
1
+ # Changelog
2
+
3
+ All notable changes to this project will be documented in this file.
4
+
5
+ The format is based on [Keep a Changelog](http://keepachangelog.com/)
6
+ and this project adheres to [Semantic Versioning](http://semver.org/).
7
+
8
+ ## [Unreleased]
9
+
10
+ ## [0.3.0] - 2025-03-26
11
+ ### Added
12
+ - Description in package.json for the project
13
+
14
+ ## [0.2.1] - 2024-12-10
15
+ ### Fixed
16
+ - DASH loading failure when SegmentTimeline with $number format is used (#6)
17
+ - Duplicate CMCD query parameters for Live manifest (#5)
18
+ - Add `main` property to pacakge.json to enable usage in Jest tests
19
+
20
+ ## [0.2.0] - 2023-10-13
21
+ ### Added
22
+ - Support for adding Custom Keys statically in the configuraiton
23
+
24
+ ## 0.1.0 - 2023-05-05
25
+ ### Added
26
+ - Initial CMCD release (Beta)
27
+
28
+ [Unreleased]: https://github.com/bitmovin/bitmovin-player-web-integration-cmcd/compare/v0.3.0...HEAD
29
+ [0.3.0]: https://github.com/bitmovin/bitmovin-player-web-integration-cmcd/compare/v0.2.1...v0.3.0
30
+ [0.2.1]: https://github.com/bitmovin/bitmovin-player-web-integration-cmcd/compare/v0.2.0...v0.2.1
31
+ [0.2.0]: https://github.com/bitmovin/bitmovin-player-web-integration-cmcd/compare/v0.1.0...v0.2.0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2018 Bitmovin, Inc.
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,75 @@
1
+ # Bitmovin Player CMCD Integration
2
+
3
+ This project adds support for the Common Media Client Data (CMCD) plugin. Please find more information about the Consumer Technology Association (CTA) Specification in https://cdn.cta.tech/cta/media/media/resources/standards/pdfs/cta-5004-final.pdf
4
+
5
+ ## Install
6
+ Install with npm from this repository:
7
+ ```
8
+ npm install --save git+https://github.com/bitmovin/bitmovin-player-web-integration-cmcd.git
9
+ ```
10
+
11
+ ## Usage
12
+
13
+ Create an instance of the `CmcdIntegration` with a `CmcdConfig` and set the different callbacks in the `PlayerConfig` as follows:
14
+
15
+ ```ts
16
+ const playerConfig: PlayerConfig = {
17
+ // all configurations you would typically set
18
+ };
19
+
20
+ const cmcdConfig: CmcdConfig = {
21
+ useQueryArgs: true,
22
+ sessionId: '6e2fb550-c457-11e9-bb97-0800200c9a66',
23
+ contentId: '1111-111111-111111-11111',
24
+ };
25
+
26
+ const cmcdIntegration = new CmcdIntegration(cmcdConfig);
27
+
28
+ playerConfig.network = {
29
+ preprocessHttpRequest: cmcdIntegration.preprocessHttpRequest,
30
+ preprocessHttpResponse: cmcdIntegration.preprocessHttpResponse,
31
+ };
32
+ playerConfig.adaptation = {
33
+ desktop: {
34
+ onVideoAdaptation: cmcdIntegration.onVideoAdaptation,
35
+ onAudioAdaptation: cmcdIntegration.onAudioAdaptation,
36
+ },
37
+ mobile: {
38
+ onVideoAdaptation: cmcdIntegration.onVideoAdaptation,
39
+ onAudioAdaptation: cmcdIntegration.onAudioAdaptation,
40
+ },
41
+ };
42
+ ```
43
+ After that, you create a Bitmovin Player instance as usual, then pass the player instance to the CMCD integration:
44
+ ```js
45
+ cmcdIntegration.setPlayer(player);
46
+ ```
47
+
48
+ It is recommend to set the CMCD Session ID to the Analytics Impression ID as this enabled you to connect CDN logs with CMCD data to Analytics sessions:
49
+ ```js
50
+ cmcdIntegration.setSessionId(player.analytics.getCurrentImpressionId());
51
+ ```
52
+
53
+ Load the source into the player after these steps:
54
+ ```js
55
+ player.load(source);
56
+ ```
57
+
58
+ ## Setup for Development
59
+ 1. Run `npm install` to install dependencies
60
+ 2. Use the npm script defined in the package.json like
61
+ - Run `npm start` to start the dev server with a watch task and auto-reloading
62
+ - Run `npm run debug` to create a dev build bundle (non-minified, with source maps)
63
+ - Run `npm run build` to create a production bundle (minified)
64
+ - Run `npm run format` to format all files in the `src/` and `test/` folders
65
+
66
+ ### Preparing a release
67
+ 1. Bump version in `package.json` and `package-lock.json`
68
+ 2. Use `npx kacl release` to automatically create the release in the `CHANGELOG.md` file out of the `Unreleased` section
69
+ 3. Run `npm run build`
70
+ 4. Commit all the above changes, including the `dist/` folder
71
+ 5. Tag the commit of the release (which contains the changes of the `dist/` folder), e.g. with `1.0.0`
72
+
73
+
74
+ ## Principles
75
+ - The Bitmovin Player shall not be packaged into the JS file created by the build of this integration. To achieve this, types can be imported and used, but no code must be imported/used (including string enums!)
@@ -0,0 +1,90 @@
1
+ <!DOCTYPE html>
2
+ <html lang="en">
3
+ <head>
4
+ <title>Bitmovin Player Integration Demo</title>
5
+ <meta charset="UTF-8"/>
6
+ <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
7
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
8
+ <link href="https://cdn.bitmovin.com/player/web/8/bitmovinplayer-ui.css" rel="stylesheet">
9
+
10
+ <style>
11
+ .container {
12
+ text-align: center;
13
+ }
14
+ .container h1 {
15
+ margin-bottom: 22px;
16
+ line-height: 66px;
17
+ }
18
+ .container h2 {
19
+ font-weight: normal;
20
+ margin-bottom: 36px;
21
+ line-height: 26px;
22
+ }
23
+ .player-wrapper {
24
+ width: 95%;
25
+ margin: 20px auto;
26
+ box-shadow: 0 0 30px rgba(0,0,0,0.7);
27
+ }
28
+ </style>
29
+ </head>
30
+ <body>
31
+ <div class="container">
32
+ <h1>TEST</h1>
33
+ <div class="content">
34
+ <div class="player-wrapper">
35
+ <div id="playerContainer"></div>
36
+ </div>
37
+ </div>
38
+ </div>
39
+
40
+ <script type="text/javascript" src="//cdn.bitmovin.com/player/web/8/bitmovinplayer.js"></script>
41
+ <script type="text/javascript" src="./js/bitmovin-player-integration-cmcd.js"></script>
42
+ <script type="text/javascript">
43
+ const playerConfig = {
44
+ key: '7e9c8483-ea84-423e-b675-19cf31dec43a',
45
+ };
46
+
47
+ const cmcdConfig = {
48
+ useQueryArgs: true,
49
+ sessionId: '6e2fb550-c457-11e9-bb97-0800200c9a66',
50
+ contentId: '1111-111111-111111-11111',
51
+ };
52
+
53
+ const cmcdIntegration = new window.bitmovin.player.integration.Cmcd.CmcdIntegration(cmcdConfig);
54
+
55
+ playerConfig.network = {
56
+ preprocessHttpRequest: cmcdIntegration.preprocessHttpRequest,
57
+ preprocessHttpResponse: cmcdIntegration.preprocessHttpResponse,
58
+ };
59
+ playerConfig.adaptation = {
60
+ desktop: {
61
+ onVideoAdaptation: cmcdIntegration.onVideoAdaptation,
62
+ onAudioAdaptation: cmcdIntegration.onAudioAdaptation,
63
+ },
64
+ mobile: {
65
+ onVideoAdaptation: cmcdIntegration.onVideoAdaptation,
66
+ onAudioAdaptation: cmcdIntegration.onAudioAdaptation,
67
+ },
68
+ };
69
+
70
+ var player = new bitmovin.player.Player(
71
+ document.querySelector('#playerContainer'),
72
+ playerConfig,
73
+ );
74
+
75
+ cmcdIntegration.setPlayer(player);
76
+
77
+ const source = {
78
+ dash: 'https://cdn.bitmovin.com/content/assets/art-of-motion-dash-hls-progressive/mpds/f08e80da-bf1d-4e3d-8899-f0f6155f6efa.mpd',
79
+ hls: 'https://cdn.bitmovin.com/content/assets/art-of-motion-dash-hls-progressive/m3u8s/f08e80da-bf1d-4e3d-8899-f0f6155f6efa.m3u8',
80
+ poster: 'https://cdn.bitmovin.com/content/assets/art-of-motion-dash-hls-progressive/poster.jpg',
81
+ thumbnailTrack: {
82
+ url: 'https://cdn.bitmovin.com/content/assets/art-of-motion-dash-hls-progressive/thumbnails/f08e80da-bf1d-4e3d-8899-f0f6155f6efa.vtt'
83
+ },
84
+ };
85
+
86
+ player.load(source);
87
+
88
+ </script>
89
+ </body>
90
+ </html>
@@ -0,0 +1,356 @@
1
+ /**
2
+ * Enums, keys, classes for CMCD v1.0 support according to
3
+ * https://cdn.cta.tech/cta/media/media/resources/standards/pdfs/cta-5004-final.pdf
4
+ *
5
+ * Limitation:
6
+ * - JSON is not supported, only HTTP Headers and Query Args.
7
+ */
8
+ export declare enum CmcdObjectTypeToken {
9
+ AudioOnly = "a",
10
+ VideoOnly = "v",
11
+ MuxedVideoAudio = "av",
12
+ ManifestOrPlaylistTextFile = "m",
13
+ InitSegment = "i",
14
+ CaptionOrSubtitle = "c",
15
+ TimedTextTrack = "tt",
16
+ CryptographicKeyOrLicenseOrCertificate = "k",
17
+ Other = "o"
18
+ }
19
+ export declare enum CmcdStreamingFormatToken {
20
+ MpegDash = "d",
21
+ Hls = "h",
22
+ Smooth = "s",
23
+ Other = "o"
24
+ }
25
+ export declare enum CmcdStreamTypeToken {
26
+ Vod = "v",
27
+ Live = "l"
28
+ }
29
+ export interface CmcdHeaders {
30
+ [CmcdHeaderType.Request]?: string;
31
+ [CmcdHeaderType.Object]?: string;
32
+ [CmcdHeaderType.Session]?: string;
33
+ [CmcdHeaderType.Status]?: string;
34
+ }
35
+ export declare enum CmcdVersionNumbers {
36
+ v1 = 1
37
+ }
38
+ /**
39
+ * Enum containing all CMCD keys as defined in
40
+ * https://cdn.cta.tech/cta/media/media/resources/standards/pdfs/cta-5004-final.pdf
41
+ */
42
+ export declare enum CmcdKeysToken {
43
+ EncodedBitrate = "br",
44
+ BufferLength = "bl",
45
+ BufferStarvation = "bs",
46
+ ContentId = "cid",
47
+ ObjectDuration = "d",
48
+ Deadline = "dl",
49
+ MeasuredThroughput = "mtp",
50
+ NextObjectRequest = "nor",
51
+ NextRangeRequest = "nrr",
52
+ ObjectType = "ot",
53
+ PlaybackRate = "pr",
54
+ RequestedMaximumThroughput = "rtp",
55
+ StreamingFormat = "sf",
56
+ SessionId = "sid",
57
+ StreamType = "st",
58
+ Startup = "su",
59
+ TopBitrate = "tb",
60
+ CmcdVersion = "v"
61
+ }
62
+ declare enum CmcdHeaderType {
63
+ Object = "CMCD-Object",
64
+ Request = "CMCD-Request",
65
+ Status = "CMCD-Status",
66
+ Session = "CMCD-Session"
67
+ }
68
+ type IntegerKbps = number;
69
+ type IntegerMilliSecs = number;
70
+ export declare function cmcdDataToHeader(data: CmcdBase[]): CmcdHeaders;
71
+ export declare function cmcdDataToUrlParameter(data: CmcdBase[]): string;
72
+ export declare function cmcdDataToJson(data: CmcdBase[]): string;
73
+ export declare abstract class CmcdBase {
74
+ readonly value: unknown;
75
+ abstract readonly key: CmcdKeysToken | string;
76
+ abstract readonly type: CmcdHeaderType;
77
+ constructor(value: unknown);
78
+ /**
79
+ * 2. The key and value MUST be separated by an equals sign Unicode 0x3D.
80
+ *
81
+ * @returns
82
+ */
83
+ keyValuePairToString(): string;
84
+ }
85
+ /**
86
+ * The encoded bitrate of the audio or video object
87
+ * being requested. This may not be known precisely
88
+ * by the player; however, it MAY be estimated based
89
+ * upon playlist/manifest declarations. If the playlist
90
+ * declares both peak and average bitrate values, the
91
+ * peak value should be transmitted.
92
+ */
93
+ export declare class CmcdEncodedBitrate extends CmcdBase {
94
+ readonly key = CmcdKeysToken.EncodedBitrate;
95
+ readonly type = CmcdHeaderType.Object;
96
+ constructor(value: IntegerKbps);
97
+ }
98
+ /**
99
+ * The buffer length associated with the media object
100
+ * being requested. This value MUST be rounded to
101
+ * the nearest 100 ms. This key SHOULD only be sent
102
+ * with an object type of ‘a’, ‘v’ or ‘av’.
103
+ */
104
+ export declare class CmcdBufferLength extends CmcdBase {
105
+ readonly key = CmcdKeysToken.BufferLength;
106
+ readonly type = CmcdHeaderType.Request;
107
+ constructor(value: IntegerMilliSecs);
108
+ }
109
+ /**
110
+ * Key is included without a value if the buffer was
111
+ * starved at some point between the prior request
112
+ * and this object request, resulting in the player
113
+ * being in a rebuffering state and the video or audio
114
+ * playback being stalled. This key MUST NOT be sent
115
+ * if the buffer was not starved since the prior
116
+ * request.
117
+ * If the object type ‘ot’ key is sent along with this
118
+ * key, then the ‘bs’ key refers to the buffer
119
+ * associated with the particular object type. If no
120
+ * object type is communicated, then the buffer state
121
+ * applies to the current session.
122
+ */
123
+ export declare class CmcdBufferStarvation extends CmcdBase {
124
+ readonly key = CmcdKeysToken.BufferStarvation;
125
+ readonly type = CmcdHeaderType.Status;
126
+ constructor(value: boolean);
127
+ }
128
+ /**
129
+ * A unique string identifying the current content.
130
+ * Maximum length is 64 characters. This value is
131
+ * consistent across multiple different sessions and
132
+ * devices and is defined and updated at the
133
+ * discretion of the service provider.
134
+ */
135
+ export declare class CmcdContentId extends CmcdBase {
136
+ readonly key = CmcdKeysToken.ContentId;
137
+ readonly type = CmcdHeaderType.Session;
138
+ constructor(value: string);
139
+ }
140
+ /**
141
+ * The playback duration in milliseconds of the object
142
+ * being requested. If a partial segment is being
143
+ * requested, then this value MUST indicate the
144
+ * playback duration of that part and not that of its
145
+ * parent segment. This value can be an
146
+ * approximation of the estimated duration if the
147
+ * explicit value is not known.
148
+ */
149
+ export declare class CmcdObjectDuration extends CmcdBase {
150
+ readonly key = CmcdKeysToken.ObjectDuration;
151
+ readonly type = CmcdHeaderType.Object;
152
+ constructor(value: IntegerMilliSecs);
153
+ }
154
+ /**
155
+ * Deadline from the request time until the first
156
+ * sample of this Segment/Object needs to be
157
+ * available in order to not create a buffer underrun
158
+ * or any other playback problems. This value MUST
159
+ * be rounded to the nearest 100ms. For a playback
160
+ * rate of 1, this may be equivalent to the player’s
161
+ * remaining buffer length.
162
+ */
163
+ export declare class CmcdDeadline extends CmcdBase {
164
+ readonly key = CmcdKeysToken.Deadline;
165
+ readonly type = CmcdHeaderType.Request;
166
+ constructor(value: IntegerMilliSecs);
167
+ }
168
+ /**
169
+ * The throughput between client and server, as
170
+ * measured by the client and MUST be rounded to
171
+ * the nearest 100 kbps. This value, however derived,
172
+ * SHOULD be the value that the client is using to
173
+ * make its next Adaptive Bitrate switching decision.
174
+ * If the client is connected to multiple servers
175
+ * concurrently, it must take care to report only the
176
+ * throughput measured against the receiving server.
177
+ * If the client has multiple concurrent connections to
178
+ * the server, then the intent is that this value
179
+ * communicates the aggregate throughput the client
180
+ * sees across all those connections.
181
+ */
182
+ export declare class CmcdMeasuredThroughput extends CmcdBase {
183
+ readonly key = CmcdKeysToken.MeasuredThroughput;
184
+ readonly type = CmcdHeaderType.Request;
185
+ constructor(value: IntegerKbps);
186
+ }
187
+ /**
188
+ * Relative path of the next object to be requested.
189
+ * This can be used to trigger pre-fetching by the
190
+ * CDN. This MUST be a path relative to the current
191
+ * request. This string MUST be URLEncoded [5]. The
192
+ * client SHOULD NOT depend upon any pre-fetch
193
+ * action being taken - it is merely a request for such
194
+ * a pre-fetch to take place.
195
+ */
196
+ export declare class CmcdNextObjectRequest extends CmcdBase {
197
+ readonly key = CmcdKeysToken.NextObjectRequest;
198
+ readonly type = CmcdHeaderType.Request;
199
+ constructor(value: string);
200
+ }
201
+ /**
202
+ * If the next request will be a partial object request,
203
+ * then this string denotes the byte range to be
204
+ * requested. If the ‘nor’ field is not set, then the
205
+ * object is assumed to match the object currently
206
+ * being requested. The client SHOULD NOT depend
207
+ * upon any pre-fetch action being taken – it is
208
+ * merely a request for such a pre-fetch to take place.
209
+ * Formatting is similar to the HTTP Range header,
210
+ * except that the unit MUST be ‘byte’, the ‘Range:’
211
+ * prefix is NOT required and specifying multiple
212
+ * ranges is NOT allowed. Valid combinations are:
213
+ * - "<range-start>-"
214
+ * - "<range-start>-<range-end>"
215
+ * - "-<suffix-length>"
216
+ */
217
+ export declare class CmcdNextRangeRequest extends CmcdBase {
218
+ readonly key = CmcdKeysToken.NextRangeRequest;
219
+ readonly type = CmcdHeaderType.Request;
220
+ constructor(value: string);
221
+ }
222
+ /**
223
+ * The media type of the current object being
224
+ * requested:
225
+ * - m = text file, such as a manifest or playlist
226
+ * - a = audio only
227
+ * - v = video only
228
+ * - av = muxed audio and video
229
+ * - i = init segment
230
+ * - c = caption or subtitle
231
+ * - tt = ISOBMFF timed text track
232
+ * - k = cryptographic key, license or certificate.
233
+ * - o = other
234
+ *
235
+ * If the object type being requested is unknown,
236
+ * then this key MUST NOT be used.
237
+ */
238
+ export declare class CmcdObjectType extends CmcdBase {
239
+ readonly key = CmcdKeysToken.ObjectType;
240
+ readonly type = CmcdHeaderType.Object;
241
+ constructor(value: CmcdObjectTypeToken);
242
+ keyValuePairToString(): string;
243
+ }
244
+ /**
245
+ * 1 if real-time, 2 if double speed, 0 if not playing.
246
+ * SHOULD only be sent if not equal to 1.
247
+ */
248
+ export declare class CmcdPlaybackRate extends CmcdBase {
249
+ readonly key = CmcdKeysToken.PlaybackRate;
250
+ readonly type = CmcdHeaderType.Session;
251
+ constructor(value: number);
252
+ keyValuePairToString(): string;
253
+ }
254
+ /**
255
+ * The requested maximum throughput that the
256
+ * client considers sufficient for delivery of the asset.
257
+ * Values MUST be rounded to the nearest 100kbps.
258
+ * For example, a client would indicate that the
259
+ * current segment, encoded at 2Mbps, is to be
260
+ * delivered at no more than 10Mbps, by using
261
+ * rtp=10000.
262
+ * Note: This can benefit clients by preventing buffer
263
+ * saturation through over-delivery and can also
264
+ * deliver a community benefit through fair-share
265
+ * delivery. The concept is that each client receives
266
+ * the throughput necessary for great performance,
267
+ * but no more. The CDN may not support the rtp
268
+ * feature.
269
+ */
270
+ export declare class CmcdRequestedMaximumThroughput extends CmcdBase {
271
+ readonly key = CmcdKeysToken.RequestedMaximumThroughput;
272
+ readonly type = CmcdHeaderType.Status;
273
+ constructor(value: number);
274
+ }
275
+ /**
276
+ * The streaming format that defines the current
277
+ * request.
278
+ * - d = MPEG DASH
279
+ * - h = HTTP Live Streaming (HLS)
280
+ * - s = Smooth Streaming
281
+ * - o = other
282
+ *
283
+ * If the streaming format being requested is
284
+ * unknown, then this key MUST NOT be used.
285
+ */
286
+ export declare class CmcdStreamingFormat extends CmcdBase {
287
+ readonly key = CmcdKeysToken.StreamingFormat;
288
+ readonly type = CmcdHeaderType.Session;
289
+ constructor(value: CmcdStreamingFormatToken);
290
+ keyValuePairToString(): string;
291
+ }
292
+ /**
293
+ * A GUID identifying the current playback session. A
294
+ * playback session typically ties together segments
295
+ * belonging to a single media asset. Maximum length
296
+ * is 64 characters. It is RECOMMENDED to conform
297
+ * to the UUID specification [7].
298
+ */
299
+ export declare class CmcdSessionId extends CmcdBase {
300
+ readonly key = CmcdKeysToken.SessionId;
301
+ readonly type = CmcdHeaderType.Session;
302
+ constructor(value: string);
303
+ }
304
+ /**
305
+ * - v = all segments are available – e.g., VOD
306
+ * - l = segments become available over time – e.g.,
307
+ * LIVE
308
+ */
309
+ export declare class CmcdStreamType extends CmcdBase {
310
+ readonly key = CmcdKeysToken.StreamType;
311
+ readonly type = CmcdHeaderType.Session;
312
+ constructor(value: CmcdStreamTypeToken);
313
+ keyValuePairToString(): string;
314
+ }
315
+ /**
316
+ * Key is included without a value if the object is
317
+ * needed urgently due to startup, seeking or
318
+ * recovery after a buffer-empty event. The media
319
+ * SHOULD not be rendering when this request is
320
+ * made. This key MUST not be sent if it is FALSE.
321
+ */
322
+ export declare class CmcdStartup extends CmcdBase {
323
+ readonly key = CmcdKeysToken.Startup;
324
+ readonly type = CmcdHeaderType.Request;
325
+ constructor(value: boolean);
326
+ keyValuePairToString(): string;
327
+ }
328
+ /**
329
+ * The highest bitrate rendition in the manifest or
330
+ * playlist that the client is allowed to play, given
331
+ * current codec, licensing and sizing constraints.
332
+ */
333
+ export declare class CmcdTopBitrate extends CmcdBase {
334
+ readonly key = CmcdKeysToken.TopBitrate;
335
+ readonly type = CmcdHeaderType.Object;
336
+ constructor(value: IntegerKbps);
337
+ }
338
+ /**
339
+ * The version of this specification used for
340
+ * interpreting the defined key names and values. If
341
+ * this key is omitted, the client and server MUST
342
+ * interpret the values as being defined by version 1.
343
+ * Client SHOULD omit this field if the version is 1.
344
+ */
345
+ export declare class CmcdVersion extends CmcdBase {
346
+ readonly key = CmcdKeysToken.CmcdVersion;
347
+ readonly type = CmcdHeaderType.Session;
348
+ constructor(value: CmcdVersionNumbers);
349
+ keyValuePairToString(): string;
350
+ }
351
+ export declare class CmcdCustomKey extends CmcdBase {
352
+ readonly key: string;
353
+ readonly type = CmcdHeaderType.Session;
354
+ constructor(key: string, value: string | number);
355
+ }
356
+ export {};
@@ -0,0 +1,56 @@
1
+ /**
2
+ * Collect CMCD data from the Bitmovin Player and add them to the network requests.
3
+ *
4
+ * Limitations:
5
+ * - Range requests aren't supported
6
+ * - It's currently assumed all requests go to the same server
7
+ * - There is no distinguishing between media (ObjectType `a`/`v`/`av`) and initialization (ObjectType `i`) segments
8
+ * - Muxed Audio and Video into a single segment (ObjectType `av`) is not supported
9
+ * - TimedTextTrack (ObjectType `tt`) is currently not used
10
+ */
11
+ import { AudioAdaptationData, HttpRequest, HttpRequestType, HttpResponse, HttpResponseBody, PlayerAPI, VideoAdaptationData } from 'bitmovin-player';
12
+ import { CmcdCustomKey } from './Cmcd';
13
+ export { CmcdCustomKey as CustomKey } from './Cmcd';
14
+ export interface CmcdConfig {
15
+ sessionId?: string;
16
+ contentId?: string;
17
+ useQueryArgs?: boolean;
18
+ /**
19
+ * Allows to set custom keys, which will be appended to all requests.
20
+ * This list is static and cannot be changed during run-time.
21
+ *
22
+ * Please note that custom key names MUST carry a hyphenated prefix to ensure
23
+ * that there won't be a namespace collision with future revisions of CMCD.
24
+ * The prefix SHOULD also use a reverse-DNS syntax.
25
+ */
26
+ customKeys?: CmcdCustomKey[];
27
+ }
28
+ export declare class CmcdIntegration {
29
+ private sessionId;
30
+ private contentId;
31
+ private useQueryArgs;
32
+ private customKeys;
33
+ private player?;
34
+ private stalledSinceLastRequest;
35
+ private currentVideoQuality;
36
+ private currentAudioQuality;
37
+ private isSeekingOrTimeshiftingOrStartup;
38
+ private lastMeasuredThroughputAudio;
39
+ private lastMeasuredThroughputVideo;
40
+ private manifestType;
41
+ constructor(config: CmcdConfig);
42
+ setPlayer(player: PlayerAPI): void;
43
+ onVideoAdaptation: (data: VideoAdaptationData) => string;
44
+ onAudioAdaptation: (data: AudioAdaptationData) => string;
45
+ preprocessHttpRequest: (type: HttpRequestType, request: HttpRequest) => Promise<HttpRequest>;
46
+ preprocessHttpResponse: (type: HttpRequestType, response: HttpResponse<HttpResponseBody>) => Promise<HttpResponse<HttpResponseBody>>;
47
+ setSessionId(id: string): void;
48
+ setContentId(id: string): void;
49
+ private gatherCmcdData;
50
+ private getRequestedMaximumThroughput;
51
+ private getStreamingType;
52
+ private getObjectType;
53
+ private getAudioSegmentRequestSpecificData;
54
+ private getVideoSegmentRequestSpecificData;
55
+ private getNextObjectAndObjectDurationCmcdData;
56
+ }
@@ -0,0 +1 @@
1
+ !function(t,e){"object"==typeof exports&&"object"==typeof module?module.exports=e():"function"==typeof define&&define.amd?define([],e):"object"==typeof exports?exports.BitmovinPlayerIntegrationCmcd=e():(t.bitmovin=t.bitmovin||{},t.bitmovin.player=t.bitmovin.player||{},t.bitmovin.player.integration=t.bitmovin.player.integration||{},t.bitmovin.player.integration.Cmcd=e())}(self,(function(){return function(){"use strict";var t={247:function(t,e,n){n.d(e,{Ao:function(){return E},Dh:function(){return a},I3:function(){return R},J3:function(){return M},M:function(){return h},O5:function(){return b},Ph:function(){return I},QU:function(){return u},RE:function(){return s},RF:function(){return A},RZ:function(){return y},T8:function(){return m},TS:function(){return k},Vf:function(){return x},Vq:function(){return q},ZH:function(){return v},be:function(){return T},dg:function(){return O},gu:function(){return D},hq:function(){return P},mP:function(){return g},mc:function(){return i},nf:function(){return o},oI:function(){return S},x9:function(){return V}});var r,i,u,o,s,a,c,p=(r=function(t,e){return r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},r(t,e)},function(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");function n(){this.constructor=t}r(t,e),t.prototype=null===e?Object.create(e):(n.prototype=e.prototype,new n)});function l(t){return t.sort((function(t,e){var n=t.key.substring(t.key.lastIndexOf("-")+1),r=e.key.substring(e.key.lastIndexOf("-")+1);return n.localeCompare(r)})).filter((function(t){return t.keyValuePairToString()}))}function h(t){var e=l(t),n=e.filter((function(t){return t.type===c.Request})).map((function(t){return t.keyValuePairToString()})).join(","),r=e.filter((function(t){return t.type===c.Object})).map((function(t){return t.keyValuePairToString()})).join(","),i=e.filter((function(t){return t.type===c.Status})).map((function(t){return t.keyValuePairToString()})).join(","),u=e.filter((function(t){return t.type===c.Session})).map((function(t){return t.keyValuePairToString()})).join(","),o={};return n&&(o[c.Request]=n),r&&(o[c.Object]=r),i&&(o[c.Status]=i),u&&(o[c.Session]=u),o}function y(t){var e=l(t).map((function(t){return t.keyValuePairToString()})).join(",");return"CMCD=".concat(encodeURIComponent(e))}!function(t){t.AudioOnly="a",t.VideoOnly="v",t.MuxedVideoAudio="av",t.ManifestOrPlaylistTextFile="m",t.InitSegment="i",t.CaptionOrSubtitle="c",t.TimedTextTrack="tt",t.CryptographicKeyOrLicenseOrCertificate="k",t.Other="o"}(i||(i={})),function(t){t.MpegDash="d",t.Hls="h",t.Smooth="s",t.Other="o"}(u||(u={})),function(t){t.Vod="v",t.Live="l"}(o||(o={})),function(t){t[t.v1=1]="v1"}(s||(s={})),function(t){t.EncodedBitrate="br",t.BufferLength="bl",t.BufferStarvation="bs",t.ContentId="cid",t.ObjectDuration="d",t.Deadline="dl",t.MeasuredThroughput="mtp",t.NextObjectRequest="nor",t.NextRangeRequest="nrr",t.ObjectType="ot",t.PlaybackRate="pr",t.RequestedMaximumThroughput="rtp",t.StreamingFormat="sf",t.SessionId="sid",t.StreamType="st",t.Startup="su",t.TopBitrate="tb",t.CmcdVersion="v"}(a||(a={})),function(t){t.Object="CMCD-Object",t.Request="CMCD-Request",t.Status="CMCD-Status",t.Session="CMCD-Session"}(c||(c={}));var f,d=function(){function t(t){this.value=t}return t.prototype.keyValuePairToString=function(){return"string"==typeof this.value?this.value?"".concat(this.key,"=").concat((t=this.value,e=/"/g,n=/\\/g,'"'.concat(t.replace(n,"\\\\").replace(e,'\\"'),'"'))):"":"boolean"==typeof this.value&&!0===this.value?"".concat(this.key):"".concat(this.key,"=").concat(this.value);var t,e,n},t}(),v=function(t){function e(e){var n=t.call(this,e)||this;return n.key=a.EncodedBitrate,n.type=c.Object,n}return p(e,t),e}(d),S=function(t){function e(e){var n=t.call(this,100*Math.round(e/100))||this;return n.key=a.BufferLength,n.type=c.Request,n}return p(e,t),e}(d),g=function(t){function e(e){var n=t.call(this,e)||this;return n.key=a.BufferStarvation,n.type=c.Status,n}return p(e,t),e}(d),T=function(t){function e(e){var n=t.call(this,e)||this;return n.key=a.ContentId,n.type=c.Session,n}return p(e,t),e}(d),m=function(t){function e(e){var n=t.call(this,e)||this;return n.key=a.ObjectDuration,n.type=c.Object,n}return p(e,t),e}(d),b=function(t){function e(e){var n=t.call(this,100*Math.round(e/100))||this;return n.key=a.Deadline,n.type=c.Request,n}return p(e,t),e}(d),O=function(t){function e(e){var n=t.call(this,100*Math.round(e/100))||this;return n.key=a.MeasuredThroughput,n.type=c.Request,n}return p(e,t),e}(d),R=function(t){function e(e){var n=t.call(this,e)||this;return n.key=a.NextObjectRequest,n.type=c.Request,n}return p(e,t),e}(d),k=(p((function(t){var e=f.call(this,t)||this;return e.key=a.NextRangeRequest,e.type=c.Request,e}),f=d),function(t){function e(e){var n=t.call(this,e)||this;return n.key=a.ObjectType,n.type=c.Object,n}return p(e,t),e.prototype.keyValuePairToString=function(){return"".concat(this.key,"=").concat(this.value)},e}(d)),A=function(t){function e(e){var n=t.call(this,e)||this;return n.key=a.PlaybackRate,n.type=c.Session,n}return p(e,t),e.prototype.keyValuePairToString=function(){return 1===this.value?"":"".concat(this.key,"=").concat(this.value)},e}(d),M=function(t){function e(e){var n=t.call(this,e)||this;return n.key=a.RequestedMaximumThroughput,n.type=c.Status,n}return p(e,t),e}(d),x=function(t){function e(e){var n=t.call(this,e)||this;return n.key=a.StreamingFormat,n.type=c.Session,n}return p(e,t),e.prototype.keyValuePairToString=function(){return"".concat(this.key,"=").concat(this.value)},e}(d),I=function(t){function e(e){var n=t.call(this,e)||this;return n.key=a.SessionId,n.type=c.Session,n}return p(e,t),e}(d),D=function(t){function e(e){var n=t.call(this,e)||this;return n.key=a.StreamType,n.type=c.Session,n}return p(e,t),e.prototype.keyValuePairToString=function(){return"".concat(this.key,"=").concat(this.value)},e}(d),E=function(t){function e(e){var n=t.call(this,e)||this;return n.key=a.Startup,n.type=c.Request,n}return p(e,t),e.prototype.keyValuePairToString=function(){return!0===this.value?"".concat(this.key):""},e}(d),q=function(t){function e(e){var n=t.call(this,e)||this;return n.key=a.TopBitrate,n.type=c.Object,n}return p(e,t),e}(d),V=function(t){function e(e){var n=t.call(this,e)||this;return n.key=a.CmcdVersion,n.type=c.Session,n}return p(e,t),e.prototype.keyValuePairToString=function(){return this.value===s.v1?"":"".concat(this.key,"=").concat(this.value)},e}(d),P=function(t){function e(e,n){var r=t.call(this,n)||this;r.type=c.Session;var i=e.match(/^(.*-)(.*)$/);if(!i||!i[2])throw new Error("Custom key names MUST carry a hyphenated prefix (and SHOULD use a reverse-DNS syntax)");return r.key=e,r}return p(e,t),e}(d)},498:function(t,e,n){n.r(e),n.d(e,{CmcdIntegration:function(){return u},CustomKey:function(){return r.hq}});var r=n(247),i=function(){return i=Object.assign||function(t){for(var e,n=1,r=arguments.length;n<r;n++)for(var i in e=arguments[n])Object.prototype.hasOwnProperty.call(e,i)&&(t[i]=e[i]);return t},i.apply(this,arguments)},u=function(){function t(t){var e=this;this.onVideoAdaptation=function(t){return e.currentVideoQuality=t.representations.filter((function(e){return e.id===t.suggested}))[0],t.suggested},this.onAudioAdaptation=function(t){return e.currentAudioQuality=t.representations.filter((function(e){return e.id===t.suggested}))[0],t.suggested},this.preprocessHttpRequest=function(t,n){var u=e.gatherCmcdData(t,n);if(e.useQueryArgs){var o=new URL(n.url);o.searchParams.delete("CMCD");var s=(0,r.RZ)(u),a=o.toString().includes("?")?"&":"?";n.url="".concat(o.toString()).concat(a).concat(s)}else{var c=(0,r.M)(u);n.headers=i(i({},n.headers),c)}return Promise.resolve(n)},this.preprocessHttpResponse=function(t,n){var r,i,u=n.elapsedTime,o=n.length;if(!u||!o)return Promise.resolve(n);var s=o/u/1e3;return t===((null===(r=e.player)||void 0===r?void 0:r.exports.HttpRequestType.MEDIA_AUDIO)||"media/audio")&&(e.lastMeasuredThroughputAudio=Math.round(100*s)/100),t===((null===(i=e.player)||void 0===i?void 0:i.exports.HttpRequestType.MEDIA_VIDEO)||"media/video")&&(e.lastMeasuredThroughputVideo=Math.round(100*s)/100),Promise.resolve(n)},this.useQueryArgs=t.useQueryArgs||!1,this.sessionId=t.sessionId||"",this.contentId=t.contentId||"",this.customKeys=t.customKeys||[],this.stalledSinceLastRequest=!1,this.currentVideoQuality=null,this.currentAudioQuality=null,this.isSeekingOrTimeshiftingOrStartup=!0,this.lastMeasuredThroughputAudio=0,this.lastMeasuredThroughputVideo=0,this.manifestType=null}return t.prototype.setPlayer=function(t){var e=this;this.player=t,this.player.on(t.exports.PlayerEvent.StallStarted,(function(){e.stalledSinceLastRequest=!0,e.isSeekingOrTimeshiftingOrStartup=!0})),this.player.on(t.exports.PlayerEvent.StallEnded,(function(){return e.isSeekingOrTimeshiftingOrStartup=!1})),this.player.on(t.exports.PlayerEvent.Seek,(function(){return e.isSeekingOrTimeshiftingOrStartup=!0})),this.player.on(t.exports.PlayerEvent.Seeked,(function(){return e.isSeekingOrTimeshiftingOrStartup=!1})),this.player.on(t.exports.PlayerEvent.TimeShift,(function(){return e.isSeekingOrTimeshiftingOrStartup=!0})),this.player.on(t.exports.PlayerEvent.TimeShifted,(function(){return e.isSeekingOrTimeshiftingOrStartup=!1}))},t.prototype.setSessionId=function(t){this.sessionId=t},t.prototype.setContentId=function(t){this.contentId=t},t.prototype.gatherCmcdData=function(t,e){var n,i;if(!this.player)throw new Error("Bitmovin Player not provided!");var u=[];u.push(new r.x9(r.RE.v1)),u.push(new r.gu(this.player.isLive()?r.nf.Live:r.nf.Vod)),u.push(new r.RF(this.player.getPlaybackSpeed())),u.push(this.getObjectType(t)),u.push(this.getStreamingType(t)),this.contentId&&u.push(new r.be(this.contentId)),this.sessionId&&u.push(new r.Ph(this.sessionId)),this.isSeekingOrTimeshiftingOrStartup&&u.push(new r.Ao(!0)),(this.stalledSinceLastRequest||this.player.isStalled())&&(u.push(new r.mP(!0)),this.stalledSinceLastRequest=!1),t===(null===(n=this.player)||void 0===n?void 0:n.exports.HttpRequestType.MEDIA_AUDIO)?u=u.concat(this.getAudioSegmentRequestSpecificData(e)):t===(null===(i=this.player)||void 0===i?void 0:i.exports.HttpRequestType.MEDIA_VIDEO)&&(u=u.concat(this.getVideoSegmentRequestSpecificData(e))),u.concat(this.getRequestedMaximumThroughput(u));for(var o=0,s=this.customKeys;o<s.length;o++){var a=s[o];u.push(a)}return u},t.prototype.getRequestedMaximumThroughput=function(t){var e=t.find((function(t){return t.key===r.Dh.EncodedBitrate})),n=t.find((function(t){return t.key===r.Dh.ObjectDuration})),i=Boolean(t.find((function(t){return t.key===r.Dh.ObjectDuration}))),u=t.find((function(t){return t.key===r.Dh.Startup})),o=u&&!u.value;if(e&&n&&!i&&!o){var s=1e3*Number(n.value),a=Number(e.value)*(s/2);return[new r.J3(a)]}return[]},t.prototype.getStreamingType=function(t){var e,n,i;return this.manifestType||(t===(null===(e=this.player)||void 0===e?void 0:e.exports.HttpRequestType.MANIFEST_DASH)?this.manifestType=r.QU.MpegDash:t===(null===(n=this.player)||void 0===n?void 0:n.exports.HttpRequestType.MANIFEST_HLS_MASTER)?this.manifestType=r.QU.Hls:t===(null===(i=this.player)||void 0===i?void 0:i.exports.HttpRequestType.MANIFEST_SMOOTH)?this.manifestType=r.QU.Smooth:this.manifestType=r.QU.Other),new r.Vf(this.manifestType)},t.prototype.getObjectType=function(t){var e,n,i,u,o,s,a,c,p,l,h,y,f,d,v,S;switch(t){case null===(e=this.player)||void 0===e?void 0:e.exports.HttpRequestType.MEDIA_AUDIO:S=new r.TS(r.mc.AudioOnly);break;case null===(n=this.player)||void 0===n?void 0:n.exports.HttpRequestType.MEDIA_VIDEO:S=new r.TS(r.mc.VideoOnly);break;case null===(i=this.player)||void 0===i?void 0:i.exports.HttpRequestType.DRM_CERTIFICATE_FAIRPLAY:case null===(u=this.player)||void 0===u?void 0:u.exports.HttpRequestType.DRM_LICENSE_CLEARKEY:case null===(o=this.player)||void 0===o?void 0:o.exports.HttpRequestType.DRM_LICENSE_FAIRPLAY:case null===(s=this.player)||void 0===s?void 0:s.exports.HttpRequestType.DRM_LICENSE_PLAYREADY:case null===(a=this.player)||void 0===a?void 0:a.exports.HttpRequestType.DRM_LICENSE_WIDEVINE:case null===(c=this.player)||void 0===c?void 0:c.exports.HttpRequestType.KEY_HLS_AES:S=new r.TS(r.mc.CryptographicKeyOrLicenseOrCertificate);break;case null===(p=this.player)||void 0===p?void 0:p.exports.HttpRequestType.MANIFEST_ADS:case null===(l=this.player)||void 0===l?void 0:l.exports.HttpRequestType.MANIFEST_DASH:case null===(h=this.player)||void 0===h?void 0:h.exports.HttpRequestType.MANIFEST_HLS_MASTER:case null===(y=this.player)||void 0===y?void 0:y.exports.HttpRequestType.MANIFEST_HLS_VARIANT:case null===(f=this.player)||void 0===f?void 0:f.exports.HttpRequestType.MANIFEST_SMOOTH:S=new r.TS(r.mc.ManifestOrPlaylistTextFile);break;case null===(d=this.player)||void 0===d?void 0:d.exports.HttpRequestType.MEDIA_SEGMENTINDEX:S=new r.TS(r.mc.InitSegment);break;case null===(v=this.player)||void 0===v?void 0:v.exports.HttpRequestType.MEDIA_SUBTITLES:S=new r.TS(r.mc.CaptionOrSubtitle);break;default:S=new r.TS(r.mc.Other)}return S},t.prototype.getAudioSegmentRequestSpecificData=function(t){var e,n=[];if(this.currentAudioQuality&&this.currentAudioQuality.bandwidth&&n.push(new r.ZH(Math.round(this.currentAudioQuality.bandwidth/1e3))),this.lastMeasuredThroughputAudio&&n.push(new r.dg(this.lastMeasuredThroughputAudio)),!this.player)return n;var i=this.player.buffer.getLevel(this.player.exports.BufferType.ForwardDuration,this.player.exports.MediaType.Audio);if(i.targetLevel>0){n.push(new r.oI(1e3*i.level));var u=i.level/(null===(e=this.player)||void 0===e?void 0:e.getPlaybackSpeed());n.push(new r.O5(1e3*u))}var o=this.player.getAvailableAudioQualities().reduce((function(t,e){return Math.max(t,e.bitrate)}),0)/1e3;if(o>0&&n.push(new r.Vq(o)),this.currentVideoQuality)try{var s=this.player.getAvailableSegments();for(var a in s)if(a.startsWith("video/")){var c=s[a][this.currentVideoQuality.id];n=n.concat(this.getNextObjectAndObjectDurationCmcdData(c,t.url))}}catch(t){console.error("Error processing audio segments:",t)}return n},t.prototype.getVideoSegmentRequestSpecificData=function(t){var e,n=[];if(this.currentVideoQuality&&this.currentVideoQuality.bandwidth&&n.push(new r.ZH(Math.round(this.currentVideoQuality.bandwidth/1e3))),this.lastMeasuredThroughputVideo&&n.push(new r.dg(this.lastMeasuredThroughputVideo)),!this.player)return n;var i=this.player.buffer.getLevel(this.player.exports.BufferType.ForwardDuration,this.player.exports.MediaType.Video);if(i.targetLevel>0){n.push(new r.oI(1e3*i.level));var u=i.level/(null===(e=this.player)||void 0===e?void 0:e.getPlaybackSpeed());n.push(new r.O5(1e3*u))}var o=this.player.getAvailableVideoQualities().reduce((function(t,e){return Math.max(t,e.bitrate)}),0)/1e3;if(o>0&&n.push(new r.Vq(o)),this.currentVideoQuality)try{var s=this.player.getAvailableSegments();for(var a in s)if(a.startsWith("video/")){var c=s[a][this.currentVideoQuality.id];n=n.concat(this.getNextObjectAndObjectDurationCmcdData(c,t.url))}}catch(t){console.error("Error processing video segments:",t)}return n},t.prototype.getNextObjectAndObjectDurationCmcdData=function(t,e){var n=[],i=t.findIndex((function(t){return t.url===e}));if(i>-1){var u=t[i];if(Number.isNaN(u.duration)||n.push(new r.T8(1e3*Number(u.duration))),i+1<t.length){var o=t[i+1];o.url&&n.push(new r.I3(o.url))}}return n},t}()}},e={};function n(r){var i=e[r];if(void 0!==i)return i.exports;var u=e[r]={exports:{}};return t[r](u,u.exports,n),u.exports}return n.d=function(t,e){for(var r in e)n.o(e,r)&&!n.o(t,r)&&Object.defineProperty(t,r,{enumerable:!0,get:e[r]})},n.o=function(t,e){return Object.prototype.hasOwnProperty.call(t,e)},n.r=function(t){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})},n(247),n(498)}()}));
package/jest.config.js ADDED
@@ -0,0 +1,5 @@
1
+ /** @type {import('ts-jest').JestConfigWithTsJest} */
2
+ module.exports = {
3
+ preset: 'ts-jest',
4
+ testEnvironment: 'jsdom',
5
+ };
package/package.json ADDED
@@ -0,0 +1,49 @@
1
+ {
2
+ "name": "@bitmovin/player-web-integration-cmcd",
3
+ "version": "0.3.0",
4
+ "description": "Conviva analytics integration for the Bitmovin Player",
5
+ "types": "dist/js/CmcdIntegration.d.ts",
6
+ "browser": "dist/js/bitmovin-player-integration-cmcd.js",
7
+ "main": "dist/js/bitmovin-player-integration-cmcd.js",
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "ssh://git@github.com:bitmovin/bitmovin-player-web-integration-cmcd.git"
11
+ },
12
+ "scripts": {
13
+ "format": "prettier --write src/ test/",
14
+ "prepare": "husky install",
15
+ "start": "webpack serve --open --config tooling/webpack.dev.js",
16
+ "debug": "webpack --config tooling/webpack.dev.js",
17
+ "build": "webpack --config tooling/webpack.prod.js",
18
+ "clean": "rm -R dist/js",
19
+ "test": "jest",
20
+ "test-watch": "jest --watch"
21
+ },
22
+ "lint-staged": {
23
+ "**/*.{ts,js}": "prettier --write --ignore-unknown",
24
+ "CHANGELOG.md": "kacl lint --filename"
25
+ },
26
+ "author": "Bitmovin",
27
+ "license": "MIT",
28
+ "devDependencies": {
29
+ "@jest/globals": "^29.4.2",
30
+ "changelog-parser": "^3.0.1",
31
+ "husky": "^8.0.3",
32
+ "jest": "^29.4.2",
33
+ "jest-environment-jsdom": "^29.4.2",
34
+ "kacl": "^1.1.1",
35
+ "lint-staged": "^13.1.1",
36
+ "prettier": "^2.8.4",
37
+ "semver": "^7.6.3",
38
+ "ts-jest": "^29.0.5",
39
+ "ts-loader": "^9.4.2",
40
+ "typescript": "^4.9.5",
41
+ "webpack": "^5.75.0",
42
+ "webpack-cli": "^5.0.1",
43
+ "webpack-dev-server": "^4.11.1",
44
+ "webpack-merge": "^5.8.0"
45
+ },
46
+ "peerDependencies": {
47
+ "bitmovin-player": "^8.104.0"
48
+ }
49
+ }
@@ -0,0 +1,311 @@
1
+ import { describe, beforeEach, it, expect } from '@jest/globals';
2
+ import {
3
+ CmcdBufferLength,
4
+ CmcdBufferStarvation,
5
+ CmcdContentId,
6
+ CmcdCustomKey,
7
+ CmcdDeadline,
8
+ CmcdEncodedBitrate,
9
+ CmcdMeasuredThroughput,
10
+ CmcdNextObjectRequest,
11
+ CmcdNextRangeRequest,
12
+ CmcdObjectDuration,
13
+ CmcdObjectType,
14
+ CmcdObjectTypeToken,
15
+ CmcdPlaybackRate,
16
+ CmcdRequestedMaximumThroughput,
17
+ CmcdSessionId,
18
+ CmcdStartup,
19
+ CmcdStreamType,
20
+ CmcdStreamTypeToken,
21
+ CmcdStreamingFormat,
22
+ CmcdStreamingFormatToken,
23
+ CmcdTopBitrate,
24
+ CmcdVersion,
25
+ CmcdVersionNumbers,
26
+ cmcdDataToHeader,
27
+ cmcdDataToUrlParameter,
28
+ } from '../../src/ts/Cmcd';
29
+
30
+ describe('Cmcd', () => {
31
+ beforeEach(() => {
32
+ // fresh setup before every test case
33
+ });
34
+
35
+ it('should transform CMCD objects to URL parameter', () => {
36
+ const cmcdObjects = [
37
+ new CmcdEncodedBitrate(500),
38
+ new CmcdBufferLength(0),
39
+ new CmcdBufferStarvation(true),
40
+ new CmcdObjectType(CmcdObjectTypeToken.VideoOnly),
41
+ ];
42
+
43
+ expect(cmcdDataToUrlParameter(cmcdObjects)).toEqual('CMCD=bl%3D0%2Cbr%3D500%2Cbs%2Cot%3Dv');
44
+ });
45
+
46
+ it('should always sort the URL parameters alphabetically by CMCD key', () => {
47
+ const cmcdObjects1 = [
48
+ new CmcdEncodedBitrate(500),
49
+ new CmcdBufferLength(0),
50
+ new CmcdBufferStarvation(true),
51
+ new CmcdObjectType(CmcdObjectTypeToken.VideoOnly),
52
+ ];
53
+ const cmcdObjects2 = [
54
+ new CmcdBufferLength(0),
55
+ new CmcdBufferStarvation(true),
56
+ new CmcdObjectType(CmcdObjectTypeToken.VideoOnly),
57
+ new CmcdEncodedBitrate(500),
58
+ ];
59
+ const cmcdObjects3 = [
60
+ new CmcdBufferStarvation(true),
61
+ new CmcdObjectType(CmcdObjectTypeToken.VideoOnly),
62
+ new CmcdBufferLength(0),
63
+ new CmcdEncodedBitrate(500),
64
+ ];
65
+ const cmcdObjects4 = [
66
+ new CmcdObjectType(CmcdObjectTypeToken.VideoOnly),
67
+ new CmcdBufferLength(0),
68
+ new CmcdBufferStarvation(true),
69
+ new CmcdEncodedBitrate(500),
70
+ ];
71
+
72
+ const cmcdUrlParams1 = cmcdDataToUrlParameter(cmcdObjects1);
73
+ const cmcdUrlParams2 = cmcdDataToUrlParameter(cmcdObjects2);
74
+ const cmcdUrlParams3 = cmcdDataToUrlParameter(cmcdObjects3);
75
+ const cmcdUrlParams4 = cmcdDataToUrlParameter(cmcdObjects4);
76
+
77
+ expect(cmcdUrlParams1).toEqual(cmcdUrlParams2);
78
+ expect(cmcdUrlParams2).toEqual(cmcdUrlParams3);
79
+ expect(cmcdUrlParams3).toEqual(cmcdUrlParams4);
80
+ });
81
+
82
+ describe('Cmcd classes', () => {
83
+ it('should ignore keys with empty string value', () => {
84
+ expect(new CmcdContentId('').keyValuePairToString()).toEqual('');
85
+ });
86
+
87
+ it('should quote strings', () => {
88
+ expect(new CmcdContentId('test-content-id').keyValuePairToString()).toEqual('cid="test-content-id"');
89
+ });
90
+
91
+ it('should escape backslashes in strings', () => {
92
+ expect(new CmcdContentId('test-\\content\\-id').keyValuePairToString()).toEqual('cid="test-\\\\content\\\\-id"');
93
+ });
94
+
95
+ it('should escape quotes in strings', () => {
96
+ expect(new CmcdContentId('"test"-content-id').keyValuePairToString()).toEqual('cid="\\"test\\"-content-id"');
97
+ });
98
+
99
+ it('should escape quotes and backslashes in strings', () => {
100
+ expect(new CmcdContentId('"test"-content\\-id').keyValuePairToString()).toEqual(
101
+ 'cid="\\"test\\"-content\\\\-id"'
102
+ );
103
+ });
104
+
105
+ it('should truncate true boolean values to just include the CMCD key', () => {
106
+ expect(new CmcdBufferStarvation(true).keyValuePairToString()).toEqual('bs');
107
+ });
108
+
109
+ it('should explicitly list false boolean values', () => {
110
+ expect(new CmcdBufferStarvation(false).keyValuePairToString()).toEqual('bs=false');
111
+ });
112
+
113
+ it('should list number values "as is"', () => {
114
+ expect(new CmcdEncodedBitrate(5432).keyValuePairToString()).toEqual('br=5432');
115
+ });
116
+
117
+ it('should list token values "as is"', () => {
118
+ expect(new CmcdObjectType(CmcdObjectTypeToken.VideoOnly).keyValuePairToString()).toEqual('ot=v');
119
+ expect(new CmcdObjectType(CmcdObjectTypeToken.AudioOnly).keyValuePairToString()).toEqual('ot=a');
120
+ expect(new CmcdObjectType(CmcdObjectTypeToken.CaptionOrSubtitle).keyValuePairToString()).toEqual('ot=c');
121
+ expect(
122
+ new CmcdObjectType(CmcdObjectTypeToken.CryptographicKeyOrLicenseOrCertificate).keyValuePairToString()
123
+ ).toEqual('ot=k');
124
+ expect(new CmcdObjectType(CmcdObjectTypeToken.InitSegment).keyValuePairToString()).toEqual('ot=i');
125
+ expect(new CmcdObjectType(CmcdObjectTypeToken.ManifestOrPlaylistTextFile).keyValuePairToString()).toEqual('ot=m');
126
+ expect(new CmcdObjectType(CmcdObjectTypeToken.MuxedVideoAudio).keyValuePairToString()).toEqual('ot=av');
127
+ expect(new CmcdObjectType(CmcdObjectTypeToken.Other).keyValuePairToString()).toEqual('ot=o');
128
+ expect(new CmcdObjectType(CmcdObjectTypeToken.TimedTextTrack).keyValuePairToString()).toEqual('ot=tt');
129
+ });
130
+
131
+ it('should round buffer length, deadline values to nearest 100ms', () => {
132
+ expect(new CmcdBufferLength(5452).keyValuePairToString()).toEqual('bl=5500');
133
+ expect(new CmcdBufferLength(5450).keyValuePairToString()).toEqual('bl=5500');
134
+ expect(new CmcdBufferLength(5432).keyValuePairToString()).toEqual('bl=5400');
135
+ expect(new CmcdDeadline(5452).keyValuePairToString()).toEqual('dl=5500');
136
+ expect(new CmcdDeadline(5450).keyValuePairToString()).toEqual('dl=5500');
137
+ expect(new CmcdDeadline(5432).keyValuePairToString()).toEqual('dl=5400');
138
+ });
139
+
140
+ it('should round measured throughput values to nearest 100kbps', () => {
141
+ expect(new CmcdMeasuredThroughput(87654).keyValuePairToString()).toEqual('mtp=87700');
142
+ expect(new CmcdMeasuredThroughput(87650).keyValuePairToString()).toEqual('mtp=87700');
143
+ expect(new CmcdMeasuredThroughput(87649).keyValuePairToString()).toEqual('mtp=87600');
144
+ });
145
+
146
+ it('should remove playback rate if value is 1', () => {
147
+ expect(new CmcdPlaybackRate(1).keyValuePairToString()).toEqual('');
148
+ });
149
+
150
+ it('should add playback rate if value is not 1', () => {
151
+ expect(new CmcdPlaybackRate(1.08).keyValuePairToString()).toEqual('pr=1.08');
152
+ expect(new CmcdPlaybackRate(0).keyValuePairToString()).toEqual('pr=0');
153
+ expect(new CmcdPlaybackRate(2.52).keyValuePairToString()).toEqual('pr=2.52');
154
+ });
155
+
156
+ it('should remove CMCD version if value is 1', () => {
157
+ expect(new CmcdVersion(CmcdVersionNumbers.v1).keyValuePairToString()).toEqual('');
158
+ });
159
+ });
160
+
161
+ describe('CMCD Spec Examples', () => {
162
+ // Examples from CMCD v1 spec Section 6 taken as test cases
163
+
164
+ it('Section 6, Example #1:', () => {
165
+ const cmcdObjects = [new CmcdSessionId('6e2fb550-c457-11e9-bb97-0800200c9a66')];
166
+ expect(cmcdDataToUrlParameter(cmcdObjects)).toEqual('CMCD=sid%3D%226e2fb550-c457-11e9-bb97-0800200c9a66%22');
167
+ expect(cmcdDataToHeader(cmcdObjects)).toEqual({
168
+ 'CMCD-Session': 'sid="6e2fb550-c457-11e9-bb97-0800200c9a66"',
169
+ });
170
+ });
171
+
172
+ it('Section 6, Example #2:', () => {
173
+ const cmcdObjects = [
174
+ new CmcdEncodedBitrate(3200),
175
+ new CmcdBufferStarvation(true),
176
+ new CmcdObjectDuration(4004),
177
+ new CmcdMeasuredThroughput(25432),
178
+ new CmcdObjectType(CmcdObjectTypeToken.VideoOnly),
179
+ new CmcdRequestedMaximumThroughput(15000),
180
+ new CmcdSessionId('6e2fb550-c457-11e9-bb97-0800200c9a66'),
181
+ new CmcdTopBitrate(6000),
182
+ ];
183
+
184
+ expect(cmcdDataToUrlParameter(cmcdObjects)).toEqual(
185
+ 'CMCD=br%3D3200%2Cbs%2Cd%3D4004%2Cmtp%3D25400%2Cot%3Dv%2Crtp%3D15000%2Csid%3D%226e2fb550-c457-11e9-bb97-0800200c9a66%22%2Ctb%3D6000'
186
+ );
187
+ expect(cmcdDataToHeader(cmcdObjects)).toEqual({
188
+ 'CMCD-Request': 'mtp=25400',
189
+ 'CMCD-Object': 'br=3200,d=4004,ot=v,tb=6000',
190
+ 'CMCD-Status': 'bs,rtp=15000',
191
+ 'CMCD-Session': 'sid="6e2fb550-c457-11e9-bb97-0800200c9a66"',
192
+ });
193
+ });
194
+
195
+ it('Section 6, Example #3:', () => {
196
+ const cmcdObjects = [
197
+ new CmcdBufferStarvation(true),
198
+ new CmcdRequestedMaximumThroughput(15000),
199
+ new CmcdSessionId('6e2fb550-c457-11e9-bb97-0800200c9a66'),
200
+ ];
201
+ // Small mistake in the CMCD spec where 'bs' was truncated to 'b' in this query arg example
202
+ expect(cmcdDataToUrlParameter(cmcdObjects)).toEqual(
203
+ 'CMCD=bs%2Crtp%3D15000%2Csid%3D%226e2fb550-c457-11e9-bb97-0800200c9a66%22'
204
+ );
205
+ expect(cmcdDataToHeader(cmcdObjects)).toEqual({
206
+ 'CMCD-Status': 'bs,rtp=15000',
207
+ 'CMCD-Session': 'sid="6e2fb550-c457-11e9-bb97-0800200c9a66"',
208
+ });
209
+ });
210
+
211
+ it('Section 6, Example #4:', () => {
212
+ const cmcdObjects = [new CmcdBufferStarvation(true), new CmcdStartup(true)];
213
+ expect(cmcdDataToUrlParameter(cmcdObjects)).toEqual('CMCD=bs%2Csu');
214
+ expect(cmcdDataToHeader(cmcdObjects)).toEqual({
215
+ 'CMCD-Status': 'bs',
216
+ 'CMCD-Request': 'su',
217
+ });
218
+ });
219
+
220
+ it('Section 6, Example #5:', () => {
221
+ const cmcdObjects = [
222
+ new CmcdObjectDuration(4004),
223
+ new CmcdCustomKey('com.example-myNumericKey', 500),
224
+ new CmcdCustomKey('com.example-myStringKey', 'myStringValue'),
225
+ ];
226
+ expect(cmcdDataToUrlParameter(cmcdObjects)).toEqual(
227
+ 'CMCD=d%3D4004%2Ccom.example-myNumericKey%3D500%2Ccom.example-myStringKey%3D%22myStringValue%22'
228
+ );
229
+ expect(cmcdDataToHeader(cmcdObjects)).toEqual({
230
+ 'CMCD-Object': 'd=4004',
231
+ 'CMCD-Session': 'com.example-myNumericKey=500,com.example-myStringKey="myStringValue"',
232
+ });
233
+ });
234
+
235
+ it('Section 6, Example #6:', () => {
236
+ const cmcdObjects = [
237
+ new CmcdNextObjectRequest('..%2F300kbps%2Fsegment35.m4v'),
238
+ new CmcdSessionId('6e2fb550-c457-11e9-bb97-0800200c9a66'),
239
+ ];
240
+ expect(cmcdDataToUrlParameter(cmcdObjects)).toEqual(
241
+ 'CMCD=nor%3D%22..%252F300kbps%252Fsegment35.m4v%22%2Csid%3D%226e2fb550-c457-11e9-bb97-0800200c9a66%22'
242
+ );
243
+ expect(cmcdDataToHeader(cmcdObjects)).toEqual({
244
+ 'CMCD-Session': 'sid="6e2fb550-c457-11e9-bb97-0800200c9a66"',
245
+ 'CMCD-Request': 'nor="..%2F300kbps%2Fsegment35.m4v"',
246
+ });
247
+ });
248
+
249
+ it('Section 6, Example #7:', () => {
250
+ const cmcdObjects = [
251
+ new CmcdNextRangeRequest('12323-48763'),
252
+ new CmcdSessionId('6e2fb550-c457-11e9-bb97-0800200c9a66'),
253
+ ];
254
+ expect(cmcdDataToUrlParameter(cmcdObjects)).toEqual(
255
+ 'CMCD=nrr%3D%2212323-48763%22%2Csid%3D%226e2fb550-c457-11e9-bb97-0800200c9a66%22'
256
+ );
257
+ expect(cmcdDataToHeader(cmcdObjects)).toEqual({
258
+ 'CMCD-Session': 'sid="6e2fb550-c457-11e9-bb97-0800200c9a66"',
259
+ 'CMCD-Request': 'nrr="12323-48763"',
260
+ });
261
+ });
262
+
263
+ it('Section 6, Example #8:', () => {
264
+ const cmcdObjects = [
265
+ new CmcdNextObjectRequest('..%2F300kbps%2Ftrack.m4v'),
266
+ new CmcdNextRangeRequest('12323-48763'),
267
+ new CmcdSessionId('6e2fb550-c457-11e9-bb97-0800200c9a66'),
268
+ ];
269
+ expect(cmcdDataToUrlParameter(cmcdObjects)).toEqual(
270
+ 'CMCD=nor%3D%22..%252F300kbps%252Ftrack.m4v%22%2Cnrr%3D%2212323-48763%22%2Csid%3D%226e2fb550-c457-11e9-bb97-0800200c9a66%22'
271
+ );
272
+ expect(cmcdDataToHeader(cmcdObjects)).toEqual({
273
+ 'CMCD-Session': 'sid="6e2fb550-c457-11e9-bb97-0800200c9a66"',
274
+ 'CMCD-Request': 'nor="..%2F300kbps%2Ftrack.m4v",nrr="12323-48763"',
275
+ });
276
+ });
277
+
278
+ it('Section 6, Example #9:', () => {
279
+ const cmcdObjects = [
280
+ new CmcdBufferLength(21300),
281
+ new CmcdEncodedBitrate(3200),
282
+ new CmcdBufferStarvation(true),
283
+ new CmcdContentId('faec5fc2-ac30-11ea-bb37-0242ac130002'),
284
+ new CmcdObjectDuration(4004),
285
+ new CmcdDeadline(18500),
286
+ new CmcdMeasuredThroughput(48100),
287
+ new CmcdNextObjectRequest('..%2F300kbps%2Ftrack.m4v'),
288
+ new CmcdNextRangeRequest('12323-48763'),
289
+ new CmcdObjectType(CmcdObjectTypeToken.VideoOnly),
290
+ new CmcdPlaybackRate(1.08),
291
+ new CmcdRequestedMaximumThroughput(12000),
292
+ new CmcdStreamingFormat(CmcdStreamingFormatToken.MpegDash),
293
+ new CmcdSessionId('6e2fb550-c457-11e9-bb97-0800200c9a66'),
294
+ new CmcdStreamType(CmcdStreamTypeToken.Vod),
295
+ new CmcdStartup(true),
296
+ new CmcdTopBitrate(6000),
297
+ new CmcdVersion(1),
298
+ ];
299
+ expect(cmcdDataToUrlParameter(cmcdObjects)).toEqual(
300
+ 'CMCD=bl%3D21300%2Cbr%3D3200%2Cbs%2Ccid%3D%22faec5fc2-ac30-11ea-bb37-0242ac130002%22%2Cd%3D4004%2Cdl%3D18500%2Cmtp%3D48100%2Cnor%3D%22..%252F300kbps%252Ftrack.m4v%22%2Cnrr%3D%2212323-48763%22%2Cot%3Dv%2Cpr%3D1.08%2Crtp%3D12000%2Csf%3Dd%2Csid%3D%226e2fb550-c457-11e9-bb97-0800200c9a66%22%2Cst%3Dv%2Csu%2Ctb%3D6000'
301
+ );
302
+ expect(cmcdDataToHeader(cmcdObjects)).toEqual({
303
+ 'CMCD-Request': 'bl=21300,dl=18500,mtp=48100,nor="..%2F300kbps%2Ftrack.m4v",nrr="12323-48763",su',
304
+ 'CMCD-Object': 'br=3200,d=4004,ot=v,tb=6000',
305
+ 'CMCD-Status': 'bs,rtp=12000',
306
+ 'CMCD-Session':
307
+ 'cid="faec5fc2-ac30-11ea-bb37-0242ac130002",pr=1.08,sf=d,sid="6e2fb550-c457-11e9-bb97-0800200c9a66",st=v',
308
+ });
309
+ });
310
+ });
311
+ });
@@ -0,0 +1,173 @@
1
+ import { describe, beforeEach, it, expect, jest } from '@jest/globals';
2
+ import { HttpRequest, HttpRequestType, PlayerAPI } from 'bitmovin-player';
3
+ import { CmcdIntegration, CmcdConfig } from '../../src/ts/CmcdIntegration';
4
+ import { cmcdDataToHeader, cmcdDataToUrlParameter } from '../../src/ts/Cmcd';
5
+
6
+ // Jest Mocking for helper functions
7
+ jest.mock('../../src/ts/Cmcd', () => ({
8
+ CmcdVersionNumbers: {
9
+ v1: 1,
10
+ },
11
+ CmcdStreamTypeToken: {
12
+ Live: 'live',
13
+ Vod: 'vod',
14
+ },
15
+ CmcdObjectTypeToken: {
16
+ AudioOnly: 'a',
17
+ VideoOnly: 'v',
18
+ ManifestOrPlaylistTextFile: 'm',
19
+ InitSegment: 'i',
20
+ CaptionOrSubtitle: 'c',
21
+ CryptographicKeyOrLicenseOrCertificate: 'k',
22
+ MuxedVideoAudio: 'av',
23
+ Other: 'o',
24
+ TimedTextTrack: 'tt',
25
+ },
26
+ CmcdStreamingFormatToken: {
27
+ Hls: 'h',
28
+ MpegDash: 'd',
29
+ Smooth: 's',
30
+ Other: 'o',
31
+ },
32
+ CmcdKeysToken: {
33
+ EncodedBitrate: 'br',
34
+ ObjectDuration: 'd',
35
+ Startup: 'su',
36
+ },
37
+ CmcdVersion: jest.fn(),
38
+ CmcdStreamType: jest.fn(),
39
+ CmcdPlaybackRate: jest.fn(),
40
+ CmcdObjectType: jest.fn(),
41
+ CmcdStreamingFormat: jest.fn(),
42
+ CmcdStartup: jest.fn(),
43
+ CmcdBufferStarvation: jest.fn(),
44
+ CmcdBufferLength: jest.fn(),
45
+ CmcdContentId: jest.fn(),
46
+ CmcdSessionId: jest.fn(),
47
+ CmcdEncodedBitrate: jest.fn(),
48
+ CmcdDeadline: jest.fn(),
49
+ CmcdTopBitrate: jest.fn(),
50
+ cmcdDataToHeader: jest.fn(),
51
+ cmcdDataToUrlParameter: jest.fn(),
52
+ }));
53
+
54
+ describe('CmcdIntegration', () => {
55
+ let cmcdIntegration: CmcdIntegration;
56
+ let config: CmcdConfig;
57
+ let mockPlayer: PlayerAPI;
58
+
59
+ beforeEach(() => {
60
+ config = {
61
+ sessionId: 'test-session',
62
+ contentId: 'test-content',
63
+ useQueryArgs: true,
64
+ customKeys: [],
65
+ };
66
+
67
+ cmcdIntegration = new CmcdIntegration(config);
68
+
69
+ mockPlayer = {
70
+ isLive: jest.fn().mockReturnValue(false),
71
+ getPlaybackSpeed: jest.fn().mockReturnValue(1),
72
+ buffer: {
73
+ getLevel: jest.fn().mockReturnValue({
74
+ targetLevel: 10,
75
+ level: 5,
76
+ }),
77
+ },
78
+ getAvailableAudioQualities: jest
79
+ .fn()
80
+ .mockReturnValue([{ bitrate: 64000 }, { bitrate: 128000 }, { bitrate: 256000 }]),
81
+ getAvailableVideoQualities: jest
82
+ .fn()
83
+ .mockReturnValue([{ bitrate: 500000 }, { bitrate: 800000 }, { bitrate: 1200000 }]),
84
+ getAvailableSegments: jest.fn(),
85
+ isStalled: jest.fn().mockReturnValue(false),
86
+ exports: {
87
+ HttpRequestType: {
88
+ MEDIA_AUDIO: 'media/audio',
89
+ MEDIA_VIDEO: 'media/video',
90
+ MANIFEST_HLS_MASTER: 'manifest/hls/master',
91
+ },
92
+ PlayerEvent: {
93
+ StallStarted: 'stallstarted',
94
+ StallEnded: 'stallended',
95
+ Seek: 'seek',
96
+ Seeked: 'seeked',
97
+ TimeShift: 'timeshift',
98
+ TimeShifted: 'timeshifted',
99
+ },
100
+ BufferType: {
101
+ ForwardDuration: 'forwardduration',
102
+ BackwardDuration: 'backwardduration',
103
+ },
104
+ MediaType: {
105
+ Video: 'video',
106
+ Audio: 'audio',
107
+ },
108
+ },
109
+ on: jest.fn(),
110
+ } as unknown as PlayerAPI;
111
+
112
+ cmcdIntegration.setPlayer(mockPlayer);
113
+ });
114
+
115
+ describe('preprocessHttpRequest', () => {
116
+ it('should add CMCD data as query parameters when useQueryArgs is true', async () => {
117
+ const request: HttpRequest = {
118
+ credentials: undefined,
119
+ method: undefined,
120
+ responseType: undefined,
121
+ url: 'https://example.com/manifest.m3u8',
122
+ headers: {},
123
+ };
124
+
125
+ (cmcdDataToUrlParameter as jest.Mock).mockReturnValue('CMCD=mockData');
126
+
127
+ const processedRequest = await cmcdIntegration.preprocessHttpRequest(
128
+ HttpRequestType.MANIFEST_HLS_MASTER,
129
+ request
130
+ );
131
+
132
+ expect(processedRequest.url).toBe('https://example.com/manifest.m3u8?CMCD=mockData');
133
+ expect(cmcdDataToUrlParameter).toHaveBeenCalled();
134
+ });
135
+
136
+ it('should remove existing CMCD query parameters before adding new ones', async () => {
137
+ const request: HttpRequest = {
138
+ credentials: undefined,
139
+ method: undefined,
140
+ responseType: undefined,
141
+ url: 'https://example.com/manifest.m3u8?CMCD=oldData',
142
+ headers: {},
143
+ };
144
+
145
+ (cmcdDataToUrlParameter as jest.Mock).mockReturnValue('CMCD=newData');
146
+
147
+ const processedRequest = await cmcdIntegration.preprocessHttpRequest(HttpRequestType.MEDIA_VIDEO, request);
148
+
149
+ expect(processedRequest.url).toBe('https://example.com/manifest.m3u8?CMCD=newData');
150
+ expect(cmcdDataToUrlParameter).toHaveBeenCalled();
151
+ });
152
+
153
+ it('should add CMCD data as headers when useQueryArgs is false', async () => {
154
+ cmcdIntegration = new CmcdIntegration({ ...config, useQueryArgs: false });
155
+ cmcdIntegration.setPlayer(mockPlayer);
156
+
157
+ const request: HttpRequest = {
158
+ credentials: undefined,
159
+ method: undefined,
160
+ responseType: undefined,
161
+ url: 'https://example.com/manifest.m3u8?',
162
+ headers: {},
163
+ };
164
+
165
+ (cmcdDataToHeader as jest.Mock).mockReturnValue({ 'CMCD-Header': 'mockData' });
166
+
167
+ const processedRequest = await cmcdIntegration.preprocessHttpRequest(HttpRequestType.MEDIA_VIDEO, request);
168
+
169
+ expect(processedRequest.headers).toEqual({ 'CMCD-Header': 'mockData' });
170
+ expect(cmcdDataToHeader).toHaveBeenCalled();
171
+ });
172
+ });
173
+ });