void Init()
{
av_register_all();
avfilter_register_all();
avformat_network_init();
av_log_set_level(AV_LOG_ERROR);
}
二. 打开rtmp视频流
int OpenInput(char *fileName)
{
context = avformat_alloc_context();
int ret = avformat_open_input(&context, fileName, nullptr,nullptr);
if(ret <0)
{
return ret;
}
ret = avformat_find_stream_info(context,nullptr);
auto codecContext = context->streams[0]->codec;
ret = avcodec_open2(codecContext, avcodec_find_decoder(codecContext->codec_id), nullptr);
return ret;
}
三. 创建输出流
int OpenOutput(char *fileName)
{
int ret = 0;
ret = avformat_alloc_output_context2(&outputContext, nullptr, "flv", fileName);
if(ret <0)
{
goto Error;
}
ret = avio_open2(&outputContext->pb, fileName, AVIO_FLAG_READ_WRITE,nullptr, nullptr);
if(ret <0)
{
goto Error;
}
for(int i = 0; i nb_streams; i++)
{
AVStream * stream = avformat_new_stream(outputContext, nullptr);
ret = avcodec_copy_context(stream->codec, context->streams[i]->codec); if(ret <0)
{
goto Error;
}
}
ret = avformat_write_header(outputContext, nullptr);
if(ret <0)
{
goto Error;
}
return ret ;
Error:
if(outputContext)
{
for(int i = 0; i nb_streams; i++)
{
avcodec_close(outputContext->streams[i]->codec);
}
avformat_close_input(&outputContext);
}
return ret ;
}
四. 读取Packet
shared_ptr ReadPacketFromSource()
{
shared_ptr packet(static_cast(av_malloc(sizeof(AVPacket))), [&](AVPacket *p) { av_free_packet(p); av_freep(&p);});
av_init_packet(packet.get());
int ret = av_read_frame(context, packet.get());
if(ret >= 0)
{
return packet;
}
else
{
return nullptr;
}
}
五. 写Packet到服务端
av_interleaved_write_frame(outputContext, packet.get());
int _tmain(int argc, _TCHAR* argv[])
{
string fileInput= "rtsp://admin:admin@172.29.183.103/media/video1/multicast";
string fileOutput="rtmp://127.0.0.1/live/mystream";
Init();
if(OpenInput((char *)fileInput.c_str()) <0)
{
cout <<"Open file Input failed!" <streams[0]->time_base);
while(true)
{
auto packet = ReadPacketFromSource();
if(packet)
{
int ret = av_interleaved_write_frame(outputContext, packet.get());
}
else
{
cout <<"write packet end!"<
七. 小结: