解复用FLV文件(基于FFMPEG解析FLV(h264+aac))

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/hiwubihe/article/details/82346759

技术在于交流、沟通,转载请注明出处并保持作品的完整性。

原文: https://blog.csdn.net/hiwubihe/article/details/82346759

[本系列相关文章]

本篇介绍基于FFMPEG解析FLV文件,FLV由H264视频和AAC音频组成。FFMPEG 解复用出的音视频AVPacket,直接写入文件播放不了。FLV格式最常用的封装组合就是H264+AAC,FFMPEG解复用的结果AVPacket只包含实际的压缩音视频数据,不包括解码必须的信息,H264的SPS+PPS,AAC的视频头ADTS等。这就需要从FLV中提取SPS+PPS信息,和ADTS信息加到音视频帧前面。

1.FLV文件AVCDecoderConfigurationRecord

封装FLV,一般第一个VideoTag就是AVCDecoderConfigurationRecord结构,该结构就是H264的SPS+PPS信息

 AVCDecoderConfigurationRecord定义如下

aligned(8) class AVCDecoderConfigurationRecord {
	unsigned int(8) configurationVersion = 1;
	unsigned int(8) AVCProfileIndication;
	unsigned int(8) profile_compatibility;
	unsigned int(8) AVCLevelIndication; 
	bit(6) reserved = ‘111111’b;
	unsigned int(2) lengthSizeMinusOne; 
	bit(3) reserved = ‘111’b;
	unsigned int(5) numOfSequenceParameterSets;
	for (i=0; i< numOfSequenceParameterSets;  i++) {
		unsigned int(16) sequenceParameterSetLength ;
		bit(8*sequenceParameterSetLength) sequenceParameterSetNALUnit;
	}
	unsigned int(8) numOfPictureParameterSets;
	for (i=0; i< numOfPictureParameterSets;  i++) {
		unsigned int(16) pictureParameterSetLength;
		bit(8*pictureParameterSetLength) pictureParameterSetNALUnit;
	}
	bit(6) reserved = ‘111111’b;
	unsigned int(2) chroma_format;
	bit(5) reserved = ‘11111’b;
	unsigned int(3) bit_depth_luma_minus8;
	bit(5) reserved = ‘11111’b;
	unsigned int(3) bit_depth_chroma_minus8;
	unsigned int(8) numOfSequenceParameterSetExt;
	for (i=0; i< numOfSequenceParameterSetExt; i++) {
		unsigned int(16) sequenceParameterSetExtLength;
		bit(8*sequenceParameterSetExtLength) sequenceParameterSetExtNALUnit;
	}
}

2.FLV文件AudioSpecificConfig


封装FLV,一般第一个AudioTag就是AudioSpecificConfig结构,该结构就是AAC封装头ADTS需要的信息,采样率,通道数,样本深度等信息。

 AudioSpecificConfig在所有封装AAC的文件结构中都有,如FLV/MP4。 AudioSpecificConfig结构比较复杂。一般结构就是2个字节。在MP4文件中一般叫AES,一般结构如下表                                     

总体结构
5 bits: object type
if (object type == 31)
    6 bits + 32: object type
4 bits: frequency index
if (frequency index == 15)
    24 bits: frequency
