Source code

Revision control

Other Tools

1
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2
/* vim: set ts=8 sts=2 et sw=2 tw=80: */
3
/* This Source Code Form is subject to the terms of the Mozilla Public
4
* License, v. 2.0. If a copy of the MPL was not distributed with this
5
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
6
7
#include "MediaData.h"
8
9
#include "ImageContainer.h"
10
#include "MediaInfo.h"
11
#include "VideoUtils.h"
12
#include "YCbCrUtils.h"
13
#include "mozilla/layers/ImageBridgeChild.h"
14
#include "mozilla/layers/KnowsCompositor.h"
15
#include "mozilla/layers/SharedRGBImage.h"
16
17
#include <stdint.h>
18
19
#ifdef XP_WIN
20
# include "mozilla/WindowsVersion.h"
21
# include "mozilla/layers/D3D11YCbCrImage.h"
22
#endif
23
24
namespace mozilla {
25
26
using namespace mozilla::gfx;
27
using layers::ImageContainer;
28
using layers::PlanarYCbCrData;
29
using layers::PlanarYCbCrImage;
30
using media::TimeUnit;
31
32
const char* AudioData::sTypeName = "audio";
33
const char* VideoData::sTypeName = "video";
34
35
bool IsDataLoudnessHearable(const AudioDataValue aData) {
36
// We can transfer the digital value to dBFS via following formula. According
37
// to American SMPTE standard, 0 dBu equals -20 dBFS. In theory 0 dBu is still
38
// hearable, so we choose a smaller value as our threshold. If the loudness
39
// is under this threshold, it might not be hearable.
40
return 20.0f * std::log10(AudioSampleToFloat(aData)) > -100;
41
}
42
43
AudioData::AudioData(int64_t aOffset, const media::TimeUnit& aTime,
44
AlignedAudioBuffer&& aData, uint32_t aChannels,
45
uint32_t aRate, uint32_t aChannelMap)
46
: MediaData(sType, aOffset, aTime,
47
FramesToTimeUnit(aData.Length() / aChannels, aRate)),
48
mChannels(aChannels),
49
mChannelMap(aChannelMap),
50
mRate(aRate),
51
mOriginalTime(aTime),
52
mAudioData(std::move(aData)),
53
mFrames(mAudioData.Length() / aChannels) {}
54
55
Span<AudioDataValue> AudioData::Data() const {
56
return MakeSpan(GetAdjustedData(), mFrames * mChannels);
57
}
58
59
bool AudioData::AdjustForStartTime(const media::TimeUnit& aStartTime) {
60
mOriginalTime -= aStartTime;
61
if (mTrimWindow) {
62
*mTrimWindow -= aStartTime;
63
}
64
return MediaData::AdjustForStartTime(aStartTime) && mOriginalTime.IsValid();
65
}
66
67
bool AudioData::SetTrimWindow(const media::TimeInterval& aTrim) {
68
MOZ_DIAGNOSTIC_ASSERT(aTrim.mStart.IsValid() && aTrim.mEnd.IsValid(),
69
"An overflow occurred on the provided TimeInterval");
70
if (!mAudioData) {
71
// MoveableData got called. Can no longer work on it.
72
return false;
73
}
74
const size_t originalFrames = mAudioData.Length() / mChannels;
75
const TimeUnit originalDuration = FramesToTimeUnit(originalFrames, mRate);
76
if (aTrim.mStart < mOriginalTime ||
77
aTrim.mEnd > mOriginalTime + originalDuration) {
78
return false;
79
}
80
81
auto trimBefore = TimeUnitToFrames(aTrim.mStart - mOriginalTime, mRate);
82
auto trimAfter = aTrim.mEnd == GetEndTime()
83
? originalFrames
84
: TimeUnitToFrames(aTrim.mEnd - mOriginalTime, mRate);
85
if (!trimBefore.isValid() || !trimAfter.isValid()) {
86
// Overflow.
87
return false;
88
}
89
MOZ_DIAGNOSTIC_ASSERT(trimAfter.value() >= trimBefore.value(),
90
"Something went wrong with trimming value");
91
if (!mTrimWindow && trimBefore == 0 && trimAfter == originalFrames) {
92
// Nothing to change, abort early to prevent rounding errors.
93
return true;
94
}
95
96
mTrimWindow = Some(aTrim);
97
mDataOffset = trimBefore.value() * mChannels;
98
MOZ_DIAGNOSTIC_ASSERT(mDataOffset <= mAudioData.Length(),
99
"Data offset outside original buffer");
100
mFrames = (trimAfter - trimBefore).value();
101
MOZ_DIAGNOSTIC_ASSERT(mFrames <= originalFrames,
102
"More frames than found in container");
103
mTime = mOriginalTime + FramesToTimeUnit(trimBefore.value(), mRate);
104
mDuration = FramesToTimeUnit(mFrames, mRate);
105
106
return true;
107
}
108
109
AudioDataValue* AudioData::GetAdjustedData() const {
110
if (!mAudioData) {
111
return nullptr;
112
}
113
return mAudioData.Data() + mDataOffset;
114
}
115
116
void AudioData::EnsureAudioBuffer() {
117
if (mAudioBuffer || !mAudioData) {
118
return;
119
}
120
const AudioDataValue* srcData = GetAdjustedData();
121
mAudioBuffer =
122
SharedBuffer::Create(mFrames * mChannels * sizeof(AudioDataValue));
123
124
AudioDataValue* destData = static_cast<AudioDataValue*>(mAudioBuffer->Data());
125
for (uint32_t i = 0; i < mFrames; ++i) {
126
for (uint32_t j = 0; j < mChannels; ++j) {
127
destData[j * mFrames + i] = srcData[i * mChannels + j];
128
}
129
}
130
}
131
132
size_t AudioData::SizeOfIncludingThis(MallocSizeOf aMallocSizeOf) const {
133
size_t size =
134
aMallocSizeOf(this) + mAudioData.SizeOfExcludingThis(aMallocSizeOf);
135
if (mAudioBuffer) {
136
size += mAudioBuffer->SizeOfIncludingThis(aMallocSizeOf);
137
}
138
return size;
139
}
140
141
bool AudioData::IsAudible() const {
142
if (!mAudioData) {
143
return false;
144
}
145
146
const AudioDataValue* data = GetAdjustedData();
147
148
for (uint32_t frame = 0; frame < mFrames; ++frame) {
149
for (uint32_t channel = 0; channel < mChannels; ++channel) {
150
if (IsDataLoudnessHearable(data[frame * mChannels + channel])) {
151
return true;
152
}
153
}
154
}
155
return false;
156
}
157
158
AlignedAudioBuffer AudioData::MoveableData() {
159
// Trim buffer according to trimming mask.
160
mAudioData.PopFront(mDataOffset);
161
mAudioData.SetLength(mFrames * mChannels);
162
mDataOffset = 0;
163
mFrames = 0;
164
mTrimWindow.reset();
165
return std::move(mAudioData);
166
}
167
168
static bool ValidatePlane(const VideoData::YCbCrBuffer::Plane& aPlane) {
169
return aPlane.mWidth <= PlanarYCbCrImage::MAX_DIMENSION &&
170
aPlane.mHeight <= PlanarYCbCrImage::MAX_DIMENSION &&
171
aPlane.mWidth * aPlane.mHeight < MAX_VIDEO_WIDTH * MAX_VIDEO_HEIGHT &&
172
aPlane.mStride > 0 && aPlane.mWidth <= aPlane.mStride;
173
}
174
175
static bool ValidateBufferAndPicture(const VideoData::YCbCrBuffer& aBuffer,
176
const IntRect& aPicture) {
177
// The following situation should never happen unless there is a bug
178
// in the decoder
179
if (aBuffer.mPlanes[1].mWidth != aBuffer.mPlanes[2].mWidth ||
180
aBuffer.mPlanes[1].mHeight != aBuffer.mPlanes[2].mHeight) {
181
NS_ERROR("C planes with different sizes");
182
return false;
183
}
184
185
// The following situations could be triggered by invalid input
186
if (aPicture.width <= 0 || aPicture.height <= 0) {
187
NS_WARNING("Empty picture rect");
188
return false;
189
}
190
if (!ValidatePlane(aBuffer.mPlanes[0]) ||
191
!ValidatePlane(aBuffer.mPlanes[1]) ||
192
!ValidatePlane(aBuffer.mPlanes[2])) {
193
NS_WARNING("Invalid plane size");
194
return false;
195
}
196
197
// Ensure the picture size specified in the headers can be extracted out of
198
// the frame we've been supplied without indexing out of bounds.
199
CheckedUint32 xLimit = aPicture.x + CheckedUint32(aPicture.width);
200
CheckedUint32 yLimit = aPicture.y + CheckedUint32(aPicture.height);
201
if (!xLimit.isValid() || xLimit.value() > aBuffer.mPlanes[0].mStride ||
202
!yLimit.isValid() || yLimit.value() > aBuffer.mPlanes[0].mHeight) {
203
// The specified picture dimensions can't be contained inside the video
204
// frame, we'll stomp memory if we try to copy it. Fail.
205
NS_WARNING("Overflowing picture rect");
206
return false;
207
}
208
return true;
209
}
210
211
VideoData::VideoData(int64_t aOffset, const TimeUnit& aTime,
212
const TimeUnit& aDuration, bool aKeyframe,
213
const TimeUnit& aTimecode, IntSize aDisplay,
214
layers::ImageContainer::FrameID aFrameID)
215
: MediaData(Type::VIDEO_DATA, aOffset, aTime, aDuration),
216
mDisplay(aDisplay),
217
mFrameID(aFrameID),
218
mSentToCompositor(false),
219
mNextKeyFrameTime(TimeUnit::Invalid()) {
220
MOZ_ASSERT(!mDuration.IsNegative(), "Frame must have non-negative duration.");
221
mKeyframe = aKeyframe;
222
mTimecode = aTimecode;
223
}
224
225
VideoData::~VideoData() {}
226
227
size_t VideoData::SizeOfIncludingThis(MallocSizeOf aMallocSizeOf) const {
228
size_t size = aMallocSizeOf(this);
229
230
// Currently only PLANAR_YCBCR has a well defined function for determining
231
// it's size, so reporting is limited to that type.
232
if (mImage && mImage->GetFormat() == ImageFormat::PLANAR_YCBCR) {
233
const mozilla::layers::PlanarYCbCrImage* img =
234
static_cast<const mozilla::layers::PlanarYCbCrImage*>(mImage.get());
235
size += img->SizeOfIncludingThis(aMallocSizeOf);
236
}
237
238
return size;
239
}
240
241
void VideoData::UpdateDuration(const TimeUnit& aDuration) {
242
MOZ_ASSERT(!aDuration.IsNegative());
243
mDuration = aDuration;
244
}
245
246
void VideoData::UpdateTimestamp(const TimeUnit& aTimestamp) {
247
MOZ_ASSERT(!aTimestamp.IsNegative());
248
249
auto updatedDuration = GetEndTime() - aTimestamp;
250
MOZ_ASSERT(!updatedDuration.IsNegative());
251
252
mTime = aTimestamp;
253
mDuration = updatedDuration;
254
}
255
256
PlanarYCbCrData ConstructPlanarYCbCrData(const VideoInfo& aInfo,
257
const VideoData::YCbCrBuffer& aBuffer,
258
const IntRect& aPicture) {
259
const VideoData::YCbCrBuffer::Plane& Y = aBuffer.mPlanes[0];
260
const VideoData::YCbCrBuffer::Plane& Cb = aBuffer.mPlanes[1];
261
const VideoData::YCbCrBuffer::Plane& Cr = aBuffer.mPlanes[2];
262
263
PlanarYCbCrData data;
264
data.mYChannel = Y.mData + Y.mOffset;
265
data.mYSize = IntSize(Y.mWidth, Y.mHeight);
266
data.mYStride = Y.mStride;
267
data.mYSkip = Y.mSkip;
268
data.mCbChannel = Cb.mData + Cb.mOffset;
269
data.mCrChannel = Cr.mData + Cr.mOffset;
270
data.mCbCrSize = IntSize(Cb.mWidth, Cb.mHeight);
271
data.mCbCrStride = Cb.mStride;
272
data.mCbSkip = Cb.mSkip;
273
data.mCrSkip = Cr.mSkip;
274
data.mPicX = aPicture.x;
275
data.mPicY = aPicture.y;
276
data.mPicSize = aPicture.Size();
277
data.mStereoMode = aInfo.mStereoMode;
278
data.mYUVColorSpace = aBuffer.mYUVColorSpace;
279
data.mColorDepth = aBuffer.mColorDepth;
280
return data;
281
}
282
283
/* static */
284
bool VideoData::SetVideoDataToImage(PlanarYCbCrImage* aVideoImage,
285
const VideoInfo& aInfo,
286
const YCbCrBuffer& aBuffer,
287
const IntRect& aPicture, bool aCopyData) {
288
if (!aVideoImage) {
289
return false;
290
}
291
292
MOZ_ASSERT(aBuffer.mYUVColorSpace != gfx::YUVColorSpace::UNKNOWN,
293
"We must know the colorframe at this point");
294
295
PlanarYCbCrData data = ConstructPlanarYCbCrData(aInfo, aBuffer, aPicture);
296
297
aVideoImage->SetDelayedConversion(true);
298
if (aCopyData) {
299
return aVideoImage->CopyData(data);
300
} else {
301
return aVideoImage->AdoptData(data);
302
}
303
}
304
305
/* static */
306
already_AddRefed<VideoData> VideoData::CreateAndCopyData(
307
const VideoInfo& aInfo, ImageContainer* aContainer, int64_t aOffset,
308
const TimeUnit& aTime, const TimeUnit& aDuration,
309
const YCbCrBuffer& aBuffer, bool aKeyframe, const TimeUnit& aTimecode,
310
const IntRect& aPicture, layers::KnowsCompositor* aAllocator) {
311
if (!aContainer) {
312
// Create a dummy VideoData with no image. This gives us something to
313
// send to media streams if necessary.
314
RefPtr<VideoData> v(new VideoData(aOffset, aTime, aDuration, aKeyframe,
315
aTimecode, aInfo.mDisplay, 0));
316
return v.forget();
317
}
318
319
if (!ValidateBufferAndPicture(aBuffer, aPicture)) {
320
return nullptr;
321
}
322
323
MOZ_ASSERT(aBuffer.mYUVColorSpace != gfx::YUVColorSpace::UNKNOWN,
324
"We must know the colorframe at this point");
325
326
RefPtr<VideoData> v(new VideoData(aOffset, aTime, aDuration, aKeyframe,
327
aTimecode, aInfo.mDisplay, 0));
328
329
// Currently our decoder only knows how to output to ImageFormat::PLANAR_YCBCR
330
// format.
331
#if XP_WIN
332
// We disable this code path on Windows version earlier of Windows 8 due to
333
// intermittent crashes with old drivers. See bug 1405110.
334
// D3D11YCbCrImage can only handle YCbCr images using 3 non-interleaved planes
335
// non-zero mSkip value indicates that one of the plane would be interleaved.
336
if (IsWin8OrLater() && !XRE_IsParentProcess() && aAllocator &&
337
aAllocator->SupportsD3D11() && aBuffer.mPlanes[0].mSkip == 0 &&
338
aBuffer.mPlanes[1].mSkip == 0 && aBuffer.mPlanes[2].mSkip == 0) {
339
RefPtr<layers::D3D11YCbCrImage> d3d11Image = new layers::D3D11YCbCrImage();
340
PlanarYCbCrData data = ConstructPlanarYCbCrData(aInfo, aBuffer, aPicture);
341
if (d3d11Image->SetData(layers::ImageBridgeChild::GetSingleton()
342
? layers::ImageBridgeChild::GetSingleton().get()
343
: aAllocator,
344
aContainer, data)) {
345
v->mImage = d3d11Image;
346
return v.forget();
347
}
348
}
349
#endif
350
if (!v->mImage) {
351
v->mImage = aContainer->CreatePlanarYCbCrImage();
352
}
353
354
if (!v->mImage) {
355
return nullptr;
356
}
357
NS_ASSERTION(v->mImage->GetFormat() == ImageFormat::PLANAR_YCBCR,
358
"Wrong format?");
359
PlanarYCbCrImage* videoImage = v->mImage->AsPlanarYCbCrImage();
360
MOZ_ASSERT(videoImage);
361
362
if (!VideoData::SetVideoDataToImage(videoImage, aInfo, aBuffer, aPicture,
363
true /* aCopyData */)) {
364
return nullptr;
365
}
366
367
return v.forget();
368
}
369
370
/* static */
371
already_AddRefed<VideoData> VideoData::CreateAndCopyData(
372
const VideoInfo& aInfo, ImageContainer* aContainer, int64_t aOffset,
373
const TimeUnit& aTime, const TimeUnit& aDuration,
374
const YCbCrBuffer& aBuffer, const YCbCrBuffer::Plane& aAlphaPlane,
375
bool aKeyframe, const TimeUnit& aTimecode, const IntRect& aPicture) {
376
if (!aContainer) {
377
// Create a dummy VideoData with no image. This gives us something to
378
// send to media streams if necessary.
379
RefPtr<VideoData> v(new VideoData(aOffset, aTime, aDuration, aKeyframe,
380
aTimecode, aInfo.mDisplay, 0));
381
return v.forget();
382
}
383
384
if (!ValidateBufferAndPicture(aBuffer, aPicture)) {
385
return nullptr;
386
}
387
388
RefPtr<VideoData> v(new VideoData(aOffset, aTime, aDuration, aKeyframe,
389
aTimecode, aInfo.mDisplay, 0));
390
391
// Convert from YUVA to BGRA format on the software side.
392
RefPtr<layers::SharedRGBImage> videoImage =
393
aContainer->CreateSharedRGBImage();
394
v->mImage = videoImage;
395
396
if (!v->mImage) {
397
return nullptr;
398
}
399
if (!videoImage->Allocate(
400
IntSize(aBuffer.mPlanes[0].mWidth, aBuffer.mPlanes[0].mHeight),
401
SurfaceFormat::B8G8R8A8)) {
402
return nullptr;
403
}
404
405
RefPtr<layers::TextureClient> texture =
406
videoImage->GetTextureClient(/* aKnowsCompositor */ nullptr);
407
if (!texture) {
408
NS_WARNING("Failed to allocate TextureClient");
409
return nullptr;
410
}
411
412
layers::TextureClientAutoLock autoLock(texture,
413
layers::OpenMode::OPEN_WRITE_ONLY);
414
if (!autoLock.Succeeded()) {
415
NS_WARNING("Failed to lock TextureClient");
416
return nullptr;
417
}
418
419
layers::MappedTextureData buffer;
420
if (!texture->BorrowMappedData(buffer)) {
421
NS_WARNING("Failed to borrow mapped data");
422
return nullptr;
423
}
424
425
// The naming convention for libyuv and associated utils is word-order.
426
// The naming convention in the gfx stack is byte-order.
427
ConvertYCbCrAToARGB(aBuffer.mPlanes[0].mData, aBuffer.mPlanes[1].mData,
428
aBuffer.mPlanes[2].mData, aAlphaPlane.mData,
429
aBuffer.mPlanes[0].mStride, aBuffer.mPlanes[1].mStride,
430
buffer.data, buffer.stride, buffer.size.width,
431
buffer.size.height);
432
433
return v.forget();
434
}
435
436
/* static */
437
already_AddRefed<VideoData> VideoData::CreateFromImage(
438
const IntSize& aDisplay, int64_t aOffset, const TimeUnit& aTime,
439
const TimeUnit& aDuration, const RefPtr<Image>& aImage, bool aKeyframe,
440
const TimeUnit& aTimecode) {
441
RefPtr<VideoData> v(new VideoData(aOffset, aTime, aDuration, aKeyframe,
442
aTimecode, aDisplay, 0));
443
v->mImage = aImage;
444
return v.forget();
445
}
446
447
MediaRawData::MediaRawData()
448
: MediaData(Type::RAW_DATA), mCrypto(mCryptoInternal) {}
449
450
MediaRawData::MediaRawData(const uint8_t* aData, size_t aSize)
451
: MediaData(Type::RAW_DATA),
452
mCrypto(mCryptoInternal),
453
mBuffer(aData, aSize) {}
454
455
MediaRawData::MediaRawData(const uint8_t* aData, size_t aSize,
456
const uint8_t* aAlphaData, size_t aAlphaSize)
457
: MediaData(Type::RAW_DATA),
458
mCrypto(mCryptoInternal),
459
mBuffer(aData, aSize),
460
mAlphaBuffer(aAlphaData, aAlphaSize) {}
461
462
already_AddRefed<MediaRawData> MediaRawData::Clone() const {
463
RefPtr<MediaRawData> s = new MediaRawData;
464
s->mTimecode = mTimecode;
465
s->mTime = mTime;
466
s->mDuration = mDuration;
467
s->mOffset = mOffset;
468
s->mKeyframe = mKeyframe;
469
s->mExtraData = mExtraData;
470
s->mCryptoInternal = mCryptoInternal;
471
s->mTrackInfo = mTrackInfo;
472
s->mEOS = mEOS;
473
s->mOriginalPresentationWindow = mOriginalPresentationWindow;
474
if (!s->mBuffer.Append(mBuffer.Data(), mBuffer.Length())) {
475
return nullptr;
476
}
477
if (!s->mAlphaBuffer.Append(mAlphaBuffer.Data(), mAlphaBuffer.Length())) {
478
return nullptr;
479
}
480
return s.forget();
481
}
482
483
MediaRawData::~MediaRawData() {}
484
485
size_t MediaRawData::SizeOfIncludingThis(MallocSizeOf aMallocSizeOf) const {
486
size_t size = aMallocSizeOf(this);
487
size += mBuffer.SizeOfExcludingThis(aMallocSizeOf);
488
return size;
489
}
490
491
UniquePtr<MediaRawDataWriter> MediaRawData::CreateWriter() {
492
UniquePtr<MediaRawDataWriter> p(new MediaRawDataWriter(this));
493
return p;
494
}
495
496
MediaRawDataWriter::MediaRawDataWriter(MediaRawData* aMediaRawData)
497
: mCrypto(aMediaRawData->mCryptoInternal), mTarget(aMediaRawData) {}
498
499
bool MediaRawDataWriter::SetSize(size_t aSize) {
500
return mTarget->mBuffer.SetLength(aSize);
501
}
502
503
bool MediaRawDataWriter::Prepend(const uint8_t* aData, size_t aSize) {
504
return mTarget->mBuffer.Prepend(aData, aSize);
505
}
506
507
bool MediaRawDataWriter::Append(const uint8_t* aData, size_t aSize) {
508
return mTarget->mBuffer.Append(aData, aSize);
509
}
510
511
bool MediaRawDataWriter::Replace(const uint8_t* aData, size_t aSize) {
512
return mTarget->mBuffer.Replace(aData, aSize);
513
}
514
515
void MediaRawDataWriter::Clear() { mTarget->mBuffer.Clear(); }
516
517
uint8_t* MediaRawDataWriter::Data() { return mTarget->mBuffer.Data(); }
518
519
size_t MediaRawDataWriter::Size() { return mTarget->Size(); }
520
521
void MediaRawDataWriter::PopFront(size_t aSize) {
522
mTarget->mBuffer.PopFront(aSize);
523
}
524
525
} // namespace mozilla