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/ffmpeg_video_decoder.h"
10 #include "base/bind.h"
11 #include "base/callback_helpers.h"
12 #include "base/command_line.h"
13 #include "base/location.h"
14 #include "base/single_thread_task_runner.h"
15 #include "base/strings/string_number_conversions.h"
16 #include "media/base/bind_to_current_loop.h"
17 #include "media/base/decoder_buffer.h"
18 #include "media/base/limits.h"
19 #include "media/base/media_switches.h"
20 #include "media/base/pipeline.h"
21 #include "media/base/timestamp_constants.h"
22 #include "media/base/video_frame.h"
23 #include "media/base/video_util.h"
24 #include "media/ffmpeg/ffmpeg_common.h"
25 #include "media/filters/ffmpeg_glue.h"
29 // Always try to use three threads for video decoding. There is little reason
30 // not to since current day CPUs tend to be multi-core and we measured
31 // performance benefits on older machines such as P4s with hyperthreading.
33 // Handling decoding on separate threads also frees up the pipeline thread to
34 // continue processing. Although it'd be nice to have the option of a single
35 // decoding thread, FFmpeg treats having one thread the same as having zero
36 // threads (i.e., avcodec_decode_video() will execute on the calling thread).
37 // Yet another reason for having two threads :)
38 static const int kDecodeThreads
= 2;
39 static const int kMaxDecodeThreads
= 16;
41 // Returns the number of threads given the FFmpeg CodecID. Also inspects the
42 // command line for a valid --video-threads flag.
43 static int GetThreadCount(AVCodecID codec_id
) {
44 // Refer to http://crbug.com/93932 for tsan suppressions on decoding.
45 int decode_threads
= kDecodeThreads
;
47 const base::CommandLine
* cmd_line
= base::CommandLine::ForCurrentProcess();
48 std::string
threads(cmd_line
->GetSwitchValueASCII(switches::kVideoThreads
));
49 if (threads
.empty() || !base::StringToInt(threads
, &decode_threads
))
50 return decode_threads
;
52 decode_threads
= std::max(decode_threads
, 0);
53 decode_threads
= std::min(decode_threads
, kMaxDecodeThreads
);
54 return decode_threads
;
57 static int GetVideoBufferImpl(struct AVCodecContext
* s
,
60 FFmpegVideoDecoder
* decoder
= static_cast<FFmpegVideoDecoder
*>(s
->opaque
);
61 return decoder
->GetVideoBuffer(s
, frame
, flags
);
64 static void ReleaseVideoBufferImpl(void* opaque
, uint8
* data
) {
65 scoped_refptr
<VideoFrame
> video_frame
;
66 video_frame
.swap(reinterpret_cast<VideoFrame
**>(&opaque
));
70 bool FFmpegVideoDecoder::IsCodecSupported(VideoCodec codec
) {
71 FFmpegGlue::InitializeFFmpeg();
72 return avcodec_find_decoder(VideoCodecToCodecID(codec
)) != nullptr;
75 FFmpegVideoDecoder::FFmpegVideoDecoder(
76 const scoped_refptr
<base::SingleThreadTaskRunner
>& task_runner
)
77 : task_runner_(task_runner
), state_(kUninitialized
),
78 decode_nalus_(false) {}
80 int FFmpegVideoDecoder::GetVideoBuffer(struct AVCodecContext
* codec_context
,
83 // Don't use |codec_context_| here! With threaded decoding,
84 // it will contain unsynchronized width/height/pix_fmt values,
85 // whereas |codec_context| contains the current threads's
86 // updated width/height/pix_fmt, which can change for adaptive
88 const VideoPixelFormat format
=
89 AVPixelFormatToVideoPixelFormat(codec_context
->pix_fmt
);
91 if (format
== PIXEL_FORMAT_UNKNOWN
)
92 return AVERROR(EINVAL
);
93 DCHECK(format
== PIXEL_FORMAT_YV12
|| format
== PIXEL_FORMAT_YV16
||
94 format
== PIXEL_FORMAT_YV24
);
96 gfx::Size
size(codec_context
->width
, codec_context
->height
);
97 const int ret
= av_image_check_size(size
.width(), size
.height(), 0, NULL
);
101 gfx::Size natural_size
;
102 if (codec_context
->sample_aspect_ratio
.num
> 0) {
103 natural_size
= GetNaturalSize(size
,
104 codec_context
->sample_aspect_ratio
.num
,
105 codec_context
->sample_aspect_ratio
.den
);
107 natural_size
= config_
.natural_size();
110 // FFmpeg has specific requirements on the allocation size of the frame. The
111 // following logic replicates FFmpeg's allocation strategy to ensure buffers
112 // are not overread / overwritten. See ff_init_buffer_info() for details.
114 // When lowres is non-zero, dimensions should be divided by 2^(lowres), but
115 // since we don't use this, just DCHECK that it's zero.
116 DCHECK_EQ(codec_context
->lowres
, 0);
117 gfx::Size
coded_size(std::max(size
.width(), codec_context
->coded_width
),
118 std::max(size
.height(), codec_context
->coded_height
));
120 if (!VideoFrame::IsValidConfig(format
, VideoFrame::STORAGE_UNKNOWN
,
121 coded_size
, gfx::Rect(size
), natural_size
)) {
122 return AVERROR(EINVAL
);
125 // FFmpeg expects the initialize allocation to be zero-initialized. Failure
126 // to do so can lead to unitialized value usage. See http://crbug.com/390941
127 scoped_refptr
<VideoFrame
> video_frame
= frame_pool_
.CreateFrame(
128 format
, coded_size
, gfx::Rect(size
), natural_size
, kNoTimestamp());
130 // Prefer the color space from the codec context. If it's not specified (or is
131 // set to an unsupported value), fall back on the value from the config.
132 ColorSpace color_space
= AVColorSpaceToColorSpace(codec_context
->colorspace
,
133 codec_context
->color_range
);
134 if (color_space
== COLOR_SPACE_UNSPECIFIED
)
135 color_space
= config_
.color_space();
136 video_frame
->metadata()->SetInteger(VideoFrameMetadata::COLOR_SPACE
,
139 for (size_t i
= 0; i
< VideoFrame::NumPlanes(video_frame
->format()); i
++) {
140 frame
->data
[i
] = video_frame
->data(i
);
141 frame
->linesize
[i
] = video_frame
->stride(i
);
144 frame
->width
= coded_size
.width();
145 frame
->height
= coded_size
.height();
146 frame
->format
= codec_context
->pix_fmt
;
147 frame
->reordered_opaque
= codec_context
->reordered_opaque
;
149 // Now create an AVBufferRef for the data just allocated. It will own the
150 // reference to the VideoFrame object.
152 video_frame
.swap(reinterpret_cast<VideoFrame
**>(&opaque
));
154 av_buffer_create(frame
->data
[0],
155 VideoFrame::AllocationSize(format
, coded_size
),
156 ReleaseVideoBufferImpl
,
162 std::string
FFmpegVideoDecoder::GetDisplayName() const {
163 return "FFmpegVideoDecoder";
166 void FFmpegVideoDecoder::Initialize(const VideoDecoderConfig
& config
,
168 const InitCB
& init_cb
,
169 const OutputCB
& output_cb
) {
170 DCHECK(task_runner_
->BelongsToCurrentThread());
171 DCHECK(!config
.is_encrypted());
172 DCHECK(!output_cb
.is_null());
174 FFmpegGlue::InitializeFFmpeg();
177 InitCB bound_init_cb
= BindToCurrentLoop(init_cb
);
179 if (!config
.IsValidConfig() || !ConfigureDecoder(low_delay
)) {
180 bound_init_cb
.Run(false);
184 output_cb_
= BindToCurrentLoop(output_cb
);
188 bound_init_cb
.Run(true);
191 void FFmpegVideoDecoder::Decode(const scoped_refptr
<DecoderBuffer
>& buffer
,
192 const DecodeCB
& decode_cb
) {
193 DCHECK(task_runner_
->BelongsToCurrentThread());
194 DCHECK(buffer
.get());
195 DCHECK(!decode_cb
.is_null());
196 CHECK_NE(state_
, kUninitialized
);
198 DecodeCB decode_cb_bound
= BindToCurrentLoop(decode_cb
);
200 if (state_
== kError
) {
201 decode_cb_bound
.Run(kDecodeError
);
205 if (state_
== kDecodeFinished
) {
206 decode_cb_bound
.Run(kOk
);
210 DCHECK_EQ(state_
, kNormal
);
212 // During decode, because reads are issued asynchronously, it is possible to
213 // receive multiple end of stream buffers since each decode is acked. When the
214 // first end of stream buffer is read, FFmpeg may still have frames queued
215 // up in the decoder so we need to go through the decode loop until it stops
216 // giving sensible data. After that, the decoder should output empty
217 // frames. There are three states the decoder can be in:
219 // kNormal: This is the starting state. Buffers are decoded. Decode errors
221 // kDecodeFinished: All calls return empty frames.
222 // kError: Unexpected error happened.
224 // These are the possible state transitions.
226 // kNormal -> kDecodeFinished:
227 // When EOS buffer is received and the codec has been flushed.
228 // kNormal -> kError:
229 // A decoding error occurs and decoding needs to stop.
230 // (any state) -> kNormal:
231 // Any time Reset() is called.
233 bool has_produced_frame
;
235 has_produced_frame
= false;
236 if (!FFmpegDecode(buffer
, &has_produced_frame
)) {
238 decode_cb_bound
.Run(kDecodeError
);
241 // Repeat to flush the decoder after receiving EOS buffer.
242 } while (buffer
->end_of_stream() && has_produced_frame
);
244 if (buffer
->end_of_stream())
245 state_
= kDecodeFinished
;
247 // VideoDecoderShim expects that |decode_cb| is called only after
249 decode_cb_bound
.Run(kOk
);
252 void FFmpegVideoDecoder::Reset(const base::Closure
& closure
) {
253 DCHECK(task_runner_
->BelongsToCurrentThread());
255 avcodec_flush_buffers(codec_context_
.get());
257 task_runner_
->PostTask(FROM_HERE
, closure
);
260 FFmpegVideoDecoder::~FFmpegVideoDecoder() {
261 DCHECK(task_runner_
->BelongsToCurrentThread());
263 if (state_
!= kUninitialized
)
264 ReleaseFFmpegResources();
267 bool FFmpegVideoDecoder::FFmpegDecode(
268 const scoped_refptr
<DecoderBuffer
>& buffer
,
269 bool* has_produced_frame
) {
270 DCHECK(!*has_produced_frame
);
272 // Create a packet for input data.
273 // Due to FFmpeg API changes we no longer have const read-only pointers.
275 av_init_packet(&packet
);
276 if (buffer
->end_of_stream()) {
280 packet
.data
= const_cast<uint8
*>(buffer
->data());
281 packet
.size
= buffer
->data_size();
283 // Let FFmpeg handle presentation timestamp reordering.
284 codec_context_
->reordered_opaque
= buffer
->timestamp().InMicroseconds();
287 int frame_decoded
= 0;
288 int result
= avcodec_decode_video2(codec_context_
.get(),
292 // Log the problem if we can't decode a video frame and exit early.
294 LOG(ERROR
) << "Error decoding video: " << buffer
->AsHumanReadableString();
298 // FFmpeg says some codecs might have multiple frames per packet. Previous
299 // discussions with rbultje@ indicate this shouldn't be true for the codecs
301 DCHECK_EQ(result
, packet
.size
);
303 // If no frame was produced then signal that more data is required to
304 // produce more frames. This can happen under two circumstances:
305 // 1) Decoder was recently initialized/flushed
306 // 2) End of stream was reached and all internal frames have been output
307 if (frame_decoded
== 0) {
311 // TODO(fbarchard): Work around for FFmpeg http://crbug.com/27675
312 // The decoder is in a bad state and not decoding correctly.
313 // Checking for NULL avoids a crash in CopyPlane().
314 if (!av_frame_
->data
[VideoFrame::kYPlane
] ||
315 !av_frame_
->data
[VideoFrame::kUPlane
] ||
316 !av_frame_
->data
[VideoFrame::kVPlane
]) {
317 LOG(ERROR
) << "Video frame was produced yet has invalid frame data.";
318 av_frame_unref(av_frame_
.get());
322 scoped_refptr
<VideoFrame
> frame
=
323 reinterpret_cast<VideoFrame
*>(av_buffer_get_opaque(av_frame_
->buf
[0]));
324 frame
->set_timestamp(
325 base::TimeDelta::FromMicroseconds(av_frame_
->reordered_opaque
));
326 *has_produced_frame
= true;
327 output_cb_
.Run(frame
);
329 av_frame_unref(av_frame_
.get());
333 void FFmpegVideoDecoder::ReleaseFFmpegResources() {
334 codec_context_
.reset();
338 bool FFmpegVideoDecoder::ConfigureDecoder(bool low_delay
) {
339 // Release existing decoder resources if necessary.
340 ReleaseFFmpegResources();
342 // Initialize AVCodecContext structure.
343 codec_context_
.reset(avcodec_alloc_context3(NULL
));
344 VideoDecoderConfigToAVCodecContext(config_
, codec_context_
.get());
346 codec_context_
->thread_count
= GetThreadCount(codec_context_
->codec_id
);
347 codec_context_
->thread_type
= low_delay
? FF_THREAD_SLICE
: FF_THREAD_FRAME
;
348 codec_context_
->opaque
= this;
349 codec_context_
->flags
|= CODEC_FLAG_EMU_EDGE
;
350 codec_context_
->get_buffer2
= GetVideoBufferImpl
;
351 codec_context_
->refcounted_frames
= 1;
354 codec_context_
->flags2
|= CODEC_FLAG2_CHUNKS
;
356 AVCodec
* codec
= avcodec_find_decoder(codec_context_
->codec_id
);
357 if (!codec
|| avcodec_open2(codec_context_
.get(), codec
, NULL
) < 0) {
358 ReleaseFFmpegResources();
362 av_frame_
.reset(av_frame_alloc());