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"
11 #include "base/bind.h"
12 #include "base/callback_helpers.h"
13 #include "base/command_line.h"
14 #include "base/debug/trace_event.h"
15 #include "base/location.h"
16 #include "base/logging.h"
17 #include "base/single_thread_task_runner.h"
18 #include "base/stl_util.h"
19 #include "base/strings/string_number_conversions.h"
20 #include "base/sys_byteorder.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
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"
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 CommandLine
* cmd_line
= 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)
63 else if (config
.coded_size().width() >= 1024)
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
> {
80 // Callback that will be called by libvpx when it needs a frame buffer.
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
98 base::Closure
CreateFrameCallback(void* fb_priv_data
);
101 friend class base::RefCountedThreadSafe
<VpxVideoDecoder::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
;
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
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.
136 for (; i
< frame_buffers_
.size(); ++i
) {
137 if (frame_buffers_
[i
]->ref_cnt
== 0)
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
) {
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
)
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
);
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
;
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,
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
),
199 vpx_codec_alpha_(NULL
) {}
201 VpxVideoDecoder::~VpxVideoDecoder() {
202 DCHECK(task_runner_
->BelongsToCurrentThread());
206 std::string
VpxVideoDecoder::GetDisplayName() const {
207 return "VpxVideoDecoder";
210 void VpxVideoDecoder::Initialize(const VideoDecoderConfig
& config
,
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
);
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
?
245 if (status
!= VPX_CODEC_OK
) {
246 LOG(ERROR
) << "vpx_codec_dec_init failed, status=" << status
;
253 bool VpxVideoDecoder::ConfigureDecoder(const VideoDecoderConfig
& config
) {
254 if (config
.codec() != kCodecVP8
&& config
.codec() != kCodecVP9
)
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
)
264 vpx_codec_
= InitializeVpxContext(vpx_codec_
, config
);
268 // We use our own buffers for VP9 so that there is no need to copy data after
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.";
281 if (config
.format() == VideoFrame::YV12A
) {
282 vpx_codec_alpha_
= InitializeVpxContext(vpx_codec_alpha_
, config
);
283 if (!vpx_codec_alpha_
)
290 void VpxVideoDecoder::CloseDecoder() {
292 vpx_codec_destroy(vpx_codec_
);
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
);
318 // Return empty frames if decoding has finished.
319 if (state_
== kDecodeFinished
) {
320 base::ResetAndReturn(&decode_cb_
).Run(kOk
);
324 DecodeBuffer(buffer
);
327 void VpxVideoDecoder::Reset(const base::Closure
& closure
) {
328 DCHECK(task_runner_
->BelongsToCurrentThread());
329 DCHECK(decode_cb_
.is_null());
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
);
350 scoped_refptr
<VideoFrame
> video_frame
;
351 if (!VpxDecode(buffer
, &video_frame
)) {
353 base::ResetAndReturn(&decode_cb_
).Run(kDecodeError
);
357 base::ResetAndReturn(&decode_cb_
).Run(kOk
);
359 if (video_frame
.get())
360 output_cb_
.Run(video_frame
);
363 bool VpxVideoDecoder::VpxDecode(const scoped_refptr
<DecoderBuffer
>& buffer
,
364 scoped_refptr
<VideoFrame
>* video_frame
) {
366 DCHECK(!buffer
->end_of_stream());
368 // Pass |buffer| to libvpx.
369 int64 timestamp
= buffer
->timestamp().InMicroseconds();
370 void* user_priv
= reinterpret_cast<void*>(×tamp
);
373 TRACE_EVENT1("video", "vpx_codec_decode", "timestamp", timestamp
);
374 vpx_codec_err_t status
= vpx_codec_decode(vpx_codec_
,
379 if (status
!= VPX_CODEC_OK
) {
380 LOG(ERROR
) << "vpx_codec_decode() failed, status=" << status
;
385 // Gets pointer to decoded data.
386 vpx_codec_iter_t iter
= NULL
;
387 const vpx_image_t
* vpx_image
= vpx_codec_get_frame(vpx_codec_
, &iter
);
393 if (vpx_image
->user_priv
!= reinterpret_cast<void*>(×tamp
)) {
394 LOG(ERROR
) << "Invalid output timestamp.";
398 const vpx_image_t
* vpx_image_alpha
= NULL
;
399 if (vpx_codec_alpha_
&& buffer
->side_data_size() >= 8) {
400 // Pass alpha data to libvpx.
401 int64 timestamp_alpha
= buffer
->timestamp().InMicroseconds();
402 void* user_priv_alpha
= reinterpret_cast<void*>(×tamp_alpha
);
404 // First 8 bytes of side data is side_data_id in big endian.
405 const uint64 side_data_id
= base::NetToHost64(
406 *(reinterpret_cast<const uint64
*>(buffer
->side_data())));
407 if (side_data_id
== 1) {
409 TRACE_EVENT1("video", "vpx_codec_decode_alpha",
410 "timestamp_alpha", timestamp_alpha
);
411 vpx_codec_err_t status
= vpx_codec_decode(vpx_codec_alpha_
,
412 buffer
->side_data() + 8,
413 buffer
->side_data_size() - 8,
416 if (status
!= VPX_CODEC_OK
) {
417 LOG(ERROR
) << "vpx_codec_decode() failed on alpha, status=" << status
;
422 // Gets pointer to decoded data.
423 vpx_codec_iter_t iter_alpha
= NULL
;
424 vpx_image_alpha
= vpx_codec_get_frame(vpx_codec_alpha_
, &iter_alpha
);
425 if (!vpx_image_alpha
) {
430 if (vpx_image_alpha
->user_priv
!=
431 reinterpret_cast<void*>(×tamp_alpha
)) {
432 LOG(ERROR
) << "Invalid output timestamp on alpha.";
438 CopyVpxImageTo(vpx_image
, vpx_image_alpha
, video_frame
);
439 (*video_frame
)->set_timestamp(base::TimeDelta::FromMicroseconds(timestamp
));
443 void VpxVideoDecoder::CopyVpxImageTo(const vpx_image
* vpx_image
,
444 const struct vpx_image
* vpx_image_alpha
,
445 scoped_refptr
<VideoFrame
>* video_frame
) {
447 CHECK(vpx_image
->fmt
== VPX_IMG_FMT_I420
||
448 vpx_image
->fmt
== VPX_IMG_FMT_YV12
||
449 vpx_image
->fmt
== VPX_IMG_FMT_I444
);
451 VideoFrame::Format codec_format
= VideoFrame::YV12
;
452 int uv_rows
= (vpx_image
->d_h
+ 1) / 2;
454 if (vpx_image
->fmt
== VPX_IMG_FMT_I444
) {
455 CHECK(!vpx_codec_alpha_
);
456 codec_format
= VideoFrame::YV24
;
457 uv_rows
= vpx_image
->d_h
;
458 } else if (vpx_codec_alpha_
) {
459 codec_format
= VideoFrame::YV12A
;
462 gfx::Size
size(vpx_image
->d_w
, vpx_image
->d_h
);
464 if (!vpx_codec_alpha_
&& memory_pool_
.get()) {
465 *video_frame
= VideoFrame::WrapExternalYuvData(
467 size
, gfx::Rect(size
), config_
.natural_size(),
468 vpx_image
->stride
[VPX_PLANE_Y
],
469 vpx_image
->stride
[VPX_PLANE_U
],
470 vpx_image
->stride
[VPX_PLANE_V
],
471 vpx_image
->planes
[VPX_PLANE_Y
],
472 vpx_image
->planes
[VPX_PLANE_U
],
473 vpx_image
->planes
[VPX_PLANE_V
],
475 memory_pool_
->CreateFrameCallback(vpx_image
->fb_priv
));
479 *video_frame
= frame_pool_
.CreateFrame(
483 config_
.natural_size(),
486 CopyYPlane(vpx_image
->planes
[VPX_PLANE_Y
],
487 vpx_image
->stride
[VPX_PLANE_Y
],
490 CopyUPlane(vpx_image
->planes
[VPX_PLANE_U
],
491 vpx_image
->stride
[VPX_PLANE_U
],
494 CopyVPlane(vpx_image
->planes
[VPX_PLANE_V
],
495 vpx_image
->stride
[VPX_PLANE_V
],
498 if (!vpx_codec_alpha_
)
500 if (!vpx_image_alpha
) {
502 vpx_image
->stride
[VPX_PLANE_Y
], vpx_image
->d_h
, video_frame
->get());
505 CopyAPlane(vpx_image_alpha
->planes
[VPX_PLANE_Y
],
506 vpx_image
->stride
[VPX_PLANE_Y
],