4 bits: channel configuration
var bits: AOT Specific Config
ObjectType
  • 0: Null
  • 1: AAC Main
  • 2: AAC LC (Low Complexity)
  • 3: AAC SSR (Scalable Sample Rate)
  • 4: AAC LTP (Long Term Prediction)
  • 5: SBR (Spectral Band Replication)
  • 6: AAC Scalable
  • 7: TwinVQ
  • 8: CELP (Code Excited Linear Prediction)
  • 9: HXVC (Harmonic Vector eXcitation Coding)
  • 10: Reserved
  • 11: Reserved
  • 12: TTSI (Text-To-Speech Interface)
  • 13: Main Synthesis
  • 14: Wavetable Synthesis
  • 15: General MIDI
  • 16: Algorithmic Synthesis and Audio Effects
  • 17: ER (Error Resilient) AAC LC
  • 18: Reserved
  • 19: ER AAC LTP
  • 20: ER AAC Scalable
  • 21: ER TwinVQ
  • 22: ER BSAC (Bit-Sliced Arithmetic Coding)
  • 23: ER AAC LD (Low Delay)
  • 24: ER CELP
  • 25: ER HVXC
  • 26: ER HILN (Harmonic and Individual Lines plus Noise)
  • 27: ER Parametric
  • 28: SSC (SinuSoidal Coding)
  • 29: PS (Parametric Stereo)
  • 30: MPEG Surround
  • 31: (Escape value)
  • 32: Layer-1
  • 33: Layer-2
  • 34: Layer-3
  • 35: DST (Direct Stream Transfer)
  • 36: ALS (Audio Lossless)
  • 37: SLS (Scalable LosslesS)
  • 38: SLS non-core
  • 39: ER AAC ELD (Enhanced Low Delay)
  • 40: SMR (Symbolic Music Representation) Simple
  • 41: SMR Main
  • 42: USAC (Unified Speech and Audio Coding) (no SBR)
  • 43: SAOC (Spatial Audio Object Coding)
  • 44: LD MPEG Surround
  • 45: USAC
采样率索引
  • 0: 96000 Hz
  • 1: 88200 Hz
  • 2: 64000 Hz
  • 3: 48000 Hz
  • 4: 44100 Hz
  • 5: 32000 Hz
  • 6: 24000 Hz
  • 7: 22050 Hz
  • 8: 16000 Hz
  • 9: 12000 Hz
  • 10: 11025 Hz
  • 11: 8000 Hz
  • 12: 7350 Hz
  • 13: Reserved
  • 14: Reserved
  • 15: frequency is written explictly
Channels
  • 0: Defined in AOT Specifc Config
  • 1: 1 channel: front-center
  • 2: 2 channels: front-left, front-right
  • 3: 3 channels: front-center, front-left, front-right
  • 4: 4 channels: front-center, front-left, front-right, back-center
  • 5: 5 channels: front-center, front-left, front-right, back-left, back-right
  • 6: 6 channels: front-center, front-left, front-right, back-left, back-right, LFE-channel
  • 7: 8 channels: front-center, front-left, front-right, side-left, side-right, back-left, back-right, LFE-channel
  • 8-15: Reserved

解析AES代码

typedef struct  

{
	int write_adts;  
	int objecttype;  
	int sample_rate_index;  
	int channel_conf;  

}ADTSContext;

int aac_decode_extradata(ADTSContext *adts, unsigned char *pbuf, int bufsize)  
{  
	int aot, aotext, samfreindex;  
	int i, channelconfig;  
	unsigned char *p = pbuf;  
	if (!adts || !pbuf || bufsize<2)  
	{  
		return -1;  
	}  
	aot = (p[0]>>3)&0x1f;  
	if (aot == 31)  
	{  
		aotext = (p[0]<<3 | (p[1]>>5)) & 0x3f;  
		aot = 32 + aotext;  
		samfreindex = (p[1]>>1) & 0x0f;   
		if (samfreindex == 0x0f)  
		{  
			channelconfig = ((p[4]<<3) | (p[5]>>5)) & 0x0f;  
		}  
		else  
		{  
			channelconfig = ((p[1]<<3)|(p[2]>>5)) & 0x0f;  
		}  
	}  
	else  
	{  
		samfreindex = ((p[0]<<1)|p[1]>>7) & 0x0f;  
		if (samfreindex == 0x0f)  
		{  
			channelconfig = (p[4]>>3) & 0x0f;  
		}  
		else  
		{  
			channelconfig = (p[1]>>3) & 0x0f;  
		}  
	}  
#ifdef AOT_PROFILE_CTRL  
	if (aot < 2) aot = 2;  
#endif  
	adts->objecttype = aot-1;  
	adts->sample_rate_index = samfreindex;  
	adts->channel_conf = channelconfig;  
	adts->write_adts = 1;  
	return 0;  
}  

构造AES代码

