在网上找了一圈关于ffmpeg如何接收rtp流的Example,都是使用ffmpeg 命令行来实现的,还没看到用相关ffmpeg库和API来实现的,于是自己写了个小程序,来验证ffmpeg在本地监听rtp流,代码在ffmpeg4.1+win10环境下测试可行:
有几个关键点:
1)需要提供video/audio sdp信息,用于描述基本媒体信息
2)需要自动检测一个可用的端口
#include <iostream>
#include <sstream>
#include <fstream>
extern "C" {
#include <libavcodec/avcodec.h>
#include <libavformat/avformat.h>
#include <libavutil/mathematics.h>
#include <libavutil/audio_fifo.h>
#include <libavutil/opt.h>
#include <libswresample/swresample.h>
}
#define WIN32
#ifdef WIN32
#include <winsock2.h>
#else
#include <sys/socket.h>
#include <net/if.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <netdb.h>
#include <sys/select.h>
#endif
#pragma warning(disable : 4996)
#pragma comment(lib, "WS2_32")
bool getAvailableListenPort(unsigned short *port)
{
std::string CLIENT_IP("127.0.0.1");
bool result = true;
#ifdef WIN32
WSADATA wsa;
/*初始化socket资源*/
if (WSAStartup(MAKEWORD(1, 1), &wsa) != 0)
{
return false; //代表失败
}
#endif
// 1. 创建一个socket
//int sock = socket(AF_INET, SOCK_STREAM, IPPROTO_UDP);
int sock = socket(AF_INET, SOCK_DGRAM, 0);
// 2. 创建一个sockaddr,并将它的端口号设为0
struct sockaddr_in addrto;
memset(&addrto, 0, sizeof(struct sockaddr_in));
addrto.sin_family = AF_INET;
addrto.sin_addr.s_addr = inet_addr(CLIENT_IP.c_str());
addrto.sin_port = 0;
// 3. 绑定
int ret = ::bind(sock, (struct sockaddr*) & (addrto)