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/renderers/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
,
101 const gfx::Size
& min_resolution
,
102 const gfx::Size
& max_resolution
) {
103 return (coded_size
.width() <= max_resolution
.width() &&
104 coded_size
.height() <= max_resolution
.height() &&
105 coded_size
.width() >= min_resolution
.width() &&
106 coded_size
.height() >= min_resolution
.height());
109 // Report |status| to UMA and run |cb| with it. This is super-specific to the
110 // UMA stat reported because the UMA_HISTOGRAM_ENUMERATION API requires a
111 // callsite to always be called with the same stat name (can't parameterize it).
112 static void ReportGpuVideoDecoderInitializeStatusToUMAAndRunCB(
113 const PipelineStatusCB
& cb
,
114 PipelineStatus status
) {
115 UMA_HISTOGRAM_ENUMERATION(
116 "Media.GpuVideoDecoderInitializeStatus", status
, PIPELINE_STATUS_MAX
+ 1);
120 std::string
GpuVideoDecoder::GetDisplayName() const {
124 void GpuVideoDecoder::Initialize(const VideoDecoderConfig
& config
,
125 bool /* low_delay */,
126 const PipelineStatusCB
& orig_status_cb
,
127 const OutputCB
& output_cb
) {
128 DVLOG(3) << "Initialize()";
129 DCheckGpuVideoAcceleratorFactoriesTaskRunnerIsCurrent();
130 DCHECK(config
.IsValidConfig());
131 DCHECK(!config
.is_encrypted());
133 PipelineStatusCB status_cb
=
134 base::Bind(&ReportGpuVideoDecoderInitializeStatusToUMAAndRunCB
,
135 BindToCurrentLoop(orig_status_cb
));
137 bool previously_initialized
= config_
.IsValidConfig();
138 DVLOG(1) << "(Re)initializing GVD with config: "
139 << config
.AsHumanReadableString();
141 // TODO(posciak): destroy and create a new VDA on codec/profile change
142 // (http://crbug.com/260224).
143 if (previously_initialized
&& (config_
.profile() != config
.profile())) {
144 DVLOG(1) << "Codec or profile changed, cannot reinitialize.";
145 status_cb
.Run(DECODER_ERROR_NOT_SUPPORTED
);
149 if (!IsProfileSupported(config
.profile(), config
.coded_size())) {
150 status_cb
.Run(DECODER_ERROR_NOT_SUPPORTED
);
155 needs_bitstream_conversion_
= (config
.codec() == kCodecH264
);
156 output_cb_
= BindToCurrentLoop(output_cb
);
158 if (previously_initialized
) {
159 // Reinitialization with a different config (but same codec and profile).
160 // VDA should handle it by detecting this in-stream by itself,
161 // no need to notify it.
162 status_cb
.Run(PIPELINE_OK
);
166 vda_
= factories_
->CreateVideoDecodeAccelerator().Pass();
167 if (!vda_
|| !vda_
->Initialize(config
.profile(), this)) {
168 status_cb
.Run(DECODER_ERROR_NOT_SUPPORTED
);
172 DVLOG(3) << "GpuVideoDecoder::Initialize() succeeded.";
173 status_cb
.Run(PIPELINE_OK
);
176 void GpuVideoDecoder::DestroyPictureBuffers(PictureBufferMap
* buffers
) {
177 DCheckGpuVideoAcceleratorFactoriesTaskRunnerIsCurrent();
178 for (PictureBufferMap::iterator it
= buffers
->begin(); it
!= buffers
->end();
180 factories_
->DeleteTexture(it
->second
.texture_id());
186 void GpuVideoDecoder::DestroyVDA() {
187 DCheckGpuVideoAcceleratorFactoriesTaskRunnerIsCurrent();
191 // Not destroying PictureBuffers in |picture_buffers_at_display_| yet, since
192 // their textures may still be in use by the user of this GpuVideoDecoder.
193 for (PictureBufferTextureMap::iterator it
=
194 picture_buffers_at_display_
.begin();
195 it
!= picture_buffers_at_display_
.end();
197 assigned_picture_buffers_
.erase(it
->first
);
199 DestroyPictureBuffers(&assigned_picture_buffers_
);
202 void GpuVideoDecoder::Decode(const scoped_refptr
<DecoderBuffer
>& buffer
,
203 const DecodeCB
& decode_cb
) {
204 DCheckGpuVideoAcceleratorFactoriesTaskRunnerIsCurrent();
205 DCHECK(pending_reset_cb_
.is_null());
207 DecodeCB bound_decode_cb
= BindToCurrentLoop(decode_cb
);
209 if (state_
== kError
|| !vda_
) {
210 bound_decode_cb
.Run(kDecodeError
);
215 case kDecoderDrained
:
220 case kDrainingDecoder
:
226 DCHECK_EQ(state_
, kNormal
);
228 if (buffer
->end_of_stream()) {
229 state_
= kDrainingDecoder
;
230 eos_decode_cb_
= bound_decode_cb
;
235 size_t size
= buffer
->data_size();
236 scoped_ptr
<SHMBuffer
> shm_buffer
= GetSHM(size
);
238 bound_decode_cb
.Run(kDecodeError
);
242 memcpy(shm_buffer
->shm
->memory(), buffer
->data(), size
);
243 BitstreamBuffer
bitstream_buffer(
244 next_bitstream_buffer_id_
, shm_buffer
->shm
->handle(), size
);
245 // Mask against 30 bits, to avoid (undefined) wraparound on signed integer.
246 next_bitstream_buffer_id_
= (next_bitstream_buffer_id_
+ 1) & 0x3FFFFFFF;
247 DCHECK(!ContainsKey(bitstream_buffers_in_decoder_
, bitstream_buffer
.id()));
248 bitstream_buffers_in_decoder_
.insert(std::make_pair(
249 bitstream_buffer
.id(),
250 PendingDecoderBuffer(shm_buffer
.release(), buffer
, decode_cb
)));
251 DCHECK_LE(static_cast<int>(bitstream_buffers_in_decoder_
.size()),
252 kMaxInFlightDecodes
);
253 RecordBufferData(bitstream_buffer
, *buffer
.get());
255 vda_
->Decode(bitstream_buffer
);
258 void GpuVideoDecoder::RecordBufferData(const BitstreamBuffer
& bitstream_buffer
,
259 const DecoderBuffer
& buffer
) {
260 input_buffer_data_
.push_front(BufferData(bitstream_buffer
.id(),
262 config_
.visible_rect(),
263 config_
.natural_size()));
264 // Why this value? Because why not. avformat.h:MAX_REORDER_DELAY is 16, but
265 // that's too small for some pathological B-frame test videos. The cost of
266 // using too-high a value is low (192 bits per extra slot).
267 static const size_t kMaxInputBufferDataSize
= 128;
268 // Pop from the back of the list, because that's the oldest and least likely
269 // to be useful in the future data.
270 if (input_buffer_data_
.size() > kMaxInputBufferDataSize
)
271 input_buffer_data_
.pop_back();
274 void GpuVideoDecoder::GetBufferData(int32 id
, base::TimeDelta
* timestamp
,
275 gfx::Rect
* visible_rect
,
276 gfx::Size
* natural_size
) {
277 for (std::list
<BufferData
>::const_iterator it
=
278 input_buffer_data_
.begin(); it
!= input_buffer_data_
.end();
280 if (it
->bitstream_buffer_id
!= id
)
282 *timestamp
= it
->timestamp
;
283 *visible_rect
= it
->visible_rect
;
284 *natural_size
= it
->natural_size
;
287 NOTREACHED() << "Missing bitstreambuffer id: " << id
;
290 bool GpuVideoDecoder::NeedsBitstreamConversion() const {
291 DCheckGpuVideoAcceleratorFactoriesTaskRunnerIsCurrent();
292 return needs_bitstream_conversion_
;
295 bool GpuVideoDecoder::CanReadWithoutStalling() const {
296 DCheckGpuVideoAcceleratorFactoriesTaskRunnerIsCurrent();
298 next_picture_buffer_id_
== 0 || // Decode() will ProvidePictureBuffers().
299 available_pictures_
> 0;
302 int GpuVideoDecoder::GetMaxDecodeRequests() const {
303 return kMaxInFlightDecodes
;
306 void GpuVideoDecoder::ProvidePictureBuffers(uint32 count
,
307 const gfx::Size
& size
,
308 uint32 texture_target
) {
309 DVLOG(3) << "ProvidePictureBuffers(" << count
<< ", "
310 << size
.width() << "x" << size
.height() << ")";
311 DCheckGpuVideoAcceleratorFactoriesTaskRunnerIsCurrent();
313 std::vector
<uint32
> texture_ids
;
314 std::vector
<gpu::Mailbox
> texture_mailboxes
;
315 decoder_texture_target_
= texture_target
;
316 if (!factories_
->CreateTextures(count
,
320 decoder_texture_target_
)) {
321 NotifyError(VideoDecodeAccelerator::PLATFORM_FAILURE
);
324 DCHECK_EQ(count
, texture_ids
.size());
325 DCHECK_EQ(count
, texture_mailboxes
.size());
330 std::vector
<PictureBuffer
> picture_buffers
;
331 for (size_t i
= 0; i
< texture_ids
.size(); ++i
) {
332 picture_buffers
.push_back(PictureBuffer(
333 next_picture_buffer_id_
++, size
, texture_ids
[i
], texture_mailboxes
[i
]));
334 bool inserted
= assigned_picture_buffers_
.insert(std::make_pair(
335 picture_buffers
.back().id(), picture_buffers
.back())).second
;
339 available_pictures_
+= count
;
341 vda_
->AssignPictureBuffers(picture_buffers
);
344 void GpuVideoDecoder::DismissPictureBuffer(int32 id
) {
345 DVLOG(3) << "DismissPictureBuffer(" << id
<< ")";
346 DCheckGpuVideoAcceleratorFactoriesTaskRunnerIsCurrent();
348 PictureBufferMap::iterator it
= assigned_picture_buffers_
.find(id
);
349 if (it
== assigned_picture_buffers_
.end()) {
350 NOTREACHED() << "Missing picture buffer: " << id
;
354 PictureBuffer buffer_to_dismiss
= it
->second
;
355 assigned_picture_buffers_
.erase(it
);
357 if (!picture_buffers_at_display_
.count(id
)) {
358 // We can delete the texture immediately as it's not being displayed.
359 factories_
->DeleteTexture(buffer_to_dismiss
.texture_id());
360 CHECK_GT(available_pictures_
, 0);
361 --available_pictures_
;
363 // Not destroying a texture in display in |picture_buffers_at_display_|.
364 // Postpone deletion until after it's returned to us.
367 void GpuVideoDecoder::PictureReady(const media::Picture
& picture
) {
368 DVLOG(3) << "PictureReady()";
369 DCheckGpuVideoAcceleratorFactoriesTaskRunnerIsCurrent();
371 PictureBufferMap::iterator it
=
372 assigned_picture_buffers_
.find(picture
.picture_buffer_id());
373 if (it
== assigned_picture_buffers_
.end()) {
374 NOTREACHED() << "Missing picture buffer: " << picture
.picture_buffer_id();
375 NotifyError(VideoDecodeAccelerator::PLATFORM_FAILURE
);
378 const PictureBuffer
& pb
= it
->second
;
380 // Validate picture rectangle from GPU. This is for sanity/security check
381 // even the rectangle is not used in this class.
382 if (picture
.visible_rect().IsEmpty() ||
383 !gfx::Rect(pb
.size()).Contains(picture
.visible_rect())) {
384 NOTREACHED() << "Invalid picture size from VDA: "
385 << picture
.visible_rect().ToString() << " should fit in "
386 << pb
.size().ToString();
387 NotifyError(media::VideoDecodeAccelerator::PLATFORM_FAILURE
);
391 // Update frame's timestamp.
392 base::TimeDelta timestamp
;
393 // Some of the VDAs don't support and thus don't provide us with visible
394 // size in picture.size, passing coded size instead, so always drop it and
395 // use config information instead.
396 gfx::Rect visible_rect
;
397 gfx::Size natural_size
;
398 GetBufferData(picture
.bitstream_buffer_id(), ×tamp
, &visible_rect
,
400 DCHECK(decoder_texture_target_
);
402 scoped_refptr
<VideoFrame
> frame(VideoFrame::WrapNativeTexture(
403 make_scoped_ptr(new gpu::MailboxHolder(
404 pb
.texture_mailbox(), decoder_texture_target_
, 0 /* sync_point */)),
405 BindToCurrentLoop(base::Bind(
406 &GpuVideoDecoder::ReleaseMailbox
, weak_factory_
.GetWeakPtr(),
407 factories_
, picture
.picture_buffer_id(), pb
.texture_id())),
408 pb
.size(), visible_rect
, natural_size
, timestamp
,
409 picture
.allow_overlay()));
410 CHECK_GT(available_pictures_
, 0);
411 --available_pictures_
;
413 picture_buffers_at_display_
.insert(std::make_pair(
414 picture
.picture_buffer_id(),
415 pb
.texture_id())).second
;
421 void GpuVideoDecoder::DeliverFrame(
422 const scoped_refptr
<VideoFrame
>& frame
) {
423 DCheckGpuVideoAcceleratorFactoriesTaskRunnerIsCurrent();
425 // During a pending vda->Reset(), we don't accumulate frames. Drop it on the
427 if (!pending_reset_cb_
.is_null())
430 output_cb_
.Run(frame
);
434 void GpuVideoDecoder::ReleaseMailbox(
435 base::WeakPtr
<GpuVideoDecoder
> decoder
,
436 const scoped_refptr
<media::GpuVideoAcceleratorFactories
>& factories
,
437 int64 picture_buffer_id
,
439 uint32 release_sync_point
) {
440 DCHECK(factories
->GetTaskRunner()->BelongsToCurrentThread());
441 factories
->WaitSyncPoint(release_sync_point
);
444 decoder
->ReusePictureBuffer(picture_buffer_id
);
447 // It's the last chance to delete the texture after display,
448 // because GpuVideoDecoder was destructed.
449 factories
->DeleteTexture(texture_id
);
452 void GpuVideoDecoder::ReusePictureBuffer(int64 picture_buffer_id
) {
453 DVLOG(3) << "ReusePictureBuffer(" << picture_buffer_id
<< ")";
454 DCheckGpuVideoAcceleratorFactoriesTaskRunnerIsCurrent();
456 DCHECK(!picture_buffers_at_display_
.empty());
457 PictureBufferTextureMap::iterator display_iterator
=
458 picture_buffers_at_display_
.find(picture_buffer_id
);
459 uint32 texture_id
= display_iterator
->second
;
460 DCHECK(display_iterator
!= picture_buffers_at_display_
.end());
461 picture_buffers_at_display_
.erase(display_iterator
);
463 if (!assigned_picture_buffers_
.count(picture_buffer_id
)) {
464 // This picture was dismissed while in display, so we postponed deletion.
465 factories_
->DeleteTexture(texture_id
);
469 ++available_pictures_
;
471 // DestroyVDA() might already have been called.
473 vda_
->ReusePictureBuffer(picture_buffer_id
);
476 scoped_ptr
<GpuVideoDecoder::SHMBuffer
> GpuVideoDecoder::GetSHM(
478 DCheckGpuVideoAcceleratorFactoriesTaskRunnerIsCurrent();
479 if (available_shm_segments_
.empty() ||
480 available_shm_segments_
.back()->size
< min_size
) {
481 size_t size_to_allocate
= std::max(min_size
, kSharedMemorySegmentBytes
);
482 scoped_ptr
<base::SharedMemory
> shm
=
483 factories_
->CreateSharedMemory(size_to_allocate
);
484 // CreateSharedMemory() can return NULL during Shutdown.
487 return make_scoped_ptr(new SHMBuffer(shm
.Pass(), size_to_allocate
));
489 scoped_ptr
<SHMBuffer
> ret(available_shm_segments_
.back());
490 available_shm_segments_
.pop_back();
494 void GpuVideoDecoder::PutSHM(scoped_ptr
<SHMBuffer
> shm_buffer
) {
495 DCheckGpuVideoAcceleratorFactoriesTaskRunnerIsCurrent();
496 available_shm_segments_
.push_back(shm_buffer
.release());
499 void GpuVideoDecoder::NotifyEndOfBitstreamBuffer(int32 id
) {
500 DVLOG(3) << "NotifyEndOfBitstreamBuffer(" << id
<< ")";
501 DCheckGpuVideoAcceleratorFactoriesTaskRunnerIsCurrent();
503 std::map
<int32
, PendingDecoderBuffer
>::iterator it
=
504 bitstream_buffers_in_decoder_
.find(id
);
505 if (it
== bitstream_buffers_in_decoder_
.end()) {
506 NotifyError(VideoDecodeAccelerator::PLATFORM_FAILURE
);
507 NOTREACHED() << "Missing bitstream buffer: " << id
;
511 PutSHM(make_scoped_ptr(it
->second
.shm_buffer
));
512 it
->second
.done_cb
.Run(state_
== kError
? kDecodeError
: kOk
);
513 bitstream_buffers_in_decoder_
.erase(it
);
516 GpuVideoDecoder::~GpuVideoDecoder() {
517 DVLOG(3) << __FUNCTION__
;
518 DCheckGpuVideoAcceleratorFactoriesTaskRunnerIsCurrent();
522 DCHECK(assigned_picture_buffers_
.empty());
524 for (size_t i
= 0; i
< available_shm_segments_
.size(); ++i
) {
525 delete available_shm_segments_
[i
];
527 available_shm_segments_
.clear();
529 for (std::map
<int32
, PendingDecoderBuffer
>::iterator it
=
530 bitstream_buffers_in_decoder_
.begin();
531 it
!= bitstream_buffers_in_decoder_
.end(); ++it
) {
532 delete it
->second
.shm_buffer
;
533 it
->second
.done_cb
.Run(kAborted
);
535 bitstream_buffers_in_decoder_
.clear();
537 if (!pending_reset_cb_
.is_null())
538 base::ResetAndReturn(&pending_reset_cb_
).Run();
541 void GpuVideoDecoder::NotifyFlushDone() {
542 DVLOG(3) << "NotifyFlushDone()";
543 DCheckGpuVideoAcceleratorFactoriesTaskRunnerIsCurrent();
544 DCHECK_EQ(state_
, kDrainingDecoder
);
545 state_
= kDecoderDrained
;
546 base::ResetAndReturn(&eos_decode_cb_
).Run(kOk
);
549 void GpuVideoDecoder::NotifyResetDone() {
550 DVLOG(3) << "NotifyResetDone()";
551 DCheckGpuVideoAcceleratorFactoriesTaskRunnerIsCurrent();
552 DCHECK(bitstream_buffers_in_decoder_
.empty());
554 // This needs to happen after the Reset() on vda_ is done to ensure pictures
555 // delivered during the reset can find their time data.
556 input_buffer_data_
.clear();
558 if (!pending_reset_cb_
.is_null())
559 base::ResetAndReturn(&pending_reset_cb_
).Run();
562 void GpuVideoDecoder::NotifyError(media::VideoDecodeAccelerator::Error error
) {
563 DCheckGpuVideoAcceleratorFactoriesTaskRunnerIsCurrent();
569 DLOG(ERROR
) << "VDA Error: " << error
;
573 bool GpuVideoDecoder::IsProfileSupported(VideoCodecProfile profile
,
574 const gfx::Size
& coded_size
) {
575 DCheckGpuVideoAcceleratorFactoriesTaskRunnerIsCurrent();
576 VideoDecodeAccelerator::SupportedProfiles supported_profiles
=
577 factories_
->GetVideoDecodeAcceleratorSupportedProfiles();
578 for (const auto& supported_profile
: supported_profiles
) {
579 if (profile
== supported_profile
.profile
) {
580 return IsCodedSizeSupported(coded_size
,
581 supported_profile
.min_resolution
,
582 supported_profile
.max_resolution
);
588 void GpuVideoDecoder::DCheckGpuVideoAcceleratorFactoriesTaskRunnerIsCurrent()
590 DCHECK(factories_
->GetTaskRunner()->BelongsToCurrentThread());