Files
palemoon27/dom/media/mediasource/ContainerParser.cpp
T
roytam1 93f846cd1f import changes from `dev' branch of rmottola/Arctic-Fox:
- Bug 1275016 - Rename Endian.h to EndianUtils.h to avoid #include confusion with Android's endian.h stdlib header. r=froydnj (b54a25f572)
- add crashreporter stuff (aa7ef15337)
- Bug 1261168 - Add AlignedAutoTArray type in Web Audio; r=padenot (285d2cb88b)
- Bug 1273390. Part 1 - move some functions to private. r=jya. (07a3037e59)
- Bug 1273390. Part 2 - add assertions. r=jya. (2cae7c596a)
- Bug 1273390. Part 3 - rename some functions to be consistent with other sub-classes of MediaDataDecoder. r=jya. (c48c7060ce)
- Bug 1273390. Part 4 - remove use of FlushableTaskQueue::Flush(). r=jya. (00565a65f4)
- Bug 1273390. Part 5 - remove use of FlushableTaskQueue. r=jya. (30600b204e)
- Bug 1273774. Part 1 - remove unused members and thread assertions. r=jya (f5177ed641)
- Bug 1273774. Part 2 - do decoding jobs synchronously without dispatching. r=jya. (62d840d27c)
- Bug 1273774. Part 3 - remove members no longer used. r=jya. (e957ca512a)
- Bug 1244410: [ffmpeg] Ensure the last drained frame has the proper duration set. r=gerald (d5521bfdd4)
- Bug 1271508. Part 1 - refactor FFmpegAudioDecoder code to be similar to FFmpegVideoDecoder::Input() so it would be easier to extract common code to the parent class. r=jya. (613e6c624c)
- Bug 1271508. Part 2 - rename functions so they are the same as those of FFmpegAudioDecoder so it would be easier to extract common code to the parent class. r=jya. (cb281cba26)
- Bug 1270350 - per comment 0, use SyncRunnable to repalce the boilerplate code. r=jya. (b99460e571)
- Bug 1271508. Part 3 - extract code to the parent class and remove use of mTaskQueue from sub-classes. r=jya. (2a7ff4dd1e)
- Bug 1274216 - remove use of FlushableTaskQueue from PlatformDecoderModule. r=jya. (eb160c5fa2)
- Bug 1271517. Part 1 - remove use of FlushableTaskQueue::Flush() from FFmpegDataDecoder::Flush(). r=jya. (fdf10da4ab)
- Bug 1271517. Part 2 - remove use of FlushableTaskQueue. r=jya. (a7016d8506)
- Bug 1273397. Part 1 - rename some functions to be consistent with other MediaDataDecoder sub-classes. r=jya. (7eecb164be)
- Bug 1273397. Part 2 - constify some members. r=jya. (e4482f9a23)
- Bug 1273397. Part 3 - remove use of FlushableTaskQueue::Flush(). r=jya. (0b7ee073fe)
- Bug 1273397. Part 4 - remove use of FlushableTaskQueue. r=jya. (6a612161d5)
- Bug 1273397. Part 5 - add assertions. r=jya. (ff3a62a6fb)
- Bug 1274199 - remove use of FlushableTaskQueue. r=cpearce. (adc4c84ede)
- Bug 1273405. Part 1 - rename some functions to be consistent with other MediaDataDecoder sub-classes. r=jya. (af123d6c21)
- Bug 1273405. Part 2 - remove use of FlushableTaskQueue::Flush(). r=jya. (2d144bfbcd)
- Bug 1273405. Part 3 - remove use of FlushableTaskQueue. r=jya. (1e9ea3c2c7)
- Bug 1273405. Part 4 - add assertions. r=jya. (b400647323)
- Bug 1271491: [WMF] P1. Don't use main thread only preferences methods. r=cpearce (7177454dfb)
- Bug 1262427. Don't try D3D11 harder. r=dvander (404147d6fa)
- Use gfxConfig for D3D9 preferences. (bug 1270650, r=jrmuizel) (40d89c154c)
- Bug 1271491: P2. Allow initialization of WMFPlatformDecoderModule from any threads. r=mattwoodrow (c8fe0bf009)
- Bug 1271491: P3. Remove refcounting the number of time apple's linkers are called. r=cpearce (0324ffe876)
- Bug 1271491: [ffmpeg] P4. Remove requirements to call Init on the main thread. r=cpearce (b511d7dfd5)
- Bug 1271491: [GMP] P5. Allow GMPDecoderModule::Init() to be called off the main thread. r=cpearce (2131eb0b2e)
- Bug 1266102 - Don't run VP9 benchmark on Android r=jya (57d7b573fe)
- Bug 1271491: P6. Remove the need to call PDMFactory::Init(). r=cpearce (5726cfe49c)
- Bug 1271491: P7. Remove unused members. r=alfredo (0f8a9dde73)
- Bug 1268905 - Disable D3D11 with some Toshiba DLLs - r=cpearce (b5bf77442e)
- Bug 1269204 - Disable D3D11 with idg10umd32 9.17.10.2857 - r=cpearce (7eb6a3d96b)
- Bug 1273406 - Disable D3D11 with some iSonyVideoProcessor DLLs - r=cpearce (d9b6f0cefe)
- Bug 1273406 - Ugly macros transform into beautiful constexpr goodness - r=cpearce (0671483695)
- Bug 1273691 - Implement 'media.wmf.disable-d3d11-for-dlls' pref - r=cpearce (193ae53070)
- Bug 1272225. Part 1 - add assertions to make thread constraints clear. r=jya. (83c620470e)
- Bug 1272225. Part 2 - remove use of FlushableTaskQueue::Flush(). r=jya. (9473e092d1)
- Bug 1272553. Part 1 - move code around to be able to extract common code in P2. r=jya. (d727f97ee8)
- Bug 1272553. Part 2 - extract common code to the parent class. r=jya. (2fb3cd4bd9)
- Bug 1272553. Part 3 - make mTaskQueue private. r=jya. (93fea98cb6)
- Bug 1272232. Part 1 - move code around so we can extract common code in P2. r=jya. (8cdaab9078)
- Bug 1272232. Part 2 - extract common code to the parent class. r=jya. (27156668b3)
- Bug 1272232. Part 3 - constify some members and make them private when possible. r=jya. (550b963d97)
- Bug 1272232. Part 4 - remove use of FlushableTaskQueue::Flush(). r=jya. (bdbfdeb6bc)
- Bug 1272232. Part 5 - remove use of FlushableTaskQueue. r=jya. (640f889a9d)
- Bug 1274913 - Move PDM log definition to header. r=njn (823b07f42b)
- Bug 1275538: P1. Abort early if a skip request is in progress. r=gerald,kamidphish (d67b8a2236)
- Bug 1272422 - Part 1: Expose control of suspending background video. r=cpearce (ec7193773f)
- Bug 1272422 - Part 2: Vidoe -> Video. r=cpearce (97390aee69)
- Bug 1272422 - Part 3: Don't reset audio queue. r=jya (e183db1062)
- Bug 1272964: P1. Only activate skip to next keyframe logic when next keyframe time is known. r=gerald (1be74df027)
- Bug 1272964: P2. Don't activate skip to next keyframe until we passed the internal seek target. r=gerald (c55b6ae003)
- Bug 1258922: [MSE] P1. Initialise variable. r=gerald (56a5acb345)
- Bug 1258922: [MSE] P2. Do not go over gap when attempting to find the next key frame. r=gerald (db1319f080)
- Bug 1258922: [MSE] P3. Check that the data we are attempting to skip to is buffered. r=gerald (621d71d5d6)
- Bug 1258922: [MSE] P4. Set draining flag to true when skip to next keyframe failed. r=gerald (6c75613faf)
- Bug 1272916: [MSE] P1. Don't rely only on dts gap to establish if we have a gap in our source buffer. r=gerald (8770113b83)
- Bug 1272964: [MSE] P3. Do not skip over gaps when searching for the next keyframe. r=gerald (76916c5ac6)
- Bug 1272964: P4. Only flush decoder if skip to next keyframe actually succeeds. r=cpearce (5394708eef)
- Bug 1270323: P1. Don't reset flag indicating that new data was received. r=cpearce (d32f06ef34)
- Bug 1270323: P2. Don't process new incoming data while a skip to next keyframe is pending. r=cpearce (bca7909de9)
- Bug 1270323: [ffmpeg] P3. Use the dts of the last sample input, not the dts of the last decoded sample (0d768c33ef)
- Bug 1270323: P4. Don't drain decoder if we're already waiting for new data. r=cpearce (679302cb6e)
- Bug 1270323: P5. Prevent potential null deref. r=cpearce (cc63270e06)
- Bug 1275538: P2. Drop decoded frames that we know are already too late. r=kamidphish (4e7af9398c)
- Bug 1273018: P1. Rename some members. r=gerald (3a92fbd994)
- Bug 1273018: P2. Don't reject audio waiting promise when performing a video only seek. r=gerald (34e4988db1)
- Bug 1273018: P3. Adjust range of audio assertions. r=gerald (feb2afd0ae)
- Bug 1249706 - Backout a085ea2d24bb for blowing telemetry server's mind. r=backout (d61fb51f52)
- Bug 1249706 - Fix 8fe22dd4fc8a (backout of a085ea2d24bb). r=bustage (ba65251db7)
- Bug 1272964: [MSE] P5. Default to skipping to the next keyframe if no keyframe was found past currentTime. (29086fcf56)
- Bug 1272964: P6. Exclude frames dropped due to internal seeking from calculations. r=cpearce (bf6faa7612)
- Bug 1068151 - keep decoding a corrupted video. r=jya (3b5462e5b6)
- Bug 1273947 - Update ResetDecode() to ResetDecode(TargetQueue) r=jya (6c28d46974)
- Bug 1277508: P1. Don't attempt to demux new samples while we're currently draining. r=kamidphish (64f200b921)
- Bug 1274933: Reject data promise when EOS is encountered following waiting for data. r=gerald (5bba4a7853)
- Bug 1277508: P2. Add HasPendingDrain convenience method. r=kamidphish (3d89a90a97)
2024-10-08 23:23:56 +08:00

667 lines
21 KiB
C++

/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=8 sts=2 et sw=2 tw=80: */
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#include "ContainerParser.h"
#include "WebMBufferedParser.h"
#include "mozilla/EndianUtils.h"
#include "mozilla/ErrorResult.h"
#include "mp4_demuxer/MoofParser.h"
#include "mozilla/Logging.h"
#include "mozilla/Maybe.h"
#include "MediaData.h"
#ifdef MOZ_FMP4
#include "MP4Stream.h"
#include "mp4_demuxer/AtomType.h"
#include "mp4_demuxer/ByteReader.h"
#endif
#include "SourceBufferResource.h"
extern mozilla::LogModule* GetMediaSourceSamplesLog();
#define STRINGIFY(x) #x
#define TOSTRING(x) STRINGIFY(x)
#define MSE_DEBUG(name, arg, ...) MOZ_LOG(GetMediaSourceSamplesLog(), mozilla::LogLevel::Debug, (TOSTRING(name) "(%p:%s)::%s: " arg, this, mType.get(), __func__, ##__VA_ARGS__))
#define MSE_DEBUGV(name, arg, ...) MOZ_LOG(GetMediaSourceSamplesLog(), mozilla::LogLevel::Verbose, (TOSTRING(name) "(%p:%s)::%s: " arg, this, mType.get(), __func__, ##__VA_ARGS__))
namespace mozilla {
ContainerParser::ContainerParser(const nsACString& aType)
: mHasInitData(false)
, mType(aType)
{
}
ContainerParser::~ContainerParser() = default;
bool
ContainerParser::IsInitSegmentPresent(MediaByteBuffer* aData)
{
MSE_DEBUG(ContainerParser, "aLength=%u [%x%x%x%x]",
aData->Length(),
aData->Length() > 0 ? (*aData)[0] : 0,
aData->Length() > 1 ? (*aData)[1] : 0,
aData->Length() > 2 ? (*aData)[2] : 0,
aData->Length() > 3 ? (*aData)[3] : 0);
return false;
}
bool
ContainerParser::IsMediaSegmentPresent(MediaByteBuffer* aData)
{
MSE_DEBUG(ContainerParser, "aLength=%u [%x%x%x%x]",
aData->Length(),
aData->Length() > 0 ? (*aData)[0] : 0,
aData->Length() > 1 ? (*aData)[1] : 0,
aData->Length() > 2 ? (*aData)[2] : 0,
aData->Length() > 3 ? (*aData)[3] : 0);
return false;
}
bool
ContainerParser::ParseStartAndEndTimestamps(MediaByteBuffer* aData,
int64_t& aStart, int64_t& aEnd)
{
return false;
}
bool
ContainerParser::TimestampsFuzzyEqual(int64_t aLhs, int64_t aRhs)
{
return llabs(aLhs - aRhs) <= GetRoundingError();
}
int64_t
ContainerParser::GetRoundingError()
{
NS_WARNING("Using default ContainerParser::GetRoundingError implementation");
return 0;
}
bool
ContainerParser::HasCompleteInitData()
{
return mHasInitData && !!mInitData->Length();
}
MediaByteBuffer*
ContainerParser::InitData()
{
return mInitData;
}
MediaByteRange
ContainerParser::InitSegmentRange()
{
return mCompleteInitSegmentRange;
}
MediaByteRange
ContainerParser::MediaHeaderRange()
{
return mCompleteMediaHeaderRange;
}
MediaByteRange
ContainerParser::MediaSegmentRange()
{
return mCompleteMediaSegmentRange;
}
class WebMContainerParser : public ContainerParser {
public:
explicit WebMContainerParser(const nsACString& aType)
: ContainerParser(aType)
, mParser(0)
, mOffset(0)
{}
static const unsigned NS_PER_USEC = 1000;
static const unsigned USEC_PER_SEC = 1000000;
bool IsInitSegmentPresent(MediaByteBuffer* aData) override
{
ContainerParser::IsInitSegmentPresent(aData);
// XXX: This is overly primitive, needs to collect data as it's appended
// to the SB and handle, rather than assuming everything is present in a
// single aData segment.
// 0x1a45dfa3 // EBML
// ...
// DocType == "webm"
// ...
// 0x18538067 // Segment (must be "unknown" size or contain a value large
// enough to include the Segment Information and Tracks
// elements that follow)
// 0x1549a966 // -> Segment Info
// 0x1654ae6b // -> One or more Tracks
// 0x1a45dfa3 // EBML
if (aData->Length() >= 4 &&
(*aData)[0] == 0x1a && (*aData)[1] == 0x45 && (*aData)[2] == 0xdf &&
(*aData)[3] == 0xa3) {
return true;
}
return false;
}
bool IsMediaSegmentPresent(MediaByteBuffer* aData) override
{
ContainerParser::IsMediaSegmentPresent(aData);
// XXX: This is overly primitive, needs to collect data as it's appended
// to the SB and handle, rather than assuming everything is present in a
// single aData segment.
// 0x1a45dfa3 // EBML
// ...
// DocType == "webm"
// ...
// 0x18538067 // Segment (must be "unknown" size)
// 0x1549a966 // -> Segment Info
// 0x1654ae6b // -> One or more Tracks
// 0x1f43b675 // Cluster
if (aData->Length() >= 4 &&
(*aData)[0] == 0x1f && (*aData)[1] == 0x43 && (*aData)[2] == 0xb6 &&
(*aData)[3] == 0x75) {
return true;
}
// 0x1c53bb6b // Cues
if (aData->Length() >= 4 &&
(*aData)[0] == 0x1c && (*aData)[1] == 0x53 && (*aData)[2] == 0xbb &&
(*aData)[3] == 0x6b) {
return true;
}
return false;
}
bool ParseStartAndEndTimestamps(MediaByteBuffer* aData,
int64_t& aStart, int64_t& aEnd) override
{
bool initSegment = IsInitSegmentPresent(aData);
if (mLastMapping && (initSegment || IsMediaSegmentPresent(aData))) {
// The last data contained a complete cluster but we can only detect it
// now that a new one is starting.
// We use mOffset as end position to ensure that any blocks not reported
// by WebMBufferParser are properly skipped.
mCompleteMediaSegmentRange = MediaByteRange(mLastMapping.ref().mSyncOffset,
mOffset);
mLastMapping.reset();
MSE_DEBUG(WebMContainerParser, "New cluster found at start, ending previous one");
return false;
}
if (initSegment) {
mOffset = 0;
mParser = WebMBufferedParser(0);
mOverlappedMapping.Clear();
mInitData = new MediaByteBuffer();
mResource = new SourceBufferResource(NS_LITERAL_CSTRING("video/webm"));
mCompleteMediaHeaderRange = MediaByteRange();
mCompleteMediaSegmentRange = MediaByteRange();
}
// XXX if it only adds new mappings, overlapped but not available
// (e.g. overlap < 0) frames are "lost" from the reported mappings here.
nsTArray<WebMTimeDataOffset> mapping;
mapping.AppendElements(mOverlappedMapping);
mOverlappedMapping.Clear();
ReentrantMonitor dummy("dummy");
mParser.Append(aData->Elements(), aData->Length(), mapping, dummy);
if (mResource) {
mResource->AppendData(aData);
}
// XXX This is a bit of a hack. Assume if there are no timecodes
// present and it's an init segment that it's _just_ an init segment.
// We should be more precise.
if (initSegment || !HasCompleteInitData()) {
if (mParser.mInitEndOffset > 0) {
MOZ_ASSERT(mParser.mInitEndOffset <= mResource->GetLength());
if (!mInitData->SetLength(mParser.mInitEndOffset, fallible)) {
// Super unlikely OOM
return false;
}
mCompleteInitSegmentRange = MediaByteRange(0, mParser.mInitEndOffset);
char* buffer = reinterpret_cast<char*>(mInitData->Elements());
mResource->ReadFromCache(buffer, 0, mParser.mInitEndOffset);
MSE_DEBUG(WebMContainerParser, "Stashed init of %u bytes.",
mParser.mInitEndOffset);
mResource = nullptr;
} else {
MSE_DEBUG(WebMContainerParser, "Incomplete init found.");
}
mHasInitData = true;
}
mOffset += aData->Length();
if (mapping.IsEmpty()) {
return false;
}
// Calculate media range for first media segment.
// Check if we have a cluster finishing in the current data.
uint32_t endIdx = mapping.Length() - 1;
bool foundNewCluster = false;
while (mapping[0].mSyncOffset != mapping[endIdx].mSyncOffset) {
endIdx -= 1;
foundNewCluster = true;
}
int32_t completeIdx = endIdx;
while (completeIdx >= 0 && mOffset < mapping[completeIdx].mEndOffset) {
MSE_DEBUG(WebMContainerParser, "block is incomplete, missing: %lld",
mapping[completeIdx].mEndOffset - mOffset);
completeIdx -= 1;
}
// Save parsed blocks for which we do not have all data yet.
mOverlappedMapping.AppendElements(mapping.Elements() + completeIdx + 1,
mapping.Length() - completeIdx - 1);
if (completeIdx < 0) {
mLastMapping.reset();
return false;
}
if (mCompleteMediaHeaderRange.IsEmpty()) {
mCompleteMediaHeaderRange = MediaByteRange(mapping[0].mSyncOffset,
mapping[0].mEndOffset);
}
if (foundNewCluster && mOffset >= mapping[endIdx].mEndOffset) {
// We now have all information required to delimit a complete cluster.
int64_t endOffset = mapping[endIdx+1].mSyncOffset;
if (mapping[endIdx+1].mInitOffset > mapping[endIdx].mInitOffset) {
// We have a new init segment before this cluster.
endOffset = mapping[endIdx+1].mInitOffset;
}
mCompleteMediaSegmentRange = MediaByteRange(mapping[endIdx].mSyncOffset,
endOffset);
} else if (mapping[endIdx].mClusterEndOffset >= 0 &&
mOffset >= mapping[endIdx].mClusterEndOffset) {
mCompleteMediaSegmentRange = MediaByteRange(mapping[endIdx].mSyncOffset,
mParser.EndSegmentOffset(mapping[endIdx].mClusterEndOffset));
}
Maybe<WebMTimeDataOffset> previousMapping;
if (completeIdx) {
previousMapping = Some(mapping[completeIdx - 1]);
} else {
previousMapping = mLastMapping;
}
mLastMapping = Some(mapping[completeIdx]);
if (!previousMapping && completeIdx + 1u >= mapping.Length()) {
// We have no previous nor next block available,
// so we can't estimate this block's duration.
return false;
}
uint64_t frameDuration = (completeIdx + 1u < mapping.Length())
? mapping[completeIdx + 1].mTimecode - mapping[completeIdx].mTimecode
: mapping[completeIdx].mTimecode - previousMapping.ref().mTimecode;
aStart = mapping[0].mTimecode / NS_PER_USEC;
aEnd = (mapping[completeIdx].mTimecode + frameDuration) / NS_PER_USEC;
MSE_DEBUG(WebMContainerParser, "[%lld, %lld] [fso=%lld, leo=%lld, l=%u processedIdx=%u fs=%lld]",
aStart, aEnd, mapping[0].mSyncOffset,
mapping[completeIdx].mEndOffset, mapping.Length(), completeIdx,
mCompleteMediaSegmentRange.mEnd);
return true;
}
int64_t GetRoundingError() override
{
int64_t error = mParser.GetTimecodeScale() / NS_PER_USEC;
return error * 2;
}
private:
WebMBufferedParser mParser;
nsTArray<WebMTimeDataOffset> mOverlappedMapping;
int64_t mOffset;
Maybe<WebMTimeDataOffset> mLastMapping;
};
#ifdef MOZ_FMP4
class MP4ContainerParser : public ContainerParser {
public:
explicit MP4ContainerParser(const nsACString& aType)
: ContainerParser(aType)
{}
bool IsInitSegmentPresent(MediaByteBuffer* aData) override
{
ContainerParser::IsInitSegmentPresent(aData);
// Each MP4 atom has a chunk size and chunk type. The root chunk in an MP4
// file is the 'ftyp' atom followed by a file type. We just check for a
// vaguely valid 'ftyp' atom.
AtomParser parser(mType, aData);
return parser.StartWithInitSegment();
}
bool IsMediaSegmentPresent(MediaByteBuffer* aData) override
{
AtomParser parser(mType, aData);
return parser.StartWithMediaSegment();
}
private:
class AtomParser {
public:
AtomParser(const nsACString& aType, const MediaByteBuffer* aData)
{
const nsCString mType(aType); // for logging macro.
mp4_demuxer::ByteReader reader(aData);
mp4_demuxer::AtomType initAtom("ftyp");
mp4_demuxer::AtomType mediaAtom("moof");
while (reader.Remaining() >= 8) {
uint64_t size = reader.ReadU32();
const uint8_t* typec = reader.Peek(4);
uint32_t type = reader.ReadU32();
MSE_DEBUGV(AtomParser ,"Checking atom:'%c%c%c%c' @ %u",
typec[0], typec[1], typec[2], typec[3],
(uint32_t)reader.Offset() - 8);
if (mInitOffset.isNothing() &&
mp4_demuxer::AtomType(type) == initAtom) {
mInitOffset = Some(reader.Offset());
}
if (mMediaOffset.isNothing() &&
mp4_demuxer::AtomType(type) == mediaAtom) {
mMediaOffset = Some(reader.Offset());
}
if (mInitOffset.isSome() && mMediaOffset.isSome()) {
// We have everything we need.
break;
}
if (size == 1) {
// 64 bits size.
if (!reader.CanReadType<uint64_t>()) {
break;
}
size = reader.ReadU64();
} else if (size == 0) {
// Atom extends to the end of the buffer, it can't have what we're
// looking for.
break;
}
if (reader.Remaining() < size - 8) {
// Incomplete atom.
break;
}
reader.Read(size - 8);
}
reader.DiscardRemaining();
}
bool StartWithInitSegment()
{
return mInitOffset.isSome() &&
(mMediaOffset.isNothing() || mInitOffset.ref() < mMediaOffset.ref());
}
bool StartWithMediaSegment()
{
return mMediaOffset.isSome() &&
(mInitOffset.isNothing() || mMediaOffset.ref() < mInitOffset.ref());
}
private:
Maybe<size_t> mInitOffset;
Maybe<size_t> mMediaOffset;
};
public:
bool ParseStartAndEndTimestamps(MediaByteBuffer* aData,
int64_t& aStart, int64_t& aEnd) override
{
bool initSegment = IsInitSegmentPresent(aData);
if (initSegment) {
mResource = new SourceBufferResource(NS_LITERAL_CSTRING("video/mp4"));
mStream = new MP4Stream(mResource);
// We use a timestampOffset of 0 for ContainerParser, and require
// consumers of ParseStartAndEndTimestamps to add their timestamp offset
// manually. This allows the ContainerParser to be shared across different
// timestampOffsets.
mParser = new mp4_demuxer::MoofParser(mStream, 0, /* aIsAudio = */ false);
mInitData = new MediaByteBuffer();
} else if (!mStream || !mParser) {
return false;
}
mResource->AppendData(aData);
MediaByteRangeSet byteRanges;
byteRanges +=
MediaByteRange(int64_t(mParser->mOffset), mResource->GetLength());
mParser->RebuildFragmentedIndex(byteRanges);
if (initSegment || !HasCompleteInitData()) {
MediaByteRange& range = mParser->mInitRange;
if (range.Length()) {
mCompleteInitSegmentRange = range;
if (!mInitData->SetLength(range.Length(), fallible)) {
// Super unlikely OOM
return false;
}
char* buffer = reinterpret_cast<char*>(mInitData->Elements());
mResource->ReadFromCache(buffer, range.mStart, range.Length());
MSE_DEBUG(MP4ContainerParser ,"Stashed init of %u bytes.",
range.Length());
} else {
MSE_DEBUG(MP4ContainerParser, "Incomplete init found.");
}
mHasInitData = true;
}
mp4_demuxer::Interval<mp4_demuxer::Microseconds> compositionRange =
mParser->GetCompositionRange(byteRanges);
mCompleteMediaHeaderRange = mParser->FirstCompleteMediaHeader();
mCompleteMediaSegmentRange = mParser->FirstCompleteMediaSegment();
ErrorResult rv;
if (HasCompleteInitData()) {
mResource->EvictData(mParser->mOffset, mParser->mOffset, rv);
}
if (NS_WARN_IF(rv.Failed())) {
rv.SuppressException();
return false;
}
if (compositionRange.IsNull()) {
return false;
}
aStart = compositionRange.start;
aEnd = compositionRange.end;
MSE_DEBUG(MP4ContainerParser, "[%lld, %lld]",
aStart, aEnd);
return true;
}
// Gaps of up to 35ms (marginally longer than a single frame at 30fps) are considered
// to be sequential frames.
int64_t GetRoundingError() override
{
return 35000;
}
private:
RefPtr<MP4Stream> mStream;
nsAutoPtr<mp4_demuxer::MoofParser> mParser;
};
#endif // MOZ_FMP4
#ifdef MOZ_FMP4
class ADTSContainerParser : public ContainerParser {
public:
explicit ADTSContainerParser(const nsACString& aType)
: ContainerParser(aType)
{}
typedef struct {
size_t header_length; // Length of just the initialization data.
size_t frame_length; // Includes header_length;
uint8_t aac_frames; // Number of AAC frames in the ADTS frame.
bool have_crc;
} Header;
/// Helper to parse the ADTS header, returning data we care about.
/// Returns true if the header is parsed successfully.
/// Returns false if the header is invalid or incomplete,
/// without modifying the passed-in Header object.
bool Parse(MediaByteBuffer* aData, Header& header)
{
MOZ_ASSERT(aData);
// ADTS initialization segments are just the packet header.
if (aData->Length() < 7) {
MSE_DEBUG(ADTSContainerParser, "buffer too short for header.");
return false;
}
// Check 0xfffx sync word plus layer 0.
if (((*aData)[0] != 0xff) || (((*aData)[1] & 0xf6) != 0xf0)) {
MSE_DEBUG(ADTSContainerParser, "no syncword.");
return false;
}
bool have_crc = !((*aData)[1] & 0x01);
if (have_crc && aData->Length() < 9) {
MSE_DEBUG(ADTSContainerParser, "buffer too short for header with crc.");
return false;
}
uint8_t frequency_index = ((*aData)[2] & 0x3c) >> 2;
MOZ_ASSERT(frequency_index < 16);
if (frequency_index == 15) {
MSE_DEBUG(ADTSContainerParser, "explicit frequency disallowed.");
return false;
}
size_t header_length = have_crc ? 9 : 7;
size_t data_length = (((*aData)[3] & 0x03) << 11) ||
(((*aData)[4] & 0xff) << 3) ||
(((*aData)[5] & 0xe0) >> 5);
uint8_t frames = ((*aData)[6] & 0x03) + 1;
MOZ_ASSERT(frames > 0);
MOZ_ASSERT(frames < 4);
// Return successfully parsed data.
header.header_length = header_length;
header.frame_length = header_length + data_length;
header.aac_frames = frames;
header.have_crc = have_crc;
return true;
}
bool IsInitSegmentPresent(MediaByteBuffer* aData) override
{
// Call superclass for logging.
ContainerParser::IsInitSegmentPresent(aData);
Header header;
if (!Parse(aData, header)) {
return false;
}
MSE_DEBUGV(ADTSContainerParser, "%llu byte frame %d aac frames%s",
(unsigned long long)header.frame_length, (int)header.aac_frames,
header.have_crc ? " crc" : "");
return true;
}
bool IsMediaSegmentPresent(MediaByteBuffer* aData) override
{
// Call superclass for logging.
ContainerParser::IsMediaSegmentPresent(aData);
// Make sure we have a header so we know how long the frame is.
// NB this assumes the media segment buffer starts with an
// initialization segment. Since every frame has an ADTS header
// this is a normal place to divide packets, but we can re-parse
// mInitData if we need to handle separate media segments.
Header header;
if (!Parse(aData, header)) {
return false;
}
// We're supposed to return true as long as aData contains the
// start of a media segment, whether or not it's complete. So
// return true if we have any data beyond the header.
if (aData->Length() <= header.header_length) {
return false;
}
// We should have at least a partial frame.
return true;
}
bool ParseStartAndEndTimestamps(MediaByteBuffer* aData,
int64_t& aStart, int64_t& aEnd) override
{
// ADTS header.
Header header;
if (!Parse(aData, header)) {
return false;
}
mHasInitData = true;
mCompleteInitSegmentRange = MediaByteRange(0, int64_t(header.header_length));
// Cache raw header in case the caller wants a copy.
mInitData = new MediaByteBuffer(header.header_length);
mInitData->AppendElements(aData->Elements(), header.header_length);
// Check that we have enough data for the frame body.
if (aData->Length() < header.frame_length) {
MSE_DEBUGV(ADTSContainerParser, "Not enough data for %llu byte frame"
" in %llu byte buffer.",
(unsigned long long)header.frame_length,
(unsigned long long)(aData->Length()));
return false;
}
mCompleteMediaSegmentRange = MediaByteRange(header.header_length,
header.frame_length);
// The ADTS MediaSource Byte Stream Format document doesn't
// define media header. Just treat it the same as the whole
// media segment.
mCompleteMediaHeaderRange = mCompleteMediaSegmentRange;
MSE_DEBUG(ADTSContainerParser, "[%lld, %lld]",
aStart, aEnd);
// We don't update timestamps, regardless.
return false;
}
// Audio shouldn't have gaps.
// Especially when we generate the timestamps ourselves.
int64_t GetRoundingError() override
{
return 0;
}
};
#endif // MOZ_FMP4
/*static*/ ContainerParser*
ContainerParser::CreateForMIMEType(const nsACString& aType)
{
if (aType.LowerCaseEqualsLiteral("video/webm") || aType.LowerCaseEqualsLiteral("audio/webm")) {
return new WebMContainerParser(aType);
}
#ifdef MOZ_FMP4
if (aType.LowerCaseEqualsLiteral("video/mp4") || aType.LowerCaseEqualsLiteral("audio/mp4")) {
return new MP4ContainerParser(aType);
}
if (aType.LowerCaseEqualsLiteral("audio/aac")) {
return new ADTSContainerParser(aType);
}
#endif
return new ContainerParser(aType);
}
#undef MSE_DEBUG
#undef MSE_DEBUGV
} // namespace mozilla