-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
stream_utils.js
1606 lines (1422 loc) · 49.3 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.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.Platform');
goog.requireType('shaka.media.DrmEngine');
/**
* @summary A set of utility functions for dealing with Streams and Manifests.
*/
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 {number} preferredAudioChannelCount
* @param {!Array.<string>} preferredDecodingAttributes
*/
static chooseCodecsAndFilterManifest(manifest, preferredVideoCodecs,
preferredAudioCodecs, preferredAudioChannelCount,
preferredDecodingAttributes) {
const StreamUtils = shaka.util.StreamUtils;
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);
}
// Consider a subset of variants based on audio channel
// preferences.
// For some content (#1013), surround-sound variants will use a different
// codec than stereo variants, so it is important to choose codecs **after**
// considering the audio channel config.
variants = StreamUtils.filterVariantsByAudioChannelCount(
variants, preferredAudioChannelCount);
// Now organize variants into buckets by codecs.
/** @type {!shaka.util.MultiMap.<shaka.extern.Variant>} */
let variantsByCodecs = StreamUtils.getVariantsByCodecs_(variants);
variantsByCodecs = StreamUtils.filterVariantsByDensity_(variantsByCodecs);
const bestCodecs = StreamUtils.chooseCodecsByDecodingAttributes_(
variantsByCodecs, preferredDecodingAttributes);
// 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 codecs = StreamUtils.getVariantCodecs_(variant);
if (codecs == bestCodecs) {
return true;
}
shaka.log.debug('Dropping Variant (better codec available)', variant);
return false;
});
}
/**
* Get variants by codecs.
*
* @param {!Array<shaka.extern.Variant>} variants
* @return {!shaka.util.MultiMap.<shaka.extern.Variant>}
* @private
*/
static getVariantsByCodecs_(variants) {
const variantsByCodecs = new shaka.util.MultiMap();
for (const variant of variants) {
const variantCodecs = shaka.util.StreamUtils.getVariantCodecs_(variant);
variantsByCodecs.push(variantCodecs, variant);
}
return variantsByCodecs;
}
/**
* Filters variants by density.
* Get variants by codecs map with the max density where all codecs are
* present.
*
* @param {!shaka.util.MultiMap.<shaka.extern.Variant>} variantsByCodecs
* @return {!shaka.util.MultiMap.<shaka.extern.Variant>}
* @private
*/
static filterVariantsByDensity_(variantsByCodecs) {
let maxDensity = 0;
const codecGroupsByDensity = new Map();
const countCodecs = variantsByCodecs.size();
variantsByCodecs.forEach((codecs, variants) => {
for (const variant of variants) {
const video = variant.video;
if (!video || !video.width || !video.height) {
continue;
}
const density = video.width * video.height * (video.frameRate || 1);
if (!codecGroupsByDensity.has(density)) {
codecGroupsByDensity.set(density, new shaka.util.MultiMap());
}
/** @type {!shaka.util.MultiMap.<shaka.extern.Variant>} */
const group = codecGroupsByDensity.get(density);
group.push(codecs, variant);
// We want to look at the groups in which all codecs are present.
// Take the max density from those groups where all codecs are present.
// Later, we will compare bandwidth numbers only within this group.
// Effectively, only the bandwidth differences in the highest-res and
// highest-framerate content will matter in choosing a codec.
if (group.size() === countCodecs) {
maxDensity = Math.max(maxDensity, density);
}
}
});
return maxDensity ? codecGroupsByDensity.get(maxDensity) : variantsByCodecs;
}
/**
* 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;
}
/**
* Choose the codecs by configured preferred decoding attributes.
*
* @param {!shaka.util.MultiMap.<shaka.extern.Variant>} variantsByCodecs
* @param {!Array.<string>} attributes
* @return {string}
* @private
*/
static chooseCodecsByDecodingAttributes_(variantsByCodecs, attributes) {
const StreamUtils = shaka.util.StreamUtils;
for (const attribute of attributes) {
if (attribute == StreamUtils.DecodingAttributes.SMOOTH ||
attribute == StreamUtils.DecodingAttributes.POWER) {
variantsByCodecs = StreamUtils.chooseCodecsByMediaCapabilitiesInfo_(
variantsByCodecs, attribute);
// If we only have one smooth or powerEfficient codecs, choose it as the
// best codecs.
if (variantsByCodecs.size() == 1) {
return variantsByCodecs.keys()[0];
}
} else if (attribute == StreamUtils.DecodingAttributes.BANDWIDTH) {
return StreamUtils.findCodecsByLowestBandwidth_(variantsByCodecs);
}
}
// If there's no configured decoding preferences, or we have multiple codecs
// that meets the configured decoding preferences, choose the one with
// the lowest bandwidth.
return StreamUtils.findCodecsByLowestBandwidth_(variantsByCodecs);
}
/**
* Choose the best codecs by configured preferred MediaCapabilitiesInfo
* attributes.
*
* @param {!shaka.util.MultiMap.<shaka.extern.Variant>} variantsByCodecs
* @param {string} attribute
* @return {!shaka.util.MultiMap.<shaka.extern.Variant>}
* @private
*/
static chooseCodecsByMediaCapabilitiesInfo_(variantsByCodecs, attribute) {
let highestScore = 0;
const bestVariantsByCodecs = new shaka.util.MultiMap();
variantsByCodecs.forEach((codecs, variants) => {
let sum = 0;
let num = 0;
for (const variant of variants) {
if (variant.decodingInfos.length) {
sum += variant.decodingInfos[0][attribute] ? 1 : 0;
num++;
}
}
const averageScore = sum / num;
shaka.log.debug('codecs', codecs, 'avg', attribute, averageScore);
if (averageScore > highestScore) {
bestVariantsByCodecs.clear();
bestVariantsByCodecs.push(codecs, variants);
highestScore = averageScore;
} else if (averageScore == highestScore) {
bestVariantsByCodecs.push(codecs, variants);
}
});
return bestVariantsByCodecs;
}
/**
* Find the lowest-bandwidth (best) codecs.
* Compute the average bandwidth for each group of variants.
*
* @param {!shaka.util.MultiMap.<shaka.extern.Variant>} variantsByCodecs
* @return {string}
* @private
*/
static findCodecsByLowestBandwidth_(variantsByCodecs) {
let bestCodecs = '';
let lowestAverageBandwidth = Infinity;
variantsByCodecs.forEach((codecs, variants) => {
let sum = 0;
let num = 0;
for (const variant of variants) {
sum += variant.bandwidth || 0;
++num;
}
const averageBandwidth = sum / num;
shaka.log.debug('codecs', codecs, 'avg bandwidth', averageBandwidth);
if (averageBandwidth < lowestAverageBandwidth) {
bestCodecs = codecs;
lowestAverageBandwidth = averageBandwidth;
}
});
goog.asserts.assert(bestCodecs !== '', 'Should have chosen codecs!');
goog.asserts.assert(!isNaN(lowestAverageBandwidth),
'Bandwidth should be a number!');
return bestCodecs;
}
/**
* Get a string representing all codecs used in a variant.
*
* @param {!shaka.extern.Variant} variant
* @return {string}
* @private
*/
static getVariantCodecs_(variant) {
// Only consider the base of the codec string. For example, these should
// both be considered the same codec: avc1.42c01e, avc1.4d401f
let baseVideoCodec = '';
if (variant.video) {
baseVideoCodec =
shaka.util.MimeUtils.getNormalizedCodec(variant.video.codecs);
}
let baseAudioCodec = '';
if (variant.audio) {
baseAudioCodec =
shaka.util.MimeUtils.getNormalizedCodec(variant.audio.codecs);
}
return baseVideoCodec + '-' + baseAudioCodec;
}
/**
* 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 {{width: number, height:number}} 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 {{width: number, height: number}} 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}
*/
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;
if (variant.disabledUntilTime != 0) {
if (variant.disabledUntilTime > Date.now() / 1000) {
return false;
}
variant.disabledUntilTime = 0;
}
// |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) {
if (!inRange(video.width,
restrictions.minWidth,
Math.min(restrictions.maxWidth, maxHwRes.width))) {
return false;
}
if (!inRange(video.height,
restrictions.minHeight,
Math.min(restrictions.maxHeight, maxHwRes.height))) {
return false;
}
if (!inRange(video.width * video.height,
restrictions.minPixels,
restrictions.maxPixels)) {
return false;
}
}
// |variant.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;
}
}
if (!inRange(variant.bandwidth,
restrictions.minBandwidth,
restrictions.maxBandwidth)) {
return false;
}
return true;
}
/**
* @param {!Array.<shaka.extern.Variant>} variants
* @param {shaka.extern.Restrictions} restrictions
* @param {{width: number, height: number}} 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.media.DrmEngine} drmEngine
* @param {?shaka.extern.Variant} currentVariant
* @param {shaka.extern.Manifest} manifest
*/
static async filterManifest(
drmEngine, currentVariant, manifest) {
await shaka.util.StreamUtils.filterManifestByMediaCapabilities(manifest,
manifest.offlineSessionIds.length > 0);
shaka.util.StreamUtils.filterManifestByCurrentVariant(
currentVariant, manifest);
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.extern.Manifest} manifest
* @param {boolean} usePersistentLicenses
*/
static async filterManifestByMediaCapabilities(
manifest, usePersistentLicenses) {
goog.asserts.assert(navigator.mediaCapabilities,
'MediaCapabilities should be valid.');
await shaka.util.StreamUtils.getDecodingInfosForVariants(
manifest.variants, usePersistentLicenses, /* srcEquals= */ false);
manifest.variants = manifest.variants.filter((variant) => {
// See: https://github.com/shaka-project/shaka-player/issues/3860
const video = variant.video;
const ContentType = shaka.util.ManifestParserUtils.ContentType;
if (video) {
let videoCodecs = shaka.util.StreamUtils.patchVp9(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 = shaka.util.ManifestParserUtils.guessCodecs(
ContentType.VIDEO, allCodecs);
const audioCodecs = shaka.util.ManifestParserUtils.guessCodecs(
ContentType.AUDIO, allCodecs);
const audioFullType = shaka.util.MimeUtils.getFullOrConvertedType(
video.mimeType, audioCodecs, ContentType.AUDIO);
if (!MediaSource.isTypeSupported(audioFullType)) {
return false;
}
}
const fullType = shaka.util.MimeUtils.getFullOrConvertedType(
video.mimeType, videoCodecs, ContentType.VIDEO);
if (!MediaSource.isTypeSupported(fullType)) {
return false;
}
}
const audio = variant.audio;
if (audio) {
const codecs =
shaka.util.StreamUtils.getCorrectAudioCodecs_(audio.codecs);
const fullType = shaka.util.MimeUtils.getFullOrConvertedType(
audio.mimeType, codecs, ContentType.AUDIO);
if (!MediaSource.isTypeSupported(fullType)) {
return false;
}
}
// See: https://github.com/shaka-project/shaka-player/issues/3380
if (shaka.util.Platform.isXboxOne() && video &&
((video.width && video.width > 1920) ||
(video.height && video.height > 1080)) &&
(video.codecs.includes('avc1.') ||
video.codecs.includes('avc3.'))) {
shaka.log.debug('Dropping variant - not compatible with platform',
shaka.util.StreamUtils.getVariantSummaryString_(variant));
return false;
}
const supported = variant.decodingInfos.some((decodingInfo) => {
return decodingInfo.supported;
});
// Filter out all unsupported variants.
if (!supported) {
shaka.log.debug('Dropping variant - not compatible with platform',
shaka.util.StreamUtils.getVariantSummaryString_(variant));
}
return supported;
});
}
/**
* 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
* @exportDoc
*/
static async getDecodingInfosForVariants(variants, usePersistentLicenses,
srcEquals) {
const gotDecodingInfo = variants.some((variant) =>
variant.decodingInfos.length);
if (gotDecodingInfo) {
shaka.log.debug('Already got the variants\' decodingInfo.');
return;
}
const mediaCapabilities = navigator.mediaCapabilities;
const operations = [];
const getVariantDecodingInfos = (async (variant, decodingConfig) => {
try {
const result = await mediaCapabilities.decodingInfo(decodingConfig);
variant.decodingInfos.push(result);
} catch (e) {
shaka.log.info('MediaCapabilities.decodingInfo() failed.',
JSON.stringify(decodingConfig), e);
}
});
for (const variant of variants) {
/** @type {!Array.<!MediaDecodingConfiguration>} */
const decodingConfigs = shaka.util.StreamUtils.getDecodingConfigs_(
variant, usePersistentLicenses, srcEquals);
for (const config of decodingConfigs) {
operations.push(getVariantDecodingInfos(variant, config));
}
}
await Promise.all(operations);
}
/**
* Generate a MediaDecodingConfiguration object to get the decodingInfo
* results for each variant.
* @param {!shaka.extern.Variant} variant
* @param {boolean} usePersistentLicenses
* @param {boolean} srcEquals
* @return {!Array.<!MediaDecodingConfiguration>}
* @private
*/
static getDecodingConfigs_(variant, usePersistentLicenses, srcEquals) {
const audio = variant.audio;
const video = variant.video;
const ContentType = shaka.util.ManifestParserUtils.ContentType;
/** @type {!MediaDecodingConfiguration} */
const mediaDecodingConfig = {
type: srcEquals ? 'file' : 'media-source',
};
if (video) {
let videoCodecs = video.codecs;
// For multiplexed streams with audio+video codecs, the config should have
// AudioConfiguration and VideoConfiguration.
if (video.codecs.includes(',')) {
const allCodecs = video.codecs.split(',');
videoCodecs = shaka.util.ManifestParserUtils.guessCodecs(
ContentType.VIDEO, allCodecs);
videoCodecs = shaka.util.StreamUtils.patchVp9(videoCodecs);
const audioCodecs = shaka.util.ManifestParserUtils.guessCodecs(
ContentType.AUDIO, allCodecs);
const audioFullType = shaka.util.MimeUtils.getFullOrConvertedType(
video.mimeType, audioCodecs, ContentType.AUDIO);
mediaDecodingConfig.audio = {
contentType: audioFullType,
channels: 2,
bitrate: variant.bandwidth || 1,
samplerate: 1,
spatialRendering: false,
};
}
videoCodecs = shaka.util.StreamUtils.patchVp9(videoCodecs);
const fullType = shaka.util.MimeUtils.getFullOrConvertedType(
video.mimeType, videoCodecs, ContentType.VIDEO);
// VideoConfiguration
mediaDecodingConfig.video = {
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':
mediaDecodingConfig.video.transferFunction = 'srgb';
break;
case 'PQ':
mediaDecodingConfig.video.transferFunction = 'pq';
break;
case 'HLG':
mediaDecodingConfig.video.transferFunction = 'hlg';
break;
}
}
}
if (audio) {
const codecs =
shaka.util.StreamUtils.getCorrectAudioCodecs_(audio.codecs);
const fullType = shaka.util.MimeUtils.getFullOrConvertedType(
audio.mimeType, codecs, ContentType.AUDIO);
// AudioConfiguration
mediaDecodingConfig.audio = {
contentType: fullType,
channels: audio.channelsCount || 2,
bitrate: audio.bandwidth || variant.bandwidth || 1,
samplerate: audio.audioSamplingRate || 1,
spatialRendering: audio.spatialAudio,
};
}
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 [mediaDecodingConfig];
}
// 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()) {
// Create a copy of the mediaDecodingConfig.
const config = /** @type {!MediaDecodingConfiguration} */
(Object.assign({}, mediaDecodingConfig));
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) {
initDataTypes.add(initData.initDataType);
}
if (initDataTypes.size > 1) {
shaka.log.v2('DrmInfo contains more than one initDataType,',
'and we use the initDataType of the first initData.',
info);
}
keySystemConfig.initDataType = info.initData[0].initDataType;
}
if (info.distinctiveIdentifierRequired) {
keySystemConfig.distinctiveIdentifier = 'required';
}
if (info.persistentStateRequired) {
keySystemConfig.persistentState = 'required';
}
if (info.sessionType) {
keySystemConfig.sessionTypes = [info.sessionType];
}
if (audio) {
if (!keySystemConfig.audio) {
// KeySystemTrackConfiguration
keySystemConfig.audio = {
robustness: info.audioRobustness,
};
} else {
keySystemConfig.audio.robustness =
keySystemConfig.audio.robustness || info.audioRobustness;
}
}
if (video) {
if (!keySystemConfig.video) {
// KeySystemTrackConfiguration
keySystemConfig.video = {
robustness: info.videoRobustness,
};
} else {
keySystemConfig.video.robustness =
keySystemConfig.video.robustness || info.videoRobustness;
}
}
}
config.keySystemConfiguration = keySystemConfig;
configs.push(config);
}
return configs;
}
/**
* Generates the correct audio codec for MediaDecodingConfiguration and
* for MediaSource.isTypeSupported.
* @param {string} codecs
* @return {string}
* @private
*/
static getCorrectAudioCodecs_(codecs) {
// Some Tizen devices seem to misreport AC-3 support, but correctly
// report EC-3 support. So query EC-3 as a fallback for AC-3.
// See https://github.com/shaka-project/shaka-player/issues/2989 for
// details.
if (shaka.util.Platform.isTizen()) {
return codecs.toLowerCase() == 'ac-3' ? 'ec-3' : codecs;
} else {
return codecs;
}
}
/**
* MediaCapabilities supports 'vp09...' codecs, but not 'vp9'. Translate vp9
* codec strings into 'vp09...', to allow such content to play with
* mediaCapabilities enabled.
*
* @param {string} codec
* @return {string}
*/
static patchVp9(codec) {
if (codec == 'vp9') {
// This means profile 0, level 4.1, 8-bit color. This supports 1080p @
// 60Hz. See https://en.wikipedia.org/wiki/VP9#Levels
//
// If we don't have more detailed codec info, assume this profile and
// level because it's high enough to likely accommodate the parameters we
// do have, such as width and height. If an implementation is checking
// the profile and level very strictly, we want older VP9 content to
// still work to some degree. But we don't want to set a level so high
// that it is rejected by a hardware decoder that can't handle the
// maximum requirements of the level.
//
// This became an issue specifically on Firefox on M1 Macs.
return 'vp09.00.41.08';
}
return codec;
}
/**
* Alters the given Manifest to filter out any streams uncompatible with the
* current variant.
*
* @param {?shaka.extern.Variant} currentVariant
* @param {shaka.extern.Manifest} manifest
*/
static filterManifestByCurrentVariant(currentVariant, manifest) {
const StreamUtils = shaka.util.StreamUtils;
manifest.variants = manifest.variants.filter((variant) => {
const audio = variant.audio;
const video = variant.video;
if (audio && currentVariant && currentVariant.audio) {
if (!StreamUtils.areStreamsCompatible_(audio, currentVariant.audio)) {
shaka.log.debug('Droping variant - not compatible with active audio',
'active audio',
StreamUtils.getStreamSummaryString_(currentVariant.audio),
'variant.audio',
StreamUtils.getStreamSummaryString_(audio));
return false;
}
}
if (video && currentVariant && currentVariant.video) {
if (!StreamUtils.areStreamsCompatible_(video, currentVariant.video)) {
shaka.log.debug('Droping variant - not compatible with active video',
'active video',
StreamUtils.getStreamSummaryString_(currentVariant.video),
'variant.video',
StreamUtils.getStreamSummaryString_(video));
return false;
}
}
return true;
});
}
/**
* Alters the given Manifest to filter out any unsupported text streams.
*
* @param {shaka.extern.Manifest} manifest
* @private
*/
static filterTextStreams_(manifest) {
// Filter text streams.
manifest.textStreams = manifest.textStreams.filter((stream) => {
const fullMimeType = shaka.util.MimeUtils.getFullType(
stream.mimeType, stream.codecs);
const keep = shaka.text.TextEngine.isTypeSupported(fullMimeType);
if (!keep) {
shaka.log.debug('Dropping text stream. Is not supported by the ' +
'platform.', stream);
}
return keep;
});
}
/**
* Alters the given Manifest to filter out any unsupported image streams.
*
* @param {shaka.extern.Manifest} manifest
* @private
*/
static async filterImageStreams_(manifest) {
const imageStreams = [];
for (const stream of manifest.imageStreams) {
const mimeType = stream.mimeType;
if (!shaka.util.StreamUtils.supportedImageMimeTypes_.has(mimeType)) {
const minImage = shaka.util.StreamUtils.minImage_.get(mimeType);
if (minImage) {
// eslint-disable-next-line no-await-in-loop
const res = await shaka.util.StreamUtils.isImageSupported_(minImage);
shaka.util.StreamUtils.supportedImageMimeTypes_.set(mimeType, res);
} else {
shaka.util.StreamUtils.supportedImageMimeTypes_.set(mimeType, false);
}
}
const keep =
shaka.util.StreamUtils.supportedImageMimeTypes_.get(mimeType);
if (!keep) {
shaka.log.debug('Dropping image stream. Is not supported by the ' +
'platform.', stream);
} else {
imageStreams.push(stream);
}
}
manifest.imageStreams = imageStreams;
}
/**
* @param {string} minImage
* @return {!Promise.<boolean>}
* @private
*/
static isImageSupported_(minImage) {
return new Promise((resolve) => {
const imageElement = /** @type {HTMLImageElement} */(new Image());
imageElement.src = minImage;
if ('decode' in imageElement) {
imageElement.decode().then(() => {
resolve(true);
}).catch(() => {
resolve(false);
});
} else {
imageElement.onload = imageElement.onerror = () => {
resolve(imageElement.height === 2);
};
}
});
}
/**
* @param {shaka.extern.Stream} s0
* @param {shaka.extern.Stream} s1
* @return {boolean}
* @private
*/
static areStreamsCompatible_(s0, s1) {
// Basic mime types and basic codecs need to match.
// For example, we can't adapt between WebM and MP4,
// nor can we adapt between mp4a.* to ec-3.
// We can switch between text types on the fly,
// so don't run this check on text.
if (s0.mimeType != s1.mimeType) {
return false;
}
if (s0.codecs.split('.')[0] != s1.codecs.split('.')[0]) {
return false;
}
return true;
}
/**
* @param {shaka.extern.Variant} variant
* @return {shaka.extern.Track}
*/
static variantToTrack(variant) {
/** @type {?shaka.extern.Stream} */
const audio = variant.audio;
/** @type {?shaka.extern.Stream} */
const video = variant.video;
/** @type {?string} */
const audioMimeType = audio ? audio.mimeType : null;
/** @type {?string} */
const videoMimeType = video ? video.mimeType : null;
/** @type {?string} */
const audioCodec = audio ? audio.codecs : null;
/** @type {?string} */
const videoCodec = video ? video.codecs : null;
/** @type {!Array.<string>} */
const codecs = [];
if (videoCodec) {
codecs.push(videoCodec);
}
if (audioCodec) {
codecs.push(audioCodec);
}
/** @type {!Array.<string>} */
const mimeTypes = [];
if (video) {
mimeTypes.push(video.mimeType);
}
if (audio) {
mimeTypes.push(audio.mimeType);
}
/** @type {?string} */
const mimeType = mimeTypes[0] || null;
/** @type {!Array.<string>} */
const kinds = [];
if (audio) {
kinds.push(audio.kind);
}
if (video) {
kinds.push(video.kind);
}
/** @type {?string} */
const kind = kinds[0] || null;
/** @type {!Set.<string>} */
const roles = new Set();
if (audio) {
for (const role of audio.roles) {
roles.add(role);
}
}
if (video) {
for (const role of video.roles) {
roles.add(role);
}
}
/** @type {shaka.extern.Track} */
const track = {
id: variant.id,
active: false,
type: 'variant',
bandwidth: variant.bandwidth,
language: variant.language,
label: null,
kind: kind,
width: null,
height: null,
frameRate: null,
pixelAspectRatio: null,
hdr: null,
mimeType: mimeType,
audioMimeType: audioMimeType,