ffmepg rtmp 拉取播放c
时间: 2023-07-24 13:08:49 浏览: 36
如果你想在 C++ 中使用 FFMPEG 拉取 RTMP 流并播放,可以使用 FFMPEG 库中的 AVFormat 和 AVCodec 来实现。下面是一个简单的示例代码:
```c++
#include <iostream>
extern "C" {
#include <libavformat/avformat.h>
#include <libavcodec/avcodec.h>
}
int main(int argc, char* argv[]) {
AVFormatContext* pFormatCtx = NULL;
AVCodecContext* pCodecCtxOrig = NULL;
AVCodecContext* pCodecCtx = NULL;
AVCodec* pCodec = NULL;
AVPacket* packet = NULL;
AVFrame* pFrame = NULL;
int i, videoStream;
int frameFinished;
AVDictionary* optionsDict = NULL;
// 初始化 FFmpeg
av_register_all();
// 打开 RTMP 流
if (avformat_open_input(&pFormatCtx, "rtmp://example.com/live/stream", NULL, NULL) != 0) {
std::cerr << "Error: Couldn't open input stream." << std::endl;
return -1;
}
// 查找流信息
if (avformat_find_stream_info(pFormatCtx, NULL) < 0) {
std::cerr << "Error: Couldn't find stream information." << std::endl;
return -1;
}
// 打印流信息
av_dump_format(pFormatCtx, 0, "rtmp://example.com/live/stream", 0);
// 查找视频流
videoStream = -1;
for (i = 0; i < pFormatCtx->nb_streams; i++) {
if (pFormatCtx->streams[i]->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
videoStream = i;
break;
}
}
if (videoStream == -1) {
std::cerr << "Error: Couldn't find a video stream." << std::endl;
return -1;
}
// 获取视频编解码器
pCodecCtxOrig = pFormatCtx->streams[videoStream]->codec;
pCodec = avcodec_find_decoder(pCodecCtxOrig->codec_id);
if (pCodec == NULL) {
std::cerr << "Error: Unsupported codec." << std::endl;
return -1;
}
// 分配编解码器上下文
pCodecCtx = avcodec_alloc_context3(pCodec);
if (avcodec_parameters_to_context(pCodecCtx, pFormatCtx->streams[videoStream]->codecpar) < 0) {
std::cerr << "Error: Couldn't copy codec parameters to codec context." << std::endl;
return -1;
}
// 打开编解码器
if (avcodec_open2(pCodecCtx, pCodec, &optionsDict) < 0) {
std::cerr << "Error: Couldn't open codec." << std::endl;
return -1;
}
// 分配帧和数据包
packet = av_packet_alloc();
pFrame = av_frame_alloc();
// 读取数据帧
while (av_read_frame(pFormatCtx, packet) >= 0) {
// 判断是否是视频帧
if (packet->stream_index == videoStream) {
// 解码视频帧
avcodec_send_packet(pCodecCtx, packet);
while (avcodec_receive_frame(pCodecCtx, pFrame) == 0) {
// 处理视频帧
std::cout << "Got a frame!" << std::endl;
}
}
// 释放数据包
av_packet_unref(packet);
}
// 释放帧和数据包
av_frame_free(&pFrame);
av_packet_free(&packet);
// 关闭编解码器
avcodec_close(pCodecCtx);
// 关闭输入流
avformat_close_input(&pFormatCtx);
return 0;
}
```
这个示例代码使用 AVFormat 和 AVCodec 函数来打开 RTMP 流、查找视频流、获取视频编解码器、分配帧和数据包、读取数据帧、解码视频帧,并在控制台输出 "Got a frame!"。你可以根据自己的需求修改这个代码。