//获取音频AES值
bool GetDecoderSpecificInfo(AdtsHeadInfo stAdtsHeadInfo,unsigned char*pBuffer,unsigned long &lSizeOfDecoderSpecificInfo)
{

	lSizeOfDecoderSpecificInfo = 2;
	memset(pBuffer,0,lSizeOfDecoderSpecificInfo);
	bits_buffer_t bw;

	bits_initwrite (&bw, lSizeOfDecoderSpecificInfo, pBuffer);
	bits_write (&bw, 5, stAdtsHeadInfo.iProfile);
	bits_write (&bw, 4, stAdtsHeadInfo.iSampleRateIndex);
	bits_write (&bw, 4, stAdtsHeadInfo.iChans);

	memcpy(pBuffer, bw.p_data, lSizeOfDecoderSpecificInfo);
	

	return true;
	
}

3.FFMPEG处理原理

在av_read_frame函数调用中,如果读到AVCDecoderConfigurationRecord或者AudioSpecificConfig结构时,会把信息保存在每个stream的streams[index]->codec->extradata扩展数据中。处理H264数据时,提供一个叫 “h264_mp4toannexb”比特流过滤器,在av_read_frame读取到正常数据包时,需要调用比特流过滤器处理每个数据包,其实就是判断是否是I帧,是I帧的话,解析AVCDecoderConfigurationRecord结构成SPS+PPS,然后把SPS+PPS保存加到I帧前面。可以参考FFMPEG源码,版本3.2.4.r86064。下面代码就是循环处理接受到的数据,添加SPS/PPS。

static int h264_mp4toannexb_filter(AVBSFContext *ctx, AVPacket *out)
{
    H264BSFContext *s = ctx->priv_data;

    AVPacket *in;
    uint8_t unit_type;
    int32_t nal_size;
    uint32_t cumul_size    = 0;
    const uint8_t *buf;
    const uint8_t *buf_end;
    int            buf_size;
    int ret = 0, i;

    //读取的数据包复制到in
    ret = ff_bsf_get_packet(ctx, &in);
    if (ret < 0)
        return ret;

    /* nothing to filter */
    //不需要过滤 直接赋值
    if (!s->extradata_parsed)
    {
        av_packet_move_ref(out, in);
        av_packet_free(&in);
        return 0;
    }

    buf      = in->data;
    buf_size = in->size;
    buf_end  = in->data + in->size;

    do
    {
        ret= AVERROR(EINVAL);
        //长度错误
        if (buf + s->length_size > buf_end)
            goto fail;
        //获取NALU长度
        for (nal_size = 0, i = 0; i<s->length_size; i++)
            nal_size = (nal_size << 8) | buf[i];
        //向后移动s->length_size
        buf += s->length_size;
        //NALU type
        unit_type = *buf & 0x1f;
        //长度出错
        if (nal_size > buf_end - buf || nal_size < 0)
            goto fail;
        //SPS数据 新的IDR标志 SPS直接拷贝加到缓存中
        if (unit_type == 7)
            s->idr_sps_seen = s->new_idr = 1;
        //PPS数据 新的IDR标志
        else if (unit_type == 8)
        {
            s->idr_pps_seen = s->new_idr = 1;
            /* if SPS has not been seen yet, prepend the AVCC one to PPS */
            //当前是收到pps包 前面却没有SPS包,需要从扩展数据中把SPS加上
            //如果有sps 直接走到 一般数据拷贝else
            if (!s->idr_sps_seen)
            {
                if (s->sps_offset == -1)
                    av_log(ctx, AV_LOG_WARNING, "SPS not present in the stream, nor in AVCC, stream may be unreadable\n");
                else
                {
                    //把sps和pps 都拷贝到数据缓存中
                    if ((ret = alloc_and_copy(out,
                                              ctx->par_out->extradata + s->sps_offset,
                                              s->pps_offset != -1 ? s->pps_offset : ctx->par_out->extradata_size - s->sps_offset,
                                              buf, nal_size)) < 0)
                        goto fail;
                    s->idr_sps_seen = 1;
                    goto next_nal;
                }
            }
        }

        /* if this is a new IDR picture following an IDR picture, reset the idr flag.
         * Just check first_mb_in_slice to be 0 as this is the simplest solution.
         * This could be checking idr_pic_id instead, but would complexify the parsing. */
        if (!s->new_idr && unit_type == 5 && (buf[1] & 0x80))
            s->new_idr = 1;

        /* prepend only to the first type 5 NAL unit of an IDR picture, if no sps/pps are already present */
        //新的IDR
        if (s->new_idr && unit_type == 5 && !s->idr_sps_seen && !s->idr_pps_seen)
        {
            if ((ret=alloc_and_copy(out,
                                    ctx->par_out->extradata, ctx->par_out->extradata_size,
                                    buf, nal_size)) < 0)
                goto fail;
            s->new_idr = 0;
            /* if only SPS has been seen, also insert PPS */
        }
        else if (s->new_idr && unit_type == 5 && s->idr_sps_seen && !s->idr_pps_seen)
        {
            if (s->pps_offset == -1)
            {
                av_log(ctx, AV_LOG_WARNING, "PPS not present in the stream, nor in AVCC, stream may be unreadable\n");
                if ((ret = alloc_and_copy(out, NULL, 0, buf, nal_size)) < 0)
                    goto fail;
            }
            else if ((ret = alloc_and_copy(out,
                                           ctx->par_out->extradata + s->pps_offset, ctx->par_out->extradata_size - s->pps_offset,
                                           buf, nal_size)) < 0)
                goto fail;
        }
        else
        {
            if ((ret=alloc_and_copy(out, NULL, 0, buf, nal_size)) < 0)
                goto fail;
            if (!s->new_idr && unit_type == 1)
            {
                s->new_idr = 1;
                s->idr_sps_seen = 0;
                s->idr_pps_seen = 0;
            }
        }

next_nal:
        buf        += nal_size;
        cumul_size += nal_size + s->length_size;
    }
    while (cumul_size < buf_size);

    ret = av_packet_copy_props(out, in);
    if (ret < 0)
        goto fail;

fail:
    if (ret < 0)
        av_packet_unref(out);
    av_packet_free(&in);

    return ret;
}

