int main() {
//註冊
av_register_all();
avformat_network_init();
//打開音視頻
AVFormatContext* infContext = avformat_alloc_context();
AVFormatContext* outContext = avformat_alloc_context();
AVPacket* pkt = av_packet_alloc();
const char *inpath = "rtsp://184.72.239.149/vod/mp4://BigBuckBunny_175k.mov";
const char* outpath = "udp://127.0.0.1:1234";
AVStream *inputstream;
AVStream *outputstream;
AVRational src_tb;
AVRational dst_tb;
int reg = avformat_open_input(&infContext, inpath, NULL, NULL);
if (reg<0)
{
cout << "open url fail\n" << endl;
goto ERROR;
}
//尋找音視頻流信息
reg = avformat_find_stream_info(infContext, NULL);
if (reg<0)
{
cout << "open input file stream fail\n" << endl;
goto ERROR;
}
else
{
cout << "open input file stream sucesse"<<reg << endl;
}
//打開輸出地址
reg = avformat_alloc_output_context2(&outContext, NULL, "mpegts", outpath);
if (reg<0)
{
cout << "open output file fail\n" << endl;
goto ERROR;
}
else
{
cout << "open output file success\n" << endl;
}
if (avio_open2(&outContext->pb, outpath, AVIO_FLAG_WRITE, NULL, NULL)<0)
{
cout << "open avio fail\n"<<endl;
goto ERROR;
}
cout << "open avio success\n" << endl;
for (int i = 0; i < infContext->nb_streams; i++)
{
AVStream* stream = avformat_new_stream(outContext, infContext->streams[i]->codec->codec);
reg = avcodec_copy_context(stream->codec, infContext->streams[i]->codec);
if (reg<0)
{
cout << "copy context fail\n" << endl;
goto ERROR;
}
cout << "copy context success\n" << endl;
}
reg = avformat_write_header(outContext, NULL);
if (reg<0)
{
cout<<"write hearder fail\n"<<endl;
goto ERROR;
}
//av_init_packet(pkt);
while (true)
{
reg = av_read_frame(infContext, pkt);
if (reg < 0)
{
cout << "read frame fail\n" << endl;
goto ERROR;
}
//寫入數據
inputstream = infContext->streams[pkt->stream_index];
outputstream = outContext->streams[pkt->stream_index];
src_tb = inputstream->time_base;
dst_tb = outputstream->time_base;
if (pkt->pts != AV_NOPTS_VALUE)
pkt->pts = av_rescale_q(pkt->pts, src_tb, dst_tb);
if (pkt->dts != AV_NOPTS_VALUE)
pkt->dts = av_rescale_q(pkt->dts, src_tb, dst_tb);
if (pkt->duration > 0)
pkt->duration = av_rescale_q(pkt->duration, src_tb, dst_tb);
reg = av_interleaved_write_frame(outContext, pkt);
if (reg < 0)
{
cout << "write fail\n" << endl;
}
else
{
cout << "write success\n" << endl;
}
}
ERROR:
cout << "錯誤信息" << reg << endl;
return reg;
return 0;
}