前言
喜大普奔,终于更新啦,上期说到,如何使用ffmpeg+rtmp进行拉流,不熟悉的小伙伴们,可以先看上一期。今天我们要实现的是使用ffmpeg+rtmp拉流,拉完的FLV流,提取出H.264视频,再提取出YUV,再提取出rgb图,最后用opencv处理图像。我的任务是得到rgb图像,从而可以对图像进行处理。
整体流程:rtmp拉流–>FLV–>H.264–>YUV–>RGB–>OPENCV处理
框架示意图:我们要实现下图绿色框部分:
源码
首先说明一下,filter在这里的作用就是从原复用格式中提取出相关的格式,比如FLV包含了H.264与AAC,filter就可以提取出其中的H.264,这里的filter仍使用旧版的api,编译会出现warning,但目前仍可以使用,等有空的时候我再更新代码吧。同样的,这次也是拉芒果台的视频。
main.cpp
:
#include <iostream>
extern "C"
{
#include "libavformat/avformat.h"
#include <libavutil/mathematics.h>
#include <libavutil/time.h>
#include <libavutil/samplefmt.h>
#include <libavcodec/avcodec.h>
};
#include "opencv2/core.hpp"
#include<opencv2/opencv.hpp>
void AVFrame2Img(AVFrame *pFrame, cv::Mat& img);
void Yuv420p2Rgb32(const uchar *yuvBuffer_in, const uchar *rgbBuffer_out, int width, int height);
using namespace std;
using namespace cv;
int main(int argc, char* argv[])
{
AVFormatContext *ifmt_ctx = NULL;
AVPacket pkt;
AVFrame *pframe = NULL;
int ret, i;
int videoindex=-1;
AVCodecContext *pCodecCtx;
AVCodec *pCodec;
const char *in_filename = "rtmp://58.200.131.2:1935/livetv/hunantv"; //芒果台rtmp地址
const char *out_filename_v = "test.h264"; //Output file URL
//Register
av_register_all();
//Network
avformat_network_init();
//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=