4.解析AudioSpecificConfig

AAC也会把AudioSpecificConfig保存到streams[index]->codec->extradata扩展数据中,但是FFMPEG 没有提供加ADTS的比特流过滤器,需要自己解析AudioSpecificConfig,然后添加到AAC帧前面。

//解析AudioSpecificConfig
int aac_decode_extradata(ADTSContext *adts, unsigned char *pbuf, int bufsize)  
{  
	int aot, aotext, samfreindex;  
	int i, channelconfig;  
	unsigned char *p = pbuf;  
	if (!adts || !pbuf || bufsize<2)  
	{  
		return -1;  
	}  
	aot = (p[0]>>3)&0x1f;  
	if (aot == 31)  
	{  
		aotext = (p[0]<<3 | (p[1]>>5)) & 0x3f;  
		aot = 32 + aotext;  
		samfreindex = (p[1]>>1) & 0x0f;   
		if (samfreindex == 0x0f)  
		{  
			channelconfig = ((p[4]<<3) | (p[5]>>5)) & 0x0f;  
		}  
		else  
		{  
			channelconfig = ((p[1]<<3)|(p[2]>>5)) & 0x0f;  
		}  
	}  
	else  
	{  
		samfreindex = ((p[0]<<1)|p[1]>>7) & 0x0f;  
		if (samfreindex == 0x0f)  
		{  
			channelconfig = (p[4]>>3) & 0x0f;  
		}  
		else  
		{  
			channelconfig = (p[1]>>3) & 0x0f;  
		}  
	}  
#ifdef AOT_PROFILE_CTRL  
	if (aot < 2) aot = 2;  
#endif  
	adts->objecttype = aot-1;  
	adts->sample_rate_index = samfreindex;  
	adts->channel_conf = channelconfig;  
	adts->write_adts = 1;  
	return 0;  
}  

5.DEMO程序

程序运用ffmpeg把h264+aac封装的FLV,解复用成两个文件,h264文件和AAC文件。

