FFmpeg中RTSP客户端拉流测试代码
生活随笔
收集整理的這篇文章主要介紹了
FFmpeg中RTSP客户端拉流测试代码
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
之前在https://blog.csdn.net/fengbingchun/article/details/91355410中給出了通過LIVE555實現拉流的測試代碼,這里通過FFmpeg來實現,代碼量遠小于LIVE555,實現模塊在libavformat。
在4.0及以上版本中,FFmpeg有了些變動,好像不再推薦使用av_register_all、avformat_network_init、av_init_packet等函數。
FFmpeg拉流測試代碼如下(test_ffmpeg_rtsp_client.cpp):
#include "funset.hpp"
#include <iostream>#ifdef __cplusplus
extern "C" {
#endif#include <libavformat/avformat.h>#ifdef __cplusplus
}
#endifint test_ffmpeg_rtsp_client()
{// Allocate an AVFormatContextAVFormatContext* format_ctx = avformat_alloc_context();// open rtsp: Open an input stream and read the header. The codecs are not openedconst char* url = "rtsp://184.72.239.149/vod/mp4://BigBuckBunny_175k.mov";int ret = -1;ret = avformat_open_input(&format_ctx, url, nullptr, nullptr);if (ret != 0) {fprintf(stderr, "fail to open url: %s, return value: %d\n", url, ret);return -1;}// Read packets of a media file to get stream informationret = avformat_find_stream_info(format_ctx, nullptr);if ( ret < 0) {fprintf(stderr, "fail to get stream information: %d\n", ret);return -1;}// audio/video stream indexint video_stream_index = -1;int audio_stream_index = -1;fprintf(stdout, "Number of elements in AVFormatContext.streams: %d\n", format_ctx->nb_streams);for (int i = 0; i < format_ctx->nb_streams; ++i) {const AVStream* stream = format_ctx->streams[i];fprintf(stdout, "type of the encoded data: %d\n", stream->codecpar->codec_id);if (stream->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {video_stream_index = i;fprintf(stdout, "dimensions of the video frame in pixels: width: %d, height: %d, pixel format: %d\n",stream->codecpar->width, stream->codecpar->height, stream->codecpar->format);} else if (stream->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {audio_stream_index = i;fprintf(stdout, "audio sample format: %d\n", stream->codecpar->format);}}if (video_stream_index == -1) {fprintf(stderr, "no video stream\n");return -1;}if (audio_stream_index == -1) {fprintf(stderr, "no audio stream\n");}int cnt = 0;AVPacket pkt;while (1) {if (++cnt > 100) break;ret = av_read_frame(format_ctx, &pkt);if (ret < 0) {fprintf(stderr, "error or end of file: %d\n", ret);continue;}if (pkt.stream_index == video_stream_index) {fprintf(stdout, "video stream, packet size: %d\n", pkt.size);}if (pkt.stream_index == audio_stream_index) {fprintf(stdout, "audio stream, packet size: %d\n", pkt.size);}av_packet_unref(&pkt);}avformat_free_context(format_ctx);return 0;
}
執行結果如下圖所示:
GitHub:https://github.com/fengbingchun/OpenCV_Test
總結
以上是生活随笔為你收集整理的FFmpeg中RTSP客户端拉流测试代码的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: LIVE555中RTSP客户端接收媒体流
- 下一篇: 远程过程调用RPC简介