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 "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
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"
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)
62 else if (config
.coded_size().width() >= 1024)
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
> {
86 // Callback that will be called by libvpx when it needs a frame buffer.
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
104 base::Closure
CreateFrameCallback(void* fb_priv_data
);
107 friend class base::RefCountedThreadSafe
<VpxVideoDecoder::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
;
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
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.
142 for (; i
< frame_buffers_
.size(); ++i
) {
143 if (frame_buffers_
[i
]->ref_cnt
== 0)
147 if (i
== frame_buffers_
.size()) {
148 // Maximum number of frame buffers reached.
149 if (i
== kVP9MaxFrameBuffers
)
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
) {
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
)
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
);
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
;
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,
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
),
209 vpx_codec_alpha_(NULL
) {}
211 VpxVideoDecoder::~VpxVideoDecoder() {
212 DCHECK_EQ(kUninitialized
, state_
);
216 void VpxVideoDecoder::Initialize(const VideoDecoderConfig
& config
,
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
);
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
?
249 if (status
!= VPX_CODEC_OK
) {
250 LOG(ERROR
) << "vpx_codec_dec_init failed, status=" << status
;
257 bool VpxVideoDecoder::ConfigureDecoder(const VideoDecoderConfig
& config
) {
258 if (config
.codec() != kCodecVP8
&& config
.codec() != kCodecVP9
)
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
)
267 vpx_codec_
= InitializeVpxContext(vpx_codec_
, config
);
271 // We use our own buffers for VP9 so that there is no need to copy data after
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
,
279 LOG(ERROR
) << "Failed to configure external buffers.";
284 if (config
.format() == VideoFrame::YV12A
) {
285 vpx_codec_alpha_
= InitializeVpxContext(vpx_codec_alpha_
, config
);
286 if (!vpx_codec_alpha_
)
293 void VpxVideoDecoder::CloseDecoder() {
295 vpx_codec_destroy(vpx_codec_
);
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
);
321 // Return empty frames if decoding has finished.
322 if (state_
== kDecodeFinished
) {
323 base::ResetAndReturn(&decode_cb_
).Run(kOk
, VideoFrame::CreateEOSFrame());
327 DecodeBuffer(buffer
);
330 void VpxVideoDecoder::Reset(const base::Closure
& closure
) {
331 DCHECK(task_runner_
->BelongsToCurrentThread());
332 DCHECK(decode_cb_
.is_null());
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());
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());
359 scoped_refptr
<VideoFrame
> video_frame
;
360 if (!VpxDecode(buffer
, &video_frame
)) {
362 base::ResetAndReturn(&decode_cb_
).Run(kDecodeError
, NULL
);
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
);
372 base::ResetAndReturn(&decode_cb_
).Run(kOk
, video_frame
);
375 bool VpxVideoDecoder::VpxDecode(const scoped_refptr
<DecoderBuffer
>& buffer
,
376 scoped_refptr
<VideoFrame
>* 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*>(×tamp
);
383 vpx_codec_err_t status
= vpx_codec_decode(vpx_codec_
,
388 if (status
!= VPX_CODEC_OK
) {
389 LOG(ERROR
) << "vpx_codec_decode() failed, status=" << status
;
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
);
401 if (vpx_image
->user_priv
!= reinterpret_cast<void*>(×tamp
)) {
402 LOG(ERROR
) << "Invalid output timestamp.";
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*>(×tamp_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,
422 if (status
!= VPX_CODEC_OK
) {
423 LOG(ERROR
) << "vpx_codec_decode() failed on alpha, status=" << status
;
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
) {
435 if (vpx_image_alpha
->user_priv
!=
436 reinterpret_cast<void*>(×tamp_alpha
)) {
437 LOG(ERROR
) << "Invalid output timestamp on alpha.";
443 CopyVpxImageTo(vpx_image
, vpx_image_alpha
, video_frame
);
444 (*video_frame
)->set_timestamp(base::TimeDelta::FromMicroseconds(timestamp
));
448 void VpxVideoDecoder::CopyVpxImageTo(const vpx_image
* vpx_image
,
449 const struct vpx_image
* vpx_image_alpha
,
450 scoped_refptr
<VideoFrame
>* video_frame
) {
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(
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
],
468 memory_pool_
->CreateFrameCallback(vpx_image
->fb_priv
));
472 *video_frame
= frame_pool_
.CreateFrame(
473 vpx_codec_alpha_
? VideoFrame::YV12A
: VideoFrame::YV12
,
476 config_
.natural_size(),
479 CopyYPlane(vpx_image
->planes
[VPX_PLANE_Y
],
480 vpx_image
->stride
[VPX_PLANE_Y
],
483 CopyUPlane(vpx_image
->planes
[VPX_PLANE_U
],
484 vpx_image
->stride
[VPX_PLANE_U
],
485 (vpx_image
->d_h
+ 1) / 2,
487 CopyVPlane(vpx_image
->planes
[VPX_PLANE_V
],
488 vpx_image
->stride
[VPX_PLANE_V
],
489 (vpx_image
->d_h
+ 1) / 2,
491 if (!vpx_codec_alpha_
)
493 if (!vpx_image_alpha
) {
495 vpx_image
->stride
[VPX_PLANE_Y
], vpx_image
->d_h
, video_frame
->get());
498 CopyAPlane(vpx_image_alpha
->planes
[VPX_PLANE_Y
],
499 vpx_image
->stride
[VPX_PLANE_Y
],