1 /* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
5 #include "VideoUtils.h"
10 #include "CubebUtils.h"
11 #include "ImageContainer.h"
12 #include "MediaContainerType.h"
13 #include "MediaResource.h"
14 #include "TimeUnits.h"
15 #include "mozilla/Base64.h"
16 #include "mozilla/dom/ContentChild.h"
17 #include "mozilla/SchedulerGroup.h"
18 #include "mozilla/SharedThreadPool.h"
19 #include "mozilla/StaticPrefs_accessibility.h"
20 #include "mozilla/StaticPrefs_media.h"
21 #include "mozilla/TaskQueue.h"
22 #include "mozilla/Telemetry.h"
23 #include "nsCharSeparatedTokenizer.h"
24 #include "nsContentTypeParser.h"
25 #include "nsIConsoleService.h"
26 #include "nsINetworkLinkService.h"
27 #include "nsIRandomGenerator.h"
28 #include "nsMathUtils.h"
30 #include "nsServiceManagerUtils.h"
31 #include "nsThreadUtils.h"
32 #include "AudioStream.h"
36 using gfx::ColorRange
;
37 using gfx::CICP::ColourPrimaries
;
38 using gfx::CICP::MatrixCoefficients
;
39 using gfx::CICP::TransferCharacteristics
;
40 using layers::PlanarYCbCrImage
;
41 using media::TimeUnit
;
43 double ToMicrosecondResolution(double aSeconds
) {
45 modf(aSeconds
* USECS_PER_S
, &integer
);
46 return integer
/ USECS_PER_S
;
49 CheckedInt64
SaferMultDiv(int64_t aValue
, uint64_t aMul
, uint64_t aDiv
) {
50 if (aMul
> INT64_MAX
|| aDiv
> INT64_MAX
) {
51 return CheckedInt64(INT64_MAX
) + 1; // Return an invalid checked int.
53 int64_t mul
= AssertedCast
<int64_t>(aMul
);
54 int64_t div
= AssertedCast
<int64_t>(aDiv
);
55 int64_t major
= aValue
/ div
;
56 int64_t remainder
= aValue
% div
;
57 return CheckedInt64(remainder
) * mul
/ div
+ CheckedInt64(major
) * mul
;
60 // Converts from number of audio frames to microseconds, given the specified
62 CheckedInt64
FramesToUsecs(int64_t aFrames
, uint32_t aRate
) {
63 return SaferMultDiv(aFrames
, USECS_PER_S
, aRate
);
66 // Converts from microseconds to number of audio frames, given the specified
68 CheckedInt64
UsecsToFrames(int64_t aUsecs
, uint32_t aRate
) {
69 return SaferMultDiv(aUsecs
, aRate
, USECS_PER_S
);
72 // Format TimeUnit as number of frames at given rate.
73 CheckedInt64
TimeUnitToFrames(const TimeUnit
& aTime
, uint32_t aRate
) {
74 return aTime
.IsValid() ? UsecsToFrames(aTime
.ToMicroseconds(), aRate
)
75 : CheckedInt64(INT64_MAX
) + 1;
78 nsresult
SecondsToUsecs(double aSeconds
, int64_t& aOutUsecs
) {
79 if (aSeconds
* double(USECS_PER_S
) > double(INT64_MAX
)) {
80 return NS_ERROR_FAILURE
;
82 aOutUsecs
= int64_t(aSeconds
* double(USECS_PER_S
));
86 static int32_t ConditionDimension(float aValue
) {
87 // This will exclude NaNs and too-big values.
88 if (aValue
> 1.0 && aValue
<= float(INT32_MAX
)) {
89 return int32_t(NS_round(aValue
));
94 void ScaleDisplayByAspectRatio(gfx::IntSize
& aDisplay
, float aAspectRatio
) {
95 if (aAspectRatio
> 1.0) {
96 // Increase the intrinsic width
98 ConditionDimension(aAspectRatio
* AssertedCast
<float>(aDisplay
.width
));
100 // Increase the intrinsic height
102 ConditionDimension(AssertedCast
<float>(aDisplay
.height
) / aAspectRatio
);
106 static int64_t BytesToTime(int64_t offset
, int64_t length
, int64_t durationUs
) {
107 NS_ASSERTION(length
> 0, "Must have positive length");
108 double r
= double(offset
) / double(length
);
112 return int64_t(double(durationUs
) * r
);
115 media::TimeIntervals
GetEstimatedBufferedTimeRanges(
116 mozilla::MediaResource
* aStream
, int64_t aDurationUsecs
) {
117 media::TimeIntervals buffered
;
118 // Nothing to cache if the media takes 0us to play.
119 if (aDurationUsecs
<= 0 || !aStream
) {
123 // Special case completely cached files. This also handles local files.
124 if (aStream
->IsDataCachedToEndOfResource(0)) {
125 buffered
+= media::TimeInterval(TimeUnit::Zero(),
126 TimeUnit::FromMicroseconds(aDurationUsecs
));
130 int64_t totalBytes
= aStream
->GetLength();
132 // If we can't determine the total size, pretend that we have nothing
133 // buffered. This will put us in a state of eternally-low-on-undecoded-data
134 // which is not great, but about the best we can do.
135 if (totalBytes
<= 0) {
139 int64_t startOffset
= aStream
->GetNextCachedData(0);
140 while (startOffset
>= 0) {
141 int64_t endOffset
= aStream
->GetCachedDataEnd(startOffset
);
142 // Bytes [startOffset..endOffset] are cached.
143 NS_ASSERTION(startOffset
>= 0, "Integer underflow in GetBuffered");
144 NS_ASSERTION(endOffset
>= 0, "Integer underflow in GetBuffered");
146 int64_t startUs
= BytesToTime(startOffset
, totalBytes
, aDurationUsecs
);
147 int64_t endUs
= BytesToTime(endOffset
, totalBytes
, aDurationUsecs
);
148 if (startUs
!= endUs
) {
149 buffered
+= media::TimeInterval(TimeUnit::FromMicroseconds(startUs
),
150 TimeUnit::FromMicroseconds(endUs
));
152 startOffset
= aStream
->GetNextCachedData(endOffset
);
157 void DownmixStereoToMono(mozilla::AudioDataValue
* aBuffer
, uint32_t aFrames
) {
159 const int channels
= 2;
160 for (uint32_t fIdx
= 0; fIdx
< aFrames
; ++fIdx
) {
161 #ifdef MOZ_SAMPLE_TYPE_FLOAT32
166 // The sample of the buffer would be interleaved.
167 sample
= (aBuffer
[fIdx
* channels
] + aBuffer
[fIdx
* channels
+ 1]) * 0.5f
;
168 aBuffer
[fIdx
* channels
] = aBuffer
[fIdx
* channels
+ 1] = sample
;
172 uint32_t DecideAudioPlaybackChannels(const AudioInfo
& info
) {
173 if (StaticPrefs::accessibility_monoaudio_enable()) {
177 if (StaticPrefs::media_forcestereo_enabled()) {
181 return info
.mChannels
;
184 uint32_t DecideAudioPlaybackSampleRate(const AudioInfo
& aInfo
,
185 bool aShouldResistFingerprinting
) {
186 bool resampling
= StaticPrefs::media_resampling_enabled();
192 } else if (aInfo
.mRate
>= 44100) {
193 // The original rate is of good quality and we want to minimize unecessary
194 // resampling, so we let cubeb decide how to resample (if needed).
197 // We will resample all data to match cubeb's preferred sampling rate.
198 rate
= CubebUtils::PreferredSampleRate(aShouldResistFingerprinting
);
200 // bogus rate, fall back to something else;
204 MOZ_DIAGNOSTIC_ASSERT(rate
, "output rate can't be 0.");
209 bool IsDefaultPlaybackDeviceMono() {
210 return CubebUtils::MaxNumberOfChannels() == 1;
213 bool IsVideoContentType(const nsCString
& aContentType
) {
214 constexpr auto video
= "video"_ns
;
215 return FindInReadable(video
, aContentType
);
218 bool IsValidVideoRegion(const gfx::IntSize
& aFrame
,
219 const gfx::IntRect
& aPicture
,
220 const gfx::IntSize
& aDisplay
) {
221 return aFrame
.width
> 0 && aFrame
.width
<= PlanarYCbCrImage::MAX_DIMENSION
&&
223 aFrame
.height
<= PlanarYCbCrImage::MAX_DIMENSION
&&
224 aFrame
.width
* aFrame
.height
<= MAX_VIDEO_WIDTH
* MAX_VIDEO_HEIGHT
&&
225 aPicture
.width
> 0 &&
226 aPicture
.width
<= PlanarYCbCrImage::MAX_DIMENSION
&&
227 aPicture
.x
< PlanarYCbCrImage::MAX_DIMENSION
&&
228 aPicture
.x
+ aPicture
.width
< PlanarYCbCrImage::MAX_DIMENSION
&&
229 aPicture
.height
> 0 &&
230 aPicture
.height
<= PlanarYCbCrImage::MAX_DIMENSION
&&
231 aPicture
.y
< PlanarYCbCrImage::MAX_DIMENSION
&&
232 aPicture
.y
+ aPicture
.height
< PlanarYCbCrImage::MAX_DIMENSION
&&
233 aPicture
.width
* aPicture
.height
<=
234 MAX_VIDEO_WIDTH
* MAX_VIDEO_HEIGHT
&&
235 aDisplay
.width
> 0 &&
236 aDisplay
.width
<= PlanarYCbCrImage::MAX_DIMENSION
&&
237 aDisplay
.height
> 0 &&
238 aDisplay
.height
<= PlanarYCbCrImage::MAX_DIMENSION
&&
239 aDisplay
.width
* aDisplay
.height
<= MAX_VIDEO_WIDTH
* MAX_VIDEO_HEIGHT
;
242 already_AddRefed
<SharedThreadPool
> GetMediaThreadPool(MediaThreadType aType
) {
244 uint32_t threads
= 4;
246 case MediaThreadType::PLATFORM_DECODER
:
247 name
= "MediaPDecoder";
249 case MediaThreadType::WEBRTC_CALL_THREAD
:
250 name
= "WebrtcCallThread";
253 case MediaThreadType::WEBRTC_WORKER
:
254 name
= "WebrtcWorker";
256 case MediaThreadType::MDSM
:
257 name
= "MediaDecoderStateMachine";
260 case MediaThreadType::PLATFORM_ENCODER
:
261 name
= "MediaPEncoder";
264 MOZ_FALLTHROUGH_ASSERT("Unexpected MediaThreadType");
265 case MediaThreadType::SUPERVISOR
:
266 name
= "MediaSupervisor";
270 RefPtr
<SharedThreadPool
> pool
=
271 SharedThreadPool::Get(nsDependentCString(name
), threads
);
273 // Ensure a larger stack for platform decoder threads
274 if (aType
== MediaThreadType::PLATFORM_DECODER
) {
275 const uint32_t minStackSize
= 512 * 1024;
277 MOZ_ALWAYS_SUCCEEDS(pool
->GetThreadStackSize(&stackSize
));
278 if (stackSize
< minStackSize
) {
279 MOZ_ALWAYS_SUCCEEDS(pool
->SetThreadStackSize(minStackSize
));
283 return pool
.forget();
286 bool ExtractVPXCodecDetails(const nsAString
& aCodec
, uint8_t& aProfile
,
287 uint8_t& aLevel
, uint8_t& aBitDepth
) {
288 uint8_t dummyChromaSubsampling
= 1;
289 VideoColorSpace dummyColorspace
;
290 return ExtractVPXCodecDetails(aCodec
, aProfile
, aLevel
, aBitDepth
,
291 dummyChromaSubsampling
, dummyColorspace
);
294 bool ExtractVPXCodecDetails(const nsAString
& aCodec
, uint8_t& aProfile
,
295 uint8_t& aLevel
, uint8_t& aBitDepth
,
296 uint8_t& aChromaSubsampling
,
297 VideoColorSpace
& aColorSpace
) {
298 // Assign default value.
299 aChromaSubsampling
= 1;
300 auto splitter
= aCodec
.Split(u
'.');
301 auto fieldsItr
= splitter
.begin();
302 auto fourCC
= *fieldsItr
;
304 if (!fourCC
.EqualsLiteral("vp09") && !fourCC
.EqualsLiteral("vp08")) {
309 uint8_t primary
, transfer
, matrix
, range
;
310 uint8_t* fields
[] = {&aProfile
, &aLevel
, &aBitDepth
, &aChromaSubsampling
,
311 &primary
, &transfer
, &matrix
, &range
};
314 for (; fieldsItr
!= splitter
.end(); ++fieldsItr
, ++fieldsCount
) {
315 if (fieldsCount
> 7) {
316 // No more than 8 fields are expected.
319 *(fields
[fieldsCount
]) =
320 static_cast<uint8_t>((*fieldsItr
).ToInteger(&rv
, 10));
321 // We got invalid field value, parsing error.
322 NS_ENSURE_SUCCESS(rv
, false);
325 // <sample entry 4CC>.<profile>.<level>.<bitDepth>.
327 // <chromaSubsampling>.<colourPrimaries>.<transferCharacteristics>.
328 // <matrixCoefficients>.<videoFullRangeFlag>
329 // First three fields are mandatory(we have parsed 4CC).
330 if (fieldsCount
< 3) {
331 // Invalid number of fields.
334 // Start to validate the parsing value.
336 // profile should be 0,1,2 or 3.
337 // See https://www.webmproject.org/vp9/profiles/
343 // level, See https://www.webmproject.org/vp9/mp4/#semantics_1
365 if (aBitDepth
!= 8 && aBitDepth
!= 10 && aBitDepth
!= 12) {
370 if (fieldsCount
== 3) {
375 // chromaSubsampling should be 0,1,2,3...4~7 are reserved.
376 if (aChromaSubsampling
> 3) {
380 if (fieldsCount
== 4) {
385 // It is an integer that is defined by the "Colour primaries"
386 // section of ISO/IEC 23001-8:2016 Table 2.
387 // We treat reserved value as false case.
388 if (primary
== 0 || primary
== 3 || primary
> 22) {
392 if (primary
> 12 && primary
< 22) {
393 // 13~21 are reserved values.
396 aColorSpace
.mPrimaries
= static_cast<ColourPrimaries
>(primary
);
398 if (fieldsCount
== 5) {
403 // It is an integer that is defined by the
404 // "Transfer characteristics" section of ISO/IEC 23001-8:2016 Table 3.
405 // We treat reserved value as false case.
406 if (transfer
== 0 || transfer
== 3 || transfer
> 18) {
410 aColorSpace
.mTransfer
= static_cast<TransferCharacteristics
>(transfer
);
412 if (fieldsCount
== 6) {
417 // It is an integer that is defined by the
418 // "Matrix coefficients" section of ISO/IEC 23001-8:2016 Table 4.
419 // We treat reserved value as false case.
420 if (matrix
== 3 || matrix
> 11) {
423 aColorSpace
.mMatrix
= static_cast<MatrixCoefficients
>(matrix
);
425 // If matrixCoefficients is 0 (RGB), then chroma subsampling MUST be 3
427 if (aColorSpace
.mMatrix
== MatrixCoefficients::MC_IDENTITY
&&
428 aChromaSubsampling
!= 3) {
432 if (fieldsCount
== 7) {
437 // videoFullRangeFlag indicates the black level and range of the luma and
438 // chroma signals. 0 = legal range (e.g. 16-235 for 8 bit sample depth);
439 // 1 = full range (e.g. 0-255 for 8-bit sample depth).
440 aColorSpace
.mRange
= static_cast<ColorRange
>(range
);
444 bool ExtractH264CodecDetails(const nsAString
& aCodec
, uint8_t& aProfile
,
445 uint8_t& aConstraint
, uint8_t& aLevel
) {
446 // H.264 codecs parameters have a type defined as avcN.PPCCLL, where
447 // N = avc type. avc3 is avcc with SPS & PPS implicit (within stream)
448 // PP = profile_idc, CC = constraint_set flags, LL = level_idc.
449 // We ignore the constraint_set flags, as it's not clear from any
450 // documentation what constraints the platform decoders support.
452 // http://blog.pearce.org.nz/2013/11/what-does-h264avc1-codecs-parameters.html
454 if (aCodec
.Length() != strlen("avc1.PPCCLL")) {
458 // Verify the codec starts with "avc1." or "avc3.".
459 const nsAString
& sample
= Substring(aCodec
, 0, 5);
460 if (!sample
.EqualsASCII("avc1.") && !sample
.EqualsASCII("avc3.")) {
464 // Extract the profile_idc, constraint_flags and level_idc.
466 aProfile
= Substring(aCodec
, 5, 2).ToInteger(&rv
, 16);
467 NS_ENSURE_SUCCESS(rv
, false);
469 // Constraint flags are stored on the 6 most significant bits, first two bits
470 // are reserved_zero_2bits.
471 aConstraint
= Substring(aCodec
, 7, 2).ToInteger(&rv
, 16);
472 NS_ENSURE_SUCCESS(rv
, false);
474 aLevel
= Substring(aCodec
, 9, 2).ToInteger(&rv
, 16);
475 NS_ENSURE_SUCCESS(rv
, false);
478 aLevel
= H264_LEVEL_1_b
;
479 } else if (aLevel
<= 5) {
486 bool IsH265ProfileRecognizable(uint8_t aProfile
,
487 int32_t aProfileCompabilityFlags
) {
490 eHighThroughputScreenExtended
,
491 eScalableRangeExtension
,
502 Profile p
= eUnknown
;
505 if (aProfile
== 11 || (aProfileCompabilityFlags
& 0x800)) {
506 p
= eHighThroughputScreenExtended
;
509 if (aProfile
== 10 || (aProfileCompabilityFlags
& 0x400)) {
510 p
= eScalableRangeExtension
;
513 if (aProfile
== 9 || (aProfileCompabilityFlags
& 0x200)) {
517 if (aProfile
== 8 || (aProfileCompabilityFlags
& 0x100)) {
521 if (aProfile
== 7 || (aProfileCompabilityFlags
& 0x80)) {
525 if (aProfile
== 6 || (aProfileCompabilityFlags
& 0x40)) {
529 if (aProfile
== 5 || (aProfileCompabilityFlags
& 0x20)) {
533 if (aProfile
== 4 || (aProfileCompabilityFlags
& 0x10)) {
537 // NOTICE: Do not change the order of below sections
538 if (aProfile
== 2 || (aProfileCompabilityFlags
& 0x4)) {
542 // When aProfileCompabilityFlags[1] is equal to 1,
543 // aProfileCompabilityFlags[2] should be equal to 1 as well.
544 if (aProfile
== 1 || (aProfileCompabilityFlags
& 0x2)) {
548 // When aProfileCompabilityFlags[3] is equal to 1,
549 // aProfileCompabilityFlags[1] and
550 // aProfileCompabilityFlags[2] should be equal to 1 as well.
551 if (aProfile
== 3 || (aProfileCompabilityFlags
& 0x8)) {
552 p
= eMainStillPicture
;
555 return p
!= eUnknown
;
558 bool ExtractH265CodecDetails(const nsAString
& aCodec
, uint8_t& aProfile
,
559 uint8_t& aLevel
, nsTArray
<uint8_t>& aConstraints
) {
560 // HEVC codec id consists of:
561 const size_t maxHevcCodecIdLength
=
562 5 + // 'hev1.' or 'hvc1.' prefix (5 chars)
563 4 + // profile, e.g. '.A12' (max 4 chars)
564 9 + // profile_compatibility, dot + 32-bit hex number (max 9 chars)
565 5 + // tier and level, e.g. '.H120' (max 5 chars)
566 18; // up to 6 constraint bytes, bytes are dot-separated and hex-encoded.
568 if (aCodec
.Length() > maxHevcCodecIdLength
) {
572 // Verify the codec starts with "hev1." or "hvc1.".
573 const nsAString
& sample
= Substring(aCodec
, 0, 5);
574 if (!sample
.EqualsASCII("hev1.") && !sample
.EqualsASCII("hvc1.")) {
579 CheckedUint8 profile
;
580 int32_t compabilityFlags
= 0;
581 CheckedUint8 level
= 0;
582 nsTArray
<uint8_t> constraints
;
584 auto splitter
= aCodec
.Split(u
'.');
586 for (auto iter
= splitter
.begin(); iter
!= splitter
.end(); ++iter
, ++count
) {
587 const auto& fieldStr
= *iter
;
588 if (fieldStr
.IsEmpty()) {
593 MOZ_RELEASE_ASSERT(fieldStr
.EqualsASCII("hev1") ||
594 fieldStr
.EqualsASCII("hvc1"));
598 if (count
== 1) { // profile
599 Maybe
<uint8_t> validProfileSpace
;
600 if (fieldStr
.First() == u
'A' || fieldStr
.First() == u
'B' ||
601 fieldStr
.First() == u
'C') {
602 validProfileSpace
.emplace(1 + (fieldStr
.First() - 'A'));
604 // If fieldStr.First() is not A, B, C or a digit, ToInteger() should fail.
605 profile
= validProfileSpace
? Substring(fieldStr
, 1).ToInteger(&rv
)
606 : fieldStr
.ToInteger(&rv
);
607 if (NS_FAILED(rv
) || !profile
.isValid() || profile
.value() > 0x1F) {
613 if (count
== 2) { // profile compatibility flags
614 compabilityFlags
= fieldStr
.ToInteger(&rv
, 16);
615 NS_ENSURE_SUCCESS(rv
, false);
619 if (count
== 3) { // tier and level
620 Maybe
<uint8_t> validProfileTier
;
621 if (fieldStr
.First() == u
'L' || fieldStr
.First() == u
'H') {
622 validProfileTier
.emplace(fieldStr
.First() == u
'L' ? 0 : 1);
624 // If fieldStr.First() is not L, H, or a digit, ToInteger() should fail.
625 level
= validProfileTier
? Substring(fieldStr
, 1).ToInteger(&rv
)
626 : fieldStr
.ToInteger(&rv
);
627 if (NS_FAILED(rv
) || !level
.isValid()) {
633 // The rest is constraint bytes.
638 CheckedUint8
byte(fieldStr
.ToInteger(&rv
, 16));
639 if (NS_FAILED(rv
) || !byte
.isValid()) {
642 constraints
.AppendElement(byte
.value());
645 if (count
< 4 /* Parse til level at least */ || constraints
.Length() > 6 ||
646 !IsH265ProfileRecognizable(profile
.value(), compabilityFlags
)) {
650 aProfile
= profile
.value();
651 aLevel
= level
.value();
652 aConstraints
= std::move(constraints
);
656 bool ExtractAV1CodecDetails(const nsAString
& aCodec
, uint8_t& aProfile
,
657 uint8_t& aLevel
, uint8_t& aTier
, uint8_t& aBitDepth
,
658 bool& aMonochrome
, bool& aSubsamplingX
,
659 bool& aSubsamplingY
, uint8_t& aChromaSamplePosition
,
660 VideoColorSpace
& aColorSpace
) {
661 auto fourCC
= Substring(aCodec
, 0, 4);
663 if (!fourCC
.EqualsLiteral("av01")) {
669 // av01.N.NN[MH].NN.B.BBN.NN.NN.NN.B
672 // [] = single character
675 // <sample entry 4CC>.<profile>.<level><tier>.<bitDepth>
676 // [.<monochrome>.<chromaSubsampling>
677 // .<colorPrimaries>.<transferCharacteristics>.<matrixCoefficients>
678 // .<videoFullRangeFlag>]
680 // If any optional field is found, all the rest must be included.
682 // Parsing stops but does not fail upon encountering unexpected characters
683 // at the end of an otherwise well-formed string.
685 // See https://aomediacodec.github.io/av1-isobmff/#codecsparam
697 AV1Field fields
[] = {{&aProfile
, 1},
699 // parsing loop skips tier
708 auto splitter
= aCodec
.Split(u
'.');
709 auto iter
= splitter
.begin();
711 size_t fieldCount
= 0;
712 while (iter
!= splitter
.end()) {
713 // Exit if there are too many fields.
714 if (fieldCount
>= 9) {
718 AV1Field
& field
= fields
[fieldCount
];
719 auto fieldStr
= *iter
;
721 if (field
.field
== &aLevel
) {
722 // Parse tier and remove it from the level field.
723 if (fieldStr
.Length() < 3) {
726 auto tier
= fieldStr
[2];
737 fieldStr
.SetLength(2);
740 if (fieldStr
.Length() < field
.length
) {
744 // Manually parse values since nsString.ToInteger silently stops parsing
745 // upon encountering unknown characters.
747 for (size_t i
= 0; i
< field
.length
; i
++) {
748 uint8_t oldValue
= value
;
749 char16_t character
= fieldStr
[i
];
750 if ('0' <= character
&& character
<= '9') {
751 value
= (value
* 10) + (character
- '0');
755 if (value
< oldValue
) {
756 // Overflow is possible on the 3-digit subsampling field.
761 *field
.field
= value
;
766 // Field had extra characters, exit early.
767 if (fieldStr
.Length() > field
.length
) {
768 // Disallow numbers as unexpected characters.
769 char16_t character
= fieldStr
[field
.length
];
770 if ('0' <= character
&& character
<= '9') {
777 // Spec requires profile, level/tier, bitdepth, or for all possible fields to
779 if (fieldCount
!= 3 && fieldCount
!= 9) {
783 // Valid profiles are: Main (0), High (1), Professional (2).
784 // Levels range from 0 to 23, or 31 to remove level restrictions.
785 if (aProfile
> 2 || (aLevel
> 23 && aLevel
!= 31)) {
789 if (fieldCount
== 3) {
790 // If only required fields are included, set to the spec defaults for the
791 // rest and continue validating.
793 aSubsamplingX
= true;
794 aSubsamplingY
= true;
795 aChromaSamplePosition
= 0;
796 aColorSpace
.mPrimaries
= ColourPrimaries::CP_BT709
;
797 aColorSpace
.mTransfer
= TransferCharacteristics::TC_BT709
;
798 aColorSpace
.mMatrix
= MatrixCoefficients::MC_BT709
;
799 aColorSpace
.mRange
= ColorRange::LIMITED
;
801 // Extract the individual values for the remaining fields, and check for
802 // valid values for each.
804 // Monochrome is a boolean.
805 if (monochrome
> 1) {
808 aMonochrome
= !!monochrome
;
810 // Extract individual digits of the subsampling field.
811 // Subsampling is two binary digits for x and y
812 // and one enumerated sample position field of
813 // Unknown (0), Vertical (1), Colocated (2).
814 uint8_t subsamplingX
= (subsampling
/ 100) % 10;
815 uint8_t subsamplingY
= (subsampling
/ 10) % 10;
816 if (subsamplingX
> 1 || subsamplingY
> 1) {
819 aSubsamplingX
= !!subsamplingX
;
820 aSubsamplingY
= !!subsamplingY
;
821 aChromaSamplePosition
= subsampling
% 10;
822 if (aChromaSamplePosition
> 2) {
826 // We can validate the color space values using CICP enums, as the values
827 // are standardized in Rec. ITU-T H.273.
828 aColorSpace
.mPrimaries
= static_cast<ColourPrimaries
>(primary
);
829 aColorSpace
.mTransfer
= static_cast<TransferCharacteristics
>(transfer
);
830 aColorSpace
.mMatrix
= static_cast<MatrixCoefficients
>(matrix
);
831 if (gfx::CICP::IsReserved(aColorSpace
.mPrimaries
) ||
832 gfx::CICP::IsReserved(aColorSpace
.mTransfer
) ||
833 gfx::CICP::IsReserved(aColorSpace
.mMatrix
)) {
836 // Range is a boolean, true meaning full and false meaning limited range.
840 aColorSpace
.mRange
= static_cast<ColorRange
>(range
);
843 // Begin validating all parameter values:
845 // Only Levels 8 and above (4.0 and greater) can specify Tier.
846 // See: 5.5.1. General sequence header OBU syntax,
847 // if ( seq_level_idx[ i ] > 7 ) seq_tier[ i ] = f(1)
848 // https://aomediacodec.github.io/av1-spec/av1-spec.pdf#page=42
849 // Also: Annex A, A.3. Levels, columns MainMbps and HighMbps
850 // at https://aomediacodec.github.io/av1-spec/av1-spec.pdf#page=652
851 if (aLevel
< 8 && aTier
> 0) {
855 // Supported bit depths are 8, 10 and 12.
856 if (aBitDepth
!= 8 && aBitDepth
!= 10 && aBitDepth
!= 12) {
859 // Profiles 0 and 1 only support 8-bit and 10-bit.
860 if (aProfile
< 2 && aBitDepth
== 12) {
864 // x && y subsampling is used to specify monochrome 4:0:0 as well
865 bool is420or400
= aSubsamplingX
&& aSubsamplingY
;
866 bool is422
= aSubsamplingX
&& !aSubsamplingY
;
867 bool is444
= !aSubsamplingX
&& !aSubsamplingY
;
869 // Profile 0 only supports 4:2:0.
870 if (aProfile
== 0 && !is420or400
) {
873 // Profile 1 only supports 4:4:4.
874 if (aProfile
== 1 && !is444
) {
877 // Profile 2 only allows 4:2:2 at 10 bits and below.
878 if (aProfile
== 2 && aBitDepth
< 12 && !is422
) {
881 // Chroma sample position can only be specified with 4:2:0.
882 if (aChromaSamplePosition
!= 0 && !is420or400
) {
886 // When video is monochrome, subsampling must be 4:0:0.
887 if (aMonochrome
&& (aChromaSamplePosition
!= 0 || !is420or400
)) {
890 // Monochrome can only be signaled when profile is 0 or 2.
891 // Note: This check is redundant with the above subsampling check,
892 // as profile 1 only supports 4:4:4.
893 if (aMonochrome
&& aProfile
!= 0 && aProfile
!= 2) {
897 // Identity matrix requires 4:4:4 subsampling.
898 if (aColorSpace
.mMatrix
== MatrixCoefficients::MC_IDENTITY
&&
899 (aSubsamplingX
|| aSubsamplingY
||
900 aColorSpace
.mRange
!= gfx::ColorRange::FULL
)) {
907 nsresult
GenerateRandomName(nsCString
& aOutSalt
, uint32_t aLength
) {
909 nsCOMPtr
<nsIRandomGenerator
> rg
=
910 do_GetService("@mozilla.org/security/random-generator;1", &rv
);
915 // For each three bytes of random data we will get four bytes of ASCII.
916 const uint32_t requiredBytesLength
=
917 static_cast<uint32_t>((aLength
+ 3) / 4 * 3);
920 rv
= rg
->GenerateRandomBytes(requiredBytesLength
, &buffer
);
926 nsDependentCSubstring
randomData(reinterpret_cast<const char*>(buffer
),
927 requiredBytesLength
);
928 rv
= Base64Encode(randomData
, temp
);
935 aOutSalt
= std::move(temp
);
939 nsresult
GenerateRandomPathName(nsCString
& aOutSalt
, uint32_t aLength
) {
940 nsresult rv
= GenerateRandomName(aOutSalt
, aLength
);
945 // Base64 characters are alphanumeric (a-zA-Z0-9) and '+' and '/', so we need
946 // to replace illegal characters -- notably '/'
947 aOutSalt
.ReplaceChar(FILE_PATH_SEPARATOR FILE_ILLEGAL_CHARACTERS
, '_');
951 already_AddRefed
<TaskQueue
> CreateMediaDecodeTaskQueue(const char* aName
) {
952 RefPtr
<TaskQueue
> queue
= TaskQueue::Create(
953 GetMediaThreadPool(MediaThreadType::PLATFORM_DECODER
), aName
);
954 return queue
.forget();
957 void SimpleTimer::Cancel() {
960 nsCOMPtr
<nsIEventTarget
> target
;
961 mTimer
->GetTarget(getter_AddRefs(target
));
963 nsresult rv
= target
->IsOnCurrentThread(&onCurrent
);
964 MOZ_ASSERT(NS_SUCCEEDED(rv
) && onCurrent
);
973 SimpleTimer::Notify(nsITimer
* timer
) {
974 RefPtr
<SimpleTimer
> deathGrip(this);
983 SimpleTimer::GetName(nsACString
& aName
) {
984 aName
.AssignLiteral("SimpleTimer");
988 nsresult
SimpleTimer::Init(nsIRunnable
* aTask
, uint32_t aTimeoutMs
,
989 nsIEventTarget
* aTarget
) {
992 // Get target thread first, so we don't have to cancel the timer if it fails.
993 nsCOMPtr
<nsIEventTarget
> target
;
997 target
= GetMainThreadSerialEventTarget();
999 return NS_ERROR_NOT_AVAILABLE
;
1003 rv
= NS_NewTimerWithCallback(getter_AddRefs(mTimer
), this, aTimeoutMs
,
1004 nsITimer::TYPE_ONE_SHOT
, target
);
1005 if (NS_FAILED(rv
)) {
1013 NS_IMPL_ISUPPORTS(SimpleTimer
, nsITimerCallback
, nsINamed
)
1015 already_AddRefed
<SimpleTimer
> SimpleTimer::Create(nsIRunnable
* aTask
,
1016 uint32_t aTimeoutMs
,
1017 nsIEventTarget
* aTarget
) {
1018 RefPtr
<SimpleTimer
> t(new SimpleTimer());
1019 if (NS_FAILED(t
->Init(aTask
, aTimeoutMs
, aTarget
))) {
1025 void LogToBrowserConsole(const nsAString
& aMsg
) {
1026 if (!NS_IsMainThread()) {
1028 nsCOMPtr
<nsIRunnable
> task
= NS_NewRunnableFunction(
1029 "LogToBrowserConsole", [msg
]() { LogToBrowserConsole(msg
); });
1030 SchedulerGroup::Dispatch(task
.forget());
1033 nsCOMPtr
<nsIConsoleService
> console(
1034 do_GetService("@mozilla.org/consoleservice;1"));
1036 NS_WARNING("Failed to log message to console.");
1039 nsAutoString
msg(aMsg
);
1040 console
->LogStringMessage(msg
.get());
1043 bool ParseCodecsString(const nsAString
& aCodecs
,
1044 nsTArray
<nsString
>& aOutCodecs
) {
1046 bool expectMoreTokens
= false;
1047 nsCharSeparatedTokenizer
tokenizer(aCodecs
, ',');
1048 while (tokenizer
.hasMoreTokens()) {
1049 const nsAString
& token
= tokenizer
.nextToken();
1050 expectMoreTokens
= tokenizer
.separatorAfterCurrentToken();
1051 aOutCodecs
.AppendElement(token
);
1053 return !expectMoreTokens
;
1056 bool ParseMIMETypeString(const nsAString
& aMIMEType
,
1057 nsString
& aOutContainerType
,
1058 nsTArray
<nsString
>& aOutCodecs
) {
1059 nsContentTypeParser
parser(aMIMEType
);
1060 nsresult rv
= parser
.GetType(aOutContainerType
);
1061 if (NS_FAILED(rv
)) {
1066 parser
.GetParameter("codecs", codecsStr
);
1067 return ParseCodecsString(codecsStr
, aOutCodecs
);
1071 static bool StartsWith(const nsACString
& string
, const char (&prefix
)[N
]) {
1072 if (N
- 1 > string
.Length()) {
1075 return memcmp(string
.Data(), prefix
, N
- 1) == 0;
1078 bool IsH264CodecString(const nsAString
& aCodec
) {
1079 uint8_t profile
= 0;
1080 uint8_t constraint
= 0;
1082 return ExtractH264CodecDetails(aCodec
, profile
, constraint
, level
);
1085 bool IsH265CodecString(const nsAString
& aCodec
) {
1086 uint8_t profile
= 0;
1088 nsTArray
<uint8_t> constraints
;
1089 return ExtractH265CodecDetails(aCodec
, profile
, level
, constraints
);
1092 bool IsAACCodecString(const nsAString
& aCodec
) {
1093 return aCodec
.EqualsLiteral("mp4a.40.2") || // MPEG4 AAC-LC
1094 aCodec
.EqualsLiteral(
1095 "mp4a.40.02") || // MPEG4 AAC-LC(for compatibility)
1096 aCodec
.EqualsLiteral("mp4a.40.5") || // MPEG4 HE-AAC
1097 aCodec
.EqualsLiteral(
1098 "mp4a.40.05") || // MPEG4 HE-AAC(for compatibility)
1099 aCodec
.EqualsLiteral("mp4a.67") || // MPEG2 AAC-LC
1100 aCodec
.EqualsLiteral("mp4a.40.29"); // MPEG4 HE-AACv2
1103 bool IsVP8CodecString(const nsAString
& aCodec
) {
1104 uint8_t profile
= 0;
1106 uint8_t bitDepth
= 0;
1107 return aCodec
.EqualsLiteral("vp8") || aCodec
.EqualsLiteral("vp8.0") ||
1108 (StartsWith(NS_ConvertUTF16toUTF8(aCodec
), "vp08") &&
1109 ExtractVPXCodecDetails(aCodec
, profile
, level
, bitDepth
));
1112 bool IsVP9CodecString(const nsAString
& aCodec
) {
1113 uint8_t profile
= 0;
1115 uint8_t bitDepth
= 0;
1116 return aCodec
.EqualsLiteral("vp9") || aCodec
.EqualsLiteral("vp9.0") ||
1117 (StartsWith(NS_ConvertUTF16toUTF8(aCodec
), "vp09") &&
1118 ExtractVPXCodecDetails(aCodec
, profile
, level
, bitDepth
));
1121 bool IsAV1CodecString(const nsAString
& aCodec
) {
1122 uint8_t profile
, level
, tier
, bitDepth
, chromaPosition
;
1123 bool monochrome
, subsamplingX
, subsamplingY
;
1124 VideoColorSpace colorSpace
;
1125 return aCodec
.EqualsLiteral("av1") ||
1126 (StartsWith(NS_ConvertUTF16toUTF8(aCodec
), "av01") &&
1127 ExtractAV1CodecDetails(aCodec
, profile
, level
, tier
, bitDepth
,
1128 monochrome
, subsamplingX
, subsamplingY
,
1129 chromaPosition
, colorSpace
));
1132 UniquePtr
<TrackInfo
> CreateTrackInfoWithMIMEType(
1133 const nsACString
& aCodecMIMEType
) {
1134 UniquePtr
<TrackInfo
> trackInfo
;
1135 if (StartsWith(aCodecMIMEType
, "audio/")) {
1136 trackInfo
.reset(new AudioInfo());
1137 trackInfo
->mMimeType
= aCodecMIMEType
;
1138 } else if (StartsWith(aCodecMIMEType
, "video/")) {
1139 trackInfo
.reset(new VideoInfo());
1140 trackInfo
->mMimeType
= aCodecMIMEType
;
1145 UniquePtr
<TrackInfo
> CreateTrackInfoWithMIMETypeAndContainerTypeExtraParameters(
1146 const nsACString
& aCodecMIMEType
,
1147 const MediaContainerType
& aContainerType
) {
1148 UniquePtr
<TrackInfo
> trackInfo
= CreateTrackInfoWithMIMEType(aCodecMIMEType
);
1150 VideoInfo
* videoInfo
= trackInfo
->GetAsVideoInfo();
1152 Maybe
<int32_t> maybeWidth
= aContainerType
.ExtendedType().GetWidth();
1153 if (maybeWidth
&& *maybeWidth
> 0) {
1154 videoInfo
->mImage
.width
= *maybeWidth
;
1155 videoInfo
->mDisplay
.width
= *maybeWidth
;
1157 Maybe
<int32_t> maybeHeight
= aContainerType
.ExtendedType().GetHeight();
1158 if (maybeHeight
&& *maybeHeight
> 0) {
1159 videoInfo
->mImage
.height
= *maybeHeight
;
1160 videoInfo
->mDisplay
.height
= *maybeHeight
;
1162 } else if (trackInfo
->GetAsAudioInfo()) {
1163 AudioInfo
* audioInfo
= trackInfo
->GetAsAudioInfo();
1164 Maybe
<int32_t> maybeChannels
=
1165 aContainerType
.ExtendedType().GetChannels();
1166 if (maybeChannels
&& *maybeChannels
> 0) {
1167 audioInfo
->mChannels
= *maybeChannels
;
1169 Maybe
<int32_t> maybeSamplerate
=
1170 aContainerType
.ExtendedType().GetSamplerate();
1171 if (maybeSamplerate
&& *maybeSamplerate
> 0) {
1172 audioInfo
->mRate
= *maybeSamplerate
;
1179 bool OnCellularConnection() {
1180 uint32_t linkType
= nsINetworkLinkService::LINK_TYPE_UNKNOWN
;
1181 if (XRE_IsContentProcess()) {
1182 mozilla::dom::ContentChild
* cpc
=
1183 mozilla::dom::ContentChild::GetSingleton();
1185 NS_WARNING("Can't get ContentChild singleton in content process!");
1188 linkType
= cpc
->NetworkLinkType();
1191 nsCOMPtr
<nsINetworkLinkService
> nls
=
1192 do_GetService(NS_NETWORK_LINK_SERVICE_CONTRACTID
, &rv
);
1193 if (NS_FAILED(rv
)) {
1194 NS_WARNING("Can't get nsINetworkLinkService.");
1198 rv
= nls
->GetLinkType(&linkType
);
1199 if (NS_FAILED(rv
)) {
1200 NS_WARNING("Can't get network link type.");
1206 case nsINetworkLinkService::LINK_TYPE_UNKNOWN
:
1207 case nsINetworkLinkService::LINK_TYPE_ETHERNET
:
1208 case nsINetworkLinkService::LINK_TYPE_USB
:
1209 case nsINetworkLinkService::LINK_TYPE_WIFI
:
1211 case nsINetworkLinkService::LINK_TYPE_WIMAX
:
1212 case nsINetworkLinkService::LINK_TYPE_MOBILE
:
1219 } // end namespace mozilla