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/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
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 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)
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 if (video_frame
.get())
358 output_cb_
.Run(video_frame
);
360 // VideoDecoderShim expects that |decode_cb| is called only after
362 base::ResetAndReturn(&decode_cb_
).Run(kOk
);
365 bool VpxVideoDecoder::VpxDecode(const scoped_refptr
<DecoderBuffer
>& buffer
,
366 scoped_refptr
<VideoFrame
>* 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*>(×tamp
);
375 TRACE_EVENT1("video", "vpx_codec_decode", "timestamp", timestamp
);
376 vpx_codec_err_t status
= vpx_codec_decode(vpx_codec_
,
381 if (status
!= VPX_CODEC_OK
) {
382 LOG(ERROR
) << "vpx_codec_decode() failed, status=" << status
;
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
);
395 if (vpx_image
->user_priv
!= reinterpret_cast<void*>(×tamp
)) {
396 LOG(ERROR
) << "Invalid output timestamp.";
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*>(×tamp_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,
418 if (status
!= VPX_CODEC_OK
) {
419 LOG(ERROR
) << "vpx_codec_decode() failed on alpha, status=" << status
;
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
) {
432 if (vpx_image_alpha
->user_priv
!=
433 reinterpret_cast<void*>(×tamp_alpha
)) {
434 LOG(ERROR
) << "Invalid output timestamp on alpha.";
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 "
447 CopyVpxImageTo(vpx_image
, vpx_image_alpha
, video_frame
);
448 (*video_frame
)->set_timestamp(base::TimeDelta::FromMicroseconds(timestamp
));
452 void VpxVideoDecoder::CopyVpxImageTo(const vpx_image
* vpx_image
,
453 const struct vpx_image
* vpx_image_alpha
,
454 scoped_refptr
<VideoFrame
>* video_frame
) {
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(
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
],
494 memory_pool_
->CreateFrameCallback(vpx_image
->fb_priv
));
498 *video_frame
= frame_pool_
.CreateFrame(
501 gfx::Rect(visible_size
),
502 config_
.natural_size(),
505 CopyYPlane(vpx_image
->planes
[VPX_PLANE_Y
],
506 vpx_image
->stride
[VPX_PLANE_Y
],
509 CopyUPlane(vpx_image
->planes
[VPX_PLANE_U
],
510 vpx_image
->stride
[VPX_PLANE_U
],
513 CopyVPlane(vpx_image
->planes
[VPX_PLANE_V
],
514 vpx_image
->stride
[VPX_PLANE_V
],
517 if (!vpx_codec_alpha_
)
519 if (!vpx_image_alpha
) {
521 vpx_image
->stride
[VPX_PLANE_Y
], vpx_image
->d_h
, video_frame
->get());
524 CopyAPlane(vpx_image_alpha
->planes
[VPX_PLANE_Y
],
525 vpx_image_alpha
->stride
[VPX_PLANE_Y
],
526 vpx_image_alpha
->d_h
,