/*******************************************************************************
Copyright (c) wubihe Tech. Co., Ltd. All rights reserved.
--------------------------------------------------------------------------------

Date Created:	2014-10-25
Author:			wubihe QQ:1269122125 Email:[email protected]
Description:	解复用flv保存成h264文件和aac文件
--------------------------------------------------------------------------------
Modification History
DATE          AUTHOR          DESCRIPTION
--------------------------------------------------------------------------------

********************************************************************************/

#include <stdio.h>

#define __STDC_CONSTANT_MACROS


extern "C"
{
#include "libavformat/avformat.h"
};



//封装格式MKV/MP4/FLV中如果有AAC的情况,首先这些封装格式中包含AudioSpecificConfig,
//保存在音频流的AVCodecContext->extradata 里面,需要解析然后封装ADTS即可



#define DEMUXER_AAC 1
#define DEMUXER_MP3 0

#define  ADTS_HEADER_SIZE (7)

//FLV封装音视频 AAC封装在第一个AAC TAG会封装一个AudioSpecificConfig结构 
//AudioSpecificConfig解析结果保存在该结构体中
typedef struct  
{
	int write_adts;  
	int objecttype;  
	int sample_rate_index;  
	int channel_conf;  

}ADTSContext;  


//解析AudioSpecificConfig
int aac_decode_extradata(ADTSContext *adts, unsigned char *pbuf, int bufsize)  
{  
	int aot, aotext, samfreindex;  
	int i, channelconfig;  
	unsigned char *p = pbuf;  
	if (!adts || !pbuf || bufsize<2)  
	{  
		return -1;  
	}  
	aot = (p[0]>>3)&0x1f;  
	if (aot == 31)  
	{  
		aotext = (p[0]<<3 | (p[1]>>5)) & 0x3f;  
		aot = 32 + aotext;  
		samfreindex = (p[1]>>1) & 0x0f;   
		if (samfreindex == 0x0f)  
		{  
			channelconfig = ((p[4]<<3) | (p[5]>>5)) & 0x0f;  
		}  
		else  
		{  
			channelconfig = ((p[1]<<3)|(p[2]>>5)) & 0x0f;  
		}  
	}  
	else  
	{  
		samfreindex = ((p[0]<<1)|p[1]>>7) & 0x0f;  
		if (samfreindex == 0x0f)  
		{  
			channelconfig = (p[4]>>3) & 0x0f;  
		}  
		else  
		{  
			channelconfig = (p[1]>>3) & 0x0f;  
		}  
	}  
#ifdef AOT_PROFILE_CTRL  
	if (aot < 2) aot = 2;  
#endif  
	adts->objecttype = aot-1;  
	adts->sample_rate_index = samfreindex;  
	adts->channel_conf = channelconfig;  
	adts->write_adts = 1;  
	return 0;  
}  

//添加ADTS头
int aac_set_adts_head(ADTSContext *acfg, unsigned char *buf, int size)  
{         
	unsigned char byte;    
	if (size < ADTS_HEADER_SIZE)  
	{  
		return -1;  
	}       
	buf[0] = 0xff;  
	buf[1] = 0xf1;  
	byte = 0;  
	byte |= (acfg->objecttype & 0x03) << 6;  
	byte |= (acfg->sample_rate_index & 0x0f) << 2;  
	byte |= (acfg->channel_conf & 0x07) >> 2;  
	buf[2] = byte;  
	byte = 0;  
	byte |= (acfg->channel_conf & 0x07) << 6;  
	byte |= (ADTS_HEADER_SIZE + size) >> 11;  
	buf[3] = byte;  
	byte = 0;  
	byte |= (ADTS_HEADER_SIZE + size) >> 3;  
	buf[4] = byte;  
	byte = 0;  
	byte |= ((ADTS_HEADER_SIZE + size) & 0x7) << 5;  
	byte |= (0x7ff >> 6) & 0x1f;  
	buf[5] = byte;  
	byte = 0;  
	byte |= (0x7ff & 0x3f) << 2;  
	buf[6] = byte;     
	return 0;  
}  






