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/video_decoder_config.h"
23 #include "media/renderers/gpu_video_accelerator_factories.h"
24 #include "third_party/skia/include/core/SkBitmap.h"
28 const char GpuVideoDecoder::kDecoderName
[] = "GpuVideoDecoder";
30 // Maximum number of concurrent VDA::Decode() operations GVD will maintain.
31 // Higher values allow better pipelining in the GPU, but also require more
33 enum { kMaxInFlightDecodes
= 4 };
35 // Size of shared-memory segments we allocate. Since we reuse them we let them
36 // be on the beefy side.
37 static const size_t kSharedMemorySegmentBytes
= 100 << 10;
39 GpuVideoDecoder::SHMBuffer::SHMBuffer(scoped_ptr
<base::SharedMemory
> m
,
41 : shm(m
.Pass()), size(s
) {
44 GpuVideoDecoder::SHMBuffer::~SHMBuffer() {}
46 GpuVideoDecoder::PendingDecoderBuffer::PendingDecoderBuffer(
48 const scoped_refptr
<DecoderBuffer
>& b
,
49 const DecodeCB
& done_cb
)
50 : shm_buffer(s
), buffer(b
), done_cb(done_cb
) {
53 GpuVideoDecoder::PendingDecoderBuffer::~PendingDecoderBuffer() {}
55 GpuVideoDecoder::BufferData::BufferData(
56 int32 bbid
, base::TimeDelta ts
, const gfx::Rect
& vr
, const gfx::Size
& ns
)
57 : bitstream_buffer_id(bbid
), timestamp(ts
), visible_rect(vr
),
61 GpuVideoDecoder::BufferData::~BufferData() {}
63 GpuVideoDecoder::GpuVideoDecoder(
64 const scoped_refptr
<GpuVideoAcceleratorFactories
>& factories
)
65 : needs_bitstream_conversion_(false),
66 factories_(factories
),
68 decoder_texture_target_(0),
69 next_picture_buffer_id_(0),
70 next_bitstream_buffer_id_(0),
71 available_pictures_(0),
73 DCHECK(factories_
.get());
76 void GpuVideoDecoder::Reset(const base::Closure
& closure
) {
77 DVLOG(3) << "Reset()";
78 DCheckGpuVideoAcceleratorFactoriesTaskRunnerIsCurrent();
80 if (state_
== kDrainingDecoder
) {
81 base::MessageLoop::current()->PostTask(
84 &GpuVideoDecoder::Reset
, weak_factory_
.GetWeakPtr(), closure
));
89 base::MessageLoop::current()->PostTask(FROM_HERE
, closure
);
93 DCHECK(pending_reset_cb_
.is_null());
94 pending_reset_cb_
= BindToCurrentLoop(closure
);
99 static bool IsCodedSizeSupported(const gfx::Size
& coded_size
,
100 const gfx::Size
& min_resolution
,
101 const gfx::Size
& max_resolution
) {
102 return (coded_size
.width() <= max_resolution
.width() &&
103 coded_size
.height() <= max_resolution
.height() &&
104 coded_size
.width() >= min_resolution
.width() &&
105 coded_size
.height() >= min_resolution
.height());
108 // Report |success| to UMA and run |cb| with it. This is super-specific to the
109 // UMA stat reported because the UMA_HISTOGRAM_ENUMERATION API requires a
110 // callsite to always be called with the same stat name (can't parameterize it).
111 static void ReportGpuVideoDecoderInitializeStatusToUMAAndRunCB(
112 const VideoDecoder::InitCB
& cb
,
114 // TODO(xhwang): Report |success| directly.
115 PipelineStatus status
= success
? PIPELINE_OK
: DECODER_ERROR_NOT_SUPPORTED
;
116 UMA_HISTOGRAM_ENUMERATION(
117 "Media.GpuVideoDecoderInitializeStatus", status
, PIPELINE_STATUS_MAX
+ 1);
121 std::string
GpuVideoDecoder::GetDisplayName() const {
125 void GpuVideoDecoder::Initialize(const VideoDecoderConfig
& config
,
126 bool /* low_delay */,
127 const InitCB
& init_cb
,
128 const OutputCB
& output_cb
) {
129 DVLOG(3) << "Initialize()";
130 DCheckGpuVideoAcceleratorFactoriesTaskRunnerIsCurrent();
131 DCHECK(config
.IsValidConfig());
132 DCHECK(!config
.is_encrypted());
134 InitCB bound_init_cb
=
135 base::Bind(&ReportGpuVideoDecoderInitializeStatusToUMAAndRunCB
,
136 BindToCurrentLoop(init_cb
));
138 bool previously_initialized
= config_
.IsValidConfig();
139 DVLOG(1) << "(Re)initializing GVD with config: "
140 << config
.AsHumanReadableString();
142 // TODO(posciak): destroy and create a new VDA on codec/profile change
143 // (http://crbug.com/260224).
144 if (previously_initialized
&& (config_
.profile() != config
.profile())) {
145 DVLOG(1) << "Codec or profile changed, cannot reinitialize.";
146 bound_init_cb
.Run(false);
150 if (!IsProfileSupported(config
.profile(), config
.coded_size())) {
151 bound_init_cb
.Run(false);
156 needs_bitstream_conversion_
= (config
.codec() == kCodecH264
);
157 output_cb_
= BindToCurrentLoop(output_cb
);
159 if (previously_initialized
) {
160 // Reinitialization with a different config (but same codec and profile).
161 // VDA should handle it by detecting this in-stream by itself,
162 // no need to notify it.
163 bound_init_cb
.Run(true);
167 vda_
= factories_
->CreateVideoDecodeAccelerator().Pass();
168 if (!vda_
|| !vda_
->Initialize(config
.profile(), this)) {
169 bound_init_cb
.Run(false);
173 DVLOG(3) << "GpuVideoDecoder::Initialize() succeeded.";
174 bound_init_cb
.Run(true);
177 void GpuVideoDecoder::DestroyPictureBuffers(PictureBufferMap
* buffers
) {
178 DCheckGpuVideoAcceleratorFactoriesTaskRunnerIsCurrent();
179 for (PictureBufferMap::iterator it
= buffers
->begin(); it
!= buffers
->end();
181 factories_
->DeleteTexture(it
->second
.texture_id());
187 void GpuVideoDecoder::DestroyVDA() {
188 DCheckGpuVideoAcceleratorFactoriesTaskRunnerIsCurrent();
192 // Not destroying PictureBuffers in |picture_buffers_at_display_| yet, since
193 // their textures may still be in use by the user of this GpuVideoDecoder.
194 for (PictureBufferTextureMap::iterator it
=
195 picture_buffers_at_display_
.begin();
196 it
!= picture_buffers_at_display_
.end();
198 assigned_picture_buffers_
.erase(it
->first
);
200 DestroyPictureBuffers(&assigned_picture_buffers_
);
203 void GpuVideoDecoder::Decode(const scoped_refptr
<DecoderBuffer
>& buffer
,
204 const DecodeCB
& decode_cb
) {
205 DCheckGpuVideoAcceleratorFactoriesTaskRunnerIsCurrent();
206 DCHECK(pending_reset_cb_
.is_null());
208 DecodeCB bound_decode_cb
= BindToCurrentLoop(decode_cb
);
210 if (state_
== kError
|| !vda_
) {
211 bound_decode_cb
.Run(kDecodeError
);
216 case kDecoderDrained
:
221 case kDrainingDecoder
:
227 DCHECK_EQ(state_
, kNormal
);
229 if (buffer
->end_of_stream()) {
230 state_
= kDrainingDecoder
;
231 eos_decode_cb_
= bound_decode_cb
;
236 size_t size
= buffer
->data_size();
237 scoped_ptr
<SHMBuffer
> shm_buffer
= GetSHM(size
);
239 bound_decode_cb
.Run(kDecodeError
);
243 memcpy(shm_buffer
->shm
->memory(), buffer
->data(), size
);
244 BitstreamBuffer
bitstream_buffer(
245 next_bitstream_buffer_id_
, shm_buffer
->shm
->handle(), size
);
246 // Mask against 30 bits, to avoid (undefined) wraparound on signed integer.
247 next_bitstream_buffer_id_
= (next_bitstream_buffer_id_
+ 1) & 0x3FFFFFFF;
248 DCHECK(!ContainsKey(bitstream_buffers_in_decoder_
, bitstream_buffer
.id()));
249 bitstream_buffers_in_decoder_
.insert(std::make_pair(
250 bitstream_buffer
.id(),
251 PendingDecoderBuffer(shm_buffer
.release(), buffer
, decode_cb
)));
252 DCHECK_LE(static_cast<int>(bitstream_buffers_in_decoder_
.size()),
253 kMaxInFlightDecodes
);
254 RecordBufferData(bitstream_buffer
, *buffer
.get());
256 vda_
->Decode(bitstream_buffer
);
259 void GpuVideoDecoder::RecordBufferData(const BitstreamBuffer
& bitstream_buffer
,
260 const DecoderBuffer
& buffer
) {
261 input_buffer_data_
.push_front(BufferData(bitstream_buffer
.id(),
263 config_
.visible_rect(),
264 config_
.natural_size()));
265 // Why this value? Because why not. avformat.h:MAX_REORDER_DELAY is 16, but
266 // that's too small for some pathological B-frame test videos. The cost of
267 // using too-high a value is low (192 bits per extra slot).
268 static const size_t kMaxInputBufferDataSize
= 128;
269 // Pop from the back of the list, because that's the oldest and least likely
270 // to be useful in the future data.
271 if (input_buffer_data_
.size() > kMaxInputBufferDataSize
)
272 input_buffer_data_
.pop_back();
275 void GpuVideoDecoder::GetBufferData(int32 id
, base::TimeDelta
* timestamp
,
276 gfx::Rect
* visible_rect
,
277 gfx::Size
* natural_size
) {
278 for (std::list
<BufferData
>::const_iterator it
=
279 input_buffer_data_
.begin(); it
!= input_buffer_data_
.end();
281 if (it
->bitstream_buffer_id
!= id
)
283 *timestamp
= it
->timestamp
;
284 *visible_rect
= it
->visible_rect
;
285 *natural_size
= it
->natural_size
;
288 NOTREACHED() << "Missing bitstreambuffer id: " << id
;
291 bool GpuVideoDecoder::NeedsBitstreamConversion() const {
292 DCheckGpuVideoAcceleratorFactoriesTaskRunnerIsCurrent();
293 return needs_bitstream_conversion_
;
296 bool GpuVideoDecoder::CanReadWithoutStalling() const {
297 DCheckGpuVideoAcceleratorFactoriesTaskRunnerIsCurrent();
299 next_picture_buffer_id_
== 0 || // Decode() will ProvidePictureBuffers().
300 available_pictures_
> 0;
303 int GpuVideoDecoder::GetMaxDecodeRequests() const {
304 return kMaxInFlightDecodes
;
307 void GpuVideoDecoder::ProvidePictureBuffers(uint32 count
,
308 const gfx::Size
& size
,
309 uint32 texture_target
) {
310 DVLOG(3) << "ProvidePictureBuffers(" << count
<< ", "
311 << size
.width() << "x" << size
.height() << ")";
312 DCheckGpuVideoAcceleratorFactoriesTaskRunnerIsCurrent();
314 std::vector
<uint32
> texture_ids
;
315 std::vector
<gpu::Mailbox
> texture_mailboxes
;
316 decoder_texture_target_
= texture_target
;
317 if (!factories_
->CreateTextures(count
,
321 decoder_texture_target_
)) {
322 NotifyError(VideoDecodeAccelerator::PLATFORM_FAILURE
);
325 DCHECK_EQ(count
, texture_ids
.size());
326 DCHECK_EQ(count
, texture_mailboxes
.size());
331 std::vector
<PictureBuffer
> picture_buffers
;
332 for (size_t i
= 0; i
< texture_ids
.size(); ++i
) {
333 picture_buffers
.push_back(PictureBuffer(
334 next_picture_buffer_id_
++, size
, texture_ids
[i
], texture_mailboxes
[i
]));
335 bool inserted
= assigned_picture_buffers_
.insert(std::make_pair(
336 picture_buffers
.back().id(), picture_buffers
.back())).second
;
340 available_pictures_
+= count
;
342 vda_
->AssignPictureBuffers(picture_buffers
);
345 void GpuVideoDecoder::DismissPictureBuffer(int32 id
) {
346 DVLOG(3) << "DismissPictureBuffer(" << id
<< ")";
347 DCheckGpuVideoAcceleratorFactoriesTaskRunnerIsCurrent();
349 PictureBufferMap::iterator it
= assigned_picture_buffers_
.find(id
);
350 if (it
== assigned_picture_buffers_
.end()) {
351 NOTREACHED() << "Missing picture buffer: " << id
;
355 PictureBuffer buffer_to_dismiss
= it
->second
;
356 assigned_picture_buffers_
.erase(it
);
358 if (!picture_buffers_at_display_
.count(id
)) {
359 // We can delete the texture immediately as it's not being displayed.
360 factories_
->DeleteTexture(buffer_to_dismiss
.texture_id());
361 CHECK_GT(available_pictures_
, 0);
362 --available_pictures_
;
364 // Not destroying a texture in display in |picture_buffers_at_display_|.
365 // Postpone deletion until after it's returned to us.
368 void GpuVideoDecoder::PictureReady(const media::Picture
& picture
) {
369 DVLOG(3) << "PictureReady()";
370 DCheckGpuVideoAcceleratorFactoriesTaskRunnerIsCurrent();
372 PictureBufferMap::iterator it
=
373 assigned_picture_buffers_
.find(picture
.picture_buffer_id());
374 if (it
== assigned_picture_buffers_
.end()) {
375 NOTREACHED() << "Missing picture buffer: " << picture
.picture_buffer_id();
376 NotifyError(VideoDecodeAccelerator::PLATFORM_FAILURE
);
379 const PictureBuffer
& pb
= it
->second
;
381 // Validate picture rectangle from GPU. This is for sanity/security check
382 // even the rectangle is not used in this class.
383 if (picture
.visible_rect().IsEmpty() ||
384 !gfx::Rect(pb
.size()).Contains(picture
.visible_rect())) {
385 NOTREACHED() << "Invalid picture size from VDA: "
386 << picture
.visible_rect().ToString() << " should fit in "
387 << pb
.size().ToString();
388 NotifyError(media::VideoDecodeAccelerator::PLATFORM_FAILURE
);
392 // Update frame's timestamp.
393 base::TimeDelta timestamp
;
394 // Some of the VDAs don't support and thus don't provide us with visible
395 // size in picture.size, passing coded size instead, so always drop it and
396 // use config information instead.
397 gfx::Rect visible_rect
;
398 gfx::Size natural_size
;
399 GetBufferData(picture
.bitstream_buffer_id(), ×tamp
, &visible_rect
,
401 DCHECK(decoder_texture_target_
);
403 scoped_refptr
<VideoFrame
> frame(VideoFrame::WrapNativeTexture(
405 gpu::MailboxHolder(pb
.texture_mailbox(), decoder_texture_target_
,
407 BindToCurrentLoop(base::Bind(
408 &GpuVideoDecoder::ReleaseMailbox
, weak_factory_
.GetWeakPtr(),
409 factories_
, picture
.picture_buffer_id(), pb
.texture_id())),
410 pb
.size(), visible_rect
, natural_size
, timestamp
));
411 if (picture
.allow_overlay())
412 frame
->metadata()->SetBoolean(VideoFrameMetadata::ALLOW_OVERLAY
, true);
413 CHECK_GT(available_pictures_
, 0);
414 --available_pictures_
;
416 picture_buffers_at_display_
.insert(std::make_pair(
417 picture
.picture_buffer_id(),
418 pb
.texture_id())).second
;
424 void GpuVideoDecoder::DeliverFrame(
425 const scoped_refptr
<VideoFrame
>& frame
) {
426 DCheckGpuVideoAcceleratorFactoriesTaskRunnerIsCurrent();
428 // During a pending vda->Reset(), we don't accumulate frames. Drop it on the
430 if (!pending_reset_cb_
.is_null())
433 output_cb_
.Run(frame
);
437 void GpuVideoDecoder::ReleaseMailbox(
438 base::WeakPtr
<GpuVideoDecoder
> decoder
,
439 const scoped_refptr
<media::GpuVideoAcceleratorFactories
>& factories
,
440 int64 picture_buffer_id
,
442 uint32 release_sync_point
) {
443 DCHECK(factories
->GetTaskRunner()->BelongsToCurrentThread());
444 factories
->WaitSyncPoint(release_sync_point
);
447 decoder
->ReusePictureBuffer(picture_buffer_id
);
450 // It's the last chance to delete the texture after display,
451 // because GpuVideoDecoder was destructed.
452 factories
->DeleteTexture(texture_id
);
455 void GpuVideoDecoder::ReusePictureBuffer(int64 picture_buffer_id
) {
456 DVLOG(3) << "ReusePictureBuffer(" << picture_buffer_id
<< ")";
457 DCheckGpuVideoAcceleratorFactoriesTaskRunnerIsCurrent();
459 DCHECK(!picture_buffers_at_display_
.empty());
460 PictureBufferTextureMap::iterator display_iterator
=
461 picture_buffers_at_display_
.find(picture_buffer_id
);
462 uint32 texture_id
= display_iterator
->second
;
463 DCHECK(display_iterator
!= picture_buffers_at_display_
.end());
464 picture_buffers_at_display_
.erase(display_iterator
);
466 if (!assigned_picture_buffers_
.count(picture_buffer_id
)) {
467 // This picture was dismissed while in display, so we postponed deletion.
468 factories_
->DeleteTexture(texture_id
);
472 ++available_pictures_
;
474 // DestroyVDA() might already have been called.
476 vda_
->ReusePictureBuffer(picture_buffer_id
);
479 scoped_ptr
<GpuVideoDecoder::SHMBuffer
> GpuVideoDecoder::GetSHM(
481 DCheckGpuVideoAcceleratorFactoriesTaskRunnerIsCurrent();
482 if (available_shm_segments_
.empty() ||
483 available_shm_segments_
.back()->size
< min_size
) {
484 size_t size_to_allocate
= std::max(min_size
, kSharedMemorySegmentBytes
);
485 scoped_ptr
<base::SharedMemory
> shm
=
486 factories_
->CreateSharedMemory(size_to_allocate
);
487 // CreateSharedMemory() can return NULL during Shutdown.
490 return make_scoped_ptr(new SHMBuffer(shm
.Pass(), size_to_allocate
));
492 scoped_ptr
<SHMBuffer
> ret(available_shm_segments_
.back());
493 available_shm_segments_
.pop_back();
497 void GpuVideoDecoder::PutSHM(scoped_ptr
<SHMBuffer
> shm_buffer
) {
498 DCheckGpuVideoAcceleratorFactoriesTaskRunnerIsCurrent();
499 available_shm_segments_
.push_back(shm_buffer
.release());
502 void GpuVideoDecoder::NotifyEndOfBitstreamBuffer(int32 id
) {
503 DVLOG(3) << "NotifyEndOfBitstreamBuffer(" << id
<< ")";
504 DCheckGpuVideoAcceleratorFactoriesTaskRunnerIsCurrent();
506 std::map
<int32
, PendingDecoderBuffer
>::iterator it
=
507 bitstream_buffers_in_decoder_
.find(id
);
508 if (it
== bitstream_buffers_in_decoder_
.end()) {
509 NotifyError(VideoDecodeAccelerator::PLATFORM_FAILURE
);
510 NOTREACHED() << "Missing bitstream buffer: " << id
;
514 PutSHM(make_scoped_ptr(it
->second
.shm_buffer
));
515 it
->second
.done_cb
.Run(state_
== kError
? kDecodeError
: kOk
);
516 bitstream_buffers_in_decoder_
.erase(it
);
519 GpuVideoDecoder::~GpuVideoDecoder() {
520 DVLOG(3) << __FUNCTION__
;
521 DCheckGpuVideoAcceleratorFactoriesTaskRunnerIsCurrent();
525 DCHECK(assigned_picture_buffers_
.empty());
527 for (size_t i
= 0; i
< available_shm_segments_
.size(); ++i
) {
528 delete available_shm_segments_
[i
];
530 available_shm_segments_
.clear();
532 for (std::map
<int32
, PendingDecoderBuffer
>::iterator it
=
533 bitstream_buffers_in_decoder_
.begin();
534 it
!= bitstream_buffers_in_decoder_
.end(); ++it
) {
535 delete it
->second
.shm_buffer
;
536 it
->second
.done_cb
.Run(kAborted
);
538 bitstream_buffers_in_decoder_
.clear();
540 if (!pending_reset_cb_
.is_null())
541 base::ResetAndReturn(&pending_reset_cb_
).Run();
544 void GpuVideoDecoder::NotifyFlushDone() {
545 DVLOG(3) << "NotifyFlushDone()";
546 DCheckGpuVideoAcceleratorFactoriesTaskRunnerIsCurrent();
547 DCHECK_EQ(state_
, kDrainingDecoder
);
548 state_
= kDecoderDrained
;
549 base::ResetAndReturn(&eos_decode_cb_
).Run(kOk
);
552 void GpuVideoDecoder::NotifyResetDone() {
553 DVLOG(3) << "NotifyResetDone()";
554 DCheckGpuVideoAcceleratorFactoriesTaskRunnerIsCurrent();
555 DCHECK(bitstream_buffers_in_decoder_
.empty());
557 // This needs to happen after the Reset() on vda_ is done to ensure pictures
558 // delivered during the reset can find their time data.
559 input_buffer_data_
.clear();
561 if (!pending_reset_cb_
.is_null())
562 base::ResetAndReturn(&pending_reset_cb_
).Run();
565 void GpuVideoDecoder::NotifyError(media::VideoDecodeAccelerator::Error error
) {
566 DCheckGpuVideoAcceleratorFactoriesTaskRunnerIsCurrent();
572 DLOG(ERROR
) << "VDA Error: " << error
;
576 bool GpuVideoDecoder::IsProfileSupported(VideoCodecProfile profile
,
577 const gfx::Size
& coded_size
) {
578 DCheckGpuVideoAcceleratorFactoriesTaskRunnerIsCurrent();
579 VideoDecodeAccelerator::SupportedProfiles supported_profiles
=
580 factories_
->GetVideoDecodeAcceleratorSupportedProfiles();
581 for (const auto& supported_profile
: supported_profiles
) {
582 if (profile
== supported_profile
.profile
) {
583 return IsCodedSizeSupported(coded_size
,
584 supported_profile
.min_resolution
,
585 supported_profile
.max_resolution
);
591 void GpuVideoDecoder::DCheckGpuVideoAcceleratorFactoriesTaskRunnerIsCurrent()
593 DCHECK(factories_
->GetTaskRunner()->BelongsToCurrentThread());