[Extensions Toolbar] Move context menu logic to view delegates
[chromium-blink-merge.git] / media / filters / vpx_video_decoder.cc
blobdc034005d0ca0ebc2c194f31ed22d9ce42ac6ebd
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/vpx_video_decoder.h"
7 #include <algorithm>
8 #include <string>
9 #include <vector>
11 #include "base/bind.h"
12 #include "base/callback_helpers.h"
13 #include "base/command_line.h"
14 #include "base/location.h"
15 #include "base/logging.h"
16 #include "base/single_thread_task_runner.h"
17 #include "base/stl_util.h"
18 #include "base/strings/string_number_conversions.h"
19 #include "base/sys_byteorder.h"
20 #include "base/trace_event/trace_event.h"
21 #include "media/base/bind_to_current_loop.h"
22 #include "media/base/decoder_buffer.h"
23 #include "media/base/demuxer_stream.h"
24 #include "media/base/limits.h"
25 #include "media/base/media_switches.h"
26 #include "media/base/pipeline.h"
27 #include "media/base/video_decoder_config.h"
28 #include "media/base/video_frame.h"
29 #include "media/base/video_util.h"
31 // Include libvpx header files.
32 // VPX_CODEC_DISABLE_COMPAT excludes parts of the libvpx API that provide
33 // backwards compatibility for legacy applications using the library.
34 #define VPX_CODEC_DISABLE_COMPAT 1
35 extern "C" {
36 #include "third_party/libvpx/source/libvpx/vpx/vpx_decoder.h"
37 #include "third_party/libvpx/source/libvpx/vpx/vpx_frame_buffer.h"
38 #include "third_party/libvpx/source/libvpx/vpx/vp8dx.h"
41 namespace media {
43 // Always try to use three threads for video decoding. There is little reason
44 // not to since current day CPUs tend to be multi-core and we measured
45 // performance benefits on older machines such as P4s with hyperthreading.
46 static const int kDecodeThreads = 2;
47 static const int kMaxDecodeThreads = 16;
49 // Returns the number of threads.
50 static int GetThreadCount(const VideoDecoderConfig& config) {
51 // Refer to http://crbug.com/93932 for tsan suppressions on decoding.
52 int decode_threads = kDecodeThreads;
54 const base::CommandLine* cmd_line = base::CommandLine::ForCurrentProcess();
55 std::string threads(cmd_line->GetSwitchValueASCII(switches::kVideoThreads));
56 if (threads.empty() || !base::StringToInt(threads, &decode_threads)) {
57 if (config.codec() == kCodecVP9) {
58 // For VP9 decode when using the default thread count, increase the number
59 // of decode threads to equal the maximum number of tiles possible for
60 // higher resolution streams.
61 if (config.coded_size().width() >= 2048)
62 decode_threads = 8;
63 else if (config.coded_size().width() >= 1024)
64 decode_threads = 4;
67 return decode_threads;
70 decode_threads = std::max(decode_threads, 0);
71 decode_threads = std::min(decode_threads, kMaxDecodeThreads);
72 return decode_threads;
75 class VpxVideoDecoder::MemoryPool
76 : public base::RefCountedThreadSafe<VpxVideoDecoder::MemoryPool> {
77 public:
78 MemoryPool();
80 // Callback that will be called by libvpx when it needs a frame buffer.
81 // Parameters:
82 // |user_priv| Private data passed to libvpx (pointer to memory pool).
83 // |min_size| Minimum size needed by libvpx to decompress the next frame.
84 // |fb| Pointer to the frame buffer to update.
85 // Returns 0 on success. Returns < 0 on failure.
86 static int32 GetVP9FrameBuffer(void* user_priv, size_t min_size,
87 vpx_codec_frame_buffer* fb);
89 // Callback that will be called by libvpx when the frame buffer is no longer
90 // being used by libvpx. Parameters:
91 // |user_priv| Private data passed to libvpx (pointer to memory pool).
92 // |fb| Pointer to the frame buffer that's being released.
93 static int32 ReleaseVP9FrameBuffer(void *user_priv,
94 vpx_codec_frame_buffer *fb);
96 // Generates a "no_longer_needed" closure that holds a reference
97 // to this pool.
98 base::Closure CreateFrameCallback(void* fb_priv_data);
100 private:
101 friend class base::RefCountedThreadSafe<VpxVideoDecoder::MemoryPool>;
102 ~MemoryPool();
104 // Reference counted frame buffers used for VP9 decoding. Reference counting
105 // is done manually because both chromium and libvpx has to release this
106 // before a buffer can be re-used.
107 struct VP9FrameBuffer {
108 VP9FrameBuffer() : ref_cnt(0) {}
109 std::vector<uint8> data;
110 uint32 ref_cnt;
113 // Gets the next available frame buffer for use by libvpx.
114 VP9FrameBuffer* GetFreeFrameBuffer(size_t min_size);
116 // Method that gets called when a VideoFrame that references this pool gets
117 // destroyed.
118 void OnVideoFrameDestroyed(VP9FrameBuffer* frame_buffer);
120 // Frame buffers to be used by libvpx for VP9 Decoding.
121 std::vector<VP9FrameBuffer*> frame_buffers_;
123 DISALLOW_COPY_AND_ASSIGN(MemoryPool);
126 VpxVideoDecoder::MemoryPool::MemoryPool() {}
128 VpxVideoDecoder::MemoryPool::~MemoryPool() {
129 STLDeleteElements(&frame_buffers_);
132 VpxVideoDecoder::MemoryPool::VP9FrameBuffer*
133 VpxVideoDecoder::MemoryPool::GetFreeFrameBuffer(size_t min_size) {
134 // Check if a free frame buffer exists.
135 size_t i = 0;
136 for (; i < frame_buffers_.size(); ++i) {
137 if (frame_buffers_[i]->ref_cnt == 0)
138 break;
141 if (i == frame_buffers_.size()) {
142 // Create a new frame buffer.
143 frame_buffers_.push_back(new VP9FrameBuffer());
146 // Resize the frame buffer if necessary.
147 if (frame_buffers_[i]->data.size() < min_size)
148 frame_buffers_[i]->data.resize(min_size);
149 return frame_buffers_[i];
152 int32 VpxVideoDecoder::MemoryPool::GetVP9FrameBuffer(
153 void* user_priv, size_t min_size, vpx_codec_frame_buffer* fb) {
154 DCHECK(user_priv);
155 DCHECK(fb);
157 VpxVideoDecoder::MemoryPool* memory_pool =
158 static_cast<VpxVideoDecoder::MemoryPool*>(user_priv);
160 VP9FrameBuffer* fb_to_use = memory_pool->GetFreeFrameBuffer(min_size);
161 if (fb_to_use == NULL)
162 return -1;
164 fb->data = &fb_to_use->data[0];
165 fb->size = fb_to_use->data.size();
166 ++fb_to_use->ref_cnt;
168 // Set the frame buffer's private data to point at the external frame buffer.
169 fb->priv = static_cast<void*>(fb_to_use);
170 return 0;
173 int32 VpxVideoDecoder::MemoryPool::ReleaseVP9FrameBuffer(
174 void *user_priv, vpx_codec_frame_buffer *fb) {
175 VP9FrameBuffer* frame_buffer = static_cast<VP9FrameBuffer*>(fb->priv);
176 --frame_buffer->ref_cnt;
177 return 0;
180 base::Closure VpxVideoDecoder::MemoryPool::CreateFrameCallback(
181 void* fb_priv_data) {
182 VP9FrameBuffer* frame_buffer = static_cast<VP9FrameBuffer*>(fb_priv_data);
183 ++frame_buffer->ref_cnt;
184 return BindToCurrentLoop(
185 base::Bind(&MemoryPool::OnVideoFrameDestroyed, this,
186 frame_buffer));
189 void VpxVideoDecoder::MemoryPool::OnVideoFrameDestroyed(
190 VP9FrameBuffer* frame_buffer) {
191 --frame_buffer->ref_cnt;
194 VpxVideoDecoder::VpxVideoDecoder(
195 const scoped_refptr<base::SingleThreadTaskRunner>& task_runner)
196 : task_runner_(task_runner),
197 state_(kUninitialized),
198 vpx_codec_(NULL),
199 vpx_codec_alpha_(NULL) {}
201 VpxVideoDecoder::~VpxVideoDecoder() {
202 DCHECK(task_runner_->BelongsToCurrentThread());
203 CloseDecoder();
206 std::string VpxVideoDecoder::GetDisplayName() const {
207 return "VpxVideoDecoder";
210 void VpxVideoDecoder::Initialize(const VideoDecoderConfig& config,
211 bool low_delay,
212 const PipelineStatusCB& status_cb,
213 const OutputCB& output_cb) {
214 DCHECK(task_runner_->BelongsToCurrentThread());
215 DCHECK(config.IsValidConfig());
216 DCHECK(!config.is_encrypted());
217 DCHECK(decode_cb_.is_null());
219 if (!ConfigureDecoder(config)) {
220 status_cb.Run(DECODER_ERROR_NOT_SUPPORTED);
221 return;
224 // Success!
225 config_ = config;
226 state_ = kNormal;
227 output_cb_ = BindToCurrentLoop(output_cb);
228 status_cb.Run(PIPELINE_OK);
231 static vpx_codec_ctx* InitializeVpxContext(vpx_codec_ctx* context,
232 const VideoDecoderConfig& config) {
233 context = new vpx_codec_ctx();
234 vpx_codec_dec_cfg_t vpx_config = {0};
235 vpx_config.w = config.coded_size().width();
236 vpx_config.h = config.coded_size().height();
237 vpx_config.threads = GetThreadCount(config);
239 vpx_codec_err_t status = vpx_codec_dec_init(context,
240 config.codec() == kCodecVP9 ?
241 vpx_codec_vp9_dx() :
242 vpx_codec_vp8_dx(),
243 &vpx_config,
245 if (status != VPX_CODEC_OK) {
246 LOG(ERROR) << "vpx_codec_dec_init failed, status=" << status;
247 delete context;
248 return NULL;
250 return context;
253 bool VpxVideoDecoder::ConfigureDecoder(const VideoDecoderConfig& config) {
254 if (config.codec() != kCodecVP8 && config.codec() != kCodecVP9)
255 return false;
257 // In VP8 videos, only those with alpha are handled by VpxVideoDecoder. All
258 // other VP8 videos go to FFmpegVideoDecoder.
259 if (config.codec() == kCodecVP8 && config.format() != VideoFrame::YV12A)
260 return false;
262 CloseDecoder();
264 vpx_codec_ = InitializeVpxContext(vpx_codec_, config);
265 if (!vpx_codec_)
266 return false;
268 // We use our own buffers for VP9 so that there is no need to copy data after
269 // decoding.
270 if (config.codec() == kCodecVP9) {
271 memory_pool_ = new MemoryPool();
272 if (vpx_codec_set_frame_buffer_functions(vpx_codec_,
273 &MemoryPool::GetVP9FrameBuffer,
274 &MemoryPool::ReleaseVP9FrameBuffer,
275 memory_pool_.get())) {
276 LOG(ERROR) << "Failed to configure external buffers.";
277 return false;
281 if (config.format() == VideoFrame::YV12A) {
282 vpx_codec_alpha_ = InitializeVpxContext(vpx_codec_alpha_, config);
283 if (!vpx_codec_alpha_)
284 return false;
287 return true;
290 void VpxVideoDecoder::CloseDecoder() {
291 if (vpx_codec_) {
292 vpx_codec_destroy(vpx_codec_);
293 delete vpx_codec_;
294 vpx_codec_ = NULL;
295 memory_pool_ = NULL;
297 if (vpx_codec_alpha_) {
298 vpx_codec_destroy(vpx_codec_alpha_);
299 delete vpx_codec_alpha_;
300 vpx_codec_alpha_ = NULL;
304 void VpxVideoDecoder::Decode(const scoped_refptr<DecoderBuffer>& buffer,
305 const DecodeCB& decode_cb) {
306 DCHECK(task_runner_->BelongsToCurrentThread());
307 DCHECK(!decode_cb.is_null());
308 CHECK_NE(state_, kUninitialized);
309 CHECK(decode_cb_.is_null()) << "Overlapping decodes are not supported.";
311 decode_cb_ = BindToCurrentLoop(decode_cb);
313 if (state_ == kError) {
314 base::ResetAndReturn(&decode_cb_).Run(kDecodeError);
315 return;
318 // Return empty frames if decoding has finished.
319 if (state_ == kDecodeFinished) {
320 base::ResetAndReturn(&decode_cb_).Run(kOk);
321 return;
324 DecodeBuffer(buffer);
327 void VpxVideoDecoder::Reset(const base::Closure& closure) {
328 DCHECK(task_runner_->BelongsToCurrentThread());
329 DCHECK(decode_cb_.is_null());
331 state_ = kNormal;
332 task_runner_->PostTask(FROM_HERE, closure);
335 void VpxVideoDecoder::DecodeBuffer(const scoped_refptr<DecoderBuffer>& buffer) {
336 DCHECK(task_runner_->BelongsToCurrentThread());
337 DCHECK_NE(state_, kUninitialized);
338 DCHECK_NE(state_, kDecodeFinished);
339 DCHECK_NE(state_, kError);
340 DCHECK(!decode_cb_.is_null());
341 DCHECK(buffer.get());
343 // Transition to kDecodeFinished on the first end of stream buffer.
344 if (state_ == kNormal && buffer->end_of_stream()) {
345 state_ = kDecodeFinished;
346 base::ResetAndReturn(&decode_cb_).Run(kOk);
347 return;
350 scoped_refptr<VideoFrame> video_frame;
351 if (!VpxDecode(buffer, &video_frame)) {
352 state_ = kError;
353 base::ResetAndReturn(&decode_cb_).Run(kDecodeError);
354 return;
357 if (video_frame.get())
358 output_cb_.Run(video_frame);
360 // VideoDecoderShim expects that |decode_cb| is called only after
361 // |output_cb_|.
362 base::ResetAndReturn(&decode_cb_).Run(kOk);
365 bool VpxVideoDecoder::VpxDecode(const scoped_refptr<DecoderBuffer>& buffer,
366 scoped_refptr<VideoFrame>* video_frame) {
367 DCHECK(video_frame);
368 DCHECK(!buffer->end_of_stream());
370 // Pass |buffer| to libvpx.
371 int64 timestamp = buffer->timestamp().InMicroseconds();
372 void* user_priv = reinterpret_cast<void*>(&timestamp);
375 TRACE_EVENT1("video", "vpx_codec_decode", "timestamp", timestamp);
376 vpx_codec_err_t status = vpx_codec_decode(vpx_codec_,
377 buffer->data(),
378 buffer->data_size(),
379 user_priv,
381 if (status != VPX_CODEC_OK) {
382 LOG(ERROR) << "vpx_codec_decode() failed, status=" << status;
383 return false;
387 // Gets pointer to decoded data.
388 vpx_codec_iter_t iter = NULL;
389 const vpx_image_t* vpx_image = vpx_codec_get_frame(vpx_codec_, &iter);
390 if (!vpx_image) {
391 *video_frame = NULL;
392 return true;
395 if (vpx_image->user_priv != reinterpret_cast<void*>(&timestamp)) {
396 LOG(ERROR) << "Invalid output timestamp.";
397 return false;
400 const vpx_image_t* vpx_image_alpha = NULL;
401 if (vpx_codec_alpha_ && buffer->side_data_size() >= 8) {
402 // Pass alpha data to libvpx.
403 int64 timestamp_alpha = buffer->timestamp().InMicroseconds();
404 void* user_priv_alpha = reinterpret_cast<void*>(&timestamp_alpha);
406 // First 8 bytes of side data is side_data_id in big endian.
407 const uint64 side_data_id = base::NetToHost64(
408 *(reinterpret_cast<const uint64*>(buffer->side_data())));
409 if (side_data_id == 1) {
411 TRACE_EVENT1("video", "vpx_codec_decode_alpha",
412 "timestamp_alpha", timestamp_alpha);
413 vpx_codec_err_t status = vpx_codec_decode(vpx_codec_alpha_,
414 buffer->side_data() + 8,
415 buffer->side_data_size() - 8,
416 user_priv_alpha,
418 if (status != VPX_CODEC_OK) {
419 LOG(ERROR) << "vpx_codec_decode() failed on alpha, status=" << status;
420 return false;
424 // Gets pointer to decoded data.
425 vpx_codec_iter_t iter_alpha = NULL;
426 vpx_image_alpha = vpx_codec_get_frame(vpx_codec_alpha_, &iter_alpha);
427 if (!vpx_image_alpha) {
428 *video_frame = NULL;
429 return true;
432 if (vpx_image_alpha->user_priv !=
433 reinterpret_cast<void*>(&timestamp_alpha)) {
434 LOG(ERROR) << "Invalid output timestamp on alpha.";
435 return false;
438 if (vpx_image_alpha->d_h != vpx_image->d_h ||
439 vpx_image_alpha->d_w != vpx_image->d_w) {
440 LOG(ERROR) << "The alpha plane dimensions are not the same as the "
441 "image dimensions.";
442 return false;
447 CopyVpxImageTo(vpx_image, vpx_image_alpha, video_frame);
448 (*video_frame)->set_timestamp(base::TimeDelta::FromMicroseconds(timestamp));
449 return true;
452 void VpxVideoDecoder::CopyVpxImageTo(const vpx_image* vpx_image,
453 const struct vpx_image* vpx_image_alpha,
454 scoped_refptr<VideoFrame>* video_frame) {
455 CHECK(vpx_image);
456 CHECK(vpx_image->fmt == VPX_IMG_FMT_I420 ||
457 vpx_image->fmt == VPX_IMG_FMT_YV12 ||
458 vpx_image->fmt == VPX_IMG_FMT_I444);
460 VideoFrame::Format codec_format = VideoFrame::YV12;
461 int uv_rows = (vpx_image->d_h + 1) / 2;
463 if (vpx_image->fmt == VPX_IMG_FMT_I444) {
464 CHECK(!vpx_codec_alpha_);
465 codec_format = VideoFrame::YV24;
466 uv_rows = vpx_image->d_h;
467 } else if (vpx_codec_alpha_) {
468 // TODO(watk): A limitation of conflating color space with pixel format is
469 // that it's not possible to have BT709 with alpha.
470 // Until color space is separated from format, prefer YV12A over YV12HD.
471 codec_format = VideoFrame::YV12A;
472 } else if (vpx_image->cs == VPX_CS_BT_709) {
473 codec_format = VideoFrame::YV12HD;
476 // The mixed |w|/|d_h| in |coded_size| is intentional. Setting the correct
477 // coded width is necessary to allow coalesced memory access, which may avoid
478 // frame copies. Setting the correct coded height however does not have any
479 // benefit, and only risk copying too much data.
480 const gfx::Size coded_size(vpx_image->w, vpx_image->d_h);
481 const gfx::Size visible_size(vpx_image->d_w, vpx_image->d_h);
483 if (!vpx_codec_alpha_ && memory_pool_.get()) {
484 *video_frame = VideoFrame::WrapExternalYuvData(
485 codec_format,
486 coded_size, gfx::Rect(visible_size), config_.natural_size(),
487 vpx_image->stride[VPX_PLANE_Y],
488 vpx_image->stride[VPX_PLANE_U],
489 vpx_image->stride[VPX_PLANE_V],
490 vpx_image->planes[VPX_PLANE_Y],
491 vpx_image->planes[VPX_PLANE_U],
492 vpx_image->planes[VPX_PLANE_V],
493 kNoTimestamp(),
494 memory_pool_->CreateFrameCallback(vpx_image->fb_priv));
495 return;
498 *video_frame = frame_pool_.CreateFrame(
499 codec_format,
500 visible_size,
501 gfx::Rect(visible_size),
502 config_.natural_size(),
503 kNoTimestamp());
505 CopyYPlane(vpx_image->planes[VPX_PLANE_Y],
506 vpx_image->stride[VPX_PLANE_Y],
507 vpx_image->d_h,
508 video_frame->get());
509 CopyUPlane(vpx_image->planes[VPX_PLANE_U],
510 vpx_image->stride[VPX_PLANE_U],
511 uv_rows,
512 video_frame->get());
513 CopyVPlane(vpx_image->planes[VPX_PLANE_V],
514 vpx_image->stride[VPX_PLANE_V],
515 uv_rows,
516 video_frame->get());
517 if (!vpx_codec_alpha_)
518 return;
519 if (!vpx_image_alpha) {
520 MakeOpaqueAPlane(
521 vpx_image->stride[VPX_PLANE_Y], vpx_image->d_h, video_frame->get());
522 return;
524 CopyAPlane(vpx_image_alpha->planes[VPX_PLANE_Y],
525 vpx_image_alpha->stride[VPX_PLANE_Y],
526 vpx_image_alpha->d_h,
527 video_frame->get());
530 } // namespace media