int main(int argc, char* argv[])
{

	AVFormatContext *ifmt_ctx = NULL;
	AVPacket pkt;
	int ret, i;
	int videoindex=-1,audioindex=-1;
	#if DEMUXER_AAC
	const char *in_filename    = "titanic.flv";		//Input file URL
	const char *out_filename_v = "titanic.h264";	//Output file URL
	const char *out_filename_a = "titanic.aac";
	#endif

	#if DEMUXER_MP3
	const char *in_filename    = "titanic.flv";		//Input file URL
	const char *out_filename_v = "titanic.h264";	//Output file URL
	const char *out_filename_a = "titanic.mp3";
	#endif




	av_register_all();
	//Input
	if ((ret = avformat_open_input(&ifmt_ctx, in_filename, 0, 0)) < 0) 
	{
		printf( "Could not open input file.");
		return -1;
	}
	if ((ret = avformat_find_stream_info(ifmt_ctx, 0)) < 0) 
	{
		printf( "Failed to retrieve input stream information");
		return -1;
	}

	videoindex=-1;
	for(i=0; i<ifmt_ctx->nb_streams; i++) 
	{
		if(ifmt_ctx->streams[i]->codec->codec_type==AVMEDIA_TYPE_VIDEO)
		{
			videoindex=i;
		}else if(ifmt_ctx->streams[i]->codec->codec_type==AVMEDIA_TYPE_AUDIO)
		{
			audioindex=i;
		}
	}

	FILE *fp_audio=fopen(out_filename_a,"wb+");  
	FILE *fp_video=fopen(out_filename_v,"wb+");  

	//FLV/MP4/MKV等结构中,h264需要h264_mp4toannexb处理。添加SPS/PPS等信息。FLV封装时,可以把
	//多个NALU放在一个VIDEO TAG中,结构为4B NALU长度+NALU1+4B NALU长度+NALU2+...,需要做的处理把4B
	//长度换成00000001或者000001

	AVBitStreamFilterContext* h264bsfc =  av_bitstream_filter_init("h264_mp4toannexb"); 

#if DEMUXER_AAC
	ADTSContext stADTSContext;
	unsigned char pAdtsHead[7];
#endif

	while(av_read_frame(ifmt_ctx, &pkt)>=0)
	{
		if(pkt.stream_index==videoindex)
		{

			av_bitstream_filter_filter(h264bsfc, ifmt_ctx->streams[videoindex]->codec, NULL, &pkt.data, &pkt.size, pkt.data, pkt.size, 0);

			printf("Write Video Packet. size:%d\tpts:%lld\n",pkt.size,pkt.pts);
			fwrite(pkt.data,1,pkt.size,fp_video);
		}
		else if(pkt.stream_index==audioindex)
		{
			//AAC在封装结构MKV/FLV/MP4结构中,需要手动添加ADTS
	#if DEMUXER_AAC
			aac_decode_extradata(&stADTSContext, ifmt_ctx->streams[audioindex]->codec->extradata, ifmt_ctx->streams[audioindex]->codec->extradata_size);
			aac_set_adts_head(&stADTSContext, pAdtsHead, pkt.size);
			fwrite(pAdtsHead, 1, 7, fp_audio);
	#endif
			//一般结构如MP3直接写文件即可
			
			printf("Write Audio Packet. size:%d\tpts:%lld\n",pkt.size,pkt.pts);
			fwrite(pkt.data,1,pkt.size,fp_audio);
		}
		av_free_packet(&pkt);
	}


	av_bitstream_filter_close(h264bsfc);  


	fclose(fp_video);
	fclose(fp_audio);

	avformat_close_input(&ifmt_ctx);

	if (ret < 0 && ret != AVERROR_EOF) 
	{
		printf( "Error occurred.\n");
		return -1;
	}
	return 0;
}


6.运行结果

生成titanic.h264和titanic.aac两个文件,用ffplay.exe可以验证播放。


编译环境:   Win7_64bit+VS2008

DEMO下载地址:https://download.csdn.net/download/hiwubihe/10643142

猜你喜欢

转载自blog.csdn.net/hiwubihe/article/details/82346759
FLV