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_audio_decoder.h"
7 #include "base/callback_helpers.h"
8 #include "base/single_thread_task_runner.h"
9 #include "media/base/audio_buffer.h"
10 #include "media/base/audio_bus.h"
11 #include "media/base/audio_decoder_config.h"
12 #include "media/base/audio_discard_helper.h"
13 #include "media/base/bind_to_current_loop.h"
14 #include "media/base/decoder_buffer.h"
15 #include "media/base/limits.h"
16 #include "media/base/sample_format.h"
17 #include "media/ffmpeg/ffmpeg_common.h"
18 #include "media/filters/ffmpeg_glue.h"
22 // Returns true if the decode result was end of stream.
23 static inline bool IsEndOfStream(int result,
25 const scoped_refptr<DecoderBuffer>& input) {
26 // Three conditions to meet to declare end of stream for this decoder:
27 // 1. FFmpeg didn't read anything.
28 // 2. FFmpeg didn't output anything.
29 // 3. An end of stream buffer is received.
30 return result == 0 && decoded_size == 0 && input->end_of_stream();
33 // Return the number of channels from the data in |frame|.
34 static inline int DetermineChannels(AVFrame* frame) {
35 #if defined(CHROMIUM_NO_AVFRAME_CHANNELS)
36 // When use_system_ffmpeg==1, libav's AVFrame doesn't have channels field.
37 return av_get_channel_layout_nb_channels(frame->channel_layout);
39 return frame->channels;
43 // Called by FFmpeg's allocation routine to free a buffer. |opaque| is the
44 // AudioBuffer allocated, so unref it.
45 static void ReleaseAudioBufferImpl(void* opaque, uint8* data) {
46 scoped_refptr<AudioBuffer> buffer;
47 buffer.swap(reinterpret_cast<AudioBuffer**>(&opaque));
50 // Called by FFmpeg's allocation routine to allocate a buffer. Uses
51 // AVCodecContext.opaque to get the object reference in order to call
52 // GetAudioBuffer() to do the actual allocation.
53 static int GetAudioBuffer(struct AVCodecContext* s, AVFrame* frame, int flags) {
54 DCHECK(s->codec->capabilities & CODEC_CAP_DR1);
55 DCHECK_EQ(s->codec_type, AVMEDIA_TYPE_AUDIO);
57 // Since this routine is called by FFmpeg when a buffer is required for audio
58 // data, use the values supplied by FFmpeg (ignoring the current settings).
59 // FFmpegDecode() gets to determine if the buffer is useable or not.
60 AVSampleFormat format = static_cast<AVSampleFormat>(frame->format);
61 SampleFormat sample_format = AVSampleFormatToSampleFormat(format);
62 int channels = DetermineChannels(frame);
63 if (channels <= 0 || channels >= limits::kMaxChannels) {
64 DLOG(ERROR) << "Requested number of channels (" << channels
65 << ") exceeds limit.";
66 return AVERROR(EINVAL);
69 int bytes_per_channel = SampleFormatToBytesPerChannel(sample_format);
70 if (frame->nb_samples <= 0)
71 return AVERROR(EINVAL);
73 if (s->channels != channels) {
74 DLOG(ERROR) << "AVCodecContext and AVFrame disagree on channel count.";
75 return AVERROR(EINVAL);
78 // Determine how big the buffer should be and allocate it. FFmpeg may adjust
79 // how big each channel data is in order to meet the alignment policy, so
80 // we need to take this into consideration.
81 int buffer_size_in_bytes =
82 av_samples_get_buffer_size(&frame->linesize[0],
86 AudioBuffer::kChannelAlignment);
87 // Check for errors from av_samples_get_buffer_size().
88 if (buffer_size_in_bytes < 0)
89 return buffer_size_in_bytes;
90 int frames_required = buffer_size_in_bytes / bytes_per_channel / channels;
91 DCHECK_GE(frames_required, frame->nb_samples);
92 scoped_refptr<AudioBuffer> buffer = AudioBuffer::CreateBuffer(
94 ChannelLayoutToChromeChannelLayout(s->channel_layout, s->channels),
99 // Initialize the data[] and extended_data[] fields to point into the memory
100 // allocated for AudioBuffer. |number_of_planes| will be 1 for interleaved
101 // audio and equal to |channels| for planar audio.
102 int number_of_planes = buffer->channel_data().size();
103 if (number_of_planes <= AV_NUM_DATA_POINTERS) {
104 DCHECK_EQ(frame->extended_data, frame->data);
105 for (int i = 0; i < number_of_planes; ++i)
106 frame->data[i] = buffer->channel_data()[i];
108 // There are more channels than can fit into data[], so allocate
109 // extended_data[] and fill appropriately.
110 frame->extended_data = static_cast<uint8**>(
111 av_malloc(number_of_planes * sizeof(*frame->extended_data)));
113 for (; i < AV_NUM_DATA_POINTERS; ++i)
114 frame->extended_data[i] = frame->data[i] = buffer->channel_data()[i];
115 for (; i < number_of_planes; ++i)
116 frame->extended_data[i] = buffer->channel_data()[i];
119 // Now create an AVBufferRef for the data just allocated. It will own the
120 // reference to the AudioBuffer object.
122 buffer.swap(reinterpret_cast<AudioBuffer**>(&opaque));
123 frame->buf[0] = av_buffer_create(
124 frame->data[0], buffer_size_in_bytes, ReleaseAudioBufferImpl, opaque, 0);
128 FFmpegAudioDecoder::FFmpegAudioDecoder(
129 const scoped_refptr<base::SingleThreadTaskRunner>& task_runner,
131 : task_runner_(task_runner),
132 state_(kUninitialized),
133 av_sample_format_(0),
137 FFmpegAudioDecoder::~FFmpegAudioDecoder() {
138 DCHECK_EQ(state_, kUninitialized);
139 DCHECK(!codec_context_);
143 void FFmpegAudioDecoder::Initialize(const AudioDecoderConfig& config,
144 const PipelineStatusCB& status_cb) {
145 DCHECK(task_runner_->BelongsToCurrentThread());
146 DCHECK(!config.is_encrypted());
148 FFmpegGlue::InitializeFFmpeg();
151 PipelineStatusCB initialize_cb = BindToCurrentLoop(status_cb);
153 if (!config.IsValidConfig() || !ConfigureDecoder()) {
154 initialize_cb.Run(DECODER_ERROR_NOT_SUPPORTED);
160 initialize_cb.Run(PIPELINE_OK);
163 void FFmpegAudioDecoder::Decode(const scoped_refptr<DecoderBuffer>& buffer,
164 const DecodeCB& decode_cb) {
165 DCHECK(task_runner_->BelongsToCurrentThread());
166 DCHECK(!decode_cb.is_null());
167 CHECK_NE(state_, kUninitialized);
168 DecodeCB decode_cb_bound = BindToCurrentLoop(decode_cb);
170 if (state_ == kError) {
171 decode_cb_bound.Run(kDecodeError, NULL);
175 // Return empty frames if decoding has finished.
176 if (state_ == kDecodeFinished) {
177 decode_cb_bound.Run(kOk, AudioBuffer::CreateEOSBuffer());
182 decode_cb_bound.Run(kAborted, NULL);
186 DecodeBuffer(buffer, decode_cb_bound);
189 scoped_refptr<AudioBuffer> FFmpegAudioDecoder::GetDecodeOutput() {
190 DCHECK(task_runner_->BelongsToCurrentThread());
191 if (queued_audio_.empty())
193 scoped_refptr<AudioBuffer> out = queued_audio_.front();
194 queued_audio_.pop_front();
198 void FFmpegAudioDecoder::Reset(const base::Closure& closure) {
199 DCHECK(task_runner_->BelongsToCurrentThread());
201 avcodec_flush_buffers(codec_context_.get());
203 ResetTimestampState();
204 task_runner_->PostTask(FROM_HERE, closure);
207 void FFmpegAudioDecoder::Stop() {
208 DCHECK(task_runner_->BelongsToCurrentThread());
210 if (state_ == kUninitialized)
213 ReleaseFFmpegResources();
214 ResetTimestampState();
215 state_ = kUninitialized;
218 void FFmpegAudioDecoder::DecodeBuffer(
219 const scoped_refptr<DecoderBuffer>& buffer,
220 const DecodeCB& decode_cb) {
221 DCHECK(task_runner_->BelongsToCurrentThread());
222 DCHECK_NE(state_, kUninitialized);
223 DCHECK_NE(state_, kDecodeFinished);
224 DCHECK_NE(state_, kError);
228 // During decode, because reads are issued asynchronously, it is possible to
229 // receive multiple end of stream buffers since each decode is acked. When the
230 // first end of stream buffer is read, FFmpeg may still have frames queued
231 // up in the decoder so we need to go through the decode loop until it stops
232 // giving sensible data. After that, the decoder should output empty
233 // frames. There are three states the decoder can be in:
235 // kNormal: This is the starting state. Buffers are decoded. Decode errors
237 // kFlushCodec: There isn't any more input data. Call avcodec_decode_audio4
238 // until no more data is returned to flush out remaining
239 // frames. The input buffer is ignored at this point.
240 // kDecodeFinished: All calls return empty frames.
241 // kError: Unexpected error happened.
243 // These are the possible state transitions.
245 // kNormal -> kFlushCodec:
246 // When buffer->end_of_stream() is first true.
247 // kNormal -> kError:
248 // A decoding error occurs and decoding needs to stop.
249 // kFlushCodec -> kDecodeFinished:
250 // When avcodec_decode_audio4() returns 0 data.
251 // kFlushCodec -> kError:
252 // When avcodec_decode_audio4() errors out.
253 // (any state) -> kNormal:
254 // Any time Reset() is called.
256 // Make sure we are notified if http://crbug.com/49709 returns. Issue also
257 // occurs with some damaged files.
258 if (!buffer->end_of_stream() && buffer->timestamp() == kNoTimestamp()) {
259 DVLOG(1) << "Received a buffer without timestamps!";
260 decode_cb.Run(kDecodeError, NULL);
264 if (!buffer->end_of_stream() && !discard_helper_->initialized() &&
265 codec_context_->codec_id == AV_CODEC_ID_VORBIS &&
266 buffer->timestamp() < base::TimeDelta()) {
267 // Dropping frames for negative timestamps as outlined in section A.2
268 // in the Vorbis spec. http://xiph.org/vorbis/doc/Vorbis_I_spec.html
269 const int discard_frames =
270 discard_helper_->TimeDeltaToFrames(-buffer->timestamp());
271 discard_helper_->Reset(discard_frames);
274 // Transition to kFlushCodec on the first end of stream buffer.
275 if (state_ == kNormal && buffer->end_of_stream()) {
276 state_ = kFlushCodec;
279 if (!FFmpegDecode(buffer)) {
281 decode_cb.Run(kDecodeError, NULL);
285 if (queued_audio_.empty()) {
286 if (state_ == kFlushCodec) {
287 DCHECK(buffer->end_of_stream());
288 state_ = kDecodeFinished;
289 decode_cb.Run(kOk, AudioBuffer::CreateEOSBuffer());
293 decode_cb.Run(kNotEnoughData, NULL);
297 decode_cb.Run(kOk, queued_audio_.front());
298 queued_audio_.pop_front();
301 bool FFmpegAudioDecoder::FFmpegDecode(
302 const scoped_refptr<DecoderBuffer>& buffer) {
303 DCHECK(queued_audio_.empty());
306 av_init_packet(&packet);
307 if (buffer->end_of_stream()) {
311 packet.data = const_cast<uint8*>(buffer->data());
312 packet.size = buffer->data_size();
315 // Each audio packet may contain several frames, so we must call the decoder
316 // until we've exhausted the packet. Regardless of the packet size we always
317 // want to hand it to the decoder at least once, otherwise we would end up
318 // skipping end of stream packets since they have a size of zero.
320 int frame_decoded = 0;
321 const int result = avcodec_decode_audio4(
322 codec_context_.get(), av_frame_.get(), &frame_decoded, &packet);
325 DCHECK(!buffer->end_of_stream())
326 << "End of stream buffer produced an error! "
327 << "This is quite possibly a bug in the audio decoder not handling "
328 << "end of stream AVPackets correctly.";
331 << "Failed to decode an audio frame with timestamp: "
332 << buffer->timestamp().InMicroseconds() << " us, duration: "
333 << buffer->duration().InMicroseconds() << " us, packet size: "
334 << buffer->data_size() << " bytes";
339 // Update packet size and data pointer in case we need to call the decoder
340 // with the remaining bytes from this packet.
341 packet.size -= result;
342 packet.data += result;
344 scoped_refptr<AudioBuffer> output;
345 const int channels = DetermineChannels(av_frame_.get());
347 if (av_frame_->sample_rate != config_.samples_per_second() ||
348 channels != ChannelLayoutToChannelCount(config_.channel_layout()) ||
349 av_frame_->format != av_sample_format_) {
350 DLOG(ERROR) << "Unsupported midstream configuration change!"
351 << " Sample Rate: " << av_frame_->sample_rate << " vs "
352 << config_.samples_per_second()
353 << ", Channels: " << channels << " vs "
354 << ChannelLayoutToChannelCount(config_.channel_layout())
355 << ", Sample Format: " << av_frame_->format << " vs "
356 << av_sample_format_;
358 if (config_.codec() == kCodecAAC &&
359 av_frame_->sample_rate == 2 * config_.samples_per_second()) {
360 MEDIA_LOG(log_cb_) << "Implicit HE-AAC signalling is being used."
361 << " Please use mp4a.40.5 instead of mp4a.40.2 in"
364 // This is an unrecoverable error, so bail out.
365 queued_audio_.clear();
366 av_frame_unref(av_frame_.get());
370 // Get the AudioBuffer that the data was decoded into. Adjust the number
371 // of frames, in case fewer than requested were actually decoded.
372 output = reinterpret_cast<AudioBuffer*>(
373 av_buffer_get_opaque(av_frame_->buf[0]));
375 DCHECK_EQ(ChannelLayoutToChannelCount(config_.channel_layout()),
376 output->channel_count());
377 const int unread_frames = output->frame_count() - av_frame_->nb_samples;
378 DCHECK_GE(unread_frames, 0);
379 if (unread_frames > 0)
380 output->TrimEnd(unread_frames);
382 av_frame_unref(av_frame_.get());
385 // WARNING: |av_frame_| no longer has valid data at this point.
386 const int decoded_frames = frame_decoded ? output->frame_count() : 0;
387 if (IsEndOfStream(result, decoded_frames, buffer)) {
388 DCHECK_EQ(packet.size, 0);
389 queued_audio_.push_back(AudioBuffer::CreateEOSBuffer());
390 } else if (discard_helper_->ProcessBuffers(buffer, output)) {
391 queued_audio_.push_back(output);
393 } while (packet.size > 0);
398 void FFmpegAudioDecoder::ReleaseFFmpegResources() {
399 codec_context_.reset();
403 bool FFmpegAudioDecoder::ConfigureDecoder() {
404 if (!config_.IsValidConfig()) {
405 DLOG(ERROR) << "Invalid audio stream -"
406 << " codec: " << config_.codec()
407 << " channel layout: " << config_.channel_layout()
408 << " bits per channel: " << config_.bits_per_channel()
409 << " samples per second: " << config_.samples_per_second();
413 if (config_.is_encrypted()) {
414 DLOG(ERROR) << "Encrypted audio stream not supported";
418 // Release existing decoder resources if necessary.
419 ReleaseFFmpegResources();
421 // Initialize AVCodecContext structure.
422 codec_context_.reset(avcodec_alloc_context3(NULL));
423 AudioDecoderConfigToAVCodecContext(config_, codec_context_.get());
425 codec_context_->opaque = this;
426 codec_context_->get_buffer2 = GetAudioBuffer;
427 codec_context_->refcounted_frames = 1;
429 AVCodec* codec = avcodec_find_decoder(codec_context_->codec_id);
430 if (!codec || avcodec_open2(codec_context_.get(), codec, NULL) < 0) {
431 DLOG(ERROR) << "Could not initialize audio decoder: "
432 << codec_context_->codec_id;
433 ReleaseFFmpegResources();
434 state_ = kUninitialized;
439 av_frame_.reset(av_frame_alloc());
440 discard_helper_.reset(new AudioDiscardHelper(config_.samples_per_second(),
441 config_.codec_delay()));
442 av_sample_format_ = codec_context_->sample_fmt;
444 if (codec_context_->channels !=
445 ChannelLayoutToChannelCount(config_.channel_layout())) {
446 DLOG(ERROR) << "Audio configuration specified "
447 << ChannelLayoutToChannelCount(config_.channel_layout())
448 << " channels, but FFmpeg thinks the file contains "
449 << codec_context_->channels << " channels";
450 ReleaseFFmpegResources();
451 state_ = kUninitialized;
455 ResetTimestampState();
459 void FFmpegAudioDecoder::ResetTimestampState() {
460 discard_helper_->Reset(config_.codec_delay());