如何用FFmpeg将输出的TS流写到内存-程序员宅基地

技术标签: 内存流  ffmpeg  TS  

     最近需要实现一个功能:利用FFmpeg将编码出来的视频流和音频流混合封装成TS格式,然后通过自定义协议将TS流发送出去。因为发送协议是自己定义的,FFmpeg不支持这种网络协议,不能用它内置的协议。后来发现原来FFmpeg也支持将输出的流回调到给上层去处理,下面简单讲一下实现的流程。

    首先,我们按照把流输出到文件的方式来处理,但是有小小的不同,下面是初始化输出流的代码:

AVOutputFormat *m_fmt;
AVFormatContext *m_oc;
AVStream *audio_st, *video_st;
typedef struct _capstuff {

	UINT  m_nPixelFormat; //enum PixelFormat
	int   m_videobitrate; //视频码率
	int   m_audiobitrate; //音频码率
	int   m_audio_samplerate; //音频采样率
	int   m_framerate; //帧率
 	UINT   m_nRCMode; //视频的编码模式,0--CBR, 1--VBR
	UINT   m_StreamType; //0--Video, 1--Audio, 2--Video+Audio
	UINT   m_IFramesIntervals; //关键帧间距
        UINT   m_nVideoCodec;//CodecID
        UINT   m_nAudioCodec; //CodecID
	UINT   m_Quant; //质量系数
	char   m_szFormatName[64]; //流的封装格式,比如TS,MOV,MPG,MP4
	BOOL   m_bDefaultCodec;

}CAPSTUFF;

CAPSTUFF  m_CapStuff[8]; //最多支持8个输入流
BOOL CVideoDevice::InitFFmpeg()
{
  m_fmt = NULL;
  m_oc = NULL;

    /* initialize libavcodec, and register all codecs and formats */
    av_register_all();

   char outputformat[64] = {0};
   strcpy(outputformat, "1.ts"); //默认使用TS

  /* allocate the output media context */
    avformat_alloc_output_context2(&m_oc, NULL, NULL, outputformat);
    if (!m_oc) {
        TRACE("Could not deduce output format from file extension: using MPEG.\n");
        avformat_alloc_output_context2(&m_oc, NULL, "mpeg", "1.mpg");
    }
    if (!m_oc) {
        return FALSE;
    }
    m_fmt = m_oc->oformat;

#if 0
	const char *filename = "D:\\camera_ffmpeg.ts";
	strcpy(m_oc->filename, filename);
#else
	const char *filename = outputformat;
	unsigned char* outbuffer = NULL;
	outbuffer = (unsigned char*)av_malloc(65536);
	AVIOContext *avio_out = avio_alloc_context(outbuffer, 65536, 0, this, NULL, write_buffer,NULL); 
	m_oc->pb = avio_out;
	m_oc->flags |= AVFMT_FLAG_CUSTOM_IO;
    m_oc->flags |= AVFMT_FLAG_FLUSH_PACKETS;
	m_fmt->flags |= AVFMT_NOFILE; //不生成文件
#endif


    /* add the audio and video streams using the default format codecs
       and initialize the codecs */
    video_st = NULL;
    audio_st = NULL;
    if (m_fmt->video_codec != CODEC_ID_NONE) {
	video_st = add_video_stream(m_oc, 
			(CodecID)m_CapStuff[0].m_nVideoCodec, 
			m_CapStuff[0].m_capwidth, m_CapStuff[0].m_capheight,
			m_CapStuff[0].m_videobitrate, m_CapStuff[0].m_framerate, 
			m_CapStuff[0].m_IFramesIntervals);
    }

    if (m_fmt->audio_codec != CODEC_ID_NONE) {
	audio_st = add_audio_stream(m_oc, 
			(CodecID)m_CapStuff[0].m_nAudioCodec, 
			m_CapStuff[0].m_audiobitrate, m_CapStuff[0].m_audio_samplerate, 2);

    }

   //av_dump_format(m_oc, 0, filename, 1);

    /* now that all the parameters are set, we can open the audio and
       video codecs and allocate the necessary encode buffers */
    if (video_st)
        open_video(m_oc, video_st);
    if (audio_st)
        open_audio(m_oc, audio_st);

#if 1
    /* open the output file, if needed */
    if (!(m_fmt->flags & AVFMT_NOFILE))
    {
        if (avio_open(&m_oc->pb, filename, AVIO_FLAG_WRITE) < 0)
        {
            TRACE("Could not open %s\n", filename);
            return FALSE;
        }
    }
#endif

    /* write the stream header, if any */
    avformat_write_header(m_oc, NULL);
      
   return TRUE;
}

    上面的CVideoDevice::InitFFmpeg()函数先生成了一个AVFormatContext类型的输出流上下文对象,并且指定输出格式为TS。然后调用avio_alloc_context函数,关键是这个函数,它指定了对流处理的几个相关的回调函数。

