ffmpeg rtsp推流 代码
时间: 2024-03-01 15:47:54 浏览: 153
ffmpeg是一个开源的跨平台音视频处理工具,可以用于音视频的录制、转码、推流等操作。下面是一个使用ffmpeg进行rtsp推流的示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
extern "C" {
#include <libformat/avformat.h>
#include <libavutil/opt.h>
}
int main(int argc, char *argv[]) {
AVFormatContext *inputContext = NULL;
AVFormatContext *outputContext = NULL;
AVPacket packet;
const char *inputUrl = "rtsp://input_url"; // 输入的rtsp地址
const char *outputUrl = "rtmp://output_url"; // 输出的rtmp地址
av_register_all();
// 打开输入流
if (avformat_open_input(&inputContext, inputUrl, NULL, NULL) != 0) {
fprintf(stderr, "Failed to open input stream\n");
return -1;
}
// 查找输入流信息
if (avformat_find_stream_info(inputContext, NULL) < 0) {
fprintf(stderr, "Failed to find input stream information\n");
return -1;
}
// 打开输出流
if (avformat_alloc_output_context2(&outputContext, NULL, "flv", outputUrl) < 0) {
fprintf(stderr, "Failed to create output context\n");
return -1;
}
// 遍历输入流,复制流信息到输出流
for (int i = 0; i < inputContext->nb_streams; i++) {
AVStream *inStream = inputContext->streams[i];
AVStream *outStream = avformat_new_stream(outputContext, inStream->codec->codec);
if (!outStream) {
fprintf(stderr, "Failed to create output stream\n");
return -1;
}
if (avcodec_copy_context(outStream->codec, inStream->codec) < 0) {
fprintf(stderr, "Failed to copy codec context\n");
return -1;
}
}
// 打开输出流
if (avio_open(&outputContext->pb, outputUrl, AVIO_FLAG_WRITE) < 0) {
fprintf(stderr, "Failed to open output stream\n");
return -1;
}
// 写入输出文件头
if (avformat_write_header(outputContext, NULL) < 0) {
fprintf(stderr, "Failed to write output file header\n");
return -1;
}
// 读取输入流数据,写入输出流
while (av_read_frame(inputContext, &packet) >= 0) {
AVStream *inStream = inputContext->streams[packet.stream_index];
AVStream *outStream = outputContext->streams[packet.stream_index];
// 设置时间基
packet.pts = av_rescale_q_rnd(packet.pts, inStream->time_base, outStream->time_base, AV_ROUND_NEAR_INF);
packet.dts = av_rescale_q_rnd(packet.dts, inStream->time_base, outStream->time_base, AV_ROUND_NEAR_INF);
packet.duration = av_rescale_q(packet.duration, inStream->time_base, outStream->time_base);
packet.pos = -1;
// 写入输出流
if (av_interleaved_write_frame(outputContext, &packet) < 0) {
fprintf(stderr, "Failed to write frame to output stream\n");
break;
}
av_packet_unref(&packet);
}
// 写入输出文件尾
av_write_trailer(outputContext);
// 关闭输入流
avformat_close_input(&inputContext);
// 关闭输出流
avio_close(outputContext->pb);
avformat_free_context(outputContext);
return 0;
}
```
这段代码使用ffmpeg库实现了从rtsp流读取数据,并将数据推流到rtmp服务器。你可以根据实际情况修改输入和输出的URL地址,以及其他参数。
阅读全文