Report errors from ChromiumEnv::GetChildren in Posix.
[chromium-blink-merge.git] / media / filters / gpu_video_decoder.cc
blob2451ed0d26947866a310864a9411bd32bbf9f266
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"
7 #include <algorithm>
9 #include "base/bind.h"
10 #include "base/callback_helpers.h"
11 #include "base/cpu.h"
12 #include "base/message_loop/message_loop.h"
13 #include "base/stl_util.h"
14 #include "base/task_runner_util.h"
15 #include "media/base/bind_to_loop.h"
16 #include "media/base/decoder_buffer.h"
17 #include "media/base/media_log.h"
18 #include "media/base/pipeline.h"
19 #include "media/base/pipeline_status.h"
20 #include "media/base/video_decoder_config.h"
21 #include "media/filters/gpu_video_accelerator_factories.h"
23 namespace media {
25 // Maximum number of concurrent VDA::Decode() operations GVD will maintain.
26 // Higher values allow better pipelining in the GPU, but also require more
27 // resources.
28 enum { kMaxInFlightDecodes = 4 };
30 // Size of shared-memory segments we allocate. Since we reuse them we let them
31 // be on the beefy side.
32 static const size_t kSharedMemorySegmentBytes = 100 << 10;
34 GpuVideoDecoder::SHMBuffer::SHMBuffer(base::SharedMemory* m, size_t s)
35 : shm(m), size(s) {
38 GpuVideoDecoder::SHMBuffer::~SHMBuffer() {}
40 GpuVideoDecoder::BufferPair::BufferPair(
41 SHMBuffer* s, const scoped_refptr<DecoderBuffer>& b)
42 : shm_buffer(s), buffer(b) {
45 GpuVideoDecoder::BufferPair::~BufferPair() {}
47 GpuVideoDecoder::BufferData::BufferData(
48 int32 bbid, base::TimeDelta ts, const gfx::Rect& vr, const gfx::Size& ns)
49 : bitstream_buffer_id(bbid), timestamp(ts), visible_rect(vr),
50 natural_size(ns) {
53 GpuVideoDecoder::BufferData::~BufferData() {}
55 GpuVideoDecoder::GpuVideoDecoder(
56 const scoped_refptr<GpuVideoAcceleratorFactories>& factories,
57 const scoped_refptr<MediaLog>& media_log)
58 : needs_bitstream_conversion_(false),
59 gvd_loop_proxy_(factories->GetMessageLoop()),
60 weak_factory_(this),
61 factories_(factories),
62 state_(kNormal),
63 media_log_(media_log),
64 decoder_texture_target_(0),
65 next_picture_buffer_id_(0),
66 next_bitstream_buffer_id_(0),
67 available_pictures_(0) {
68 DCHECK(factories_.get());
71 void GpuVideoDecoder::Reset(const base::Closure& closure) {
72 DVLOG(3) << "Reset()";
73 DCHECK(gvd_loop_proxy_->BelongsToCurrentThread());
75 if (state_ == kDrainingDecoder && !factories_->IsAborted()) {
76 gvd_loop_proxy_->PostTask(FROM_HERE, base::Bind(
77 &GpuVideoDecoder::Reset, weak_this_, closure));
78 // NOTE: if we're deferring Reset() until a Flush() completes, return
79 // queued pictures to the VDA so they can be used to finish that Flush().
80 if (pending_decode_cb_.is_null())
81 ready_video_frames_.clear();
82 return;
85 // Throw away any already-decoded, not-yet-delivered frames.
86 ready_video_frames_.clear();
88 if (!vda_) {
89 gvd_loop_proxy_->PostTask(FROM_HERE, closure);
90 return;
93 if (!pending_decode_cb_.is_null())
94 EnqueueFrameAndTriggerFrameDelivery(VideoFrame::CreateEmptyFrame());
96 DCHECK(pending_reset_cb_.is_null());
97 pending_reset_cb_ = BindToCurrentLoop(closure);
99 vda_->Reset();
102 void GpuVideoDecoder::Stop(const base::Closure& closure) {
103 DCHECK(gvd_loop_proxy_->BelongsToCurrentThread());
104 if (vda_)
105 DestroyVDA();
106 if (!pending_decode_cb_.is_null())
107 EnqueueFrameAndTriggerFrameDelivery(VideoFrame::CreateEmptyFrame());
108 if (!pending_reset_cb_.is_null())
109 base::ResetAndReturn(&pending_reset_cb_).Run();
110 BindToCurrentLoop(closure).Run();
113 static bool IsCodedSizeSupported(const gfx::Size& coded_size) {
114 // Only non-Windows, Ivy Bridge+ platforms can support more than 1920x1080.
115 // We test against 1088 to account for 16x16 macroblocks.
116 if (coded_size.width() <= 1920 && coded_size.height() <= 1088)
117 return true;
119 base::CPU cpu;
120 bool hw_large_video_support =
121 (cpu.vendor_name() == "GenuineIntel") && cpu.model() >= 58;
122 bool os_large_video_support = true;
123 #if defined(OS_WIN)
124 os_large_video_support = false;
125 #endif
126 return os_large_video_support && hw_large_video_support;
129 void GpuVideoDecoder::Initialize(const VideoDecoderConfig& config,
130 const PipelineStatusCB& orig_status_cb) {
131 DVLOG(3) << "Initialize()";
132 DCHECK(gvd_loop_proxy_->BelongsToCurrentThread());
133 DCHECK(config.IsValidConfig());
134 DCHECK(!config.is_encrypted());
136 weak_this_ = weak_factory_.GetWeakPtr();
138 PipelineStatusCB status_cb = CreateUMAReportingPipelineCB(
139 "Media.GpuVideoDecoderInitializeStatus",
140 BindToCurrentLoop(orig_status_cb));
142 bool previously_initialized = config_.IsValidConfig();
143 #if !defined(OS_CHROMEOS) && !defined(OS_WIN)
144 if (previously_initialized) {
145 // TODO(xhwang): Make GpuVideoDecoder reinitializable.
146 // See http://crbug.com/233608
147 DVLOG(1) << "GpuVideoDecoder reinitialization not supported.";
148 status_cb.Run(DECODER_ERROR_NOT_SUPPORTED);
149 return;
151 #endif
152 DVLOG(1) << "(Re)initializing GVD with config: "
153 << config.AsHumanReadableString();
155 // TODO(posciak): destroy and create a new VDA on codec/profile change
156 // (http://crbug.com/260224).
157 if (previously_initialized && (config_.profile() != config.profile())) {
158 DVLOG(1) << "Codec or profile changed, cannot reinitialize.";
159 status_cb.Run(DECODER_ERROR_NOT_SUPPORTED);
160 return;
163 if (!IsCodedSizeSupported(config.coded_size())) {
164 status_cb.Run(DECODER_ERROR_NOT_SUPPORTED);
165 return;
168 config_ = config;
169 needs_bitstream_conversion_ = (config.codec() == kCodecH264);
171 if (previously_initialized) {
172 // Reinitialization with a different config (but same codec and profile).
173 // VDA should handle it by detecting this in-stream by itself,
174 // no need to notify it.
175 status_cb.Run(PIPELINE_OK);
176 return;
179 vda_ =
180 factories_->CreateVideoDecodeAccelerator(config.profile(), this).Pass();
181 if (!vda_) {
182 status_cb.Run(DECODER_ERROR_NOT_SUPPORTED);
183 return;
186 DVLOG(3) << "GpuVideoDecoder::Initialize() succeeded.";
187 media_log_->SetStringProperty("video_decoder", "gpu");
188 status_cb.Run(PIPELINE_OK);
191 void GpuVideoDecoder::DestroyPictureBuffers(PictureBufferMap* buffers) {
192 for (PictureBufferMap::iterator it = buffers->begin(); it != buffers->end();
193 ++it) {
194 factories_->DeleteTexture(it->second.texture_id());
197 buffers->clear();
200 void GpuVideoDecoder::DestroyVDA() {
201 DCHECK(gvd_loop_proxy_->BelongsToCurrentThread());
203 if (vda_)
204 vda_.release()->Destroy();
206 DestroyPictureBuffers(&assigned_picture_buffers_);
207 // Not destroying PictureBuffers in |dismissed_picture_buffers_| yet, since
208 // their textures may still be in use by the user of this GpuVideoDecoder.
211 void GpuVideoDecoder::Decode(const scoped_refptr<DecoderBuffer>& buffer,
212 const DecodeCB& decode_cb) {
213 DCHECK(gvd_loop_proxy_->BelongsToCurrentThread());
214 DCHECK(pending_reset_cb_.is_null());
215 DCHECK(pending_decode_cb_.is_null());
217 pending_decode_cb_ = BindToCurrentLoop(decode_cb);
219 if (state_ == kError || !vda_) {
220 base::ResetAndReturn(&pending_decode_cb_).Run(kDecodeError, NULL);
221 return;
224 switch (state_) {
225 case kDecoderDrained:
226 if (!ready_video_frames_.empty()) {
227 EnqueueFrameAndTriggerFrameDelivery(NULL);
228 return;
230 state_ = kNormal;
231 // Fall-through.
232 case kNormal:
233 break;
234 case kDrainingDecoder:
235 DCHECK(buffer->end_of_stream());
236 // Do nothing. Will be satisfied either by a PictureReady or
237 // NotifyFlushDone below.
238 return;
239 case kError:
240 NOTREACHED();
241 return;
244 if (buffer->end_of_stream()) {
245 if (state_ == kNormal) {
246 state_ = kDrainingDecoder;
247 vda_->Flush();
248 // If we have ready frames, go ahead and process them to ensure that the
249 // Flush operation does not block in the VDA due to lack of picture
250 // buffers.
251 if (!ready_video_frames_.empty())
252 EnqueueFrameAndTriggerFrameDelivery(NULL);
254 return;
257 size_t size = buffer->data_size();
258 SHMBuffer* shm_buffer = GetSHM(size);
259 if (!shm_buffer) {
260 base::ResetAndReturn(&pending_decode_cb_).Run(kDecodeError, NULL);
261 return;
264 memcpy(shm_buffer->shm->memory(), buffer->data(), size);
265 BitstreamBuffer bitstream_buffer(
266 next_bitstream_buffer_id_, shm_buffer->shm->handle(), size);
267 // Mask against 30 bits, to avoid (undefined) wraparound on signed integer.
268 next_bitstream_buffer_id_ = (next_bitstream_buffer_id_ + 1) & 0x3FFFFFFF;
269 bool inserted = bitstream_buffers_in_decoder_.insert(std::make_pair(
270 bitstream_buffer.id(), BufferPair(shm_buffer, buffer))).second;
271 DCHECK(inserted);
272 RecordBufferData(bitstream_buffer, *buffer.get());
274 vda_->Decode(bitstream_buffer);
276 if (!ready_video_frames_.empty()) {
277 EnqueueFrameAndTriggerFrameDelivery(NULL);
278 return;
281 if (CanMoreDecodeWorkBeDone())
282 base::ResetAndReturn(&pending_decode_cb_).Run(kNotEnoughData, NULL);
285 bool GpuVideoDecoder::CanMoreDecodeWorkBeDone() {
286 return bitstream_buffers_in_decoder_.size() < kMaxInFlightDecodes;
289 void GpuVideoDecoder::RecordBufferData(const BitstreamBuffer& bitstream_buffer,
290 const DecoderBuffer& buffer) {
291 input_buffer_data_.push_front(BufferData(bitstream_buffer.id(),
292 buffer.timestamp(),
293 config_.visible_rect(),
294 config_.natural_size()));
295 // Why this value? Because why not. avformat.h:MAX_REORDER_DELAY is 16, but
296 // that's too small for some pathological B-frame test videos. The cost of
297 // using too-high a value is low (192 bits per extra slot).
298 static const size_t kMaxInputBufferDataSize = 128;
299 // Pop from the back of the list, because that's the oldest and least likely
300 // to be useful in the future data.
301 if (input_buffer_data_.size() > kMaxInputBufferDataSize)
302 input_buffer_data_.pop_back();
305 void GpuVideoDecoder::GetBufferData(int32 id, base::TimeDelta* timestamp,
306 gfx::Rect* visible_rect,
307 gfx::Size* natural_size) {
308 for (std::list<BufferData>::const_iterator it =
309 input_buffer_data_.begin(); it != input_buffer_data_.end();
310 ++it) {
311 if (it->bitstream_buffer_id != id)
312 continue;
313 *timestamp = it->timestamp;
314 *visible_rect = it->visible_rect;
315 *natural_size = it->natural_size;
316 return;
318 NOTREACHED() << "Missing bitstreambuffer id: " << id;
321 bool GpuVideoDecoder::HasAlpha() const {
322 DCHECK(gvd_loop_proxy_->BelongsToCurrentThread());
323 return true;
326 bool GpuVideoDecoder::NeedsBitstreamConversion() const {
327 DCHECK(gvd_loop_proxy_->BelongsToCurrentThread());
328 return needs_bitstream_conversion_;
331 bool GpuVideoDecoder::CanReadWithoutStalling() const {
332 DCHECK(gvd_loop_proxy_->BelongsToCurrentThread());
333 return available_pictures_ > 0 || !ready_video_frames_.empty();
336 void GpuVideoDecoder::NotifyInitializeDone() {
337 NOTREACHED() << "GpuVideoDecodeAcceleratorHost::Initialize is synchronous!";
340 void GpuVideoDecoder::ProvidePictureBuffers(uint32 count,
341 const gfx::Size& size,
342 uint32 texture_target) {
343 DVLOG(3) << "ProvidePictureBuffers(" << count << ", "
344 << size.width() << "x" << size.height() << ")";
345 DCHECK(gvd_loop_proxy_->BelongsToCurrentThread());
347 std::vector<uint32> texture_ids;
348 std::vector<gpu::Mailbox> texture_mailboxes;
349 decoder_texture_target_ = texture_target;
350 // Discards the sync point returned here since PictureReady will imply that
351 // the produce has already happened, and the texture is ready for use.
352 if (!factories_->CreateTextures(count,
353 size,
354 &texture_ids,
355 &texture_mailboxes,
356 decoder_texture_target_)) {
357 NotifyError(VideoDecodeAccelerator::PLATFORM_FAILURE);
358 return;
360 DCHECK_EQ(count, texture_ids.size());
361 DCHECK_EQ(count, texture_mailboxes.size());
363 if (!vda_)
364 return;
366 std::vector<PictureBuffer> picture_buffers;
367 for (size_t i = 0; i < texture_ids.size(); ++i) {
368 picture_buffers.push_back(PictureBuffer(
369 next_picture_buffer_id_++, size, texture_ids[i], texture_mailboxes[i]));
370 bool inserted = assigned_picture_buffers_.insert(std::make_pair(
371 picture_buffers.back().id(), picture_buffers.back())).second;
372 DCHECK(inserted);
375 available_pictures_ += count;
377 vda_->AssignPictureBuffers(picture_buffers);
380 void GpuVideoDecoder::DismissPictureBuffer(int32 id) {
381 DVLOG(3) << "DismissPictureBuffer(" << id << ")";
382 DCHECK(gvd_loop_proxy_->BelongsToCurrentThread());
384 PictureBufferMap::iterator it = assigned_picture_buffers_.find(id);
385 if (it == assigned_picture_buffers_.end()) {
386 NOTREACHED() << "Missing picture buffer: " << id;
387 return;
390 PictureBuffer buffer_to_dismiss = it->second;
391 assigned_picture_buffers_.erase(it);
393 std::set<int32>::iterator at_display_it =
394 picture_buffers_at_display_.find(id);
396 if (at_display_it == picture_buffers_at_display_.end()) {
397 // We can delete the texture immediately as it's not being displayed.
398 factories_->DeleteTexture(buffer_to_dismiss.texture_id());
399 CHECK_GT(available_pictures_, 0);
400 --available_pictures_;
401 } else {
402 // Texture in display. Postpone deletion until after it's returned to us.
403 bool inserted = dismissed_picture_buffers_.insert(std::make_pair(
404 id, buffer_to_dismiss)).second;
405 DCHECK(inserted);
409 void GpuVideoDecoder::PictureReady(const media::Picture& picture) {
410 DVLOG(3) << "PictureReady()";
411 DCHECK(gvd_loop_proxy_->BelongsToCurrentThread());
413 PictureBufferMap::iterator it =
414 assigned_picture_buffers_.find(picture.picture_buffer_id());
415 if (it == assigned_picture_buffers_.end()) {
416 NOTREACHED() << "Missing picture buffer: " << picture.picture_buffer_id();
417 NotifyError(VideoDecodeAccelerator::PLATFORM_FAILURE);
418 return;
420 const PictureBuffer& pb = it->second;
422 // Update frame's timestamp.
423 base::TimeDelta timestamp;
424 gfx::Rect visible_rect;
425 gfx::Size natural_size;
426 GetBufferData(picture.bitstream_buffer_id(), &timestamp, &visible_rect,
427 &natural_size);
428 DCHECK(decoder_texture_target_);
430 scoped_refptr<VideoFrame> frame(VideoFrame::WrapNativeTexture(
431 new VideoFrame::MailboxHolder(
432 pb.texture_mailbox(),
433 0, // sync_point
434 BindToCurrentLoop(base::Bind(&GpuVideoDecoder::ReusePictureBuffer,
435 weak_this_,
436 picture.picture_buffer_id()))),
437 decoder_texture_target_,
438 pb.size(),
439 visible_rect,
440 natural_size,
441 timestamp,
442 base::Bind(&GpuVideoAcceleratorFactories::ReadPixels,
443 factories_,
444 pb.texture_id(),
445 gfx::Size(visible_rect.width(), visible_rect.height())),
446 base::Closure()));
447 CHECK_GT(available_pictures_, 0);
448 --available_pictures_;
449 bool inserted =
450 picture_buffers_at_display_.insert(picture.picture_buffer_id()).second;
451 DCHECK(inserted);
453 EnqueueFrameAndTriggerFrameDelivery(frame);
456 void GpuVideoDecoder::EnqueueFrameAndTriggerFrameDelivery(
457 const scoped_refptr<VideoFrame>& frame) {
458 DCHECK(gvd_loop_proxy_->BelongsToCurrentThread());
460 // During a pending vda->Reset(), we don't accumulate frames. Drop it on the
461 // floor and return.
462 if (!pending_reset_cb_.is_null())
463 return;
465 if (frame.get())
466 ready_video_frames_.push_back(frame);
467 else
468 DCHECK(!ready_video_frames_.empty());
470 if (pending_decode_cb_.is_null())
471 return;
473 base::ResetAndReturn(&pending_decode_cb_)
474 .Run(kOk, ready_video_frames_.front());
475 ready_video_frames_.pop_front();
478 void GpuVideoDecoder::ReusePictureBuffer(int64 picture_buffer_id,
479 uint32 sync_point) {
480 DVLOG(3) << "ReusePictureBuffer(" << picture_buffer_id << ")";
481 DCHECK(gvd_loop_proxy_->BelongsToCurrentThread());
483 if (!vda_)
484 return;
486 CHECK(!picture_buffers_at_display_.empty());
488 size_t num_erased = picture_buffers_at_display_.erase(picture_buffer_id);
489 DCHECK(num_erased);
491 PictureBufferMap::iterator it =
492 assigned_picture_buffers_.find(picture_buffer_id);
494 if (it == assigned_picture_buffers_.end()) {
495 // This picture was dismissed while in display, so we postponed deletion.
496 it = dismissed_picture_buffers_.find(picture_buffer_id);
497 DCHECK(it != dismissed_picture_buffers_.end());
498 factories_->DeleteTexture(it->second.texture_id());
499 dismissed_picture_buffers_.erase(it);
500 return;
503 factories_->WaitSyncPoint(sync_point);
504 ++available_pictures_;
506 vda_->ReusePictureBuffer(picture_buffer_id);
509 GpuVideoDecoder::SHMBuffer* GpuVideoDecoder::GetSHM(size_t min_size) {
510 DCHECK(gvd_loop_proxy_->BelongsToCurrentThread());
511 if (available_shm_segments_.empty() ||
512 available_shm_segments_.back()->size < min_size) {
513 size_t size_to_allocate = std::max(min_size, kSharedMemorySegmentBytes);
514 base::SharedMemory* shm = factories_->CreateSharedMemory(size_to_allocate);
515 // CreateSharedMemory() can return NULL during Shutdown.
516 if (!shm)
517 return NULL;
518 return new SHMBuffer(shm, size_to_allocate);
520 SHMBuffer* ret = available_shm_segments_.back();
521 available_shm_segments_.pop_back();
522 return ret;
525 void GpuVideoDecoder::PutSHM(SHMBuffer* shm_buffer) {
526 DCHECK(gvd_loop_proxy_->BelongsToCurrentThread());
527 available_shm_segments_.push_back(shm_buffer);
530 void GpuVideoDecoder::NotifyEndOfBitstreamBuffer(int32 id) {
531 DVLOG(3) << "NotifyEndOfBitstreamBuffer(" << id << ")";
532 DCHECK(gvd_loop_proxy_->BelongsToCurrentThread());
534 std::map<int32, BufferPair>::iterator it =
535 bitstream_buffers_in_decoder_.find(id);
536 if (it == bitstream_buffers_in_decoder_.end()) {
537 NotifyError(VideoDecodeAccelerator::PLATFORM_FAILURE);
538 NOTREACHED() << "Missing bitstream buffer: " << id;
539 return;
542 PutSHM(it->second.shm_buffer);
543 bitstream_buffers_in_decoder_.erase(it);
545 if (pending_reset_cb_.is_null() && state_ != kDrainingDecoder &&
546 CanMoreDecodeWorkBeDone() && !pending_decode_cb_.is_null()) {
547 base::ResetAndReturn(&pending_decode_cb_).Run(kNotEnoughData, NULL);
551 GpuVideoDecoder::~GpuVideoDecoder() {
552 DCHECK(!vda_.get()); // Stop should have been already called.
553 DCHECK(pending_decode_cb_.is_null());
554 for (size_t i = 0; i < available_shm_segments_.size(); ++i) {
555 available_shm_segments_[i]->shm->Close();
556 delete available_shm_segments_[i];
558 available_shm_segments_.clear();
559 for (std::map<int32, BufferPair>::iterator it =
560 bitstream_buffers_in_decoder_.begin();
561 it != bitstream_buffers_in_decoder_.end(); ++it) {
562 it->second.shm_buffer->shm->Close();
564 bitstream_buffers_in_decoder_.clear();
566 DestroyPictureBuffers(&assigned_picture_buffers_);
567 DestroyPictureBuffers(&dismissed_picture_buffers_);
570 void GpuVideoDecoder::NotifyFlushDone() {
571 DVLOG(3) << "NotifyFlushDone()";
572 DCHECK(gvd_loop_proxy_->BelongsToCurrentThread());
573 DCHECK_EQ(state_, kDrainingDecoder);
574 state_ = kDecoderDrained;
575 EnqueueFrameAndTriggerFrameDelivery(VideoFrame::CreateEmptyFrame());
578 void GpuVideoDecoder::NotifyResetDone() {
579 DVLOG(3) << "NotifyResetDone()";
580 DCHECK(gvd_loop_proxy_->BelongsToCurrentThread());
581 DCHECK(ready_video_frames_.empty());
583 // This needs to happen after the Reset() on vda_ is done to ensure pictures
584 // delivered during the reset can find their time data.
585 input_buffer_data_.clear();
587 if (!pending_reset_cb_.is_null())
588 base::ResetAndReturn(&pending_reset_cb_).Run();
590 if (!pending_decode_cb_.is_null())
591 EnqueueFrameAndTriggerFrameDelivery(VideoFrame::CreateEmptyFrame());
594 void GpuVideoDecoder::NotifyError(media::VideoDecodeAccelerator::Error error) {
595 DCHECK(gvd_loop_proxy_->BelongsToCurrentThread());
596 if (!vda_)
597 return;
599 DLOG(ERROR) << "VDA Error: " << error;
600 DestroyVDA();
602 state_ = kError;
604 if (!pending_decode_cb_.is_null()) {
605 base::ResetAndReturn(&pending_decode_cb_).Run(kDecodeError, NULL);
606 return;
610 } // namespace media