Files
palemoon27/dom/media/platforms/gonk/GonkVideoDecoderManager.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

703 lines
23 KiB
C++

/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim:set ts=2 sw=2 sts=2 et cindent: */
/* 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 "MediaCodecProxy.h"
#include <OMX_IVCommon.h>
#include <gui/Surface.h>
#include <ICrypto.h>
#include "GonkVideoDecoderManager.h"
#include "GrallocImages.h"
#include "MediaDecoderReader.h"
#include "ImageContainer.h"
#include "VideoUtils.h"
#include "nsThreadUtils.h"
#include "Layers.h"
#include "mozilla/Logging.h"
#include <stagefright/MediaBuffer.h>
#include <stagefright/MetaData.h>
#include <stagefright/MediaErrors.h>
#include <stagefright/foundation/AString.h>
#include "GonkNativeWindow.h"
#include "mozilla/layers/GrallocTextureClient.h"
#include "mozilla/layers/ImageBridgeChild.h"
#include "mozilla/layers/TextureClient.h"
#include "mozilla/layers/TextureClientRecycleAllocator.h"
#include <cutils/properties.h>
#define CODECCONFIG_TIMEOUT_US 10000LL
#define READ_OUTPUT_BUFFER_TIMEOUT_US 0LL
#include <android/log.h>
#define GVDM_LOG(...) __android_log_print(ANDROID_LOG_DEBUG, "GonkVideoDecoderManager", __VA_ARGS__)
#define LOG(...) MOZ_LOG(sPDMLog, mozilla::LogLevel::Debug, (__VA_ARGS__))
using namespace mozilla::layers;
using namespace android;
typedef android::MediaCodecProxy MediaCodecProxy;
namespace mozilla {
GonkVideoDecoderManager::GonkVideoDecoderManager(
mozilla::layers::ImageContainer* aImageContainer,
const VideoInfo& aConfig)
: mConfig(aConfig)
, mImageContainer(aImageContainer)
, mColorConverterBufferSize(0)
, mPendingReleaseItemsLock("GonkVideoDecoderManager::mPendingReleaseItemsLock")
, mNeedsCopyBuffer(false)
{
MOZ_COUNT_CTOR(GonkVideoDecoderManager);
}
GonkVideoDecoderManager::~GonkVideoDecoderManager()
{
MOZ_COUNT_DTOR(GonkVideoDecoderManager);
}
nsresult
GonkVideoDecoderManager::Shutdown()
{
mVideoCodecRequest.DisconnectIfExists();
return GonkDecoderManager::Shutdown();
}
RefPtr<MediaDataDecoder::InitPromise>
GonkVideoDecoderManager::Init()
{
mNeedsCopyBuffer = false;
uint32_t maxWidth, maxHeight;
char propValue[PROPERTY_VALUE_MAX];
property_get("ro.moz.omx.hw.max_width", propValue, "-1");
maxWidth = -1 == atoi(propValue) ? MAX_VIDEO_WIDTH : atoi(propValue);
property_get("ro.moz.omx.hw.max_height", propValue, "-1");
maxHeight = -1 == atoi(propValue) ? MAX_VIDEO_HEIGHT : atoi(propValue) ;
if (uint32_t(mConfig.mImage.width * mConfig.mImage.height) > maxWidth * maxHeight) {
GVDM_LOG("Video resolution exceeds hw codec capability");
return InitPromise::CreateAndReject(DecoderFailureReason::INIT_ERROR, __func__);
}
// Validate the container-reported frame and pictureRect sizes. This ensures
// that our video frame creation code doesn't overflow.
if (!IsValidVideoRegion(mConfig.mImage, mConfig.ImageRect(), mConfig.mDisplay)) {
GVDM_LOG("It is not a valid region");
return InitPromise::CreateAndReject(DecoderFailureReason::INIT_ERROR, __func__);
}
mReaderTaskQueue = AbstractThread::GetCurrent()->AsTaskQueue();
MOZ_ASSERT(mReaderTaskQueue);
if (mDecodeLooper.get() != nullptr) {
return InitPromise::CreateAndReject(DecoderFailureReason::INIT_ERROR, __func__);
}
if (!InitLoopers(MediaData::VIDEO_DATA)) {
return InitPromise::CreateAndReject(DecoderFailureReason::INIT_ERROR, __func__);
}
RefPtr<InitPromise> p = mInitPromise.Ensure(__func__);
android::sp<GonkVideoDecoderManager> self = this;
mDecoder = MediaCodecProxy::CreateByType(mDecodeLooper,
mConfig.mMimeType.get(),
false);
uint32_t capability = MediaCodecProxy::kEmptyCapability;
if (mDecoder->getCapability(&capability) == OK && (capability &
MediaCodecProxy::kCanExposeGraphicBuffer)) {
#if ANDROID_VERSION >= 21
sp<IGonkGraphicBufferConsumer> consumer;
GonkBufferQueue::createBufferQueue(&mGraphicBufferProducer, &consumer);
mNativeWindow = new GonkNativeWindow(consumer);
#else
mNativeWindow = new GonkNativeWindow();
#endif
}
mVideoCodecRequest.Begin(mDecoder->AsyncAllocateVideoMediaCodec()
->Then(mReaderTaskQueue, __func__,
[self] (bool) -> void {
self->mVideoCodecRequest.Complete();
self->codecReserved();
}, [self] (bool) -> void {
self->mVideoCodecRequest.Complete();
self->codecCanceled();
}));
return p;
}
nsresult
GonkVideoDecoderManager::CreateVideoData(MediaBuffer* aBuffer,
int64_t aStreamOffset,
VideoData **v)
{
*v = nullptr;
RefPtr<VideoData> data;
int64_t timeUs;
int32_t keyFrame;
if (aBuffer == nullptr) {
GVDM_LOG("Video Buffer is not valid!");
return NS_ERROR_UNEXPECTED;
}
AutoReleaseMediaBuffer autoRelease(aBuffer, mDecoder.get());
if (!aBuffer->meta_data()->findInt64(kKeyTime, &timeUs)) {
GVDM_LOG("Decoder did not return frame time");
return NS_ERROR_UNEXPECTED;
}
if (mLastTime > timeUs) {
GVDM_LOG("Output decoded sample time is revert. time=%lld", timeUs);
return NS_ERROR_NOT_AVAILABLE;
}
mLastTime = timeUs;
if (aBuffer->range_length() == 0) {
// Some decoders may return spurious empty buffers that we just want to ignore
// quoted from Android's AwesomePlayer.cpp
return NS_ERROR_NOT_AVAILABLE;
}
if (!aBuffer->meta_data()->findInt32(kKeyIsSyncFrame, &keyFrame)) {
keyFrame = 0;
}
gfx::IntRect picture =
mConfig.ScaledImageRect(mFrameInfo.mWidth, mFrameInfo.mHeight);
if (aBuffer->graphicBuffer().get()) {
data = CreateVideoDataFromGraphicBuffer(aBuffer, picture);
if (data && !mNeedsCopyBuffer) {
// RecycleCallback() will be responsible for release the buffer.
autoRelease.forget();
}
mNeedsCopyBuffer = false;
} else {
data = CreateVideoDataFromDataBuffer(aBuffer, picture);
}
if (!data) {
return NS_ERROR_UNEXPECTED;
}
// Fill necessary info.
data->mOffset = aStreamOffset;
data->mTime = timeUs;
data->mKeyframe = keyFrame;
data.forget(v);
return NS_OK;
}
// Copy pixels from one planar YUV to another.
static void
CopyYUV(PlanarYCbCrData& aSource, PlanarYCbCrData& aDestination)
{
// Fill Y plane.
uint8_t* srcY = aSource.mYChannel;
gfx::IntSize ySize = aSource.mYSize;
uint8_t* destY = aDestination.mYChannel;
// Y plane.
for (int i = 0; i < ySize.height; i++) {
memcpy(destY, srcY, ySize.width);
srcY += aSource.mYStride;
destY += aDestination.mYStride;
}
// Fill UV plane.
// Line start
uint8_t* srcU = aSource.mCbChannel;
uint8_t* srcV = aSource.mCrChannel;
uint8_t* destU = aDestination.mCbChannel;
uint8_t* destV = aDestination.mCrChannel;
gfx::IntSize uvSize = aSource.mCbCrSize;
for (int i = 0; i < uvSize.height; i++) {
uint8_t* su = srcU;
uint8_t* sv = srcV;
uint8_t* du = destU;
uint8_t* dv =destV;
for (int j = 0; j < uvSize.width; j++) {
*du++ = *su++;
*dv++ = *sv++;
// Move to next pixel.
su += aSource.mCbSkip;
sv += aSource.mCrSkip;
du += aDestination.mCbSkip;
dv += aDestination.mCrSkip;
}
// Move to next line.
srcU += aSource.mCbCrStride;
srcV += aSource.mCbCrStride;
destU += aDestination.mCbCrStride;
destV += aDestination.mCbCrStride;
}
}
inline static int
Align(int aX, int aAlign)
{
return (aX + aAlign - 1) & ~(aAlign - 1);
}
static void
CopyGraphicBuffer(sp<GraphicBuffer>& aSource, sp<GraphicBuffer>& aDestination)
{
void* srcPtr = nullptr;
aSource->lock(GraphicBuffer::USAGE_SW_READ_OFTEN, &srcPtr);
void* destPtr = nullptr;
aDestination->lock(GraphicBuffer::USAGE_SW_WRITE_OFTEN, &destPtr);
MOZ_ASSERT(srcPtr && destPtr);
// Build PlanarYCbCrData for source buffer.
PlanarYCbCrData srcData;
switch (aSource->getPixelFormat()) {
case HAL_PIXEL_FORMAT_YV12:
// Android YV12 format is defined in system/core/include/system/graphics.h
srcData.mYChannel = static_cast<uint8_t*>(srcPtr);
srcData.mYSkip = 0;
srcData.mYSize.width = aSource->getWidth();
srcData.mYSize.height = aSource->getHeight();
srcData.mYStride = aSource->getStride();
// 4:2:0.
srcData.mCbCrSize.width = srcData.mYSize.width / 2;
srcData.mCbCrSize.height = srcData.mYSize.height / 2;
srcData.mCrChannel = srcData.mYChannel + (srcData.mYStride * srcData.mYSize.height);
// Aligned to 16 bytes boundary.
srcData.mCbCrStride = Align(srcData.mYStride / 2, 16);
srcData.mCrSkip = 0;
srcData.mCbChannel = srcData.mCrChannel + (srcData.mCbCrStride * srcData.mCbCrSize.height);
srcData.mCbSkip = 0;
break;
case GrallocImage::HAL_PIXEL_FORMAT_YCbCr_420_SP_VENUS:
// Venus formats are doucmented in kernel/include/media/msm_media_info.h:
srcData.mYChannel = static_cast<uint8_t*>(srcPtr);
srcData.mYSkip = 0;
srcData.mYSize.width = aSource->getWidth();
srcData.mYSize.height = aSource->getHeight();
// - Y & UV Width aligned to 128
srcData.mYStride = aSource->getStride();
srcData.mCbCrSize.width = (srcData.mYSize.width + 1) / 2;
srcData.mCbCrSize.height = (srcData.mYSize.height + 1) / 2;
// - Y height aligned to 32
srcData.mCbChannel = srcData.mYChannel + (srcData.mYStride * Align(srcData.mYSize.height, 32));
// Interleaved VU plane.
srcData.mCbSkip = 1;
srcData.mCrChannel = srcData.mCbChannel + 1;
srcData.mCrSkip = 1;
srcData.mCbCrStride = srcData.mYStride;
break;
default:
NS_ERROR("Unsupported input gralloc image type. Should never be here.");
}
// Build PlanarYCbCrData for destination buffer.
PlanarYCbCrData destData;
destData.mYChannel = static_cast<uint8_t*>(destPtr);
destData.mYSkip = 0;
destData.mYSize.width = aDestination->getWidth();
destData.mYSize.height = aDestination->getHeight();
destData.mYStride = aDestination->getStride();
// 4:2:0.
destData.mCbCrSize.width = destData.mYSize.width / 2;
destData.mCbCrSize.height = destData.mYSize.height / 2;
destData.mCrChannel = destData.mYChannel + (destData.mYStride * destData.mYSize.height);
// Aligned to 16 bytes boundary.
destData.mCbCrStride = Align(destData.mYStride / 2, 16);
destData.mCrSkip = 0;
destData.mCbChannel = destData.mCrChannel + (destData.mCbCrStride * destData.mCbCrSize.height);
destData.mCbSkip = 0;
CopyYUV(srcData, destData);
aSource->unlock();
aDestination->unlock();
}
already_AddRefed<VideoData>
GonkVideoDecoderManager::CreateVideoDataFromGraphicBuffer(MediaBuffer* aSource,
gfx::IntRect& aPicture)
{
sp<GraphicBuffer> srcBuffer(aSource->graphicBuffer());
RefPtr<TextureClient> textureClient;
if (mNeedsCopyBuffer) {
// Copy buffer contents for bug 1199809.
if (!mCopyAllocator) {
mCopyAllocator = new TextureClientRecycleAllocator(ImageBridgeChild::GetSingleton());
}
if (!mCopyAllocator) {
GVDM_LOG("Create buffer allocator failed!");
return nullptr;
}
gfx::IntSize size(Align(aPicture.width, 2) , Align(aPicture.height, 2));
textureClient =
mCopyAllocator->CreateOrRecycle(gfx::SurfaceFormat::YUV, size,
BackendSelector::Content,
TextureFlags::DEFAULT,
ALLOC_DISALLOW_BUFFERTEXTURECLIENT);
if (!textureClient) {
GVDM_LOG("Copy buffer allocation failed!");
return nullptr;
}
// Update size to match buffer's.
aPicture.width = size.width;
aPicture.height = size.height;
sp<GraphicBuffer> destBuffer =
static_cast<GrallocTextureData*>(textureClient->GetInternalData())->GetGraphicBuffer();
CopyGraphicBuffer(srcBuffer, destBuffer);
} else {
textureClient = mNativeWindow->getTextureClientFromBuffer(srcBuffer.get());
textureClient->SetRecycleCallback(GonkVideoDecoderManager::RecycleCallback, this);
static_cast<GrallocTextureData*>(textureClient->GetInternalData())->SetMediaBuffer(aSource);
}
RefPtr<VideoData> data = VideoData::Create(mConfig,
mImageContainer,
0, // Filled later by caller.
0, // Filled later by caller.
1, // No way to pass sample duration from muxer to
// OMX codec, so we hardcode the duration here.
textureClient,
false, // Filled later by caller.
-1,
aPicture);
return data.forget();
}
already_AddRefed<VideoData>
GonkVideoDecoderManager::CreateVideoDataFromDataBuffer(MediaBuffer* aSource, gfx::IntRect& aPicture)
{
if (!aSource->data()) {
GVDM_LOG("No data in Video Buffer!");
return nullptr;
}
uint8_t *yuv420p_buffer = (uint8_t *)aSource->data();
int32_t stride = mFrameInfo.mStride;
int32_t slice_height = mFrameInfo.mSliceHeight;
// Converts to OMX_COLOR_FormatYUV420Planar
if (mFrameInfo.mColorFormat != OMX_COLOR_FormatYUV420Planar) {
ARect crop;
crop.top = 0;
crop.bottom = mFrameInfo.mHeight;
crop.left = 0;
crop.right = mFrameInfo.mWidth;
yuv420p_buffer = GetColorConverterBuffer(mFrameInfo.mWidth, mFrameInfo.mHeight);
if (mColorConverter.convertDecoderOutputToI420(aSource->data(),
mFrameInfo.mWidth, mFrameInfo.mHeight, crop, yuv420p_buffer) != OK) {
GVDM_LOG("Color conversion failed!");
return nullptr;
}
stride = mFrameInfo.mWidth;
slice_height = mFrameInfo.mHeight;
}
size_t yuv420p_y_size = stride * slice_height;
size_t yuv420p_u_size = ((stride + 1) / 2) * ((slice_height + 1) / 2);
uint8_t *yuv420p_y = yuv420p_buffer;
uint8_t *yuv420p_u = yuv420p_y + yuv420p_y_size;
uint8_t *yuv420p_v = yuv420p_u + yuv420p_u_size;
VideoData::YCbCrBuffer b;
b.mPlanes[0].mData = yuv420p_y;
b.mPlanes[0].mWidth = mFrameInfo.mWidth;
b.mPlanes[0].mHeight = mFrameInfo.mHeight;
b.mPlanes[0].mStride = stride;
b.mPlanes[0].mOffset = 0;
b.mPlanes[0].mSkip = 0;
b.mPlanes[1].mData = yuv420p_u;
b.mPlanes[1].mWidth = (mFrameInfo.mWidth + 1) / 2;
b.mPlanes[1].mHeight = (mFrameInfo.mHeight + 1) / 2;
b.mPlanes[1].mStride = (stride + 1) / 2;
b.mPlanes[1].mOffset = 0;
b.mPlanes[1].mSkip = 0;
b.mPlanes[2].mData = yuv420p_v;
b.mPlanes[2].mWidth =(mFrameInfo.mWidth + 1) / 2;
b.mPlanes[2].mHeight = (mFrameInfo.mHeight + 1) / 2;
b.mPlanes[2].mStride = (stride + 1) / 2;
b.mPlanes[2].mOffset = 0;
b.mPlanes[2].mSkip = 0;
RefPtr<VideoData> data = VideoData::Create(mConfig,
mImageContainer,
0, // Filled later by caller.
0, // Filled later by caller.
1, // We don't know the duration.
b,
0, // Filled later by caller.
-1,
aPicture);
return data.forget();
}
bool
GonkVideoDecoderManager::SetVideoFormat()
{
// read video metadata from MediaCodec
sp<AMessage> codecFormat;
if (mDecoder->getOutputFormat(&codecFormat) == OK) {
AString mime;
int32_t width = 0;
int32_t height = 0;
int32_t stride = 0;
int32_t slice_height = 0;
int32_t color_format = 0;
int32_t crop_left = 0;
int32_t crop_top = 0;
int32_t crop_right = 0;
int32_t crop_bottom = 0;
if (!codecFormat->findString("mime", &mime) ||
!codecFormat->findInt32("width", &width) ||
!codecFormat->findInt32("height", &height) ||
!codecFormat->findInt32("stride", &stride) ||
!codecFormat->findInt32("slice-height", &slice_height) ||
!codecFormat->findInt32("color-format", &color_format) ||
!codecFormat->findRect("crop", &crop_left, &crop_top, &crop_right, &crop_bottom)) {
GVDM_LOG("Failed to find values");
return false;
}
mFrameInfo.mWidth = width;
mFrameInfo.mHeight = height;
mFrameInfo.mStride = stride;
mFrameInfo.mSliceHeight = slice_height;
mFrameInfo.mColorFormat = color_format;
nsIntSize displaySize(width, height);
if (!IsValidVideoRegion(mConfig.mDisplay,
mConfig.ScaledImageRect(width, height),
displaySize)) {
GVDM_LOG("It is not a valid region");
return false;
}
return true;
}
GVDM_LOG("Fail to get output format");
return false;
}
// Blocks until decoded sample is produced by the deoder.
nsresult
GonkVideoDecoderManager::Output(int64_t aStreamOffset,
RefPtr<MediaData>& aOutData)
{
aOutData = nullptr;
status_t err;
if (mDecoder == nullptr) {
GVDM_LOG("Decoder is not inited");
return NS_ERROR_UNEXPECTED;
}
MediaBuffer* outputBuffer = nullptr;
err = mDecoder->Output(&outputBuffer, READ_OUTPUT_BUFFER_TIMEOUT_US);
switch (err) {
case OK:
{
RefPtr<VideoData> data;
nsresult rv = CreateVideoData(outputBuffer, aStreamOffset, getter_AddRefs(data));
if (rv == NS_ERROR_NOT_AVAILABLE) {
// Decoder outputs a empty video buffer, try again
return NS_ERROR_NOT_AVAILABLE;
} else if (rv != NS_OK || data == nullptr) {
GVDM_LOG("Failed to create VideoData");
return NS_ERROR_UNEXPECTED;
}
aOutData = data;
return NS_OK;
}
case android::INFO_FORMAT_CHANGED:
{
// If the format changed, update our cached info.
GVDM_LOG("Decoder format changed");
if (!SetVideoFormat()) {
return NS_ERROR_UNEXPECTED;
}
return Output(aStreamOffset, aOutData);
}
case android::INFO_OUTPUT_BUFFERS_CHANGED:
{
if (mDecoder->UpdateOutputBuffers()) {
return Output(aStreamOffset, aOutData);
}
GVDM_LOG("Fails to update output buffers!");
return NS_ERROR_FAILURE;
}
case -EAGAIN:
{
// GVDM_LOG("Need to try again!");
return NS_ERROR_NOT_AVAILABLE;
}
case android::ERROR_END_OF_STREAM:
{
GVDM_LOG("Got the EOS frame!");
RefPtr<VideoData> data;
nsresult rv = CreateVideoData(outputBuffer, aStreamOffset, getter_AddRefs(data));
if (rv == NS_ERROR_NOT_AVAILABLE) {
// For EOS, no need to do any thing.
return NS_ERROR_ABORT;
}
if (rv != NS_OK || data == nullptr) {
GVDM_LOG("Failed to create video data");
return NS_ERROR_UNEXPECTED;
}
aOutData = data;
return NS_ERROR_ABORT;
}
case -ETIMEDOUT:
{
GVDM_LOG("Timeout. can try again next time");
return NS_ERROR_UNEXPECTED;
}
default:
{
GVDM_LOG("Decoder failed, err=%d", err);
return NS_ERROR_UNEXPECTED;
}
}
return NS_OK;
}
void
GonkVideoDecoderManager::codecReserved()
{
if (mInitPromise.IsEmpty()) {
return;
}
GVDM_LOG("codecReserved");
sp<AMessage> format = new AMessage;
sp<Surface> surface;
status_t rv = OK;
// Fixed values
GVDM_LOG("Configure video mime type: %s, width:%d, height:%d", mConfig.mMimeType.get(), mConfig.mImage.width, mConfig.mImage.height);
format->setString("mime", mConfig.mMimeType.get());
format->setInt32("width", mConfig.mImage.width);
format->setInt32("height", mConfig.mImage.height);
// Set the "moz-use-undequeued-bufs" to use the undeque buffers to accelerate
// the video decoding.
format->setInt32("moz-use-undequeued-bufs", 1);
if (mNativeWindow != nullptr) {
#if ANDROID_VERSION >= 21
surface = new Surface(mGraphicBufferProducer);
#else
surface = new Surface(mNativeWindow->getBufferQueue());
#endif
}
mDecoder->configure(format, surface, nullptr, 0);
mDecoder->Prepare();
if (mConfig.mMimeType.EqualsLiteral("video/mp4v-es")) {
rv = mDecoder->Input(mConfig.mCodecSpecificConfig->Elements(),
mConfig.mCodecSpecificConfig->Length(), 0,
android::MediaCodec::BUFFER_FLAG_CODECCONFIG,
CODECCONFIG_TIMEOUT_US);
}
if (rv != OK) {
GVDM_LOG("Failed to configure codec!!!!");
mInitPromise.Reject(DecoderFailureReason::INIT_ERROR, __func__);
return;
}
mInitPromise.Resolve(TrackType::kVideoTrack, __func__);
}
void
GonkVideoDecoderManager::codecCanceled()
{
GVDM_LOG("codecCanceled");
mInitPromise.RejectIfExists(DecoderFailureReason::CANCELED, __func__);
}
// Called on GonkDecoderManager::mTaskLooper thread.
void
GonkVideoDecoderManager::onMessageReceived(const sp<AMessage> &aMessage)
{
switch (aMessage->what()) {
case kNotifyPostReleaseBuffer:
{
ReleaseAllPendingVideoBuffers();
break;
}
default:
{
GonkDecoderManager::onMessageReceived(aMessage);
break;
}
}
}
uint8_t *
GonkVideoDecoderManager::GetColorConverterBuffer(int32_t aWidth, int32_t aHeight)
{
// Allocate a temporary YUV420Planer buffer.
size_t yuv420p_y_size = aWidth * aHeight;
size_t yuv420p_u_size = ((aWidth + 1) / 2) * ((aHeight + 1) / 2);
size_t yuv420p_v_size = yuv420p_u_size;
size_t yuv420p_size = yuv420p_y_size + yuv420p_u_size + yuv420p_v_size;
if (mColorConverterBufferSize != yuv420p_size) {
mColorConverterBuffer = MakeUnique<uint8_t[]>(yuv420p_size);
mColorConverterBufferSize = yuv420p_size;
}
return mColorConverterBuffer.get();
}
/* static */
void
GonkVideoDecoderManager::RecycleCallback(TextureClient* aClient, void* aClosure)
{
MOZ_ASSERT(aClient && !aClient->IsDead());
GonkVideoDecoderManager* videoManager = static_cast<GonkVideoDecoderManager*>(aClosure);
GrallocTextureData* client = static_cast<GrallocTextureData*>(aClient->GetInternalData());
aClient->ClearRecycleCallback();
FenceHandle handle = aClient->GetAndResetReleaseFenceHandle();
videoManager->PostReleaseVideoBuffer(client->GetMediaBuffer(), handle);
}
void GonkVideoDecoderManager::PostReleaseVideoBuffer(
android::MediaBuffer *aBuffer,
FenceHandle aReleaseFence)
{
{
MutexAutoLock autoLock(mPendingReleaseItemsLock);
if (aBuffer) {
mPendingReleaseItems.AppendElement(ReleaseItem(aBuffer, aReleaseFence));
}
}
sp<AMessage> notify =
new AMessage(kNotifyPostReleaseBuffer, id());
notify->post();
}
void GonkVideoDecoderManager::ReleaseAllPendingVideoBuffers()
{
nsTArray<ReleaseItem> releasingItems;
{
MutexAutoLock autoLock(mPendingReleaseItemsLock);
releasingItems.AppendElements(mPendingReleaseItems);
mPendingReleaseItems.Clear();
}
// Free all pending video buffers without holding mPendingReleaseItemsLock.
size_t size = releasingItems.Length();
for (size_t i = 0; i < size; i++) {
RefPtr<FenceHandle::FdObj> fdObj = releasingItems[i].mReleaseFence.GetAndResetFdObj();
sp<Fence> fence = new Fence(fdObj->GetAndResetFd());
fence->waitForever("GonkVideoDecoderManager");
mDecoder->ReleaseMediaBuffer(releasingItems[i].mBuffer);
}
releasingItems.Clear();
}
} // namespace mozilla