1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "media/filters/gpu_video_decoder.h"
10 #include "base/callback_helpers.h"
11 #include "base/command_line.h"
13 #include "base/message_loop/message_loop.h"
14 #include "base/metrics/histogram.h"
15 #include "base/stl_util.h"
16 #include "base/task_runner_util.h"
17 #include "gpu/command_buffer/common/mailbox_holder.h"
18 #include "media/base/bind_to_current_loop.h"
19 #include "media/base/decoder_buffer.h"
20 #include "media/base/media_switches.h"
21 #include "media/base/pipeline.h"
22 #include "media/base/pipeline_status.h"
23 #include "media/base/video_decoder_config.h"
24 #include "media/filters/gpu_video_accelerator_factories.h"
25 #include "third_party/skia/include/core/SkBitmap.h"
29 const char GpuVideoDecoder::kDecoderName
[] = "GpuVideoDecoder";
31 // Maximum number of concurrent VDA::Decode() operations GVD will maintain.
32 // Higher values allow better pipelining in the GPU, but also require more
34 enum { kMaxInFlightDecodes
= 4 };
36 // Size of shared-memory segments we allocate. Since we reuse them we let them
37 // be on the beefy side.
38 static const size_t kSharedMemorySegmentBytes
= 100 << 10;
40 GpuVideoDecoder::SHMBuffer::SHMBuffer(scoped_ptr
<base::SharedMemory
> m
,
42 : shm(m
.Pass()), size(s
) {
45 GpuVideoDecoder::SHMBuffer::~SHMBuffer() {}
47 GpuVideoDecoder::PendingDecoderBuffer::PendingDecoderBuffer(
49 const scoped_refptr
<DecoderBuffer
>& b
,
50 const DecodeCB
& done_cb
)
51 : shm_buffer(s
), buffer(b
), done_cb(done_cb
) {
54 GpuVideoDecoder::PendingDecoderBuffer::~PendingDecoderBuffer() {}
56 GpuVideoDecoder::BufferData::BufferData(
57 int32 bbid
, base::TimeDelta ts
, const gfx::Rect
& vr
, const gfx::Size
& ns
)
58 : bitstream_buffer_id(bbid
), timestamp(ts
), visible_rect(vr
),
62 GpuVideoDecoder::BufferData::~BufferData() {}
64 GpuVideoDecoder::GpuVideoDecoder(
65 const scoped_refptr
<GpuVideoAcceleratorFactories
>& factories
)
66 : needs_bitstream_conversion_(false),
67 factories_(factories
),
69 decoder_texture_target_(0),
70 next_picture_buffer_id_(0),
71 next_bitstream_buffer_id_(0),
72 available_pictures_(0),
74 DCHECK(factories_
.get());
77 void GpuVideoDecoder::Reset(const base::Closure
& closure
) {
78 DVLOG(3) << "Reset()";
79 DCheckGpuVideoAcceleratorFactoriesTaskRunnerIsCurrent();
81 if (state_
== kDrainingDecoder
) {
82 base::MessageLoop::current()->PostTask(
85 &GpuVideoDecoder::Reset
, weak_factory_
.GetWeakPtr(), closure
));
90 base::MessageLoop::current()->PostTask(FROM_HERE
, closure
);
94 DCHECK(pending_reset_cb_
.is_null());
95 pending_reset_cb_
= BindToCurrentLoop(closure
);
100 static bool IsCodedSizeSupported(const gfx::Size
& coded_size
) {
102 // Windows Media Foundation H.264 decoding does not support decoding videos
103 // with any dimension smaller than 48 pixels:
104 // http://msdn.microsoft.com/en-us/library/windows/desktop/dd797815
105 if (coded_size
.width() < 48 || coded_size
.height() < 48)
109 // Only non-Windows, Ivy Bridge+ platforms can support more than 1920x1080.
110 // We test against 1088 to account for 16x16 macroblocks.
111 if (coded_size
.width() <= 1920 && coded_size
.height() <= 1088)
114 // NOTE: additional autodetection logic may require updating input buffer size
115 // selection in platform-specific implementations, such as
116 // V4L2VideoDecodeAccelerator.
118 bool hw_large_video_support
=
119 base::CommandLine::ForCurrentProcess()->HasSwitch(
120 switches::kIgnoreResolutionLimitsForAcceleratedVideoDecode
) ||
121 ((cpu
.vendor_name() == "GenuineIntel") && cpu
.model() >= 55);
122 bool os_large_video_support
= true;
124 os_large_video_support
= false;
126 return os_large_video_support
&& hw_large_video_support
;
129 // Report |status| to UMA and run |cb| with it. This is super-specific to the
130 // UMA stat reported because the UMA_HISTOGRAM_ENUMERATION API requires a
131 // callsite to always be called with the same stat name (can't parameterize it).
132 static void ReportGpuVideoDecoderInitializeStatusToUMAAndRunCB(
133 const PipelineStatusCB
& cb
,
134 PipelineStatus status
) {
135 UMA_HISTOGRAM_ENUMERATION(
136 "Media.GpuVideoDecoderInitializeStatus", status
, PIPELINE_STATUS_MAX
+ 1);
140 std::string
GpuVideoDecoder::GetDisplayName() const {
144 void GpuVideoDecoder::Initialize(const VideoDecoderConfig
& config
,
145 bool /* low_delay */,
146 const PipelineStatusCB
& orig_status_cb
,
147 const OutputCB
& output_cb
) {
148 DVLOG(3) << "Initialize()";
149 DCheckGpuVideoAcceleratorFactoriesTaskRunnerIsCurrent();
150 DCHECK(config
.IsValidConfig());
151 DCHECK(!config
.is_encrypted());
153 PipelineStatusCB status_cb
=
154 base::Bind(&ReportGpuVideoDecoderInitializeStatusToUMAAndRunCB
,
155 BindToCurrentLoop(orig_status_cb
));
157 bool previously_initialized
= config_
.IsValidConfig();
158 DVLOG(1) << "(Re)initializing GVD with config: "
159 << config
.AsHumanReadableString();
161 // TODO(posciak): destroy and create a new VDA on codec/profile change
162 // (http://crbug.com/260224).
163 if (previously_initialized
&& (config_
.profile() != config
.profile())) {
164 DVLOG(1) << "Codec or profile changed, cannot reinitialize.";
165 status_cb
.Run(DECODER_ERROR_NOT_SUPPORTED
);
169 if (!IsCodedSizeSupported(config
.coded_size())) {
170 status_cb
.Run(DECODER_ERROR_NOT_SUPPORTED
);
175 needs_bitstream_conversion_
= (config
.codec() == kCodecH264
);
176 output_cb_
= BindToCurrentLoop(output_cb
);
178 if (previously_initialized
) {
179 // Reinitialization with a different config (but same codec and profile).
180 // VDA should handle it by detecting this in-stream by itself,
181 // no need to notify it.
182 status_cb
.Run(PIPELINE_OK
);
186 vda_
= factories_
->CreateVideoDecodeAccelerator().Pass();
187 if (!vda_
|| !vda_
->Initialize(config
.profile(), this)) {
188 status_cb
.Run(DECODER_ERROR_NOT_SUPPORTED
);
192 DVLOG(3) << "GpuVideoDecoder::Initialize() succeeded.";
193 status_cb
.Run(PIPELINE_OK
);
196 void GpuVideoDecoder::DestroyPictureBuffers(PictureBufferMap
* buffers
) {
197 DCheckGpuVideoAcceleratorFactoriesTaskRunnerIsCurrent();
198 for (PictureBufferMap::iterator it
= buffers
->begin(); it
!= buffers
->end();
200 factories_
->DeleteTexture(it
->second
.texture_id());
206 void GpuVideoDecoder::DestroyVDA() {
207 DCheckGpuVideoAcceleratorFactoriesTaskRunnerIsCurrent();
211 // Not destroying PictureBuffers in |picture_buffers_at_display_| yet, since
212 // their textures may still be in use by the user of this GpuVideoDecoder.
213 for (PictureBufferTextureMap::iterator it
=
214 picture_buffers_at_display_
.begin();
215 it
!= picture_buffers_at_display_
.end();
217 assigned_picture_buffers_
.erase(it
->first
);
219 DestroyPictureBuffers(&assigned_picture_buffers_
);
222 void GpuVideoDecoder::Decode(const scoped_refptr
<DecoderBuffer
>& buffer
,
223 const DecodeCB
& decode_cb
) {
224 DCheckGpuVideoAcceleratorFactoriesTaskRunnerIsCurrent();
225 DCHECK(pending_reset_cb_
.is_null());
227 DecodeCB bound_decode_cb
= BindToCurrentLoop(decode_cb
);
229 if (state_
== kError
|| !vda_
) {
230 bound_decode_cb
.Run(kDecodeError
);
235 case kDecoderDrained
:
240 case kDrainingDecoder
:
246 DCHECK_EQ(state_
, kNormal
);
248 if (buffer
->end_of_stream()) {
249 state_
= kDrainingDecoder
;
250 eos_decode_cb_
= bound_decode_cb
;
255 size_t size
= buffer
->data_size();
256 scoped_ptr
<SHMBuffer
> shm_buffer
= GetSHM(size
);
258 bound_decode_cb
.Run(kDecodeError
);
262 memcpy(shm_buffer
->shm
->memory(), buffer
->data(), size
);
263 BitstreamBuffer
bitstream_buffer(
264 next_bitstream_buffer_id_
, shm_buffer
->shm
->handle(), size
);
265 // Mask against 30 bits, to avoid (undefined) wraparound on signed integer.
266 next_bitstream_buffer_id_
= (next_bitstream_buffer_id_
+ 1) & 0x3FFFFFFF;
267 DCHECK(!ContainsKey(bitstream_buffers_in_decoder_
, bitstream_buffer
.id()));
268 bitstream_buffers_in_decoder_
.insert(std::make_pair(
269 bitstream_buffer
.id(),
270 PendingDecoderBuffer(shm_buffer
.release(), buffer
, decode_cb
)));
271 DCHECK_LE(static_cast<int>(bitstream_buffers_in_decoder_
.size()),
272 kMaxInFlightDecodes
);
273 RecordBufferData(bitstream_buffer
, *buffer
.get());
275 vda_
->Decode(bitstream_buffer
);
278 void GpuVideoDecoder::RecordBufferData(const BitstreamBuffer
& bitstream_buffer
,
279 const DecoderBuffer
& buffer
) {
280 input_buffer_data_
.push_front(BufferData(bitstream_buffer
.id(),
282 config_
.visible_rect(),
283 config_
.natural_size()));
284 // Why this value? Because why not. avformat.h:MAX_REORDER_DELAY is 16, but
285 // that's too small for some pathological B-frame test videos. The cost of
286 // using too-high a value is low (192 bits per extra slot).
287 static const size_t kMaxInputBufferDataSize
= 128;
288 // Pop from the back of the list, because that's the oldest and least likely
289 // to be useful in the future data.
290 if (input_buffer_data_
.size() > kMaxInputBufferDataSize
)
291 input_buffer_data_
.pop_back();
294 void GpuVideoDecoder::GetBufferData(int32 id
, base::TimeDelta
* timestamp
,
295 gfx::Rect
* visible_rect
,
296 gfx::Size
* natural_size
) {
297 for (std::list
<BufferData
>::const_iterator it
=
298 input_buffer_data_
.begin(); it
!= input_buffer_data_
.end();
300 if (it
->bitstream_buffer_id
!= id
)
302 *timestamp
= it
->timestamp
;
303 *visible_rect
= it
->visible_rect
;
304 *natural_size
= it
->natural_size
;
307 NOTREACHED() << "Missing bitstreambuffer id: " << id
;
310 bool GpuVideoDecoder::NeedsBitstreamConversion() const {
311 DCheckGpuVideoAcceleratorFactoriesTaskRunnerIsCurrent();
312 return needs_bitstream_conversion_
;
315 bool GpuVideoDecoder::CanReadWithoutStalling() const {
316 DCheckGpuVideoAcceleratorFactoriesTaskRunnerIsCurrent();
318 next_picture_buffer_id_
== 0 || // Decode() will ProvidePictureBuffers().
319 available_pictures_
> 0;
322 int GpuVideoDecoder::GetMaxDecodeRequests() const {
323 return kMaxInFlightDecodes
;
326 void GpuVideoDecoder::ProvidePictureBuffers(uint32 count
,
327 const gfx::Size
& size
,
328 uint32 texture_target
) {
329 DVLOG(3) << "ProvidePictureBuffers(" << count
<< ", "
330 << size
.width() << "x" << size
.height() << ")";
331 DCheckGpuVideoAcceleratorFactoriesTaskRunnerIsCurrent();
333 std::vector
<uint32
> texture_ids
;
334 std::vector
<gpu::Mailbox
> texture_mailboxes
;
335 decoder_texture_target_
= texture_target
;
336 if (!factories_
->CreateTextures(count
,
340 decoder_texture_target_
)) {
341 NotifyError(VideoDecodeAccelerator::PLATFORM_FAILURE
);
344 DCHECK_EQ(count
, texture_ids
.size());
345 DCHECK_EQ(count
, texture_mailboxes
.size());
350 std::vector
<PictureBuffer
> picture_buffers
;
351 for (size_t i
= 0; i
< texture_ids
.size(); ++i
) {
352 picture_buffers
.push_back(PictureBuffer(
353 next_picture_buffer_id_
++, size
, texture_ids
[i
], texture_mailboxes
[i
]));
354 bool inserted
= assigned_picture_buffers_
.insert(std::make_pair(
355 picture_buffers
.back().id(), picture_buffers
.back())).second
;
359 available_pictures_
+= count
;
361 vda_
->AssignPictureBuffers(picture_buffers
);
364 void GpuVideoDecoder::DismissPictureBuffer(int32 id
) {
365 DVLOG(3) << "DismissPictureBuffer(" << id
<< ")";
366 DCheckGpuVideoAcceleratorFactoriesTaskRunnerIsCurrent();
368 PictureBufferMap::iterator it
= assigned_picture_buffers_
.find(id
);
369 if (it
== assigned_picture_buffers_
.end()) {
370 NOTREACHED() << "Missing picture buffer: " << id
;
374 PictureBuffer buffer_to_dismiss
= it
->second
;
375 assigned_picture_buffers_
.erase(it
);
377 if (!picture_buffers_at_display_
.count(id
)) {
378 // We can delete the texture immediately as it's not being displayed.
379 factories_
->DeleteTexture(buffer_to_dismiss
.texture_id());
380 CHECK_GT(available_pictures_
, 0);
381 --available_pictures_
;
383 // Not destroying a texture in display in |picture_buffers_at_display_|.
384 // Postpone deletion until after it's returned to us.
387 void GpuVideoDecoder::PictureReady(const media::Picture
& picture
) {
388 DVLOG(3) << "PictureReady()";
389 DCheckGpuVideoAcceleratorFactoriesTaskRunnerIsCurrent();
391 PictureBufferMap::iterator it
=
392 assigned_picture_buffers_
.find(picture
.picture_buffer_id());
393 if (it
== assigned_picture_buffers_
.end()) {
394 NOTREACHED() << "Missing picture buffer: " << picture
.picture_buffer_id();
395 NotifyError(VideoDecodeAccelerator::PLATFORM_FAILURE
);
398 const PictureBuffer
& pb
= it
->second
;
400 // Validate picture rectangle from GPU. This is for sanity/security check
401 // even the rectangle is not used in this class.
402 if (picture
.visible_rect().IsEmpty() ||
403 !gfx::Rect(pb
.size()).Contains(picture
.visible_rect())) {
404 NOTREACHED() << "Invalid picture size from VDA: "
405 << picture
.visible_rect().ToString() << " should fit in "
406 << pb
.size().ToString();
407 NotifyError(media::VideoDecodeAccelerator::PLATFORM_FAILURE
);
411 // Update frame's timestamp.
412 base::TimeDelta timestamp
;
413 // Some of the VDAs don't support and thus don't provide us with visible
414 // size in picture.size, passing coded size instead, so always drop it and
415 // use config information instead.
416 gfx::Rect visible_rect
;
417 gfx::Size natural_size
;
418 GetBufferData(picture
.bitstream_buffer_id(), ×tamp
, &visible_rect
,
420 DCHECK(decoder_texture_target_
);
422 scoped_refptr
<VideoFrame
> frame(VideoFrame::WrapNativeTexture(
423 make_scoped_ptr(new gpu::MailboxHolder(
424 pb
.texture_mailbox(), decoder_texture_target_
, 0 /* sync_point */)),
425 BindToCurrentLoop(base::Bind(
426 &GpuVideoDecoder::ReleaseMailbox
, weak_factory_
.GetWeakPtr(),
427 factories_
, picture
.picture_buffer_id(), pb
.texture_id())),
428 pb
.size(), visible_rect
, natural_size
, timestamp
,
429 picture
.allow_overlay()));
430 CHECK_GT(available_pictures_
, 0);
431 --available_pictures_
;
433 picture_buffers_at_display_
.insert(std::make_pair(
434 picture
.picture_buffer_id(),
435 pb
.texture_id())).second
;
441 void GpuVideoDecoder::DeliverFrame(
442 const scoped_refptr
<VideoFrame
>& frame
) {
443 DCheckGpuVideoAcceleratorFactoriesTaskRunnerIsCurrent();
445 // During a pending vda->Reset(), we don't accumulate frames. Drop it on the
447 if (!pending_reset_cb_
.is_null())
450 output_cb_
.Run(frame
);
454 void GpuVideoDecoder::ReleaseMailbox(
455 base::WeakPtr
<GpuVideoDecoder
> decoder
,
456 const scoped_refptr
<media::GpuVideoAcceleratorFactories
>& factories
,
457 int64 picture_buffer_id
,
459 uint32 release_sync_point
) {
460 DCHECK(factories
->GetTaskRunner()->BelongsToCurrentThread());
461 factories
->WaitSyncPoint(release_sync_point
);
464 decoder
->ReusePictureBuffer(picture_buffer_id
);
467 // It's the last chance to delete the texture after display,
468 // because GpuVideoDecoder was destructed.
469 factories
->DeleteTexture(texture_id
);
472 void GpuVideoDecoder::ReusePictureBuffer(int64 picture_buffer_id
) {
473 DVLOG(3) << "ReusePictureBuffer(" << picture_buffer_id
<< ")";
474 DCheckGpuVideoAcceleratorFactoriesTaskRunnerIsCurrent();
476 DCHECK(!picture_buffers_at_display_
.empty());
477 PictureBufferTextureMap::iterator display_iterator
=
478 picture_buffers_at_display_
.find(picture_buffer_id
);
479 uint32 texture_id
= display_iterator
->second
;
480 DCHECK(display_iterator
!= picture_buffers_at_display_
.end());
481 picture_buffers_at_display_
.erase(display_iterator
);
483 if (!assigned_picture_buffers_
.count(picture_buffer_id
)) {
484 // This picture was dismissed while in display, so we postponed deletion.
485 factories_
->DeleteTexture(texture_id
);
489 ++available_pictures_
;
491 // DestroyVDA() might already have been called.
493 vda_
->ReusePictureBuffer(picture_buffer_id
);
496 scoped_ptr
<GpuVideoDecoder::SHMBuffer
> GpuVideoDecoder::GetSHM(
498 DCheckGpuVideoAcceleratorFactoriesTaskRunnerIsCurrent();
499 if (available_shm_segments_
.empty() ||
500 available_shm_segments_
.back()->size
< min_size
) {
501 size_t size_to_allocate
= std::max(min_size
, kSharedMemorySegmentBytes
);
502 scoped_ptr
<base::SharedMemory
> shm
=
503 factories_
->CreateSharedMemory(size_to_allocate
);
504 // CreateSharedMemory() can return NULL during Shutdown.
507 return make_scoped_ptr(new SHMBuffer(shm
.Pass(), size_to_allocate
));
509 scoped_ptr
<SHMBuffer
> ret(available_shm_segments_
.back());
510 available_shm_segments_
.pop_back();
514 void GpuVideoDecoder::PutSHM(scoped_ptr
<SHMBuffer
> shm_buffer
) {
515 DCheckGpuVideoAcceleratorFactoriesTaskRunnerIsCurrent();
516 available_shm_segments_
.push_back(shm_buffer
.release());
519 void GpuVideoDecoder::NotifyEndOfBitstreamBuffer(int32 id
) {
520 DVLOG(3) << "NotifyEndOfBitstreamBuffer(" << id
<< ")";
521 DCheckGpuVideoAcceleratorFactoriesTaskRunnerIsCurrent();
523 std::map
<int32
, PendingDecoderBuffer
>::iterator it
=
524 bitstream_buffers_in_decoder_
.find(id
);
525 if (it
== bitstream_buffers_in_decoder_
.end()) {
526 NotifyError(VideoDecodeAccelerator::PLATFORM_FAILURE
);
527 NOTREACHED() << "Missing bitstream buffer: " << id
;
531 PutSHM(make_scoped_ptr(it
->second
.shm_buffer
));
532 it
->second
.done_cb
.Run(state_
== kError
? kDecodeError
: kOk
);
533 bitstream_buffers_in_decoder_
.erase(it
);
536 GpuVideoDecoder::~GpuVideoDecoder() {
537 DVLOG(3) << __FUNCTION__
;
538 DCheckGpuVideoAcceleratorFactoriesTaskRunnerIsCurrent();
542 DCHECK(assigned_picture_buffers_
.empty());
544 for (size_t i
= 0; i
< available_shm_segments_
.size(); ++i
) {
545 delete available_shm_segments_
[i
];
547 available_shm_segments_
.clear();
549 for (std::map
<int32
, PendingDecoderBuffer
>::iterator it
=
550 bitstream_buffers_in_decoder_
.begin();
551 it
!= bitstream_buffers_in_decoder_
.end(); ++it
) {
552 delete it
->second
.shm_buffer
;
553 it
->second
.done_cb
.Run(kAborted
);
555 bitstream_buffers_in_decoder_
.clear();
557 if (!pending_reset_cb_
.is_null())
558 base::ResetAndReturn(&pending_reset_cb_
).Run();
561 void GpuVideoDecoder::NotifyFlushDone() {
562 DVLOG(3) << "NotifyFlushDone()";
563 DCheckGpuVideoAcceleratorFactoriesTaskRunnerIsCurrent();
564 DCHECK_EQ(state_
, kDrainingDecoder
);
565 state_
= kDecoderDrained
;
566 base::ResetAndReturn(&eos_decode_cb_
).Run(kOk
);
569 void GpuVideoDecoder::NotifyResetDone() {
570 DVLOG(3) << "NotifyResetDone()";
571 DCheckGpuVideoAcceleratorFactoriesTaskRunnerIsCurrent();
572 DCHECK(bitstream_buffers_in_decoder_
.empty());
574 // This needs to happen after the Reset() on vda_ is done to ensure pictures
575 // delivered during the reset can find their time data.
576 input_buffer_data_
.clear();
578 if (!pending_reset_cb_
.is_null())
579 base::ResetAndReturn(&pending_reset_cb_
).Run();
582 void GpuVideoDecoder::NotifyError(media::VideoDecodeAccelerator::Error error
) {
583 DCheckGpuVideoAcceleratorFactoriesTaskRunnerIsCurrent();
589 DLOG(ERROR
) << "VDA Error: " << error
;
593 void GpuVideoDecoder::DCheckGpuVideoAcceleratorFactoriesTaskRunnerIsCurrent()
595 DCHECK(factories_
->GetTaskRunner()->BelongsToCurrentThread());