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/video_frame.h"
22 #include "media/base/video_util.h"
23 #include "media/ffmpeg/ffmpeg_common.h"
24 #include "media/filters/ffmpeg_glue.h"
28 // Always try to use three threads for video decoding. There is little reason
29 // not to since current day CPUs tend to be multi-core and we measured
30 // performance benefits on older machines such as P4s with hyperthreading.
32 // Handling decoding on separate threads also frees up the pipeline thread to
33 // continue processing. Although it'd be nice to have the option of a single
34 // decoding thread, FFmpeg treats having one thread the same as having zero
35 // threads (i.e., avcodec_decode_video() will execute on the calling thread).
36 // Yet another reason for having two threads :)
37 static const int kDecodeThreads
= 2;
38 static const int kMaxDecodeThreads
= 16;
40 // Returns the number of threads given the FFmpeg CodecID. Also inspects the
41 // command line for a valid --video-threads flag.
42 static int GetThreadCount(AVCodecID codec_id
) {
43 // Refer to http://crbug.com/93932 for tsan suppressions on decoding.
44 int decode_threads
= kDecodeThreads
;
46 const base::CommandLine
* cmd_line
= base::CommandLine::ForCurrentProcess();
47 std::string
threads(cmd_line
->GetSwitchValueASCII(switches::kVideoThreads
));
48 if (threads
.empty() || !base::StringToInt(threads
, &decode_threads
))
49 return decode_threads
;
51 decode_threads
= std::max(decode_threads
, 0);
52 decode_threads
= std::min(decode_threads
, kMaxDecodeThreads
);
53 return decode_threads
;
56 static int GetVideoBufferImpl(struct AVCodecContext
* s
,
59 FFmpegVideoDecoder
* decoder
= static_cast<FFmpegVideoDecoder
*>(s
->opaque
);
60 return decoder
->GetVideoBuffer(s
, frame
, flags
);
63 static void ReleaseVideoBufferImpl(void* opaque
, uint8
* data
) {
64 scoped_refptr
<VideoFrame
> video_frame
;
65 video_frame
.swap(reinterpret_cast<VideoFrame
**>(&opaque
));
68 FFmpegVideoDecoder::FFmpegVideoDecoder(
69 const scoped_refptr
<base::SingleThreadTaskRunner
>& task_runner
)
70 : task_runner_(task_runner
), state_(kUninitialized
),
71 decode_nalus_(false) {}
73 int FFmpegVideoDecoder::GetVideoBuffer(struct AVCodecContext
* codec_context
,
76 // Don't use |codec_context_| here! With threaded decoding,
77 // it will contain unsynchronized width/height/pix_fmt values,
78 // whereas |codec_context| contains the current threads's
79 // updated width/height/pix_fmt, which can change for adaptive
81 const VideoPixelFormat format
=
82 PixelFormatToVideoPixelFormat(codec_context
->pix_fmt
);
84 if (format
== PIXEL_FORMAT_UNKNOWN
)
85 return AVERROR(EINVAL
);
86 DCHECK(format
== PIXEL_FORMAT_YV12
|| format
== PIXEL_FORMAT_YV16
||
87 format
== PIXEL_FORMAT_YV24
);
89 gfx::Size
size(codec_context
->width
, codec_context
->height
);
90 const int ret
= av_image_check_size(size
.width(), size
.height(), 0, NULL
);
94 gfx::Size natural_size
;
95 if (codec_context
->sample_aspect_ratio
.num
> 0) {
96 natural_size
= GetNaturalSize(size
,
97 codec_context
->sample_aspect_ratio
.num
,
98 codec_context
->sample_aspect_ratio
.den
);
100 natural_size
= config_
.natural_size();
103 // FFmpeg has specific requirements on the allocation size of the frame. The
104 // following logic replicates FFmpeg's allocation strategy to ensure buffers
105 // are not overread / overwritten. See ff_init_buffer_info() for details.
107 // When lowres is non-zero, dimensions should be divided by 2^(lowres), but
108 // since we don't use this, just DCHECK that it's zero.
109 DCHECK_EQ(codec_context
->lowres
, 0);
110 gfx::Size
coded_size(std::max(size
.width(), codec_context
->coded_width
),
111 std::max(size
.height(), codec_context
->coded_height
));
113 if (!VideoFrame::IsValidConfig(format
, VideoFrame::STORAGE_UNKNOWN
,
114 coded_size
, gfx::Rect(size
), natural_size
)) {
115 return AVERROR(EINVAL
);
118 scoped_refptr
<VideoFrame
> video_frame
= frame_pool_
.CreateFrame(
119 format
, coded_size
, gfx::Rect(size
), natural_size
, kNoTimestamp());
120 #if defined(MEMORY_SANITIZER)
121 MSAN_UNPOISON(video_frame
->data(0),
122 VideoFrame::AllocationSize(format
, coded_size
));
125 // Prefer the color space from the codec context. If it's not specified (or is
126 // set to an unsupported value), fall back on the value from the config.
127 ColorSpace color_space
= AVColorSpaceToColorSpace(codec_context
->colorspace
,
128 codec_context
->color_range
);
129 if (color_space
== COLOR_SPACE_UNSPECIFIED
)
130 color_space
= config_
.color_space();
131 video_frame
->metadata()->SetInteger(VideoFrameMetadata::COLOR_SPACE
,
134 for (int i
= 0; i
< 3; i
++) {
135 frame
->data
[i
] = video_frame
->data(i
);
136 frame
->linesize
[i
] = video_frame
->stride(i
);
139 frame
->width
= coded_size
.width();
140 frame
->height
= coded_size
.height();
141 frame
->format
= codec_context
->pix_fmt
;
142 frame
->reordered_opaque
= codec_context
->reordered_opaque
;
144 // Now create an AVBufferRef for the data just allocated. It will own the
145 // reference to the VideoFrame object.
147 video_frame
.swap(reinterpret_cast<VideoFrame
**>(&opaque
));
149 av_buffer_create(frame
->data
[0],
150 VideoFrame::AllocationSize(format
, coded_size
),
151 ReleaseVideoBufferImpl
,
157 std::string
FFmpegVideoDecoder::GetDisplayName() const {
158 return "FFmpegVideoDecoder";
161 void FFmpegVideoDecoder::Initialize(const VideoDecoderConfig
& config
,
163 const InitCB
& init_cb
,
164 const OutputCB
& output_cb
) {
165 DCHECK(task_runner_
->BelongsToCurrentThread());
166 DCHECK(!config
.is_encrypted());
167 DCHECK(!output_cb
.is_null());
169 FFmpegGlue::InitializeFFmpeg();
172 InitCB bound_init_cb
= BindToCurrentLoop(init_cb
);
174 if (!config
.IsValidConfig() || !ConfigureDecoder(low_delay
)) {
175 bound_init_cb
.Run(false);
179 output_cb_
= BindToCurrentLoop(output_cb
);
183 bound_init_cb
.Run(true);
186 void FFmpegVideoDecoder::Decode(const scoped_refptr
<DecoderBuffer
>& buffer
,
187 const DecodeCB
& decode_cb
) {
188 DCHECK(task_runner_
->BelongsToCurrentThread());
189 DCHECK(buffer
.get());
190 DCHECK(!decode_cb
.is_null());
191 CHECK_NE(state_
, kUninitialized
);
193 DecodeCB decode_cb_bound
= BindToCurrentLoop(decode_cb
);
195 if (state_
== kError
) {
196 decode_cb_bound
.Run(kDecodeError
);
200 if (state_
== kDecodeFinished
) {
201 decode_cb_bound
.Run(kOk
);
205 DCHECK_EQ(state_
, kNormal
);
207 // During decode, because reads are issued asynchronously, it is possible to
208 // receive multiple end of stream buffers since each decode is acked. When the
209 // first end of stream buffer is read, FFmpeg may still have frames queued
210 // up in the decoder so we need to go through the decode loop until it stops
211 // giving sensible data. After that, the decoder should output empty
212 // frames. There are three states the decoder can be in:
214 // kNormal: This is the starting state. Buffers are decoded. Decode errors
216 // kDecodeFinished: All calls return empty frames.
217 // kError: Unexpected error happened.
219 // These are the possible state transitions.
221 // kNormal -> kDecodeFinished:
222 // When EOS buffer is received and the codec has been flushed.
223 // kNormal -> kError:
224 // A decoding error occurs and decoding needs to stop.
225 // (any state) -> kNormal:
226 // Any time Reset() is called.
228 bool has_produced_frame
;
230 has_produced_frame
= false;
231 if (!FFmpegDecode(buffer
, &has_produced_frame
)) {
233 decode_cb_bound
.Run(kDecodeError
);
236 // Repeat to flush the decoder after receiving EOS buffer.
237 } while (buffer
->end_of_stream() && has_produced_frame
);
239 if (buffer
->end_of_stream())
240 state_
= kDecodeFinished
;
242 // VideoDecoderShim expects that |decode_cb| is called only after
244 decode_cb_bound
.Run(kOk
);
247 void FFmpegVideoDecoder::Reset(const base::Closure
& closure
) {
248 DCHECK(task_runner_
->BelongsToCurrentThread());
250 avcodec_flush_buffers(codec_context_
.get());
252 task_runner_
->PostTask(FROM_HERE
, closure
);
255 FFmpegVideoDecoder::~FFmpegVideoDecoder() {
256 DCHECK(task_runner_
->BelongsToCurrentThread());
258 if (state_
!= kUninitialized
)
259 ReleaseFFmpegResources();
262 bool FFmpegVideoDecoder::FFmpegDecode(
263 const scoped_refptr
<DecoderBuffer
>& buffer
,
264 bool* has_produced_frame
) {
265 DCHECK(!*has_produced_frame
);
267 // Create a packet for input data.
268 // Due to FFmpeg API changes we no longer have const read-only pointers.
270 av_init_packet(&packet
);
271 if (buffer
->end_of_stream()) {
275 packet
.data
= const_cast<uint8
*>(buffer
->data());
276 packet
.size
= buffer
->data_size();
278 // Let FFmpeg handle presentation timestamp reordering.
279 codec_context_
->reordered_opaque
= buffer
->timestamp().InMicroseconds();
282 int frame_decoded
= 0;
283 int result
= avcodec_decode_video2(codec_context_
.get(),
287 // Log the problem if we can't decode a video frame and exit early.
289 LOG(ERROR
) << "Error decoding video: " << buffer
->AsHumanReadableString();
293 // FFmpeg says some codecs might have multiple frames per packet. Previous
294 // discussions with rbultje@ indicate this shouldn't be true for the codecs
296 DCHECK_EQ(result
, packet
.size
);
298 // If no frame was produced then signal that more data is required to
299 // produce more frames. This can happen under two circumstances:
300 // 1) Decoder was recently initialized/flushed
301 // 2) End of stream was reached and all internal frames have been output
302 if (frame_decoded
== 0) {
306 // TODO(fbarchard): Work around for FFmpeg http://crbug.com/27675
307 // The decoder is in a bad state and not decoding correctly.
308 // Checking for NULL avoids a crash in CopyPlane().
309 if (!av_frame_
->data
[VideoFrame::kYPlane
] ||
310 !av_frame_
->data
[VideoFrame::kUPlane
] ||
311 !av_frame_
->data
[VideoFrame::kVPlane
]) {
312 LOG(ERROR
) << "Video frame was produced yet has invalid frame data.";
313 av_frame_unref(av_frame_
.get());
317 scoped_refptr
<VideoFrame
> frame
=
318 reinterpret_cast<VideoFrame
*>(av_buffer_get_opaque(av_frame_
->buf
[0]));
319 frame
->set_timestamp(
320 base::TimeDelta::FromMicroseconds(av_frame_
->reordered_opaque
));
321 *has_produced_frame
= true;
322 output_cb_
.Run(frame
);
324 av_frame_unref(av_frame_
.get());
328 void FFmpegVideoDecoder::ReleaseFFmpegResources() {
329 codec_context_
.reset();
333 bool FFmpegVideoDecoder::ConfigureDecoder(bool low_delay
) {
334 // Release existing decoder resources if necessary.
335 ReleaseFFmpegResources();
337 // Initialize AVCodecContext structure.
338 codec_context_
.reset(avcodec_alloc_context3(NULL
));
339 VideoDecoderConfigToAVCodecContext(config_
, codec_context_
.get());
341 codec_context_
->thread_count
= GetThreadCount(codec_context_
->codec_id
);
342 codec_context_
->thread_type
= low_delay
? FF_THREAD_SLICE
: FF_THREAD_FRAME
;
343 codec_context_
->opaque
= this;
344 codec_context_
->flags
|= CODEC_FLAG_EMU_EDGE
;
345 codec_context_
->get_buffer2
= GetVideoBufferImpl
;
346 codec_context_
->refcounted_frames
= 1;
349 codec_context_
->flags2
|= CODEC_FLAG2_CHUNKS
;
351 AVCodec
* codec
= avcodec_find_decoder(codec_context_
->codec_id
);
352 if (!codec
|| avcodec_open2(codec_context_
.get(), codec
, NULL
) < 0) {
353 ReleaseFFmpegResources();
357 av_frame_
.reset(av_frame_alloc());