Cast: Stop logging kVideoFrameSentToEncoder and rename a couple events.
[chromium-blink-merge.git] / media / filters / vpx_video_decoder.cc
blob894f8712c70fbf8c27efdd20f3c82d898ab86910
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 "media/base/bind_to_current_loop.h"
21 #include "media/base/decoder_buffer.h"
22 #include "media/base/demuxer_stream.h"
23 #include "media/base/limits.h"
24 #include "media/base/media_switches.h"
25 #include "media/base/pipeline.h"
26 #include "media/base/video_decoder_config.h"
27 #include "media/base/video_frame.h"
28 #include "media/base/video_util.h"
30 // Include libvpx header files.
31 // VPX_CODEC_DISABLE_COMPAT excludes parts of the libvpx API that provide
32 // backwards compatibility for legacy applications using the library.
33 #define VPX_CODEC_DISABLE_COMPAT 1
34 extern "C" {
35 #include "third_party/libvpx/source/libvpx/vpx/vpx_decoder.h"
36 #include "third_party/libvpx/source/libvpx/vpx/vpx_frame_buffer.h"
37 #include "third_party/libvpx/source/libvpx/vpx/vp8dx.h"
40 namespace media {
42 // Always try to use three threads for video decoding. There is little reason
43 // not to since current day CPUs tend to be multi-core and we measured
44 // performance benefits on older machines such as P4s with hyperthreading.
45 static const int kDecodeThreads = 2;
46 static const int kMaxDecodeThreads = 16;
48 // Returns the number of threads.
49 static int GetThreadCount(const VideoDecoderConfig& config) {
50 // Refer to http://crbug.com/93932 for tsan suppressions on decoding.
51 int decode_threads = kDecodeThreads;
53 const CommandLine* cmd_line = CommandLine::ForCurrentProcess();
54 std::string threads(cmd_line->GetSwitchValueASCII(switches::kVideoThreads));
55 if (threads.empty() || !base::StringToInt(threads, &decode_threads)) {
56 if (config.codec() == kCodecVP9) {
57 // For VP9 decode when using the default thread count, increase the number
58 // of decode threads to equal the maximum number of tiles possible for
59 // higher resolution streams.
60 if (config.coded_size().width() >= 2048)
61 decode_threads = 8;
62 else if (config.coded_size().width() >= 1024)
63 decode_threads = 4;
66 return decode_threads;
69 decode_threads = std::max(decode_threads, 0);
70 decode_threads = std::min(decode_threads, kMaxDecodeThreads);
71 return decode_threads;
74 // Maximum number of frame buffers that can be used (by both chromium and libvpx
75 // combined) for VP9 Decoding.
76 // TODO(vigneshv): Investigate if this can be relaxed to a higher number.
77 static const uint32 kVP9MaxFrameBuffers = VP9_MAXIMUM_REF_BUFFERS +
78 VPX_MAXIMUM_WORK_BUFFERS +
79 limits::kMaxVideoFrames;
81 class VpxVideoDecoder::MemoryPool
82 : public base::RefCountedThreadSafe<VpxVideoDecoder::MemoryPool> {
83 public:
84 MemoryPool();
86 // Callback that will be called by libvpx when it needs a frame buffer.
87 // Parameters:
88 // |user_priv| Private data passed to libvpx (pointer to memory pool).
89 // |min_size| Minimum size needed by libvpx to decompress the next frame.
90 // |fb| Pointer to the frame buffer to update.
91 // Returns 0 on success. Returns < 0 on failure.
92 static int32 GetVP9FrameBuffer(void* user_priv, size_t min_size,
93 vpx_codec_frame_buffer* fb);
95 // Callback that will be called by libvpx when the frame buffer is no longer
96 // being used by libvpx. Parameters:
97 // |user_priv| Private data passed to libvpx (pointer to memory pool).
98 // |fb| Pointer to the frame buffer that's being released.
99 static int32 ReleaseVP9FrameBuffer(void *user_priv,
100 vpx_codec_frame_buffer *fb);
102 // Generates a "no_longer_needed" closure that holds a reference
103 // to this pool.
104 base::Closure CreateFrameCallback(void* fb_priv_data);
106 private:
107 friend class base::RefCountedThreadSafe<VpxVideoDecoder::MemoryPool>;
108 ~MemoryPool();
110 // Reference counted frame buffers used for VP9 decoding. Reference counting
111 // is done manually because both chromium and libvpx has to release this
112 // before a buffer can be re-used.
113 struct VP9FrameBuffer {
114 VP9FrameBuffer() : ref_cnt(0) {}
115 std::vector<uint8> data;
116 uint32 ref_cnt;
119 // Gets the next available frame buffer for use by libvpx.
120 VP9FrameBuffer* GetFreeFrameBuffer(size_t min_size);
122 // Method that gets called when a VideoFrame that references this pool gets
123 // destroyed.
124 void OnVideoFrameDestroyed(VP9FrameBuffer* frame_buffer);
126 // Frame buffers to be used by libvpx for VP9 Decoding.
127 std::vector<VP9FrameBuffer*> frame_buffers_;
129 DISALLOW_COPY_AND_ASSIGN(MemoryPool);
132 VpxVideoDecoder::MemoryPool::MemoryPool() {}
134 VpxVideoDecoder::MemoryPool::~MemoryPool() {
135 STLDeleteElements(&frame_buffers_);
138 VpxVideoDecoder::MemoryPool::VP9FrameBuffer*
139 VpxVideoDecoder::MemoryPool::GetFreeFrameBuffer(size_t min_size) {
140 // Check if a free frame buffer exists.
141 size_t i = 0;
142 for (; i < frame_buffers_.size(); ++i) {
143 if (frame_buffers_[i]->ref_cnt == 0)
144 break;
147 if (i == frame_buffers_.size()) {
148 // Maximum number of frame buffers reached.
149 if (i == kVP9MaxFrameBuffers)
150 return NULL;
152 // Create a new frame buffer.
153 frame_buffers_.push_back(new VP9FrameBuffer());
156 // Resize the frame buffer if necessary.
157 if (frame_buffers_[i]->data.size() < min_size)
158 frame_buffers_[i]->data.resize(min_size);
159 return frame_buffers_[i];
162 int32 VpxVideoDecoder::MemoryPool::GetVP9FrameBuffer(
163 void* user_priv, size_t min_size, vpx_codec_frame_buffer* fb) {
164 DCHECK(user_priv);
165 DCHECK(fb);
167 VpxVideoDecoder::MemoryPool* memory_pool =
168 static_cast<VpxVideoDecoder::MemoryPool*>(user_priv);
170 VP9FrameBuffer* fb_to_use = memory_pool->GetFreeFrameBuffer(min_size);
171 if (fb_to_use == NULL)
172 return -1;
174 fb->data = &fb_to_use->data[0];
175 fb->size = fb_to_use->data.size();
176 ++fb_to_use->ref_cnt;
178 // Set the frame buffer's private data to point at the external frame buffer.
179 fb->priv = static_cast<void*>(fb_to_use);
180 return 0;
183 int32 VpxVideoDecoder::MemoryPool::ReleaseVP9FrameBuffer(
184 void *user_priv, vpx_codec_frame_buffer *fb) {
185 VP9FrameBuffer* frame_buffer = static_cast<VP9FrameBuffer*>(fb->priv);
186 --frame_buffer->ref_cnt;
187 return 0;
190 base::Closure VpxVideoDecoder::MemoryPool::CreateFrameCallback(
191 void* fb_priv_data) {
192 VP9FrameBuffer* frame_buffer = static_cast<VP9FrameBuffer*>(fb_priv_data);
193 ++frame_buffer->ref_cnt;
194 return BindToCurrentLoop(
195 base::Bind(&MemoryPool::OnVideoFrameDestroyed, this,
196 frame_buffer));
199 void VpxVideoDecoder::MemoryPool::OnVideoFrameDestroyed(
200 VP9FrameBuffer* frame_buffer) {
201 --frame_buffer->ref_cnt;
204 VpxVideoDecoder::VpxVideoDecoder(
205 const scoped_refptr<base::SingleThreadTaskRunner>& task_runner)
206 : task_runner_(task_runner),
207 state_(kUninitialized),
208 vpx_codec_(NULL),
209 vpx_codec_alpha_(NULL) {}
211 VpxVideoDecoder::~VpxVideoDecoder() {
212 DCHECK_EQ(kUninitialized, state_);
213 CloseDecoder();
216 void VpxVideoDecoder::Initialize(const VideoDecoderConfig& config,
217 bool low_delay,
218 const PipelineStatusCB& status_cb) {
219 DCHECK(task_runner_->BelongsToCurrentThread());
220 DCHECK(config.IsValidConfig());
221 DCHECK(!config.is_encrypted());
222 DCHECK(decode_cb_.is_null());
224 if (!ConfigureDecoder(config)) {
225 status_cb.Run(DECODER_ERROR_NOT_SUPPORTED);
226 return;
229 // Success!
230 config_ = config;
231 state_ = kNormal;
232 status_cb.Run(PIPELINE_OK);
235 static vpx_codec_ctx* InitializeVpxContext(vpx_codec_ctx* context,
236 const VideoDecoderConfig& config) {
237 context = new vpx_codec_ctx();
238 vpx_codec_dec_cfg_t vpx_config = {0};
239 vpx_config.w = config.coded_size().width();
240 vpx_config.h = config.coded_size().height();
241 vpx_config.threads = GetThreadCount(config);
243 vpx_codec_err_t status = vpx_codec_dec_init(context,
244 config.codec() == kCodecVP9 ?
245 vpx_codec_vp9_dx() :
246 vpx_codec_vp8_dx(),
247 &vpx_config,
249 if (status != VPX_CODEC_OK) {
250 LOG(ERROR) << "vpx_codec_dec_init failed, status=" << status;
251 delete context;
252 return NULL;
254 return context;
257 bool VpxVideoDecoder::ConfigureDecoder(const VideoDecoderConfig& config) {
258 if (config.codec() != kCodecVP8 && config.codec() != kCodecVP9)
259 return false;
260 // Only VP8 videos with alpha are handled by VpxVideoDecoder. Everything else
261 // goes to FFmpegVideoDecoder.
262 if (config.codec() == kCodecVP8 && config.format() != VideoFrame::YV12A)
263 return false;
265 CloseDecoder();
267 vpx_codec_ = InitializeVpxContext(vpx_codec_, config);
268 if (!vpx_codec_)
269 return false;
271 // We use our own buffers for VP9 so that there is no need to copy data after
272 // decoding.
273 if (config.codec() == kCodecVP9) {
274 memory_pool_ = new MemoryPool();
275 if (vpx_codec_set_frame_buffer_functions(vpx_codec_,
276 &MemoryPool::GetVP9FrameBuffer,
277 &MemoryPool::ReleaseVP9FrameBuffer,
278 memory_pool_)) {
279 LOG(ERROR) << "Failed to configure external buffers.";
280 return false;
284 if (config.format() == VideoFrame::YV12A) {
285 vpx_codec_alpha_ = InitializeVpxContext(vpx_codec_alpha_, config);
286 if (!vpx_codec_alpha_)
287 return false;
290 return true;
293 void VpxVideoDecoder::CloseDecoder() {
294 if (vpx_codec_) {
295 vpx_codec_destroy(vpx_codec_);
296 delete vpx_codec_;
297 vpx_codec_ = NULL;
298 memory_pool_ = NULL;
300 if (vpx_codec_alpha_) {
301 vpx_codec_destroy(vpx_codec_alpha_);
302 delete vpx_codec_alpha_;
303 vpx_codec_alpha_ = NULL;
307 void VpxVideoDecoder::Decode(const scoped_refptr<DecoderBuffer>& buffer,
308 const DecodeCB& decode_cb) {
309 DCHECK(task_runner_->BelongsToCurrentThread());
310 DCHECK(!decode_cb.is_null());
311 CHECK_NE(state_, kUninitialized);
312 CHECK(decode_cb_.is_null()) << "Overlapping decodes are not supported.";
314 decode_cb_ = BindToCurrentLoop(decode_cb);
316 if (state_ == kError) {
317 base::ResetAndReturn(&decode_cb_).Run(kDecodeError, NULL);
318 return;
321 // Return empty frames if decoding has finished.
322 if (state_ == kDecodeFinished) {
323 base::ResetAndReturn(&decode_cb_).Run(kOk, VideoFrame::CreateEOSFrame());
324 return;
327 DecodeBuffer(buffer);
330 void VpxVideoDecoder::Reset(const base::Closure& closure) {
331 DCHECK(task_runner_->BelongsToCurrentThread());
332 DCHECK(decode_cb_.is_null());
334 state_ = kNormal;
335 task_runner_->PostTask(FROM_HERE, closure);
338 void VpxVideoDecoder::Stop() {
339 DCHECK(task_runner_->BelongsToCurrentThread());
341 state_ = kUninitialized;
344 void VpxVideoDecoder::DecodeBuffer(const scoped_refptr<DecoderBuffer>& buffer) {
345 DCHECK(task_runner_->BelongsToCurrentThread());
346 DCHECK_NE(state_, kUninitialized);
347 DCHECK_NE(state_, kDecodeFinished);
348 DCHECK_NE(state_, kError);
349 DCHECK(!decode_cb_.is_null());
350 DCHECK(buffer);
352 // Transition to kDecodeFinished on the first end of stream buffer.
353 if (state_ == kNormal && buffer->end_of_stream()) {
354 state_ = kDecodeFinished;
355 base::ResetAndReturn(&decode_cb_).Run(kOk, VideoFrame::CreateEOSFrame());
356 return;
359 scoped_refptr<VideoFrame> video_frame;
360 if (!VpxDecode(buffer, &video_frame)) {
361 state_ = kError;
362 base::ResetAndReturn(&decode_cb_).Run(kDecodeError, NULL);
363 return;
366 // If we didn't get a frame we need more data.
367 if (!video_frame.get()) {
368 base::ResetAndReturn(&decode_cb_).Run(kNotEnoughData, NULL);
369 return;
372 base::ResetAndReturn(&decode_cb_).Run(kOk, video_frame);
375 bool VpxVideoDecoder::VpxDecode(const scoped_refptr<DecoderBuffer>& buffer,
376 scoped_refptr<VideoFrame>* video_frame) {
377 DCHECK(video_frame);
378 DCHECK(!buffer->end_of_stream());
380 // Pass |buffer| to libvpx.
381 int64 timestamp = buffer->timestamp().InMicroseconds();
382 void* user_priv = reinterpret_cast<void*>(&timestamp);
383 vpx_codec_err_t status = vpx_codec_decode(vpx_codec_,
384 buffer->data(),
385 buffer->data_size(),
386 user_priv,
388 if (status != VPX_CODEC_OK) {
389 LOG(ERROR) << "vpx_codec_decode() failed, status=" << status;
390 return false;
393 // Gets pointer to decoded data.
394 vpx_codec_iter_t iter = NULL;
395 const vpx_image_t* vpx_image = vpx_codec_get_frame(vpx_codec_, &iter);
396 if (!vpx_image) {
397 *video_frame = NULL;
398 return true;
401 if (vpx_image->user_priv != reinterpret_cast<void*>(&timestamp)) {
402 LOG(ERROR) << "Invalid output timestamp.";
403 return false;
406 const vpx_image_t* vpx_image_alpha = NULL;
407 if (vpx_codec_alpha_ && buffer->side_data_size() >= 8) {
408 // Pass alpha data to libvpx.
409 int64 timestamp_alpha = buffer->timestamp().InMicroseconds();
410 void* user_priv_alpha = reinterpret_cast<void*>(&timestamp_alpha);
412 // First 8 bytes of side data is side_data_id in big endian.
413 const uint64 side_data_id = base::NetToHost64(
414 *(reinterpret_cast<const uint64*>(buffer->side_data())));
415 if (side_data_id == 1) {
416 status = vpx_codec_decode(vpx_codec_alpha_,
417 buffer->side_data() + 8,
418 buffer->side_data_size() - 8,
419 user_priv_alpha,
422 if (status != VPX_CODEC_OK) {
423 LOG(ERROR) << "vpx_codec_decode() failed on alpha, status=" << status;
424 return false;
427 // Gets pointer to decoded data.
428 vpx_codec_iter_t iter_alpha = NULL;
429 vpx_image_alpha = vpx_codec_get_frame(vpx_codec_alpha_, &iter_alpha);
430 if (!vpx_image_alpha) {
431 *video_frame = NULL;
432 return true;
435 if (vpx_image_alpha->user_priv !=
436 reinterpret_cast<void*>(&timestamp_alpha)) {
437 LOG(ERROR) << "Invalid output timestamp on alpha.";
438 return false;
443 CopyVpxImageTo(vpx_image, vpx_image_alpha, video_frame);
444 (*video_frame)->set_timestamp(base::TimeDelta::FromMicroseconds(timestamp));
445 return true;
448 void VpxVideoDecoder::CopyVpxImageTo(const vpx_image* vpx_image,
449 const struct vpx_image* vpx_image_alpha,
450 scoped_refptr<VideoFrame>* video_frame) {
451 CHECK(vpx_image);
452 CHECK(vpx_image->fmt == VPX_IMG_FMT_I420 ||
453 vpx_image->fmt == VPX_IMG_FMT_YV12);
455 gfx::Size size(vpx_image->d_w, vpx_image->d_h);
457 if (!vpx_codec_alpha_ && memory_pool_) {
458 *video_frame = VideoFrame::WrapExternalYuvData(
459 VideoFrame::YV12,
460 size, gfx::Rect(size), config_.natural_size(),
461 vpx_image->stride[VPX_PLANE_Y],
462 vpx_image->stride[VPX_PLANE_U],
463 vpx_image->stride[VPX_PLANE_V],
464 vpx_image->planes[VPX_PLANE_Y],
465 vpx_image->planes[VPX_PLANE_U],
466 vpx_image->planes[VPX_PLANE_V],
467 kNoTimestamp(),
468 memory_pool_->CreateFrameCallback(vpx_image->fb_priv));
469 return;
472 *video_frame = frame_pool_.CreateFrame(
473 vpx_codec_alpha_ ? VideoFrame::YV12A : VideoFrame::YV12,
474 size,
475 gfx::Rect(size),
476 config_.natural_size(),
477 kNoTimestamp());
479 CopyYPlane(vpx_image->planes[VPX_PLANE_Y],
480 vpx_image->stride[VPX_PLANE_Y],
481 vpx_image->d_h,
482 video_frame->get());
483 CopyUPlane(vpx_image->planes[VPX_PLANE_U],
484 vpx_image->stride[VPX_PLANE_U],
485 (vpx_image->d_h + 1) / 2,
486 video_frame->get());
487 CopyVPlane(vpx_image->planes[VPX_PLANE_V],
488 vpx_image->stride[VPX_PLANE_V],
489 (vpx_image->d_h + 1) / 2,
490 video_frame->get());
491 if (!vpx_codec_alpha_)
492 return;
493 if (!vpx_image_alpha) {
494 MakeOpaqueAPlane(
495 vpx_image->stride[VPX_PLANE_Y], vpx_image->d_h, video_frame->get());
496 return;
498 CopyAPlane(vpx_image_alpha->planes[VPX_PLANE_Y],
499 vpx_image->stride[VPX_PLANE_Y],
500 vpx_image->d_h,
501 video_frame->get());
504 } // namespace media