Files
palemoon27/dom/media/encoder/MediaEncoder.cpp
T
roytam1 fef8b08889 import changes from `dev' branch of rmottola/Arctic-Fox:
- Bug 1237842 - Unlock mMutex before calling CloseActive. r=cpearce (d0677f1981)
- Bug 1230857 - Ensure GMPService has sufficient file permissions to delete GMPs. r=gerald (e7f0c4b2b6)
- Bug 1236380 - GMPStorage::mShutdown=true until Init() succeeds - r=cpearce (fde2025f4f)
- Bug 1254311: [mp4] Ignore empty raw sample. r=cpearce (216a9417c3)
- Bug 1215115 - part1: Replace the vorbis by opus in MediaEncoder and also reomve the VorbisTrackEncoder files. r=rillian (760c559e3c)
- Bug 1215115 - part2: Mux opus into webm, remove bitdepth. r=rillian (1c996f0aee)
- Bug 1215115 - part3: Fix gtest. Remove TestVorbisTrackEncoder.cpp. r=rillian (5a68915a4a)
- Bug 1215115 - part4: Enable MOZ_WEBM_ENCODER by default. r=ted (6638b7fffb)
- Bug 1257318: Pass TRACK_EVENT_ENDED events through to the TrackEncoders r=padenot (b92b2dcc94)
- Bug 1261007 - Part 3 - Remove the same/redundant code of checking the unique image. r=jolin (608e6477bc)
- Bug 1243611 - When EOS, call vpx_codec_encode correctly. r=rillian (83887c89c8)
- Bug 1260353 - Remove unnecessary method AnimValuesStyleRule::AddPropertiesToSet() r=hiro (36f5e7fcc9)
- Bug 1213775: VP8 automatic resizing breaks ffmpeg-based players; turn it off in VP8TrackEncoder r=jya (23c2a27371)
- Bug 1185171 - Modify gmp-test-output-protection.h to prevent failure on machines without a physical monitor attached. r=bobowen (8375c5075d)
- Bug 1185171: Add 0xc02625e5 as a valid failure code for GMPOutputProtection test. r=cpearce (1d10a75aeb)
- Bug 1151746 - Origin tuples in should include schemes. r=edwin (32610b0cfa)
- Bug 1180101 - Test 0 length atom inside moov; r=jya (3fae8aee45)
- Bug 1244523: [mp4] P4. Add gtest. r=kentuckyfriedtakahe (3f71b5060a)
- Bug 1255626: [gtest] Properly shutdown task queue should error occurs. r=gerald (4ec1bf360e)
- Bug 1224363 - Added vp8/ivf test case - r=rillian Bug 1224369 - p1: Test cases given as list - r=rillian Bug 1224369 - p2: Added vp8/ivf test case - r=rillian Bug 1224361 - Added vp8/ivf test case - r=rillian (595ebe09be)
- Bug 1231075. Respect the timestamp of video frames and don't pop frames as fast as we can in real-time mode. r=roc. (b72329c0fa)
- Bug 1237160: Do not count frames not composited as dropped. r=cpearce (e7e18d0700)
- Bug 1233648 - Fix some insufficient includes. r=kinetik. (e36cdd3e05)
- Bug 1216460 - [1.1] Refactor data types, fix logs and prevent harmful type promotions in SourceBuffer eviction handling. r=jya (047a7ca64f)
- Bug 1259916: [MSE] P1. Fix eviction. r=gerald (13195f392b)
- Bug 1216460 - [2.2] Refactor SourceBuffer frame eviction and threshold defaults. r=jya (105962c942)
- Bug 1259274: [MSE] P1. Remove unnecessary abstraction layer. r=gerald (e7b7603f30)
- Bug 1259274: [MSE] P2. Remove unused code path. r=gerald (dce9fa447c)
- Bug 1259274: [MSE] P3. Refactor handling of tasks so they only ever run concurrently. r=gerald (9c3f40d9b8)
- Bug 1259274: [MSE] P4. Add AutoTaskQueue convenience class. r=gerald Just like TaskQueue, but doesn't require to be shutdown. (0310ff2b7f)
- Bug 1259274: [MSE] P5. Use new AutoTaskQueue with MSE objects. r=gerald (3f72558eb2)
- Bug 1259916: [MSE] P2. Bump audio source buffer eviction threshold to 30MB. r=gerald (2ffe148c1a)
- Bug 1259916: [MSE] P3. Simplify eviction calculation logic. r=gerald (11250c02bc)
- Bug 1199879: [MSE] Use latest demux end time to detect discontinuities. r=gerald (f89bdd763f)
- Bug 1239983 - Diags around TrackBuffersMgr promises - r=jya (57f3e58636)
- Bug 1258410: [MSE] P1. Abort if mInputDemuxer has been reset. r=gerald (07ca58adb0)
- Bug 1258410: [MSE] P2. Disconnect init promise if any pending. r=gerald (0627c5a174)
- Bug 1259985 - Add missing return after null-check - r=jya (b6ee457b89)
- bit of Bwqug 1259274: [MSE] P3 (200d743676)
- Bug 1216560 - [3.1] Make eviction thresholds const. r=jya (b44c78f999)
- Bug 1259473 - per comment 14, move actions involving |this| to Init() from the constructor. r=jya. (30c402aacb)
- Bug 1258562: MSE] Abort if MediaSource has been shutdown. r=gerald (6fce6bc9db)
- Bug 1246358: [MSE] Take pre-roll time into consideration when seeking. r=gerald (dacbcd7f36)
- spaces (abbb56d413)
- Bug 657791 - Update WebM demuxer to clamp cueless seeks instead of failing. r=kinetik (785ae83126)
- Bug 1219178 - [9.1] Make SeekPosition available with tests disabled. a=me for fixing build problems (cd1bdef203)
- minor format (4a718e47f2)
- Bug 1265399 - Replace 0.7071 with sqrt(0.5) in downmixing equations; r=padenot (2243d331c5)
- Bug 1265794: P1. Ensure we can always fit a complete audio frame in an audio buffer. r=rillian (37f575184c)
- Bug 1256626. Workaround Microsoft macro silliness. r=me (18930fbccd)
- Bug 1264898 - Remove unnecessary |FinishAddTracks| call in |DOMHwMediaStream::Init|. r=jesup, r=pehrsons (1b610cdb4f)
- Bug 848994 - p5. Check Silverlight presence - r=cpearce (98b4521ae3)
- Bug 848994 - p6. Analyze Windows issues - r=cpearce (9de769166a)
- Bug 848994 - p7. Filter front-end notifications - r=cpearce (e3aab89a95)
- Bug 1256533 - Use std::deque<int32_t> instead of nsDeque - r=cpearce (e21c02fcab)
2024-06-23 07:20:41 +08:00

419 lines
14 KiB
C++

/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-*/
/* 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 "MediaEncoder.h"
#include "MediaDecoder.h"
#include "nsIPrincipal.h"
#include "nsMimeTypes.h"
#include "mozilla/Logging.h"
#include "mozilla/Preferences.h"
#include "mozilla/StaticPtr.h"
#include "mozilla/gfx/Point.h" // IntSize
#include"GeckoProfiler.h"
#include "OggWriter.h"
#include "OpusTrackEncoder.h"
#ifdef MOZ_WEBM_ENCODER
#include "VP8TrackEncoder.h"
#include "WebMWriter.h"
#endif
#ifdef MOZ_OMX_ENCODER
#include "OmxTrackEncoder.h"
#include "ISOMediaWriter.h"
#endif
#ifdef LOG
#undef LOG
#endif
mozilla::LazyLogModule gMediaEncoderLog("MediaEncoder");
#define LOG(type, msg) MOZ_LOG(gMediaEncoderLog, type, msg)
namespace mozilla {
void
MediaEncoder::SetDirectConnect(bool aConnected)
{
mDirectConnected = aConnected;
}
void
MediaEncoder::NotifyRealtimeData(MediaStreamGraph* aGraph,
TrackID aID,
StreamTime aTrackOffset,
uint32_t aTrackEvents,
const MediaSegment& aRealtimeMedia)
{
if (mSuspended == RECORD_NOT_SUSPENDED) {
// Process the incoming raw track data from MediaStreamGraph, called on the
// thread of MediaStreamGraph.
if (mAudioEncoder && aRealtimeMedia.GetType() == MediaSegment::AUDIO) {
mAudioEncoder->NotifyQueuedTrackChanges(aGraph, aID,
aTrackOffset, aTrackEvents,
aRealtimeMedia);
} else if (mVideoEncoder && aRealtimeMedia.GetType() == MediaSegment::VIDEO) {
mVideoEncoder->NotifyQueuedTrackChanges(aGraph, aID,
aTrackOffset, aTrackEvents,
aRealtimeMedia);
}
}
}
void
MediaEncoder::NotifyQueuedTrackChanges(MediaStreamGraph* aGraph,
TrackID aID,
StreamTime aTrackOffset,
uint32_t aTrackEvents,
const MediaSegment& aQueuedMedia,
MediaStream* aInputStream,
TrackID aInputTrackID)
{
if (!mDirectConnected) {
NotifyRealtimeData(aGraph, aID, aTrackOffset, aTrackEvents, aQueuedMedia);
} else {
if (aTrackEvents != 0) {
// forward events (TRACK_EVENT_ENDED) but not the media
if (aQueuedMedia.GetType() == MediaSegment::VIDEO) {
VideoSegment segment;
NotifyRealtimeData(aGraph, aID, aTrackOffset, aTrackEvents, segment);
} else {
AudioSegment segment;
NotifyRealtimeData(aGraph, aID, aTrackOffset, aTrackEvents, segment);
}
}
if (mSuspended == RECORD_RESUMED) {
if (mVideoEncoder) {
if (aQueuedMedia.GetType() == MediaSegment::VIDEO) {
// insert a null frame of duration equal to the first segment passed
// after Resume(), so it'll get added to one of the DirectListener frames
VideoSegment segment;
gfx::IntSize size(0,0);
segment.AppendFrame(nullptr, aQueuedMedia.GetDuration(), size,
PRINCIPAL_HANDLE_NONE);
mVideoEncoder->NotifyQueuedTrackChanges(aGraph, aID,
aTrackOffset, aTrackEvents,
segment);
mSuspended = RECORD_NOT_SUSPENDED;
}
} else {
mSuspended = RECORD_NOT_SUSPENDED; // no video
}
}
}
}
void
MediaEncoder::NotifyEvent(MediaStreamGraph* aGraph,
MediaStreamListener::MediaStreamGraphEvent event)
{
// In case that MediaEncoder does not receive a TRACK_EVENT_ENDED event.
LOG(LogLevel::Debug, ("NotifyRemoved in [MediaEncoder]."));
if (mAudioEncoder) {
mAudioEncoder->NotifyEvent(aGraph, event);
}
if (mVideoEncoder) {
mVideoEncoder->NotifyEvent(aGraph, event);
}
}
/* static */
already_AddRefed<MediaEncoder>
MediaEncoder::CreateEncoder(const nsAString& aMIMEType, uint32_t aAudioBitrate,
uint32_t aVideoBitrate, uint32_t aBitrate,
uint8_t aTrackTypes)
{
PROFILER_LABEL("MediaEncoder", "CreateEncoder",
js::ProfileEntry::Category::OTHER);
nsAutoPtr<ContainerWriter> writer;
nsAutoPtr<AudioTrackEncoder> audioEncoder;
nsAutoPtr<VideoTrackEncoder> videoEncoder;
RefPtr<MediaEncoder> encoder;
nsString mimeType;
if (!aTrackTypes) {
LOG(LogLevel::Error, ("NO TrackTypes!!!"));
return nullptr;
}
#ifdef MOZ_WEBM_ENCODER
else if (MediaEncoder::IsWebMEncoderEnabled() &&
(aMIMEType.EqualsLiteral(VIDEO_WEBM) ||
(aTrackTypes & ContainerWriter::CREATE_VIDEO_TRACK))) {
if (aTrackTypes & ContainerWriter::CREATE_AUDIO_TRACK
&& MediaDecoder::IsOpusEnabled()) {
audioEncoder = new OpusTrackEncoder();
NS_ENSURE_TRUE(audioEncoder, nullptr);
}
videoEncoder = new VP8TrackEncoder();
writer = new WebMWriter(aTrackTypes);
NS_ENSURE_TRUE(writer, nullptr);
NS_ENSURE_TRUE(videoEncoder, nullptr);
mimeType = NS_LITERAL_STRING(VIDEO_WEBM);
}
#endif //MOZ_WEBM_ENCODER
#ifdef MOZ_OMX_ENCODER
else if (MediaEncoder::IsOMXEncoderEnabled() &&
(aMIMEType.EqualsLiteral(VIDEO_MP4) ||
(aTrackTypes & ContainerWriter::CREATE_VIDEO_TRACK))) {
if (aTrackTypes & ContainerWriter::CREATE_AUDIO_TRACK) {
audioEncoder = new OmxAACAudioTrackEncoder();
NS_ENSURE_TRUE(audioEncoder, nullptr);
}
videoEncoder = new OmxVideoTrackEncoder();
writer = new ISOMediaWriter(aTrackTypes);
NS_ENSURE_TRUE(writer, nullptr);
NS_ENSURE_TRUE(videoEncoder, nullptr);
mimeType = NS_LITERAL_STRING(VIDEO_MP4);
} else if (MediaEncoder::IsOMXEncoderEnabled() &&
(aMIMEType.EqualsLiteral(AUDIO_3GPP))) {
audioEncoder = new OmxAMRAudioTrackEncoder();
NS_ENSURE_TRUE(audioEncoder, nullptr);
writer = new ISOMediaWriter(aTrackTypes, ISOMediaWriter::TYPE_FRAG_3GP);
NS_ENSURE_TRUE(writer, nullptr);
mimeType = NS_LITERAL_STRING(AUDIO_3GPP);
} else if (MediaEncoder::IsOMXEncoderEnabled() &&
(aMIMEType.EqualsLiteral(AUDIO_3GPP2))) {
audioEncoder = new OmxEVRCAudioTrackEncoder();
NS_ENSURE_TRUE(audioEncoder, nullptr);
writer = new ISOMediaWriter(aTrackTypes, ISOMediaWriter::TYPE_FRAG_3G2);
NS_ENSURE_TRUE(writer, nullptr);
mimeType = NS_LITERAL_STRING(AUDIO_3GPP2) ;
}
#endif // MOZ_OMX_ENCODER
else if (MediaDecoder::IsOggEnabled() && MediaDecoder::IsOpusEnabled() &&
(aMIMEType.EqualsLiteral(AUDIO_OGG) ||
(aTrackTypes & ContainerWriter::CREATE_AUDIO_TRACK))) {
writer = new OggWriter();
audioEncoder = new OpusTrackEncoder();
NS_ENSURE_TRUE(writer, nullptr);
NS_ENSURE_TRUE(audioEncoder, nullptr);
mimeType = NS_LITERAL_STRING(AUDIO_OGG);
}
else {
LOG(LogLevel::Error, ("Can not find any encoder to record this media stream"));
return nullptr;
}
LOG(LogLevel::Debug, ("Create encoder result:a[%d] v[%d] w[%d] mimeType = %s.",
audioEncoder != nullptr, videoEncoder != nullptr,
writer != nullptr, mimeType.get()));
if (videoEncoder && aVideoBitrate != 0) {
videoEncoder->SetBitrate(aVideoBitrate);
}
if (audioEncoder && aAudioBitrate != 0) {
audioEncoder->SetBitrate(aAudioBitrate);
}
encoder = new MediaEncoder(writer.forget(), audioEncoder.forget(),
videoEncoder.forget(), mimeType, aAudioBitrate,
aVideoBitrate, aBitrate);
return encoder.forget();
}
/**
* GetEncodedData() runs as a state machine, starting with mState set to
* GET_METADDATA, the procedure should be as follow:
*
* While non-stop
* If mState is GET_METADDATA
* Get the meta data from audio/video encoder
* If a meta data is generated
* Get meta data from audio/video encoder
* Set mState to ENCODE_TRACK
* Return the final container data
*
* If mState is ENCODE_TRACK
* Get encoded track data from audio/video encoder
* If a packet of track data is generated
* Insert encoded track data into the container stream of writer
* If the final container data is copied to aOutput
* Return the copy of final container data
* If this is the last packet of input stream
* Set mState to ENCODE_DONE
*
* If mState is ENCODE_DONE or ENCODE_ERROR
* Stop the loop
*/
void
MediaEncoder::GetEncodedData(nsTArray<nsTArray<uint8_t> >* aOutputBufs,
nsAString& aMIMEType)
{
MOZ_ASSERT(!NS_IsMainThread());
aMIMEType = mMIMEType;
PROFILER_LABEL("MediaEncoder", "GetEncodedData",
js::ProfileEntry::Category::OTHER);
bool reloop = true;
while (reloop) {
switch (mState) {
case ENCODE_METADDATA: {
LOG(LogLevel::Debug, ("ENCODE_METADDATA TimeStamp = %f", GetEncodeTimeStamp()));
nsresult rv = CopyMetadataToMuxer(mAudioEncoder.get());
if (NS_FAILED(rv)) {
LOG(LogLevel::Error, ("Error! Fail to Set Audio Metadata"));
break;
}
rv = CopyMetadataToMuxer(mVideoEncoder.get());
if (NS_FAILED(rv)) {
LOG(LogLevel::Error, ("Error! Fail to Set Video Metadata"));
break;
}
rv = mWriter->GetContainerData(aOutputBufs,
ContainerWriter::GET_HEADER);
if (aOutputBufs != nullptr) {
mSizeOfBuffer = aOutputBufs->ShallowSizeOfExcludingThis(MallocSizeOf);
}
if (NS_FAILED(rv)) {
LOG(LogLevel::Error,("Error! writer fail to generate header!"));
mState = ENCODE_ERROR;
break;
}
LOG(LogLevel::Debug, ("Finish ENCODE_METADDATA TimeStamp = %f", GetEncodeTimeStamp()));
mState = ENCODE_TRACK;
break;
}
case ENCODE_TRACK: {
LOG(LogLevel::Debug, ("ENCODE_TRACK TimeStamp = %f", GetEncodeTimeStamp()));
EncodedFrameContainer encodedData;
nsresult rv = NS_OK;
rv = WriteEncodedDataToMuxer(mAudioEncoder.get());
if (NS_FAILED(rv)) {
LOG(LogLevel::Error, ("Error! Fail to write audio encoder data to muxer"));
break;
}
LOG(LogLevel::Debug, ("Audio encoded TimeStamp = %f", GetEncodeTimeStamp()));
rv = WriteEncodedDataToMuxer(mVideoEncoder.get());
if (NS_FAILED(rv)) {
LOG(LogLevel::Error, ("Fail to write video encoder data to muxer"));
break;
}
LOG(LogLevel::Debug, ("Video encoded TimeStamp = %f", GetEncodeTimeStamp()));
// In audio only or video only case, let unavailable track's flag to be true.
bool isAudioCompleted = (mAudioEncoder && mAudioEncoder->IsEncodingComplete()) || !mAudioEncoder;
bool isVideoCompleted = (mVideoEncoder && mVideoEncoder->IsEncodingComplete()) || !mVideoEncoder;
rv = mWriter->GetContainerData(aOutputBufs,
isAudioCompleted && isVideoCompleted ?
ContainerWriter::FLUSH_NEEDED : 0);
if (aOutputBufs != nullptr) {
mSizeOfBuffer = aOutputBufs->ShallowSizeOfExcludingThis(MallocSizeOf);
}
if (NS_SUCCEEDED(rv)) {
// Successfully get the copy of final container data from writer.
reloop = false;
}
mState = (mWriter->IsWritingComplete()) ? ENCODE_DONE : ENCODE_TRACK;
LOG(LogLevel::Debug, ("END ENCODE_TRACK TimeStamp = %f "
"mState = %d aComplete %d vComplete %d",
GetEncodeTimeStamp(), mState, isAudioCompleted, isVideoCompleted));
break;
}
case ENCODE_DONE:
case ENCODE_ERROR:
LOG(LogLevel::Debug, ("MediaEncoder has been shutdown."));
mSizeOfBuffer = 0;
mShutdown = true;
reloop = false;
break;
default:
MOZ_CRASH("Invalid encode state");
}
}
}
nsresult
MediaEncoder::WriteEncodedDataToMuxer(TrackEncoder *aTrackEncoder)
{
if (aTrackEncoder == nullptr) {
return NS_OK;
}
if (aTrackEncoder->IsEncodingComplete()) {
return NS_OK;
}
PROFILER_LABEL("MediaEncoder", "WriteEncodedDataToMuxer",
js::ProfileEntry::Category::OTHER);
EncodedFrameContainer encodedVideoData;
nsresult rv = aTrackEncoder->GetEncodedTrack(encodedVideoData);
if (NS_FAILED(rv)) {
// Encoding might be canceled.
LOG(LogLevel::Error, ("Error! Fail to get encoded data from video encoder."));
mState = ENCODE_ERROR;
return rv;
}
rv = mWriter->WriteEncodedTrack(encodedVideoData,
aTrackEncoder->IsEncodingComplete() ?
ContainerWriter::END_OF_STREAM : 0);
if (NS_FAILED(rv)) {
LOG(LogLevel::Error, ("Error! Fail to write encoded video track to the media container."));
mState = ENCODE_ERROR;
}
return rv;
}
nsresult
MediaEncoder::CopyMetadataToMuxer(TrackEncoder *aTrackEncoder)
{
if (aTrackEncoder == nullptr) {
return NS_OK;
}
PROFILER_LABEL("MediaEncoder", "CopyMetadataToMuxer",
js::ProfileEntry::Category::OTHER);
RefPtr<TrackMetadataBase> meta = aTrackEncoder->GetMetadata();
if (meta == nullptr) {
LOG(LogLevel::Error, ("Error! metadata = null"));
mState = ENCODE_ERROR;
return NS_ERROR_ABORT;
}
nsresult rv = mWriter->SetMetadata(meta);
if (NS_FAILED(rv)) {
LOG(LogLevel::Error, ("Error! SetMetadata fail"));
mState = ENCODE_ERROR;
}
return rv;
}
#ifdef MOZ_WEBM_ENCODER
bool
MediaEncoder::IsWebMEncoderEnabled()
{
return Preferences::GetBool("media.encoder.webm.enabled");
}
#endif
#ifdef MOZ_OMX_ENCODER
bool
MediaEncoder::IsOMXEncoderEnabled()
{
return Preferences::GetBool("media.encoder.omx.enabled");
}
#endif
/*
* SizeOfExcludingThis measures memory being used by the Media Encoder.
* Currently it measures the size of the Encoder buffer and memory occupied
* by mAudioEncoder and mVideoEncoder.
*/
size_t
MediaEncoder::SizeOfExcludingThis(mozilla::MallocSizeOf aMallocSizeOf) const
{
size_t amount = 0;
if (mState == ENCODE_TRACK) {
amount = mSizeOfBuffer +
(mAudioEncoder != nullptr ? mAudioEncoder->SizeOfExcludingThis(aMallocSizeOf) : 0) +
(mVideoEncoder != nullptr ? mVideoEncoder->SizeOfExcludingThis(aMallocSizeOf) : 0);
}
return amount;
}
} // namespace mozilla