1 // Copyright 2012 The Chromium Authors
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_h264_to_annex_b_bitstream_converter.h"
9 #include "base/logging.h"
10 #include "media/ffmpeg/ffmpeg_common.h"
11 #include "media/formats/mp4/box_definitions.h"
15 FFmpegH264ToAnnexBBitstreamConverter::FFmpegH264ToAnnexBBitstreamConverter(
16 AVCodecParameters* stream_codec_parameters)
17 : configuration_processed_(false),
18 stream_codec_parameters_(stream_codec_parameters) {
19 CHECK(stream_codec_parameters_);
22 FFmpegH264ToAnnexBBitstreamConverter::~FFmpegH264ToAnnexBBitstreamConverter() =
25 bool FFmpegH264ToAnnexBBitstreamConverter::ConvertPacket(AVPacket* packet) {
26 std::unique_ptr<mp4::AVCDecoderConfigurationRecord> avc_config;
28 if (packet == NULL || !packet->data) {
29 DVLOG(2) << __func__ << ": Null or empty packet";
33 // Calculate the needed output buffer size.
34 if (!configuration_processed_) {
35 if (!stream_codec_parameters_->extradata ||
36 stream_codec_parameters_->extradata_size <= 0) {
37 DVLOG(2) << __func__ << ": Empty extra data";
41 avc_config = std::make_unique<mp4::AVCDecoderConfigurationRecord>();
43 if (!converter_.ParseConfiguration(stream_codec_parameters_->extradata,
44 stream_codec_parameters_->extradata_size,
46 DVLOG(2) << __func__ << ": ParseConfiguration() failure";
51 uint32_t output_packet_size = converter_.CalculateNeededOutputBufferSize(
52 packet->data, packet->size, avc_config.get());
54 if (output_packet_size == 0) {
55 DVLOG(2) << __func__ << ": zero |output_packet_size|";
56 return false; // Invalid input packet.
59 // Allocate new packet for the output.
61 if (av_new_packet(&dest_packet, output_packet_size) != 0) {
62 DVLOG(2) << __func__ << ": Memory allocation failure";
66 // This is a bit tricky: since the interface does not allow us to replace
67 // the pointer of the old packet with a new one, we will initially copy the
68 // metadata from old packet to new bigger packet.
69 av_packet_copy_props(&dest_packet, packet);
71 // Proceed with the conversion of the actual in-band NAL units, leave room
72 // for configuration in the beginning.
73 uint32_t io_size = dest_packet.size;
74 if (!converter_.ConvertNalUnitStreamToByteStream(
75 packet->data, packet->size,
77 dest_packet.data, &io_size)) {
78 DVLOG(2) << __func__ << ": ConvertNalUnitStreamToByteStream() failure";
83 configuration_processed_ = true;
85 // At the end we must destroy the old packet.
86 av_packet_unref(packet);
88 // Finally, replace the values in the input packet.
89 memcpy(packet, &dest_packet, sizeof(*packet));