AVIOContext *avio_alloc_context(  
                  unsigned char *buffer,  
                  int buffer_size,  
                  int write_flag,  
                  void *opaque,  
                  int (*read_packet)(void *opaque, uint8_t *buf, int buf_size),//重写该函数,指定从内存中读取的方法,将buf_size字节大小的数据保存到buf  
                  int (*write_packet)(void *opaque, uint8_t *buf, int buf_size),//对应的这是写内存的函数  
                  int64_t (*seek)(void *opaque, int64_t offset, int whence));  

     在我的应用中,需要实现write_packet回调函数,这样FFmpeg输出的流就会通过这个回调函数传递给应用层。下面是我的write_packet回调函数的实现:

int write_buffer(void *opaque, uint8_t *buf, int buf_size)
{
	CVideoDevice * pThisDev = (CVideoDevice*)opaque;

	pThisDev->m_pStreamSender->AddData(buf, buf_size, 0, 1);
	return buf_size;
}

    它只是把传过来的数据送给自己的协议层去处理。

   整个方案的处理流程图如下:

       但是目前还没有完毕,我们要输出TS流必须调用av_interleaved_write_frame将编码器出来的数据写进TS流容器,那么write_packet回调函数才会有数据回调。下面是一段示例的代码:

void CVideoDevice::write_video_frame(AVFormatContext *oc, AVStream *st, PixelFormat pixformat, BYTE * pSrcData, DWORD dbSize, INT64 lTimeStamp)
{
	int out_size, ret = 0;
	AVCodecContext *c;

	c = st->codec;

	int	Y_PLANE_SIZE;
	int	U2_PLANE_SIZE;
	int	V2_PLANE_SIZE;

	Y_PLANE_SIZE  = c->width * c->height;
	U2_PLANE_SIZE = Y_PLANE_SIZE/4;			
	V2_PLANE_SIZE = Y_PLANE_SIZE/4;

	uint8_t  *dest_y = pSrcData;
	uint8_t  *dest_u = pSrcData + Y_PLANE_SIZE;
	uint8_t  *dest_v = pSrcData + Y_PLANE_SIZE + V2_PLANE_SIZE;

	picture->linesize[0] = c->width;
	picture->linesize[1] = c->width / 2;
	picture->linesize[2] = c->width / 2;
	picture->data[0] = dest_y;
	picture->data[1] = dest_v;
	picture->data[2] = dest_u;

	int out_size = avcodec_encode_video(c, video_outbuf, video_outbuf_size, picture);

	if (out_size > 0)
	{
		picture->pts += 1;

		AVPacket pkt;
		av_init_packet(&pkt);
		pkt.data = NULL;
		pkt.size = 0;

		pkt.pts = (INT64)st->time_base.den * (lTimeStamp)/SYSTEM_CLOCK_TIME_BASE; 

		if(c->coded_frame->key_frame)
			pkt.flags |= AV_PKT_FLAG_KEY;

		pkt.stream_index= st->index;
		pkt.data = video_outbuf;
		pkt.size = out_size;

		//TRACE("video pkt.pts: %ld\n",  pkt.pts);

		ret = av_interleaved_write_frame(oc, &pkt);

		//av_free_packet(&pkt);
	}
}

注意:

(1) 上面代码有个问题,如果  avio_alloc_context函数调用写成这样形式:

 avio_alloc_context(outbuffer, 65536, 0, this, NULL, write_buffer,NULL); 

则会卡在av_interleaved_write_frame或av_write_frame函数,并且write_buffer回调没有被调用。

这个问题卡了我好久,后来找到解决办法,解决方法是:将 avio_alloc_context的第三个参数改成1,即改为:

 avio_alloc_context(outbuffer, 65536, 1, this, NULL, write_buffer,NULL); 

