写一个C++使用ffmpeg实现rtsp推流本地摄像头的代码
时间: 2023-03-21 08:00:26 浏览: 224
以下是一个使用FFmpeg实现本地摄像头实时推流到RTSP服务器的C代码示例:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <libavutil/opt.h>
#include <libavformat/avformat.h>
#include <libavutil/mathematics.h>
#include <libavdevice/avdevice.h>
#include <libavcodec/avcodec.h>
#define STREAM_DURATION 60.0
#define STREAM_FRAME_RATE 25 /* 25 images/s */
#define STREAM_PIX_FMT AV_PIX_FMT_YUV420P /* default pix_fmt */
int main(int argc, char **argv)
{
AVFormatContext *pFormatCtx = NULL;
AVOutputFormat *pOutputFmt = NULL;
AVStream *pStream = NULL;
AVCodecContext *pCodecCtx = NULL;
AVCodec *pCodec = NULL;
AVDictionary *options = NULL;
AVFrame *pFrame = NULL;
int ret, i, x, y;
int frame_count = 0, video_outbuf_size;
FILE *f = NULL;
/* Initialize libavcodec, and register all codecs and formats. */
av_register_all();
avdevice_register_all();
/* Open video input device */
AVInputFormat *inputFmt = av_find_input_format("video4linux2");
if ((ret = avformat_open_input(&pFormatCtx, "/dev/video0", inputFmt, NULL)) < 0) {
fprintf(stderr, "Could not open input device\n");
return ret;
}
/* Retrieve stream information */
if (avformat_find_stream_info(pFormatCtx, NULL) < 0) {
fprintf(stderr, "Could not find stream information\n");
return -1;
}
/* Find the first video stream */
for (i = 0; i < pFormatCtx->nb_streams; i++) {
if (pFormatCtx->streams[i]->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
pStream = pFormatCtx->streams[i];
break;
}
}
if (!pStream) {
fprintf(stderr, "Could not find video stream\n");
return -1;
}
/* Open output URL */
if ((ret = avformat_alloc_output_context2(&pFormatCtx, NULL, "rtsp", "rtsp://localhost:8554/test")) < 0) {
fprintf(stderr, "Could not allocate output context\n");
return ret;
}
pOutputFmt = pFormatCtx->oformat;
/* Add the video stream using the default format codec */
pCodec = avcodec_find_encoder(pOutputFmt->video_codec);
if (!pCodec) {
fprintf(stderr, "Codec not found\n");
return -1;
}
pCodecCtx = avcodec_alloc_context3(pCodec);
if (!pCodecCtx) {
fprintf(stderr, "Could not allocate codec context\n");
return -1;
}
/* Set stream parameters */
pCodecCtx->codec_id = pOutputFmt->video_codec;
pCodecCtx->codec_type = AVMEDIA_TYPE_VIDEO;
pCodecCtx->bit_rate = 400000;
pCodecCtx->width = pStream->codecpar->width;
pCodecCtx->height = pStream->codecpar->height;
pCodecCtx->time_base = (AVRational){1, STREAM_FRAME_RATE};
pCodecCtx->pix_fmt = STREAM_PIX_FMT;
/* Set the encoder's options */
av_dict_set(&options, "preset
阅读全文