-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
stream_utils.js
2046 lines (1840 loc) · 65 KB
/
stream_utils.js
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
/*! @license
* Shaka Player
* Copyright 2016 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
goog.provide('shaka.util.StreamUtils');
goog.require('goog.asserts');
goog.require('shaka.log');
goog.require('shaka.media.Capabilities');
goog.require('shaka.text.TextEngine');
goog.require('shaka.util.Functional');
goog.require('shaka.util.LanguageUtils');
goog.require('shaka.util.ManifestParserUtils');
goog.require('shaka.util.MimeUtils');
goog.require('shaka.util.MultiMap');
goog.require('shaka.util.ObjectUtils');
goog.require('shaka.util.Platform');
goog.requireType('shaka.drm.DrmEngine');
/**
* @summary A set of utility functions for dealing with Streams and Manifests.
* @export
*/
shaka.util.StreamUtils = class {
/**
* In case of multiple usable codecs, choose one based on lowest average
* bandwidth and filter out the rest.
* Also filters out variants that have too many audio channels.
* @param {!shaka.extern.Manifest} manifest
* @param {!Array.<string>} preferredVideoCodecs
* @param {!Array.<string>} preferredAudioCodecs
* @param {!Array.<string>} preferredDecodingAttributes
* @param {!Array.<string>} preferredTextFormats
*/
static chooseCodecsAndFilterManifest(manifest, preferredVideoCodecs,
preferredAudioCodecs, preferredDecodingAttributes, preferredTextFormats) {
const StreamUtils = shaka.util.StreamUtils;
const MimeUtils = shaka.util.MimeUtils;
if (preferredTextFormats.length) {
let subset = manifest.textStreams;
for (const textFormat of preferredTextFormats) {
const filtered = subset.filter((textStream) => {
if (textStream.codecs.startsWith(textFormat) ||
textStream.mimeType.startsWith(textFormat)) {
return true;
}
return false;
});
if (filtered.length) {
subset = filtered;
break;
}
}
manifest.textStreams = subset;
}
let variants = manifest.variants;
// To start, choose the codecs based on configured preferences if available.
if (preferredVideoCodecs.length || preferredAudioCodecs.length) {
variants = StreamUtils.choosePreferredCodecs(variants,
preferredVideoCodecs, preferredAudioCodecs);
}
if (preferredDecodingAttributes.length) {
// group variants by resolution and choose preferred variants only
/** @type {!shaka.util.MultiMap.<shaka.extern.Variant>} */
const variantsByResolutionMap = new shaka.util.MultiMap();
for (const variant of variants) {
variantsByResolutionMap
.push(String(variant.video.width || 0), variant);
}
const bestVariants = [];
variantsByResolutionMap.forEach((width, variantsByResolution) => {
let highestMatch = 0;
let matchingVariants = [];
for (const variant of variantsByResolution) {
const matchCount = preferredDecodingAttributes.filter(
(attribute) => variant.decodingInfos[0][attribute],
).length;
if (matchCount > highestMatch) {
highestMatch = matchCount;
matchingVariants = [variant];
} else if (matchCount == highestMatch) {
matchingVariants.push(variant);
}
}
bestVariants.push(...matchingVariants);
});
variants = bestVariants;
}
const audioStreamsSet = new Set();
const videoStreamsSet = new Set();
for (const variant of variants) {
if (variant.audio) {
audioStreamsSet.add(variant.audio);
}
if (variant.video) {
videoStreamsSet.add(variant.video);
}
}
const audioStreams = Array.from(audioStreamsSet).sort((v1, v2) => {
return v1.bandwidth - v2.bandwidth;
});
const validAudioIds = [];
const validAudioStreamsMap = new Map();
const getAudioId = (stream) => {
return stream.language + (stream.channelsCount || 0) +
(stream.audioSamplingRate || 0) + stream.roles.join(',') +
stream.label + stream.groupId + stream.fastSwitching;
};
for (const stream of audioStreams) {
const groupId = getAudioId(stream);
const validAudioStreams = validAudioStreamsMap.get(groupId) || [];
if (!validAudioStreams.length) {
validAudioStreams.push(stream);
validAudioIds.push(stream.id);
} else {
const previousStream = validAudioStreams[validAudioStreams.length - 1];
const previousCodec =
MimeUtils.getNormalizedCodec(previousStream.codecs);
const currentCodec =
MimeUtils.getNormalizedCodec(stream.codecs);
if (previousCodec == currentCodec) {
if (!stream.bandwidth || !previousStream.bandwidth ||
stream.bandwidth > previousStream.bandwidth) {
validAudioStreams.push(stream);
validAudioIds.push(stream.id);
}
}
}
validAudioStreamsMap.set(groupId, validAudioStreams);
}
// Keys based in MimeUtils.getNormalizedCodec. Lower is better
const videoCodecPreference = {
'vp8': 1,
'avc': 1,
'dovi-avc': 0.95,
'vp9': 0.9,
'vp09': 0.9,
'hevc': 0.85,
'dovi-hevc': 0.8,
'dovi-p5': 0.75,
'av01': 0.7,
'dovi-av1': 0.65,
'vvc': 0.6,
};
const videoStreams = Array.from(videoStreamsSet)
.sort((v1, v2) => {
if (!v1.bandwidth || !v2.bandwidth || v1.bandwidth == v2.bandwidth) {
if (v1.codecs && v2.codecs && v1.codecs != v2.codecs &&
v1.width == v2.width) {
const v1Codecs = MimeUtils.getNormalizedCodec(v1.codecs);
const v2Codecs = MimeUtils.getNormalizedCodec(v2.codecs);
if (v1Codecs != v2Codecs) {
const indexV1 = videoCodecPreference[v1Codecs] || 1;
const indexV2 = videoCodecPreference[v2Codecs] || 1;
return indexV1 - indexV2;
}
}
return v1.width - v2.width;
}
return v1.bandwidth - v2.bandwidth;
});
const isChangeTypeSupported =
shaka.media.Capabilities.isChangeTypeSupported();
const validVideoIds = [];
const validVideoStreamsMap = new Map();
const getVideoGroupId = (stream) => {
return Math.round(stream.frameRate || 0) + (stream.hdr || '') +
stream.fastSwitching;
};
for (const stream of videoStreams) {
const groupId = getVideoGroupId(stream);
const validVideoStreams = validVideoStreamsMap.get(groupId) || [];
if (!validVideoStreams.length) {
validVideoStreams.push(stream);
validVideoIds.push(stream.id);
} else {
const previousStream = validVideoStreams[validVideoStreams.length - 1];
if (!isChangeTypeSupported) {
const previousCodec =
MimeUtils.getNormalizedCodec(previousStream.codecs);
const currentCodec =
MimeUtils.getNormalizedCodec(stream.codecs);
if (previousCodec !== currentCodec) {
continue;
}
}
if (stream.width > previousStream.width ||
stream.height > previousStream.height) {
validVideoStreams.push(stream);
validVideoIds.push(stream.id);
} else if (stream.width == previousStream.width &&
stream.height == previousStream.height) {
const previousCodec =
MimeUtils.getNormalizedCodec(previousStream.codecs);
const currentCodec =
MimeUtils.getNormalizedCodec(stream.codecs);
if (previousCodec == currentCodec) {
if (!stream.bandwidth || !previousStream.bandwidth ||
stream.bandwidth > previousStream.bandwidth) {
validVideoStreams.push(stream);
validVideoIds.push(stream.id);
}
}
}
}
validVideoStreamsMap.set(groupId, validVideoStreams);
}
// Filter out any variants that don't match, forcing AbrManager to choose
// from a single video codec and a single audio codec possible.
manifest.variants = manifest.variants.filter((variant) => {
const audio = variant.audio;
const video = variant.video;
if (audio) {
if (!validAudioIds.includes(audio.id)) {
shaka.log.debug('Dropping Variant (better codec available)', variant);
return false;
}
}
if (video) {
if (!validVideoIds.includes(video.id)) {
shaka.log.debug('Dropping Variant (better codec available)', variant);
return false;
}
}
return true;
});
}
/**
* Choose the codecs by configured preferred audio and video codecs.
*
* @param {!Array<shaka.extern.Variant>} variants
* @param {!Array.<string>} preferredVideoCodecs
* @param {!Array.<string>} preferredAudioCodecs
* @return {!Array<shaka.extern.Variant>}
*/
static choosePreferredCodecs(variants, preferredVideoCodecs,
preferredAudioCodecs) {
let subset = variants;
for (const videoCodec of preferredVideoCodecs) {
const filtered = subset.filter((variant) => {
return variant.video && variant.video.codecs.startsWith(videoCodec);
});
if (filtered.length) {
subset = filtered;
break;
}
}
for (const audioCodec of preferredAudioCodecs) {
const filtered = subset.filter((variant) => {
return variant.audio && variant.audio.codecs.startsWith(audioCodec);
});
if (filtered.length) {
subset = filtered;
break;
}
}
return subset;
}
/**
* Filter the variants in |manifest| to only include the variants that meet
* the given restrictions.
*
* @param {!shaka.extern.Manifest} manifest
* @param {shaka.extern.Restrictions} restrictions
* @param {shaka.extern.Resolution} maxHwResolution
*/
static filterByRestrictions(manifest, restrictions, maxHwResolution) {
manifest.variants = manifest.variants.filter((variant) => {
return shaka.util.StreamUtils.meetsRestrictions(
variant, restrictions, maxHwResolution);
});
}
/**
* @param {shaka.extern.Variant} variant
* @param {shaka.extern.Restrictions} restrictions
* Configured restrictions from the user.
* @param {shaka.extern.Resolution} maxHwRes
* The maximum resolution the hardware can handle.
* This is applied separately from user restrictions because the setting
* should not be easily replaced by the user's configuration.
* @return {boolean}
* @export
*/
static meetsRestrictions(variant, restrictions, maxHwRes) {
/** @type {function(number, number, number):boolean} */
const inRange = (x, min, max) => {
return x >= min && x <= max;
};
const video = variant.video;
// |video.width| and |video.height| can be undefined, which breaks
// the math, so make sure they are there first.
if (video && video.width && video.height) {
let videoWidth = video.width;
let videoHeight = video.height;
if (videoHeight > videoWidth) {
// Vertical video.
[videoWidth, videoHeight] = [videoHeight, videoWidth];
}
if (!inRange(videoWidth,
restrictions.minWidth,
Math.min(restrictions.maxWidth, maxHwRes.width))) {
return false;
}
if (!inRange(videoHeight,
restrictions.minHeight,
Math.min(restrictions.maxHeight, maxHwRes.height))) {
return false;
}
if (!inRange(video.width * video.height,
restrictions.minPixels,
restrictions.maxPixels)) {
return false;
}
}
// |variant.video.frameRate| can be undefined, which breaks
// the math, so make sure they are there first.
if (variant && variant.video && variant.video.frameRate) {
if (!inRange(variant.video.frameRate,
restrictions.minFrameRate,
restrictions.maxFrameRate)) {
return false;
}
}
// |variant.audio.channelsCount| can be undefined, which breaks
// the math, so make sure they are there first.
if (variant && variant.audio && variant.audio.channelsCount) {
if (!inRange(variant.audio.channelsCount,
restrictions.minChannelsCount,
restrictions.maxChannelsCount)) {
return false;
}
}
if (!inRange(variant.bandwidth,
restrictions.minBandwidth,
restrictions.maxBandwidth)) {
return false;
}
return true;
}
/**
* @param {!Array.<shaka.extern.Variant>} variants
* @param {shaka.extern.Restrictions} restrictions
* @param {shaka.extern.Resolution} maxHwRes
* @return {boolean} Whether the tracks changed.
*/
static applyRestrictions(variants, restrictions, maxHwRes) {
let tracksChanged = false;
for (const variant of variants) {
const originalAllowed = variant.allowedByApplication;
variant.allowedByApplication = shaka.util.StreamUtils.meetsRestrictions(
variant, restrictions, maxHwRes);
if (originalAllowed != variant.allowedByApplication) {
tracksChanged = true;
}
}
return tracksChanged;
}
/**
* Alters the given Manifest to filter out any unplayable streams.
*
* @param {shaka.drm.DrmEngine} drmEngine
* @param {shaka.extern.Manifest} manifest
* @param {!Array<string>=} preferredKeySystems
* @param {!Object.<string, string>=} keySystemsMapping
*/
static async filterManifest(drmEngine, manifest, preferredKeySystems = [],
keySystemsMapping = {}) {
await shaka.util.StreamUtils.filterManifestByMediaCapabilities(
drmEngine, manifest, manifest.offlineSessionIds.length > 0,
preferredKeySystems, keySystemsMapping);
shaka.util.StreamUtils.filterTextStreams_(manifest);
await shaka.util.StreamUtils.filterImageStreams_(manifest);
}
/**
* Alters the given Manifest to filter out any streams unsupported by the
* platform via MediaCapabilities.decodingInfo() API.
*
* @param {shaka.drm.DrmEngine} drmEngine
* @param {shaka.extern.Manifest} manifest
* @param {boolean} usePersistentLicenses
* @param {!Array<string>} preferredKeySystems
* @param {!Object.<string, string>} keySystemsMapping
*/
static async filterManifestByMediaCapabilities(
drmEngine, manifest, usePersistentLicenses, preferredKeySystems,
keySystemsMapping) {
goog.asserts.assert(navigator.mediaCapabilities,
'MediaCapabilities should be valid.');
if (shaka.util.Platform.isXboxOne()) {
shaka.util.StreamUtils.overrideDolbyVisionCodecs(manifest.variants);
}
await shaka.util.StreamUtils.getDecodingInfosForVariants(
manifest.variants, usePersistentLicenses, /* srcEquals= */ false,
preferredKeySystems);
let keySystem = null;
if (drmEngine) {
const drmInfo = drmEngine.getDrmInfo();
if (drmInfo) {
keySystem = drmInfo.keySystem;
}
}
const StreamUtils = shaka.util.StreamUtils;
manifest.variants = manifest.variants.filter((variant) => {
const supported = StreamUtils.checkVariantSupported_(
variant, keySystem, keySystemsMapping);
// Filter out all unsupported variants.
if (!supported) {
shaka.log.debug('Dropping variant - not compatible with platform',
StreamUtils.getVariantSummaryString_(variant));
}
return supported;
});
}
/**
* Maps Dolby Vision codecs to H.264 and H.265 equivalents as a workaround
* to make Dolby Vision playback work on some platforms.
*
* Mapping is done according to the relevant Dolby documentation found here:
* https://professionalsupport.dolby.com/s/article/How-to-signal-Dolby-Vision-in-MPEG-DASH?language=en_US
* @param {!Array<!shaka.extern.Variant>} variants
*/
static overrideDolbyVisionCodecs(variants) {
/** @type {!Object<string, string>} */
const codecMap = {
'dvav': 'avc3',
'dva1': 'avc1',
'dvhe': 'hev1',
'dvh1': 'hvc1',
'dvc1': 'vvc1',
'dvi1': 'vvi1',
};
/** @type {!Set<!shaka.extern.Stream>} */
const streams = new Set();
for (const variant of variants) {
if (variant.video) {
streams.add(variant.video);
}
}
for (const video of streams) {
for (const dvCodec of Object.keys(codecMap)) {
if (video.codecs.includes(dvCodec)) {
video.codecs = video.codecs.replace(dvCodec, codecMap[dvCodec]);
break;
}
}
}
}
/**
* @param {!shaka.extern.Variant} variant
* @param {?string} keySystem
* @param {!Object.<string, string>} keySystemsMapping
* @return {boolean}
* @private
*/
static checkVariantSupported_(variant, keySystem, keySystemsMapping) {
const variantSupported = variant.decodingInfos.some((decodingInfo) => {
if (!decodingInfo.supported) {
return false;
}
if (keySystem) {
const keySystemAccess = decodingInfo.keySystemAccess;
if (keySystemAccess) {
const currentKeySystem =
keySystemsMapping[keySystemAccess.keySystem] ||
keySystemAccess.keySystem;
if (currentKeySystem != keySystem) {
return false;
}
}
}
return true;
});
if (!variantSupported) {
return false;
}
const ContentType = shaka.util.ManifestParserUtils.ContentType;
const Capabilities = shaka.media.Capabilities;
const ManifestParserUtils = shaka.util.ManifestParserUtils;
const MimeUtils = shaka.util.MimeUtils;
const StreamUtils = shaka.util.StreamUtils;
const isXboxOne = shaka.util.Platform.isXboxOne();
const isFirefoxAndroid = shaka.util.Platform.isFirefox() &&
shaka.util.Platform.isAndroid();
// See: https://github.com/shaka-project/shaka-player/issues/3860
const video = variant.video;
const videoWidth = (video && video.width) || 0;
const videoHeight = (video && video.height) || 0;
// See: https://github.com/shaka-project/shaka-player/issues/3380
// Note: it makes sense to drop early
if (isXboxOne && video && (videoWidth > 1920 || videoHeight > 1080) &&
(video.codecs.includes('avc1.') || video.codecs.includes('avc3.'))) {
return false;
}
if (video) {
let videoCodecs = StreamUtils.getCorrectVideoCodecs(video.codecs);
// For multiplexed streams. Here we must check the audio of the
// stream to see if it is compatible.
if (video.codecs.includes(',')) {
const allCodecs = video.codecs.split(',');
videoCodecs = ManifestParserUtils.guessCodecs(
ContentType.VIDEO, allCodecs);
videoCodecs = StreamUtils.getCorrectVideoCodecs(videoCodecs);
let audioCodecs = ManifestParserUtils.guessCodecs(
ContentType.AUDIO, allCodecs);
audioCodecs = StreamUtils.getCorrectAudioCodecs(
audioCodecs, video.mimeType);
const audioFullType = MimeUtils.getFullOrConvertedType(
video.mimeType, audioCodecs, ContentType.AUDIO);
if (!Capabilities.isTypeSupported(audioFullType)) {
return false;
}
// Update the codec string with the (possibly) converted codecs.
videoCodecs = [videoCodecs, audioCodecs].join(',');
}
if (video.codecs != videoCodecs) {
const fullType = MimeUtils.getFullOrConvertedType(
video.mimeType, videoCodecs, ContentType.VIDEO);
if (!Capabilities.isTypeSupported(fullType)) {
return false;
}
// Update the codec string with the (possibly) converted codecs.
video.codecs = videoCodecs;
}
}
const audio = variant.audio;
// See: https://github.com/shaka-project/shaka-player/issues/6111
// It seems that Firefox Android reports that it supports
// Opus + Widevine, but it is not actually supported.
// It makes sense to drop early.
if (isFirefoxAndroid && audio && audio.encrypted &&
audio.codecs.toLowerCase().includes('opus')) {
return false;
}
if (audio) {
const codecs = StreamUtils.getCorrectAudioCodecs(
audio.codecs, audio.mimeType);
if (audio.codecs != codecs) {
const fullType = MimeUtils.getFullOrConvertedType(
audio.mimeType, codecs, ContentType.AUDIO);
if (!Capabilities.isTypeSupported(fullType)) {
return false;
}
// Update the codec string with the (possibly) converted codecs.
audio.codecs = codecs;
}
}
return true;
}
/**
* Queries mediaCapabilities for the decoding info for that decoding config,
* and assigns it to the given variant.
* If that query has been done before, instead return a cached result.
* @param {!shaka.extern.Variant} variant
* @param {!Array.<!MediaDecodingConfiguration>} decodingConfigs
* @private
*/
static async getDecodingInfosForVariant_(variant, decodingConfigs) {
/**
* @param {?MediaCapabilitiesDecodingInfo} a
* @param {!MediaCapabilitiesDecodingInfo} b
* @return {!MediaCapabilitiesDecodingInfo}
*/
const merge = (a, b) => {
if (!a) {
return b;
} else {
const res = shaka.util.ObjectUtils.shallowCloneObject(a);
res.supported = a.supported && b.supported;
res.powerEfficient = a.powerEfficient && b.powerEfficient;
res.smooth = a.smooth && b.smooth;
if (b.keySystemAccess && !res.keySystemAccess) {
res.keySystemAccess = b.keySystemAccess;
}
return res;
}
};
const StreamUtils = shaka.util.StreamUtils;
/** @type {?MediaCapabilitiesDecodingInfo} */
let finalResult = null;
const promises = [];
for (const decodingConfig of decodingConfigs) {
const cacheKey =
shaka.util.ObjectUtils.alphabeticalKeyOrderStringify(decodingConfig);
const cache = StreamUtils.decodingConfigCache_;
if (cache[cacheKey]) {
shaka.log.v2('Using cached results of mediaCapabilities.decodingInfo',
'for key', cacheKey);
finalResult = merge(finalResult, cache[cacheKey]);
} else {
// Do a final pass-over of the decoding config: if a given stream has
// multiple codecs, that suggests that it switches between those codecs
// at points of the go-through.
// mediaCapabilities by itself will report "not supported" when you
// put in multiple different codecs, so each has to be checked
// individually. So check each and take the worst result, to determine
// overall variant compatibility.
promises.push(StreamUtils
.checkEachDecodingConfigCombination_(decodingConfig).then((res) => {
/** @type {?MediaCapabilitiesDecodingInfo} */
let acc = null;
for (const result of (res || [])) {
acc = merge(acc, result);
}
if (acc) {
cache[cacheKey] = acc;
finalResult = merge(finalResult, acc);
}
}));
}
}
await Promise.all(promises);
if (finalResult) {
variant.decodingInfos.push(finalResult);
}
}
/**
* @param {!MediaDecodingConfiguration} decodingConfig
* @return {!Promise.<?Array.<!MediaCapabilitiesDecodingInfo>>}
* @private
*/
static checkEachDecodingConfigCombination_(decodingConfig) {
let videoCodecs = [''];
if (decodingConfig.video) {
videoCodecs = shaka.util.MimeUtils.getCodecs(
decodingConfig.video.contentType).split(',');
}
let audioCodecs = [''];
if (decodingConfig.audio) {
audioCodecs = shaka.util.MimeUtils.getCodecs(
decodingConfig.audio.contentType).split(',');
}
const promises = [];
for (const videoCodec of videoCodecs) {
for (const audioCodec of audioCodecs) {
const copy = shaka.util.ObjectUtils.cloneObject(decodingConfig);
if (decodingConfig.video) {
const mimeType = shaka.util.MimeUtils.getBasicType(
copy.video.contentType);
copy.video.contentType = shaka.util.MimeUtils.getFullType(
mimeType, videoCodec);
}
if (decodingConfig.audio) {
const mimeType = shaka.util.MimeUtils.getBasicType(
copy.audio.contentType);
copy.audio.contentType = shaka.util.MimeUtils.getFullType(
mimeType, audioCodec);
}
promises.push(new Promise((resolve, reject) => {
// On some (Android) WebView environments, decodingInfo will
// not resolve or reject, at least if RESOURCE_PROTECTED_MEDIA_ID
// is not set. This is a workaround for that issue.
const TIMEOUT_FOR_DECODING_INFO_IN_SECONDS = 1;
shaka.util.Functional.promiseWithTimeout(
TIMEOUT_FOR_DECODING_INFO_IN_SECONDS,
navigator.mediaCapabilities.decodingInfo(copy),
).then((res) => {
resolve(res);
}).catch(reject);
}));
}
}
return Promise.all(promises).catch((e) => {
shaka.log.info('MediaCapabilities.decodingInfo() failed.',
JSON.stringify(decodingConfig), e);
return null;
});
}
/**
* Get the decodingInfo results of the variants via MediaCapabilities.
* This should be called after the DrmEngine is created and configured, and
* before DrmEngine sets the mediaKeys.
*
* @param {!Array.<shaka.extern.Variant>} variants
* @param {boolean} usePersistentLicenses
* @param {boolean} srcEquals
* @param {!Array<string>} preferredKeySystems
* @exportDoc
*/
static async getDecodingInfosForVariants(variants, usePersistentLicenses,
srcEquals, preferredKeySystems) {
const gotDecodingInfo = variants.some((variant) =>
variant.decodingInfos.length);
if (gotDecodingInfo) {
shaka.log.debug('Already got the variants\' decodingInfo.');
return;
}
// Try to get preferred key systems first to avoid unneeded calls to CDM.
for (const preferredKeySystem of preferredKeySystems) {
let keySystemSatisfied = false;
for (const variant of variants) {
/** @type {!Array.<!Array.<!MediaDecodingConfiguration>>} */
const decodingConfigs = shaka.util.StreamUtils.getDecodingConfigs_(
variant, usePersistentLicenses, srcEquals)
.filter((configs) => {
// All configs in a batch will have the same keySystem.
const config = configs[0];
const keySystem = config.keySystemConfiguration &&
config.keySystemConfiguration.keySystem;
return keySystem === preferredKeySystem;
});
// The reason we are performing this await in a loop rather than
// batching into a `promise.all` is performance related.
// https://github.com/shaka-project/shaka-player/pull/4708#discussion_r1022581178
for (const configs of decodingConfigs) {
// eslint-disable-next-line no-await-in-loop
await shaka.util.StreamUtils.getDecodingInfosForVariant_(
variant, configs);
}
if (variant.decodingInfos.length) {
keySystemSatisfied = true;
}
} // for (const variant of variants)
if (keySystemSatisfied) {
// Return if any preferred key system is already satisfied.
return;
}
} // for (const preferredKeySystem of preferredKeySystems)
for (const variant of variants) {
/** @type {!Array.<!Array.<!MediaDecodingConfiguration>>} */
const decodingConfigs = shaka.util.StreamUtils.getDecodingConfigs_(
variant, usePersistentLicenses, srcEquals)
.filter((configs) => {
// All configs in a batch will have the same keySystem.
const config = configs[0];
const keySystem = config.keySystemConfiguration &&
config.keySystemConfiguration.keySystem;
// Avoid checking preferred systems twice.
return !keySystem || !preferredKeySystems.includes(keySystem);
});
// The reason we are performing this await in a loop rather than
// batching into a `promise.all` is performance related.
// https://github.com/shaka-project/shaka-player/pull/4708#discussion_r1022581178
for (const configs of decodingConfigs) {
// eslint-disable-next-line no-await-in-loop
await shaka.util.StreamUtils.getDecodingInfosForVariant_(
variant, configs);
}
}
}
/**
* Generate a batch of MediaDecodingConfiguration objects to get the
* decodingInfo results for each variant.
* Each batch shares the same DRM information, and represents the various
* fullMimeType combinations of the streams.
* @param {!shaka.extern.Variant} variant
* @param {boolean} usePersistentLicenses
* @param {boolean} srcEquals
* @return {!Array.<!Array.<!MediaDecodingConfiguration>>}
* @private
*/
static getDecodingConfigs_(variant, usePersistentLicenses, srcEquals) {
const audio = variant.audio;
const video = variant.video;
const ContentType = shaka.util.ManifestParserUtils.ContentType;
const ManifestParserUtils = shaka.util.ManifestParserUtils;
const MimeUtils = shaka.util.MimeUtils;
const StreamUtils = shaka.util.StreamUtils;
const videoConfigs = [];
const audioConfigs = [];
if (video) {
for (const fullMimeType of video.fullMimeTypes) {
let videoCodecs = MimeUtils.getCodecs(fullMimeType);
// For multiplexed streams with audio+video codecs, the config should
// have AudioConfiguration and VideoConfiguration.
// We ignore the multiplexed audio when there is normal audio also.
if (videoCodecs.includes(',') && !audio) {
const allCodecs = videoCodecs.split(',');
const baseMimeType = MimeUtils.getBasicType(fullMimeType);
videoCodecs = ManifestParserUtils.guessCodecs(
ContentType.VIDEO, allCodecs);
let audioCodecs = ManifestParserUtils.guessCodecs(
ContentType.AUDIO, allCodecs);
audioCodecs = StreamUtils.getCorrectAudioCodecs(
audioCodecs, baseMimeType);
const audioFullType = MimeUtils.getFullOrConvertedType(
baseMimeType, audioCodecs, ContentType.AUDIO);
audioConfigs.push({
contentType: audioFullType,
channels: 2,
bitrate: variant.bandwidth || 1,
samplerate: 1,
spatialRendering: false,
});
}
videoCodecs = StreamUtils.getCorrectVideoCodecs(videoCodecs);
const fullType = MimeUtils.getFullOrConvertedType(
MimeUtils.getBasicType(fullMimeType), videoCodecs,
ContentType.VIDEO);
// VideoConfiguration
const videoConfig = {
contentType: fullType,
// NOTE: Some decoders strictly check the width and height fields and
// won't decode smaller than 64x64. So if we don't have this info (as
// is the case in some of our simpler tests), assume a 64x64
// resolution to fill in this required field for MediaCapabilities.
//
// This became an issue specifically on Firefox on M1 Macs.
width: video.width || 64,
height: video.height || 64,
bitrate: video.bandwidth || variant.bandwidth || 1,
// framerate must be greater than 0, otherwise the config is invalid.
framerate: video.frameRate || 1,
};
if (video.hdr) {
switch (video.hdr) {
case 'SDR':
videoConfig.transferFunction = 'srgb';
break;
case 'PQ':
videoConfig.transferFunction = 'pq';
break;
case 'HLG':
videoConfig.transferFunction = 'hlg';
break;
}
}
if (video.colorGamut) {
videoConfig.colorGamut = video.colorGamut;
}
videoConfigs.push(videoConfig);
}
}
if (audio) {
for (const fullMimeType of audio.fullMimeTypes) {
const baseMimeType = MimeUtils.getBasicType(fullMimeType);
const codecs = StreamUtils.getCorrectAudioCodecs(
MimeUtils.getCodecs(fullMimeType), baseMimeType);
const fullType = MimeUtils.getFullOrConvertedType(
baseMimeType, codecs, ContentType.AUDIO);
// AudioConfiguration
audioConfigs.push({
contentType: fullType,
channels: audio.channelsCount || 2,
bitrate: audio.bandwidth || variant.bandwidth || 1,
samplerate: audio.audioSamplingRate || 1,
spatialRendering: audio.spatialAudio,
});
}
}
// Generate each combination of video and audio config as a separate
// MediaDecodingConfiguration, inside the main "batch".
/** @type {!Array.<!MediaDecodingConfiguration>} */
const mediaDecodingConfigBatch = [];
if (videoConfigs.length == 0) {
videoConfigs.push(null);
}
if (audioConfigs.length == 0) {
audioConfigs.push(null);
}
for (const videoConfig of videoConfigs) {
for (const audioConfig of audioConfigs) {
/** @type {!MediaDecodingConfiguration} */
const mediaDecodingConfig = {
type: srcEquals ? 'file' : 'media-source',
};
if (videoConfig) {
mediaDecodingConfig.video = videoConfig;
}
if (audioConfig) {
mediaDecodingConfig.audio = audioConfig;
}
mediaDecodingConfigBatch.push(mediaDecodingConfig);
}
}
const videoDrmInfos = variant.video ? variant.video.drmInfos : [];
const audioDrmInfos = variant.audio ? variant.audio.drmInfos : [];
const allDrmInfos = videoDrmInfos.concat(audioDrmInfos);
// Return a list containing the mediaDecodingConfig for unencrypted variant.
if (!allDrmInfos.length) {
return [mediaDecodingConfigBatch];
}
// A list of MediaDecodingConfiguration objects created for the variant.
const configs = [];
// Get all the drm info so that we can avoid using nested loops when we
// just need the drm info.
const drmInfoByKeySystems = new Map();
for (const info of allDrmInfos) {
if (!drmInfoByKeySystems.get(info.keySystem)) {
drmInfoByKeySystems.set(info.keySystem, []);
}
drmInfoByKeySystems.get(info.keySystem).push(info);
}
const persistentState =
usePersistentLicenses ? 'required' : 'optional';
const sessionTypes =
usePersistentLicenses ? ['persistent-license'] : ['temporary'];
for (const keySystem of drmInfoByKeySystems.keys()) {
const modifiedMediaDecodingConfigBatch = [];
for (const base of mediaDecodingConfigBatch) {
// Create a copy of the mediaDecodingConfig.
const config = /** @type {!MediaDecodingConfiguration} */
(Object.assign({}, base));
const drmInfos = drmInfoByKeySystems.get(keySystem);
/** @type {!MediaCapabilitiesKeySystemConfiguration} */
const keySystemConfig = {
keySystem: keySystem,
initDataType: 'cenc',
persistentState: persistentState,
distinctiveIdentifier: 'optional',
sessionTypes: sessionTypes,
};
for (const info of drmInfos) {
if (info.initData && info.initData.length) {
const initDataTypes = new Set();
for (const initData of info.initData) {