这样就可以成功将Muxer输出的数据写到内存。

(2)avio_alloc_context的第二个参数是分配的输出缓冲区大小,如果赋值为65536,则write_buffer函数每次回调传入的字节数都是65536,但是我们可能更希望它写入了每一帧就回调当前帧的数据长度,如果是这样,必须设置AVFMT_FLAG_FLUSH_PACKETS参数,设置示例代码如下:

m_oc->flags |= AVFMT_FLAG_FLUSH_PACKETS;

 

下面给个较为详细的例子(将H264文件转为PS流,并输出到内存):


FILE *file = NULL;

int write_packet(void *opaque, uint8_t *buf, int buf_size)
{
	//printf("write data\n");
	if (file)
		fwrite(buf, buf_size, 1, file);//可以写文件,也可以通过协议发出去
	return 0;
}

//将一个H264文件(或其他格式)转为PS文件
int main(int argc, char **argv)
{
	fopen_s(&file, "output.dat", "ab+");//输出ps数据到文件
	if (file == NULL)
		printf("open output file failed\n");

	AVIOContext* pb = NULL;
	AVOutputFormat *ofmt = (AVOutputFormat*)av_mallocz(sizeof(AVOutputFormat));//输出格式
	AVFormatContext *ifmt_ctx = NULL, *ofmt_ctx = NULL;
	AVPacket pkt;
	const char *in_filename, *out_filename;
	int ret, i;
	in_filename = "hello.h264";//源文件

	av_register_all();

	if ((ret = avformat_open_input(&ifmt_ctx, in_filename, 0, 0)) < 0) {
		fprintf(stderr, "Could not open input file '%s'", in_filename);
		goto end;
	}
	if ((ret = avformat_find_stream_info(ifmt_ctx, 0)) < 0) {
		fprintf(stderr, "Failed to retrieve input stream information");
		goto end;
	}
	av_dump_format(ifmt_ctx, 0, in_filename, 0);

	uint8_t* buf = (uint8_t*)av_mallocz(sizeof(uint8_t)* 32768);
	pb = avio_alloc_context(buf, 32768, 1, NULL, NULL, write_packet, NULL);//注意:第3个参数赋值为1,否则write_packet回调将不能被成功调用

	avformat_alloc_output_context2(&ofmt_ctx, NULL, "dvd", NULL/*out_filename*/);//设置输出视频的格式为Mpegs-ps,在ffmpeg定义为dvd。如果需要输出TS格式,则设置为"mpegts"

	if (!ofmt_ctx) {
		fprintf(stderr, "Could not create output context\n");
		ret = AVERROR_UNKNOWN;
		goto end;
	}
	ofmt_ctx->pb = pb;//这个是关键,指定ps输出的方式
	ofmt_ctx->flags |= AVFMT_FLAG_CUSTOM_IO;

	printf("output format:%s[%s]\n", ofmt_ctx->oformat->name, ofmt_ctx->oformat->long_name);
	ofmt = ofmt_ctx->oformat;
	//输出环境上下文的初始化
	for (i = 0; i < ifmt_ctx->nb_streams; i++) {
		AVStream *in_stream = ifmt_ctx->streams[i];
		//Add a new stream to a media file
		AVStream *out_stream = avformat_new_stream(ofmt_ctx, in_stream->codec->codec);
		if (!out_stream) {
			fprintf(stderr, "Failed allocating output stream\n");
			ret = AVERROR_UNKNOWN;
			goto end;
		}
		ret = avcodec_copy_context(out_stream->codec, in_stream->codec);
		if (ret < 0) {
			fprintf(stderr, "Failed to copy context from input to output stream codec context\n");
			goto end;
		}
		out_stream->codec->codec_tag = 0;
		if (ofmt_ctx->oformat->flags & AVFMT_GLOBALHEADER)
			out_stream->codec->flags |= CODEC_FLAG_GLOBAL_HEADER;
	}
	av_dump_format(ofmt_ctx, 0, NULL, 1);
	ret = avformat_write_header(ofmt_ctx, NULL);
	if (ret < 0) {
		fprintf(stderr, "Error occurred when opening output file\n");
		goto end;
	}

	int nVideoFramesNum = 0;

	//实现REMUXING
	while (1) {
		AVStream *in_stream, *out_stream;
		ret = av_read_frame(ifmt_ctx, &pkt);
		if (ret < 0)
			break;
		in_stream = ifmt_ctx->streams[pkt.stream_index];
		out_stream = ofmt_ctx->streams[pkt.stream_index];

		if(in_stream->codec->codec_type == AVMEDIA_TYPE_VIDEO)
		{ 
			if(pkt.pts == AV_NOPTS_VALUE) //FIX:No PTS (Example: Raw H.264) 
			{
				AVRational time_base1 = out_stream->time_base; 

				//Duration between 2 frames (us) 
				int64_t calc_duration =(double)AV_TIME_BASE/av_q2d(in_stream->r_frame_rate); 

				pkt.pts = (double)(nVideoFramesNum*calc_duration)/(double)(av_q2d(time_base1)*AV_TIME_BASE); 
				pkt.dts = pkt.pts; 
				pkt.duration = (double)calc_duration/(double)(av_q2d(time_base1)*AV_TIME_BASE); 
			}
			else
			{
				pkt.pts = av_rescale_q_rnd(pkt.pts, in_stream->time_base, out_stream->time_base, (AVRounding)(AV_ROUND_NEAR_INF | AV_ROUND_PASS_MINMAX));
				pkt.dts = av_rescale_q_rnd(pkt.dts, in_stream->time_base, out_stream->time_base, (AVRounding)(AV_ROUND_NEAR_INF | AV_ROUND_PASS_MINMAX));
				pkt.duration = av_rescale_q(pkt.duration, in_stream->time_base, out_stream->time_base);
				pkt.pos = -1;
			}
			  
			nVideoFramesNum++;
		}
		else
		{
			pkt.pts = av_rescale_q_rnd(pkt.pts, in_stream->time_base, out_stream->time_base, (AVRounding)(AV_ROUND_NEAR_INF | AV_ROUND_PASS_MINMAX));
			pkt.dts = av_rescale_q_rnd(pkt.dts, in_stream->time_base, out_stream->time_base, (AVRounding)(AV_ROUND_NEAR_INF | AV_ROUND_PASS_MINMAX));
			pkt.duration = av_rescale_q(pkt.duration, in_stream->time_base, out_stream->time_base);
			pkt.pos = -1;
		}
      

		ret = av_interleaved_write_frame(ofmt_ctx, &pkt);
		if (ret < 0) {
			fprintf(stderr, "Error muxing packet\n");
			break;
		}
		av_free_packet(&pkt);
	}
	av_write_trailer(ofmt_ctx);
end:
	avformat_close_input(&ifmt_ctx);
	/* close output */
	if (ofmt_ctx && !(ofmt->flags & AVFMT_NOFILE))
		avio_close(ofmt_ctx->pb);
	avformat_free_context(ofmt_ctx);
	if (ret < 0 && ret != AVERROR_EOF) {
		return 1;
	}
	return 0;
}

