-
Notifications
You must be signed in to change notification settings - Fork 51
/
Copy pathindex.ts
1499 lines (1361 loc) · 59 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import type { ValueOf, PlaybackCore, MuxMediaProps, MuxMediaPropsInternal, MuxMediaPropTypes } from './types';
import mux, { ErrorEvent } from 'mux-embed';
import Hls from './hls';
import type { HlsInterface } from './hls';
import type { ErrorData, HlsConfig } from 'hls.js';
import { MediaError, MuxErrorCategory, MuxErrorCode, errorCategoryToTokenNameOrPrefix } from './errors';
import { setupAutoplay } from './autoplay';
import { setupPreload } from './preload';
import { setupMediaTracks } from './media-tracks';
import {
setupTextTracks,
addTextTrack,
removeTextTrack,
getTextTrack,
addCuePoints,
getCuePoints,
getActiveCuePoint,
setupCuePoints,
addChapters,
getChapters,
getActiveChapter,
setupChapters,
} from './text-tracks';
import { getStartDate, getCurrentPdt } from './pdt';
import {
inSeekableRange,
toPlaybackIdParts,
getType,
toStreamTypeFromPlaylistType,
toTargetLiveWindowFromPlaylistType,
addEventListenerWithTeardown,
i18n,
parseJwt,
} from './util';
import { StreamTypes, PlaybackTypes, ExtensionMimeTypeMap, CmcdTypes, HlsPlaylistTypes, MediaTypes } from './types';
import { getErrorFromResponse, MuxJWTAud } from './request-errors';
import MinCapLevelController from './min-cap-level-controller';
// import { MediaKeySessionContext } from 'hls.js';
export {
mux,
Hls,
MediaError,
MuxErrorCategory,
MuxErrorCode,
errorCategoryToTokenNameOrPrefix,
MuxJWTAud,
addTextTrack,
removeTextTrack,
getTextTrack,
addCuePoints,
getCuePoints,
getActiveCuePoint,
setupCuePoints,
addChapters,
getChapters,
getActiveChapter,
setupChapters,
getStartDate,
getCurrentPdt,
toPlaybackIdParts,
i18n,
parseJwt,
};
export * from './types';
const DRMType = {
FAIRPLAY: 'fairplay',
PLAYREADY: 'playready',
WIDEVINE: 'widevine',
} as const;
type DRMTypeValue = (typeof DRMType)[keyof typeof DRMType];
export const toDRMTypeFromKeySystem = (keySystem: string): DRMTypeValue | undefined => {
if (keySystem.includes('fps')) return DRMType.FAIRPLAY;
if (keySystem.includes('playready')) return DRMType.PLAYREADY;
if (keySystem.includes('widevine')) return DRMType.WIDEVINE;
return undefined;
};
export const getMediaPlaylistLinesFromMultivariantPlaylistSrc = async (src: string) => {
return fetch(src)
.then((resp) => {
if (resp.status !== 200) {
return Promise.reject(resp);
}
return resp.text();
})
.then((multivariantPlaylistStr) => {
const mediaPlaylistUrl = multivariantPlaylistStr.split('\n').find((_line, idx, lines) => {
return idx && lines[idx - 1].startsWith('#EXT-X-STREAM-INF');
}) as string;
return fetch(mediaPlaylistUrl)
.then((resp) => {
if (resp.status !== 200) {
return Promise.reject(resp);
}
return resp.text();
})
.then((mediaPlaylistStr) => mediaPlaylistStr.split('\n'));
});
};
export const getStreamInfoFromPlaylistLines = (playlistLines: string[]) => {
const typeLine = playlistLines.find((line) => line.startsWith('#EXT-X-PLAYLIST-TYPE')) ?? '';
const playlistType = typeLine.split(':')[1]?.trim() as HlsPlaylistTypes;
const streamType = toStreamTypeFromPlaylistType(playlistType);
const targetLiveWindow = toTargetLiveWindowFromPlaylistType(playlistType);
// Computation of the live edge start offset per media-ui-extensions proposal. See: https://github.com/video-dev/media-ui-extensions/blob/main/proposals/0007-live-edge.md#recommended-computation-for-rfc8216bis12-aka-hls (CJP)
let liveEdgeStartOffset = undefined;
if (streamType === StreamTypes.LIVE) {
// Required if playlist contains one or more EXT-X-PART tags. See: https://datatracker.ietf.org/doc/html/draft-pantos-hls-rfc8216bis-12#section-4.4.3.7 (CJP)
const partInfLine = playlistLines.find((line) => line.startsWith('#EXT-X-PART-INF'));
const lowLatency = !!partInfLine;
if (lowLatency) {
// The EXT-X-PART-INF only has one in-spec named attribute, PART-TARGET, which is required,
// so parsing & casting presumptuously here. See spec link above for more info. (CJP)
const partTarget = +partInfLine.split(':')[1].split('=')[1];
liveEdgeStartOffset = partTarget * 2;
} else {
// This is required for all media playlists. See: https://datatracker.ietf.org/doc/html/draft-pantos-hls-rfc8216bis-12#section-4.4.3.1 (CJP)
const targetDurationLine = playlistLines.find((line) => line.startsWith('#EXT-X-TARGETDURATION')) as string;
// EXT-X-TARGETDURATION has exactly one unnamed attribute that represents the target duration value, which is required,
// so parsing and casting presumptuously here. See spec link above for more info. (CJP)
const targetDurationValue = targetDurationLine?.split(':')?.[1];
// NOTE: Defaulting here and using optional chaining above since some people are seeing RTEs on iPhones under edge cases.
// Identifying root cause would be ideal, but this will at least avoid the RTE. (CJP)
const targetDuration = +(targetDurationValue ?? 6);
liveEdgeStartOffset = targetDuration * 3;
}
}
return {
streamType,
targetLiveWindow,
liveEdgeStartOffset,
};
};
export const getStreamInfoFromSrcAndType = async (src: string, type?: MediaTypes | '') => {
if (type === ExtensionMimeTypeMap.MP4) {
return {
streamType: StreamTypes.ON_DEMAND,
targetLiveWindow: Number.NaN,
liveEdgeStartOffset: undefined,
};
}
if (type === ExtensionMimeTypeMap.M3U8) {
const playlistLines = await getMediaPlaylistLinesFromMultivariantPlaylistSrc(src);
return getStreamInfoFromPlaylistLines(playlistLines);
}
// Unknown or undefined type.
console.error(`Media type ${type} is an unrecognized or unsupported type for src ${src}.`);
return {
streamType: undefined,
targetLiveWindow: undefined,
liveEdgeStartOffset: undefined,
};
};
export const updateStreamInfoFromSrc = async (
src: string,
mediaEl: HTMLMediaElement,
type: MediaTypes | '' = getType({ src })
) => {
const { streamType, targetLiveWindow, liveEdgeStartOffset } = await getStreamInfoFromSrcAndType(src, type);
(muxMediaState.get(mediaEl) ?? {}).liveEdgeStartOffset = liveEdgeStartOffset;
(muxMediaState.get(mediaEl) ?? {}).targetLiveWindow = targetLiveWindow;
mediaEl.dispatchEvent(new CustomEvent('targetlivewindowchange', { composed: true, bubbles: true }));
(muxMediaState.get(mediaEl) ?? {}).streamType = streamType;
mediaEl.dispatchEvent(new CustomEvent('streamtypechange', { composed: true, bubbles: true }));
};
export const getStreamInfoFromHlsjsLevelDetails = (levelDetails: any) => {
const playlistType: HlsPlaylistTypes = levelDetails.type as HlsPlaylistTypes;
const streamType = toStreamTypeFromPlaylistType(playlistType);
const targetLiveWindow = toTargetLiveWindowFromPlaylistType(playlistType);
let liveEdgeStartOffset = undefined;
const lowLatency = !!levelDetails.partList?.length;
if (streamType === StreamTypes.LIVE) {
liveEdgeStartOffset = lowLatency ? levelDetails.partTarget * 2 : levelDetails.targetduration * 3;
}
return {
streamType,
targetLiveWindow,
liveEdgeStartOffset,
lowLatency,
};
};
export const updateStreamInfoFromHlsjsLevelDetails = (
levelDetails: any,
mediaEl: HTMLMediaElement,
hls: Pick<Hls, 'config' | 'userConfig' | 'liveSyncPosition'>
) => {
const { streamType, targetLiveWindow, liveEdgeStartOffset, lowLatency } =
getStreamInfoFromHlsjsLevelDetails(levelDetails);
if (streamType === StreamTypes.LIVE) {
// Update hls.js config for live/ll-live
if (lowLatency) {
hls.config.backBufferLength = hls.userConfig.backBufferLength ?? 4;
hls.config.maxFragLookUpTolerance = hls.userConfig.maxFragLookUpTolerance ?? 0.001;
// For ll-hls, ensure that up switches are weighted the same as down switches to mitigate
// cases of getting stuck at lower bitrates.
hls.config.abrBandWidthUpFactor = hls.userConfig.abrBandWidthUpFactor ?? hls.config.abrBandWidthFactor;
} else {
hls.config.backBufferLength = hls.userConfig.backBufferLength ?? 8;
}
// Proxy `seekable.end()` to constrain based on rules in
// https://github.com/video-dev/media-ui-extensions/blob/main/proposals/0007-live-edge.md#property-constraint-on-htmlmediaelementseekableend-to-model-seekable-live-edge
const seekable: TimeRanges = Object.freeze({
get length() {
return mediaEl.seekable.length;
},
start(index: number) {
return mediaEl.seekable.start(index);
},
end(index: number) {
// Defer to native seekable for:
// 1) "out of range" cases
// 2) "finite duration" media (whether live/"DVR" that has ended or on demand)
if (index > this.length || index < 0 || Number.isFinite(mediaEl.duration)) return mediaEl.seekable.end(index);
// Otherwise rely on the live sync position (but still fall back to native seekable when nullish)
return hls.liveSyncPosition ?? mediaEl.seekable.end(index);
},
});
(muxMediaState.get(mediaEl) ?? {}).seekable = seekable;
}
(muxMediaState.get(mediaEl) ?? {}).liveEdgeStartOffset = liveEdgeStartOffset;
(muxMediaState.get(mediaEl) ?? {}).targetLiveWindow = targetLiveWindow;
mediaEl.dispatchEvent(new CustomEvent('targetlivewindowchange', { composed: true, bubbles: true }));
(muxMediaState.get(mediaEl) ?? {}).streamType = streamType;
mediaEl.dispatchEvent(new CustomEvent('streamtypechange', { composed: true, bubbles: true }));
};
declare global {
interface NavigatorUAData {
platform: string;
mobile: boolean;
brands: Array<{ brand: string; version: string }>;
}
interface Navigator {
userAgentData?: NavigatorUAData;
}
}
const userAgentStr = globalThis?.navigator?.userAgent ?? '';
const userAgentPlatform = globalThis?.navigator?.userAgentData?.platform ?? '';
// NOTE: Our primary *goal* with this is to detect "non-Apple-OS" platforms which may also support
// native HLS playback. Our primary concern with any check for this is "false negatives" where we
// identify an "Apple-OS" as a "non-Apple-OS". As such, instead of having logic to attempt to identify
// "!isAppleOS", we opt to target known platforms that can support both native playback and MSE/hls.js.
// For now, these are "Android or Android-like" platforms. If we end up matching platforms other than
// Android (or e.g. forks thereof), this is fine so long as it doesn't include Apple-OS platforms.
// Below are two strategies:
// 1. UA string parsing - here, we're extra cautious to only match if the UA string explicitly includes 'android'.
// This is prone to false negatives (aka "Android or Android-like" platforms that yield false), since
// detection using UA strings is intentionally and notoriously unreliable (See: https://developer.mozilla.org/en-US/docs/Web/HTTP/Browser_detection_using_the_user_agent)
// and Google is even officially attempting to lock this down even more for security and privacy reasons
// (See: https://developers.google.com/privacy-sandbox/blog/user-agent-reduction-android-model-and-version)
// 2. userAgentData.platform checking - here, we're matching either 'android' or 'x11', and could add more matches in the future
// While still prone to false negatives, we can be a bit more aggressive with matches here for a few reasons.
// First, navigator.userAgentData is still experimental, is only supported on a subset of Chromium browsers,
// and neither Mozilla nor Webkit have even established an official browser support position. In other words,
// Apple-OS Safari and even other Apple-OS browsers (including Chrome) will typically not even support this
// feature, and, if and when they do, the purpose of this new API is to avoid obfuscatory information, so
// we should be able to better trust userAgentData.platform to not result in erroneous matches.
const isAndroidLike =
userAgentStr.toLowerCase().includes('android') ||
['x11', 'android'].some((platformStr) => userAgentPlatform.toLowerCase().includes(platformStr));
// NOTE: Exporting for testing
export const muxMediaState: WeakMap<
HTMLMediaElement,
Partial<MuxMediaProps> & { seekable?: TimeRanges; liveEdgeStartOffset?: number }
> = new WeakMap();
const MUX_VIDEO_DOMAIN = 'mux.com';
const MSE_SUPPORTED = Hls.isSupported?.();
const DEFAULT_PREFER_MSE = isAndroidLike;
export const generatePlayerInitTime = () => {
return mux.utils.now();
};
export const generateUUID = mux.utils.generateUUID;
type MuxVideoURLProps = Partial<
Pick<
MuxMediaPropTypes,
| 'playbackId'
| 'customDomain'
| 'maxResolution'
| 'minResolution'
| 'renditionOrder'
| 'programStartTime'
| 'programEndTime'
| 'assetStartTime'
| 'assetEndTime'
| 'tokens'
| 'playbackToken'
| 'extraSourceParams'
>
>;
export const toMuxVideoURL = ({
playbackId: playbackIdWithParams,
customDomain: domain = MUX_VIDEO_DOMAIN,
maxResolution,
minResolution,
renditionOrder,
programStartTime,
programEndTime,
assetStartTime,
assetEndTime,
// Normalizes different ways of providing playback token
playbackToken,
tokens: { playback: token = playbackToken } = {},
extraSourceParams = {},
}: MuxVideoURLProps = {}) => {
if (!playbackIdWithParams) return undefined;
// Normalizes different ways of providing playback id
const [playbackId, queryPart = ''] = toPlaybackIdParts(playbackIdWithParams);
const url = new URL(`https://stream.${domain}/${playbackId}.m3u8${queryPart}`);
/*
* All identified query params here can only be added to public
* playback IDs. In order to use these features with signed URLs
* the query param must be added to the signing token.
*
* */
if (token || url.searchParams.has('token')) {
url.searchParams.forEach((_, key) => {
if (key != 'token') url.searchParams.delete(key);
});
if (token) url.searchParams.set('token', token);
} else {
if (maxResolution) {
url.searchParams.set('max_resolution', maxResolution);
}
if (minResolution) {
url.searchParams.set('min_resolution', minResolution);
if (maxResolution && +maxResolution.slice(0, -1) < +minResolution.slice(0, -1)) {
console.error(
'minResolution must be <= maxResolution',
'minResolution',
minResolution,
'maxResolution',
maxResolution
);
}
}
if (renditionOrder) {
url.searchParams.set('rendition_order', renditionOrder);
}
if (programStartTime) {
url.searchParams.set('program_start_time', `${programStartTime}`);
}
if (programEndTime) {
url.searchParams.set('program_end_time', `${programEndTime}`);
}
if (assetStartTime) {
url.searchParams.set('asset_start_time', `${assetStartTime}`);
}
if (assetEndTime) {
url.searchParams.set('asset_end_time', `${assetEndTime}`);
}
Object.entries(extraSourceParams).forEach(([k, v]) => {
if (v == undefined) return;
url.searchParams.set(k, v);
});
}
return url.toString();
};
const toPlaybackIdFromParameterized = (playbackIdWithParams: string | undefined) => {
if (!playbackIdWithParams) return undefined;
const [playbackId] = playbackIdWithParams.split('?');
// `|| undefined` is here to handle potential invalid cases
return playbackId || undefined;
};
export const toPlaybackIdFromSrc = (src: string | undefined) => {
if (!src || !src.startsWith('https://stream.')) return undefined;
const [playbackId] = new URL(src).pathname.slice(1).split('.m3u8');
// `|| undefined` is here to handle potential invalid cases
return playbackId || undefined;
};
const toVideoId = (props: Partial<MuxMediaPropsInternal>) => {
if (props?.metadata?.video_id) return props.metadata.video_id;
if (!isMuxVideoSrc(props)) return props.src;
return toPlaybackIdFromParameterized(props.playbackId) ?? toPlaybackIdFromSrc(props.src) ?? props.src;
};
export const getError = (mediaEl: HTMLMediaElement) => {
return muxMediaState.get(mediaEl)?.error;
};
export const getStreamType = (mediaEl: HTMLMediaElement) => {
return muxMediaState.get(mediaEl)?.streamType ?? StreamTypes.UNKNOWN;
};
export const getTargetLiveWindow = (mediaEl: HTMLMediaElement) => {
return muxMediaState.get(mediaEl)?.targetLiveWindow ?? Number.NaN;
};
export const getSeekable = (mediaEl: HTMLMediaElement) => {
return muxMediaState.get(mediaEl)?.seekable ?? mediaEl.seekable;
};
export const getLiveEdgeStart = (mediaEl: HTMLMediaElement) => {
const liveEdgeStartOffset = muxMediaState.get(mediaEl)?.liveEdgeStartOffset;
if (typeof liveEdgeStartOffset !== 'number') return Number.NaN;
const seekable = getSeekable(mediaEl);
// We aren't guaranteed that seekable is ready before invoking this, so handle that case.
if (!seekable.length) return Number.NaN;
return seekable.end(seekable.length - 1) - liveEdgeStartOffset;
};
const DEFAULT_ENDED_MOE = 0.034;
const isApproximatelyEqual = (x: number, y: number, moe = DEFAULT_ENDED_MOE) => Math.abs(x - y) <= moe;
const isApproximatelyGTE = (x: number, y: number, moe = DEFAULT_ENDED_MOE) => x > y || isApproximatelyEqual(x, y, moe);
export const isPseudoEnded = (mediaEl: HTMLMediaElement, moe = DEFAULT_ENDED_MOE) => {
return mediaEl.paused && isApproximatelyGTE(mediaEl.currentTime, mediaEl.duration, moe);
};
export const isStuckOnLastFragment = (
mediaEl: HTMLMediaElement,
hls?: Pick<
Hls,
/** Should we add audio fragments logic here, too? (CJP) */
// | 'audioTrack'
// | 'audioTracks'
'levels' | 'currentLevel'
>
) => {
if (!hls || !mediaEl.buffered.length) return undefined;
if (mediaEl.readyState > 2) return false;
const videoLevelDetails =
hls.currentLevel >= 0
? hls.levels?.[hls.currentLevel]?.details
: hls.levels.find((level) => !!level.details)?.details;
// Don't define for live streams (for now).
if (!videoLevelDetails || videoLevelDetails.live) return undefined;
const { fragments } = videoLevelDetails;
// Don't give a definitive true|false before we have no fragments (for now).
if (!fragments?.length) return undefined;
// Do a cheap check up front to see if we're close to the end.
// For more on TARGET_DURATION, see https://datatracker.ietf.org/doc/html/draft-pantos-hls-rfc8216bis-14#section-4.4.3.1 (CJP)
if (mediaEl.currentTime < mediaEl.duration - (videoLevelDetails.targetduration + 0.5)) return false;
const lastFragment = fragments[fragments.length - 1];
// We're not yet playing the last fragment, so we can't be stuck on it.
if (mediaEl.currentTime <= lastFragment.start) return false;
const lastFragmentMidpoint = lastFragment.start + lastFragment.duration / 2;
const lastBufferedStart = mediaEl.buffered.start(mediaEl.buffered.length - 1);
const lastBufferedEnd = mediaEl.buffered.end(mediaEl.buffered.length - 1);
// True if we've already buffered (half of) the last fragment
const lastFragmentInBuffer = lastFragmentMidpoint > lastBufferedStart && lastFragmentMidpoint < lastBufferedEnd;
// If we haven't buffered half already, assume we're still waiting to fetch+buffer the fragment, otherwise,
// since we already checked the ready state, this means we're stuck on the last segment, and should pretend we're ended!
return lastFragmentInBuffer;
};
export const getEnded = (
mediaEl: HTMLMediaElement,
hls?: Pick<
Hls,
/** Should we add audio fragments logic here, too? (CJP) */
// | 'audioTrack'
// | 'audioTracks'
'levels' | 'currentLevel'
>
) => {
// Since looping media never truly ends, don't apply pseudo-ended logic
// Also, trust when the HTMLMediaElement says we have ended (only apply pseudo-ended logic when it reports false)
if (mediaEl.ended || mediaEl.loop) return mediaEl.ended;
// Externalize conversion to boolean for "under-determined cases" here (See isStuckOnLastFragment() for details)
if (hls && !!isStuckOnLastFragment(mediaEl, hls)) return true;
return isPseudoEnded(mediaEl);
};
export const initialize = (props: Partial<MuxMediaPropsInternal>, mediaEl: HTMLMediaElement, core?: PlaybackCore) => {
// Automatically tear down previously initialized mux data & hls instance if it exists.
teardown(mediaEl, core);
// NOTE: metadata should never be nullish/nil. Adding here for type safety due to current type defs.
const { metadata = {} } = props;
const { view_session_id = generateUUID() } = metadata;
const video_id = toVideoId(props);
metadata.view_session_id = view_session_id;
metadata.video_id = video_id;
props.metadata = metadata;
// Used to signal DRM Type to Mux Data. See, e.g. `getDRMConfig()`
const drmTypeCb = (drmType?: string) => {
mediaEl.mux?.emit('hb', { view_drm_type: drmType });
};
props.drmTypeCb = drmTypeCb;
muxMediaState.set(mediaEl as HTMLMediaElement, {});
const nextHlsInstance = setupHls(props, mediaEl);
const setPreload = setupPreload(props as Pick<MuxMediaProps, 'preload' | 'src'>, mediaEl, nextHlsInstance);
setupMux(props, mediaEl, nextHlsInstance);
loadMedia(props, mediaEl, nextHlsInstance);
setupCuePoints(mediaEl);
setupChapters(mediaEl);
const setAutoplay = setupAutoplay(props as Pick<MuxMediaProps, 'autoplay'>, mediaEl, nextHlsInstance);
return {
engine: nextHlsInstance,
setAutoplay,
setPreload,
};
};
export const teardown = (mediaEl?: HTMLMediaElement | null, core?: PlaybackCore) => {
const hls = core?.engine;
if (hls) {
hls.detachMedia();
hls.destroy();
}
if (mediaEl?.mux && !mediaEl.mux.deleted) {
mediaEl.mux.destroy();
delete mediaEl.mux;
}
if (mediaEl) {
mediaEl.removeAttribute('src');
mediaEl.load();
mediaEl.removeEventListener('error', handleNativeError);
mediaEl.removeEventListener('error', handleInternalError);
mediaEl.removeEventListener('durationchange', seekInSeekableRange);
muxMediaState.delete(mediaEl);
mediaEl.dispatchEvent(new Event('teardown'));
}
};
/**
* Returns true if we should use native playback. e.g. progressive files (mp3, mp4, webm) or native HLS on Safari.
* We should use native playback for hls media sources if we
*
* a) can use native playback (excluding Android, it's MSE by default)
* b) not prefer to use MSE/hls.js if it's supported
*/
function useNative(
props: Partial<Pick<MuxMediaProps, 'preferPlayback' | 'type'>>,
mediaEl: Pick<HTMLMediaElement, 'canPlayType'>
) {
const type = getType(props);
const hlsType = type === ExtensionMimeTypeMap.M3U8;
if (!hlsType) return true;
const canUseNative = !type || (mediaEl.canPlayType(type) ?? true);
const { preferPlayback } = props;
const preferMse = preferPlayback === PlaybackTypes.MSE;
const preferNative = preferPlayback === PlaybackTypes.NATIVE;
const forceMse = MSE_SUPPORTED && (preferMse || DEFAULT_PREFER_MSE);
return canUseNative && (preferNative || !forceMse);
}
export const setupHls = (
props: Partial<
Pick<
MuxMediaPropsInternal,
'debug' | 'streamType' | 'type' | 'startTime' | 'metadata' | 'preferCmcd' | '_hlsConfig' | 'tokens' | 'drmTypeCb'
>
>,
mediaEl: Pick<HTMLMediaElement, 'canPlayType'>
) => {
const { debug, streamType, startTime: startPosition = -1, metadata, preferCmcd, _hlsConfig = {} } = props;
const type = getType(props);
const hlsType = type === ExtensionMimeTypeMap.M3U8;
const shouldUseNative = useNative(props, mediaEl);
// 1. if we are trying to play an hls media source create hls if we should be using it "under the hood"
if (hlsType && !shouldUseNative && MSE_SUPPORTED) {
const defaultConfig = {
backBufferLength: 30,
renderTextTracksNatively: false,
liveDurationInfinity: true,
capLevelToPlayerSize: true,
capLevelOnFPSDrop: true,
};
const streamTypeConfig = getStreamTypeConfig(streamType);
const drmConfig = getDRMConfig(props);
// NOTE: `metadata.view_session_id` & `metadata.video_id` are guaranteed here (CJP)
const cmcd =
preferCmcd !== CmcdTypes.NONE
? {
useHeaders: preferCmcd === CmcdTypes.HEADER,
sessionId: metadata?.view_session_id,
contentId: metadata?.video_id,
}
: undefined;
const hls = new Hls({
// Kind of like preload metadata, but causes spinner.
// autoStartLoad: false,
debug,
startPosition,
cmcd,
xhrSetup: (xhr, url) => {
if (preferCmcd && preferCmcd !== CmcdTypes.QUERY) return;
const urlObj = new URL(url);
if (!urlObj.searchParams.has('CMCD')) return;
const cmcdVal = (urlObj.searchParams.get('CMCD')?.split(',') ?? [])
.filter((cmcdKVStr) => cmcdKVStr.startsWith('sid') || cmcdKVStr.startsWith('cid'))
.join(',');
urlObj.searchParams.set('CMCD', cmcdVal);
xhr.open('GET', urlObj);
},
capLevelController: MinCapLevelController,
...defaultConfig,
...streamTypeConfig,
...drmConfig,
..._hlsConfig,
}) as HlsInterface;
return hls;
}
return undefined;
};
export const getStreamTypeConfig = (streamType?: ValueOf<StreamTypes>) => {
// for regular live videos, set backBufferLength to 8
if (streamType === StreamTypes.LIVE) {
const liveConfig = {
backBufferLength: 8,
};
return liveConfig;
}
return {};
};
export const getDRMConfig = (
props: Partial<Pick<MuxMediaPropsInternal, 'src' | 'playbackId' | 'tokens' | 'customDomain' | 'drmTypeCb'>>
): Partial<HlsConfig> => {
const {
tokens: { drm: drmToken } = {},
playbackId: playbackIdWithOptionalParams, // Since Mux Player typically sets `src` instead of `playbackId`, fall back to it here (CJP)
drmTypeCb,
} = props;
const playbackId = toPlaybackIdFromParameterized(playbackIdWithOptionalParams);
if (!drmToken || !playbackId) return {};
return {
emeEnabled: true,
drmSystems: {
'com.apple.fps': {
licenseUrl: toLicenseKeyURL(props, 'fairplay'),
serverCertificateUrl: toAppCertURL(props, 'fairplay'),
},
'com.widevine.alpha': {
licenseUrl: toLicenseKeyURL(props, 'widevine'),
},
'com.microsoft.playready': {
licenseUrl: toLicenseKeyURL(props, 'playready'),
},
},
requestMediaKeySystemAccessFunc: (keySystem, supportedConfigurations) => {
if (keySystem === 'com.widevine.alpha') {
supportedConfigurations = [
// NOTE: For widevine, by default we'll duplicate the key system configs but add L1-level
// security to the first set of duplicates so the key system will "prefer" that
// if/when available. (CJP)
// See, e.g.: https://developer.mozilla.org/en-US/docs/Web/API/Navigator/requestMediaKeySystemAccess#supportedconfigurations
...supportedConfigurations.map((mediaKeySystemConfig) => {
const videoCapabilities = mediaKeySystemConfig.videoCapabilities?.map((capability) => {
return {
...capability,
robustness: 'HW_SECURE_ALL',
};
});
return {
...mediaKeySystemConfig,
videoCapabilities,
};
}),
...supportedConfigurations,
];
}
return navigator.requestMediaKeySystemAccess(keySystem, supportedConfigurations).then((value) => {
const drmType = toDRMTypeFromKeySystem(keySystem);
drmTypeCb?.(drmType);
return value;
});
},
};
};
export const getAppCertificate = async (appCertificateUrl: string) => {
const resp = await fetch(appCertificateUrl);
if (resp.status !== 200) {
return Promise.reject(resp);
}
const body = await resp.arrayBuffer();
return body;
};
export const getLicenseKey = async (message: ArrayBuffer, licenseServerUrl: string) => {
const resp = await fetch(licenseServerUrl, {
method: 'POST',
headers: { 'Content-type': 'application/octet-stream' },
body: message,
});
if (resp.status !== 200) {
return Promise.reject(resp);
}
const keyBuffer = await resp.arrayBuffer();
return new Uint8Array(keyBuffer);
};
export const setupNativeFairplayDRM = (
props: Partial<Pick<MuxMediaPropsInternal, 'playbackId' | 'tokens' | 'playbackToken' | 'customDomain' | 'drmTypeCb'>>,
mediaEl: HTMLMediaElement
) => {
const onFpEncrypted = async (event: MediaEncryptedEvent) => {
try {
const initDataType = event.initDataType;
if (initDataType !== 'skd') {
console.error(`Received unexpected initialization data type "${initDataType}"`);
return;
}
if (!mediaEl.mediaKeys) {
const access = await navigator
.requestMediaKeySystemAccess('com.apple.fps', [
{
initDataTypes: [initDataType],
videoCapabilities: [{ contentType: 'application/vnd.apple.mpegurl', robustness: '' }],
distinctiveIdentifier: 'not-allowed',
persistentState: 'not-allowed',
sessionTypes: ['temporary'],
},
])
.then((value) => {
props.drmTypeCb?.(DRMType.FAIRPLAY);
return value;
})
.catch(() => {
const message = i18n(
'Cannot play DRM-protected content with current security configuration on this browser. Try playing in another browser.'
);
// Should we flag this as a business exception?
const mediaError = new MediaError(message, MediaError.MEDIA_ERR_ENCRYPTED, true);
mediaError.errorCategory = MuxErrorCategory.DRM;
mediaError.muxCode = MuxErrorCode.ENCRYPTED_UNSUPPORTED_KEY_SYSTEM;
saveAndDispatchError(mediaEl, mediaError);
});
if (!access) return;
const keys = await access.createMediaKeys();
try {
const fairPlayAppCert = await getAppCertificate(toAppCertURL(props, 'fairplay')).catch((errOrResp) => {
if (errOrResp instanceof Response) {
const mediaError = getErrorFromResponse(errOrResp, MuxErrorCategory.DRM, props);
console.error('mediaError', mediaError?.message, mediaError?.context);
if (mediaError) {
return Promise.reject(mediaError);
}
// NOTE: This should never happen. Adding for exhaustiveness (CJP).
return Promise.reject(new Error('Unexpected error in app cert request'));
}
return Promise.reject(errOrResp);
});
await keys.setServerCertificate(fairPlayAppCert).catch(() => {
const message = i18n(
'Your server certificate failed when attempting to set it. This may be an issue with a no longer valid certificate.'
);
const mediaError = new MediaError(message, MediaError.MEDIA_ERR_ENCRYPTED, true);
mediaError.errorCategory = MuxErrorCategory.DRM;
mediaError.muxCode = MuxErrorCode.ENCRYPTED_UPDATE_SERVER_CERT_FAILED;
return Promise.reject(mediaError);
});
// @ts-ignore
} catch (error: Error | MediaError) {
saveAndDispatchError(mediaEl, error);
return;
}
await mediaEl.setMediaKeys(keys);
}
const initData = event.initData;
if (initData == null) {
console.error(`Could not start encrypted playback due to missing initData in ${event.type} event`);
return;
}
const session = (mediaEl.mediaKeys as MediaKeys).createSession();
session.addEventListener('keystatuseschange', () => {
// recheck key statuses
// NOTE: As an improvement, we could also add checks for a status of 'expired' and
// attempt to renew the license here (CJP)
session.keyStatuses.forEach((mediaKeyStatus) => {
let mediaError;
if (mediaKeyStatus === 'internal-error') {
const message = i18n(
'The DRM Content Decryption Module system had an internal failure. Try reloading the page, upading your browser, or playing in another browser.'
);
mediaError = new MediaError(message, MediaError.MEDIA_ERR_ENCRYPTED, true);
mediaError.errorCategory = MuxErrorCategory.DRM;
mediaError.muxCode = MuxErrorCode.ENCRYPTED_CDM_ERROR;
} else if (mediaKeyStatus === 'output-restricted' || mediaKeyStatus === 'output-downscaled') {
const message = i18n(
'DRM playback is being attempted in an environment that is not sufficiently secure. User may see black screen.'
);
// NOTE: When encountered, this is a non-fatal error (though it's certainly interruptive of standard playback experience). (CJP)
mediaError = new MediaError(message, MediaError.MEDIA_ERR_ENCRYPTED, false);
mediaError.errorCategory = MuxErrorCategory.DRM;
mediaError.muxCode = MuxErrorCode.ENCRYPTED_OUTPUT_RESTRICTED;
}
if (mediaError) {
saveAndDispatchError(mediaEl, mediaError);
}
});
});
const message = await Promise.all([
session.generateRequest(initDataType, initData).catch(() => {
// eslint-disable-next-line no-shadow
const message = i18n(
'Failed to generate a DRM license request. This may be an issue with the player or your protected content.'
);
const mediaError = new MediaError(message, MediaError.MEDIA_ERR_ENCRYPTED, true);
mediaError.errorCategory = MuxErrorCategory.DRM;
mediaError.muxCode = MuxErrorCode.ENCRYPTED_GENERATE_REQUEST_FAILED;
saveAndDispatchError(mediaEl, mediaError);
}),
new Promise<MediaKeyMessageEvent['message']>((resolve) => {
session.addEventListener(
'message',
(messageEvent) => {
resolve(messageEvent.message);
},
{ once: true }
);
}),
]).then(([, messageEventMsg]) => messageEventMsg);
session.generateRequest(initDataType, initData);
const response = await getLicenseKey(message, toLicenseKeyURL(props, 'fairplay')).catch((errOrResp) => {
if (errOrResp instanceof Response) {
const mediaError = getErrorFromResponse(errOrResp, MuxErrorCategory.DRM, props);
console.error('mediaError', mediaError?.message, mediaError?.context);
if (mediaError) {
return Promise.reject(mediaError);
}
// NOTE: This should never happen. Adding for exhaustiveness (CJP).
return Promise.reject(new Error('Unexpected error in license key request'));
}
return Promise.reject(errOrResp);
});
await session.update(response).catch(() => {
// eslint-disable-next-line no-shadow
const message = i18n(
'Failed to update DRM license. This may be an issue with the player or your protected content.'
);
const mediaError = new MediaError(message, MediaError.MEDIA_ERR_ENCRYPTED, true);
mediaError.errorCategory = MuxErrorCategory.DRM;
mediaError.muxCode = MuxErrorCode.ENCRYPTED_UPDATE_LICENSE_FAILED;
return Promise.reject(mediaError);
});
// @ts-ignore
} catch (error: Error | MediaError) {
saveAndDispatchError(mediaEl, error);
return;
}
};
addEventListenerWithTeardown(mediaEl, 'encrypted', onFpEncrypted);
};
export const toLicenseKeyURL = (
{
playbackId: playbackIdWithParams,
tokens: { drm: token } = {},
customDomain = MUX_VIDEO_DOMAIN,
}: Partial<Pick<MuxMediaPropsInternal, 'playbackId' | 'tokens' | 'customDomain'>>,
scheme: 'widevine' | 'playready' | 'fairplay'
) => {
const playbackId = toPlaybackIdFromParameterized(playbackIdWithParams);
// NOTE: Mux Video currently doesn't support custom domains for license/DRM endpoints, but
// customDomain can also be used for internal use cases, so treat that as an exception case for now. (CJP)
const domain = customDomain.toLocaleLowerCase().endsWith(MUX_VIDEO_DOMAIN) ? customDomain : MUX_VIDEO_DOMAIN;
return `https://license.${domain}/license/${scheme}/${playbackId}?token=${token}`;
};
export const toAppCertURL = (
{
playbackId: playbackIdWithParams,
tokens: { drm: token } = {},
customDomain = MUX_VIDEO_DOMAIN,
}: Partial<Pick<MuxMediaPropsInternal, 'playbackId' | 'tokens' | 'customDomain'>>,
scheme: 'widevine' | 'playready' | 'fairplay'
) => {
const playbackId = toPlaybackIdFromParameterized(playbackIdWithParams);
// NOTE: Mux Video currently doesn't support custom domains for license/DRM endpoints, but
// customDomain can also be used for internal use cases, so treat that as an exception case for now. (CJP)
const domain = customDomain.toLocaleLowerCase().endsWith(MUX_VIDEO_DOMAIN) ? customDomain : MUX_VIDEO_DOMAIN;
return `https://license.${domain}/appcert/${scheme}/${playbackId}?token=${token}`;
};
export const isMuxVideoSrc = ({
playbackId,
src,
customDomain,
}: Partial<Pick<MuxMediaPropsInternal, 'playbackId' | 'src' | 'customDomain'>>) => {
if (!!playbackId) return true;
// having no playback id and no src string should never actually happen, but could
if (typeof src !== 'string') return false;
// Include base for relative paths
const base = window?.location.href;
const hostname = new URL(src, base).hostname.toLocaleLowerCase();
return hostname.includes(MUX_VIDEO_DOMAIN) || (!!customDomain && hostname.includes(customDomain.toLocaleLowerCase()));
};
export const setupMux = (
props: Partial<
Pick<
MuxMediaPropsInternal,
| 'envKey'
| 'playerInitTime'
| 'beaconCollectionDomain'
| 'errorTranslator'
| 'metadata'
| 'debug'
| 'playerSoftwareName'
| 'playerSoftwareVersion'
| 'playbackId'
| 'src'
| 'customDomain'
| 'disableCookies'
| 'disableTracking'
>
>,
mediaEl: HTMLMediaElement,
hlsjs?: HlsInterface
) => {
const { envKey: env_key, disableTracking } = props;
const inferredEnv = isMuxVideoSrc(props);
if (!disableTracking && (env_key || inferredEnv)) {
const {
playerInitTime: player_init_time,
playerSoftwareName: player_software_name,
playerSoftwareVersion: player_software_version,
beaconCollectionDomain,
debug,
disableCookies,
} = props;
const metadata = {
...props.metadata,
video_title: props?.metadata?.video_title || undefined,
};
const muxEmbedErrorTranslator = (error: ErrorEvent) => {
// mux-embed auto tracks fatal hls.js errors, turn it off.
// playback-core will emit errors with a numeric code manually to mux-embed.
if (typeof error.player_error_code === 'string') return false;
if (typeof props.errorTranslator === 'function') {
return props.errorTranslator(error);
}
return error;
};