(反过来的情况:如何让FFmpeg从内存中读取PS/TS流数据,以及怎么分离和解码视频可参考我的另外一篇博文:http://blog.csdn.net/zhoubotong2012/article/details/79349359)

 

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/zhoubotong2012/article/details/79344000

智能推荐

Docker 快速上手学习入门教程_docker菜鸟教程-程序员宅基地

文章浏览阅读2.5w次,点赞6次,收藏50次。官方解释是,docker 容器是机器上的沙盒进程,它与主机上的所有其他进程隔离。所以容器只是操作系统中被隔离开来的一个进程,所谓的容器化,其实也只是对操作系统进行欺骗的一种语法糖。_docker菜鸟教程

电脑技巧:Windows系统原版纯净软件必备的两个网站_msdn我告诉你-程序员宅基地

文章浏览阅读5.7k次,点赞3次,收藏14次。该如何避免的,今天小编给大家推荐两个下载Windows系统官方软件的资源网站,可以杜绝软件捆绑等行为。该站提供了丰富的Windows官方技术资源,比较重要的有MSDN技术资源文档库、官方工具和资源、应用程序、开发人员工具(Visual Studio 、SQLServer等等)、系统镜像、设计人员工具等。总的来说,这两个都是非常优秀的Windows系统镜像资源站,提供了丰富的Windows系统镜像资源,并且保证了资源的纯净和安全性,有需要的朋友可以去了解一下。这个非常实用的资源网站的创建者是国内的一个网友。_msdn我告诉你

vue2封装对话框el-dialog组件_<el-dialog 封装成组件 vue2-程序员宅基地

文章浏览阅读1.2k次。vue2封装对话框el-dialog组件_

MFC 文本框换行_c++ mfc同一框内输入二行怎么换行-程序员宅基地

文章浏览阅读4.7k次,点赞5次,收藏6次。MFC 文本框换行 标签: it mfc 文本框1.将Multiline属性设置为True2.换行是使用"\r\n" (宽字符串为L"\r\n")3.如果需要编辑并且按Enter键换行,还要将 Want Return 设置为 True4.如果需要垂直滚动条的话将Vertical Scroll属性设置为True,需要水平滚动条的话将Horizontal Scroll属性设_c++ mfc同一框内输入二行怎么换行

redis-desktop-manager无法连接redis-server的解决方法_redis-server doesn't support auth command or ismis-程序员宅基地

文章浏览阅读832次。检查Linux是否是否开启所需端口,默认为6379,若未打开,将其开启:以root用户执行iptables -I INPUT -p tcp --dport 6379 -j ACCEPT如果还是未能解决,修改redis.conf,修改主机地址:bind 192.168.85.**;然后使用该配置文件,重新启动Redis服务./redis-server redis.conf..._redis-server doesn't support auth command or ismisconfigured. try

实验四 数据选择器及其应用-程序员宅基地

文章浏览阅读4.9k次。济大数电实验报告_数据选择器及其应用

随便推点

灰色预测模型matlab_MATLAB实战|基于灰色预测河南省社会消费品零售总额预测-程序员宅基地

文章浏览阅读236次。1研究内容消费在生产中占据十分重要的地位,是生产的最终目的和动力,是保持省内经济稳定快速发展的核心要素。预测河南省社会消费品零售总额,是进行宏观经济调控和消费体制改变创新的基础,是河南省内人民对美好的全面和谐社会的追求的要求,保持河南省经济稳定和可持续发展具有重要意义。本文建立灰色预测模型,利用MATLAB软件,预测出2019年~2023年河南省社会消费品零售总额预测值分别为21881...._灰色预测模型用什么软件

log4qt-程序员宅基地

文章浏览阅读1.2k次。12.4-在Qt中使用Log4Qt输出Log文件,看这一篇就足够了一、为啥要使用第三方Log库,而不用平台自带的Log库二、Log4j系列库的功能介绍与基本概念三、Log4Qt库的基本介绍四、将Log4qt组装成为一个单独模块五、使用配置文件的方式配置Log4Qt六、使用代码的方式配置Log4Qt七、在Qt工程中引入Log4Qt库模块的方法八、获取示例中的源代码一、为啥要使用第三方Log库,而不用平台自带的Log库首先要说明的是,在平时开发和调试中开发平台自带的“打印输出”已经足够了。但_log4qt

100种思维模型之全局观思维模型-67_计算机中对于全局观的-程序员宅基地

文章浏览阅读786次。全局观思维模型,一个教我们由点到线,由线到面,再由面到体,不断的放大格局去思考问题的思维模型。_计算机中对于全局观的

线程间控制之CountDownLatch和CyclicBarrier使用介绍_countdownluach于cyclicbarrier的用法-程序员宅基地

文章浏览阅读330次。一、CountDownLatch介绍CountDownLatch采用减法计算;是一个同步辅助工具类和CyclicBarrier类功能类似,允许一个或多个线程等待,直到在其他线程中执行的一组操作完成。二、CountDownLatch俩种应用场景: 场景一:所有线程在等待开始信号(startSignal.await()),主流程发出开始信号通知,既执行startSignal.countDown()方法后;所有线程才开始执行;每个线程执行完发出做完信号,既执行do..._countdownluach于cyclicbarrier的用法

自动化监控系统Prometheus&Grafana_-自动化监控系统prometheus&grafana实战-程序员宅基地

文章浏览阅读508次。Prometheus 算是一个全能型选手,原生支持容器监控,当然监控传统应用也不是吃干饭的,所以就是容器和非容器他都支持,所有的监控系统都具备这个流程,_-自动化监控系统prometheus&grafana实战

React 组件封装之 Search 搜索_react search-程序员宅基地

文章浏览阅读4.7k次。输入关键字,可以通过键盘的搜索按钮完成搜索功能。_react search