基于FFmpeg的推流器(UDP推流)

2023-05-16

一、推流器对于输入输出文件无要求

1、输入文件可为网络流URL,可以实现转流器。
2、将输入的文件改为回调函数(内存读取)的形式,可以推送内存中的视频数据。
3、将输入文件改为系统设备(通过libavdevice),同时加上编码的功能,可以实现实时推流器(现场直播)。

二、代码实现

#include <stdio.h>

#define __STDC_CONSTANT_MACROS

#ifdef _WIN32
//Windows
extern "C"
{
#include "libavformat/avformat.h"
#include "libavutil/mathematics.h"
#include "libavutil/time.h"
#include "libavutil/opt.h"
};
#else
//Linux...
#ifdef __cplusplus
extern "C"
{
#endif
#include <libavformat/avformat.h>
#include <libavutil/mathematics.h>
#include <libavutil/time.h>
#include "libavutil/opt.h"

#ifdef __cplusplus
};
#endif
#endif


#pragma comment(lib,"avformat.lib")
#pragma comment(lib,"avcodec.lib")
#pragma comment(lib,"avutil.lib")
int main(int argc, char* argv[])
{
	AVOutputFormat *ofmt = NULL;
	//输入对应一个AVFormatContext,输出对应一个AVFormatContext
	//(Input AVFormatContext and Output AVFormatContext)
	AVFormatContext *ifmt_ctx = NULL, *ofmt_ctx = NULL;
	AVPacket pkt;
	const char *in_filename, *out_filename;
	int ret, i;
	int videoindex = -1;
	int frame_index = 0;
	int64_t start_time = 0;

	in_filename = "udp://238.1.1.11:1234";//可以为本地文件或者其他形式的直播流、设备等
	out_filename = "udp://238.1.1.10:6016";
	av_register_all();
	//Network
	avformat_network_init();

	AVDictionary *inputdic = NULL;

	//如果不设置的话,在输入源是直播流的时候,会花屏。单位bytes
	av_dict_set(&inputdic, "buffer_size", "10485760", 0);
	av_dict_set(&inputdic, "reuse", "1", 0);
	//输入(Input)
	if ((ret = avformat_open_input(&ifmt_ctx, in_filename, 0, &inputdic)) < 0) {
		printf("Could not open input file.");
		goto end;
	}
	if ((ret = avformat_find_stream_info(ifmt_ctx, 0)) < 0) {
		printf("Failed to retrieve input stream information");
		goto end;
	}

	for (i = 0; i<ifmt_ctx->nb_streams; i++)
		if (ifmt_ctx->streams[i]->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
			videoindex = i;
			break;
		}

	av_dump_format(ifmt_ctx, 0, in_filename, 0);

	//输出(Output)
	avformat_alloc_output_context2(&ofmt_ctx, NULL, "mpegts", out_filename);//UDP
	if (!ofmt_ctx) {
		printf("Could not create output context\n");
		ret = AVERROR_UNKNOWN;
		goto end;
	}
	ofmt = ofmt_ctx->oformat;
	for (i = 0; i < ifmt_ctx->nb_streams; i++) {
		//根据输入流创建输出流(Create output AVStream according to input AVStream)
		AVStream *in_stream = ifmt_ctx->streams[i];
		AVStream *out_stream = avformat_new_stream(ofmt_ctx, in_stream->codec->codec);
		if (!out_stream) {
			printf("Failed allocating output stream\n");
			ret = AVERROR_UNKNOWN;
			goto end;
		}
		//复制AVCodecContext的设置(Copy the settings of AVCodecContext)
		//tanzhenwen
		ret = avcodec_parameters_copy(out_stream->codecpar, ifmt_ctx->streams[i]->codecpar);
		if (ret < 0) {
			printf("Failed to copy parameters from input to output stream codec context\n");
			goto end;
		}
	/*	ret = avcodec_copy_context(out_stream->codec, in_stream->codec);
		if (ret < 0) {
			printf("Failed to copy context from input to output stream codec context\n");
			goto end;
		}*/
		out_stream->codec->codec_tag = 0;
		if (ofmt_ctx->oformat->flags & AVFMT_GLOBALHEADER)
			out_stream->codec->flags |= CODEC_FLAG_GLOBAL_HEADER;
	}
	//Dump Format------------------
	av_dump_format(ofmt_ctx, 0, out_filename, 1);
	//打开输出URL(Open output URL)
	if (!(ofmt->flags & AVFMT_NOFILE)) {
		AVDictionary*dic = NULL;
		av_dict_set(&dic, "pkt_size", "1316", 0);	//Maximum UDP packet size
		//av_dict_set(&dic, "fifo_size", "18800", 0);
		//av_dict_set(&dic, "buffer_size", "1000000", 0);
		//av_dict_set(&dic, "bitrate", "11000000", 0);
		//av_dict_set(&dic, "buffer_size", "1000000", 0);//1316
		av_dict_set(&dic, "reuse", "1", 0);
		ret = avio_open2(&ofmt_ctx->pb, out_filename, AVIO_FLAG_WRITE, NULL, &dic);
		//ret = avio_open(&ofmt_ctx->pb, out_filename, AVIO_FLAG_WRITE);

		if (ret < 0) {
			printf("Could not open output URL '%s'", out_filename);
			goto end;
		}
	}

	//av_opt_set(ofmt_ctx->priv_data, "muxrate", "11000000", 0);
		av_opt_set(ofmt_ctx->priv_data, "MpegTSWrite", "1", 0);
		av_opt_set(ofmt_ctx->priv_data, "pes_payload_size", "300", 0);
	//写文件头(Write file header)
	ret = avformat_write_header(ofmt_ctx, NULL);
	if (ret < 0) {
		printf("Error occurred when opening output URL\n");
		goto end;
	}

	start_time = av_gettime();
	int64_t deltpts = 0;
	while (1) {
		AVStream *in_stream, *out_stream;
		//获取一个AVPacket(Get an AVPacket)
		ret = av_read_frame(ifmt_ctx, &pkt);
		if (ret < 0)
			break;
		//FIX:No PTS (Example: Raw H.264)
		//Simple Write PTS
		if (pkt.pts == AV_NOPTS_VALUE) {
			//Write PTS
			AVRational time_base1 = ifmt_ctx->streams[videoindex]->time_base;
			//Duration between 2 frames (us)
			int64_t calc_duration = (double)AV_TIME_BASE / av_q2d(ifmt_ctx->streams[videoindex]->r_frame_rate);
			//Parameters
			pkt.pts = (double)(frame_index*calc_duration) / (double)(av_q2d(time_base1)*AV_TIME_BASE);
			pkt.dts = pkt.pts;
			pkt.duration = (double)calc_duration / (double)(av_q2d(time_base1)*AV_TIME_BASE);
		}
		//Important:Delay
		if (pkt.stream_index == videoindex) {
			
			AVRational time_base = ifmt_ctx->streams[videoindex]->time_base;
			AVRational time_base_q = { 1,AV_TIME_BASE };
			int64_t pts_time = av_rescale_q(pkt.dts, time_base, time_base_q);
			int64_t now_time = av_gettime() - start_time;

			static bool first = true;
			if (first)
			{
				deltpts = pts_time;
				first = false;
			}

			if (pts_time - deltpts > now_time)
				av_usleep(pts_time - deltpts - now_time);

		}

		in_stream = ifmt_ctx->streams[pkt.stream_index];
		out_stream = ofmt_ctx->streams[pkt.stream_index];
		tanzhenwen
		//if (pkt.stream_index == videoindex) {
		//	out_stream->time_base = AVRational{ 1, 25 };
		//}

		/* copy packet */
		//转换PTS/DTS(Convert PTS/DTS)
		pkt.pts = av_rescale_q_rnd(pkt.pts, in_stream->time_base, out_stream->time_base, (AVRounding)(AV_ROUND_NEAR_INF | AV_ROUND_PASS_MINMAX));
		pkt.dts = av_rescale_q_rnd(pkt.dts, in_stream->time_base, out_stream->time_base, (AVRounding)(AV_ROUND_NEAR_INF | AV_ROUND_PASS_MINMAX));
		pkt.duration = av_rescale_q(pkt.duration, in_stream->time_base, out_stream->time_base);
		pkt.pos = -1;
		//Print to Screen
		if (pkt.stream_index == videoindex) {
			//printf("Send %8d video frames to output URL\n", frame_index);
			frame_index++;
		}
		//ret = av_write_frame(ofmt_ctx, &pkt);
		ret = av_interleaved_write_frame(ofmt_ctx, &pkt);

		if (ret < 0) {
			printf("Error muxing packet\n");
			break;
		}

		av_free_packet(&pkt);

	}
	//写文件尾(Write file trailer)
	av_write_trailer(ofmt_ctx);
end:
	avformat_close_input(&ifmt_ctx);
	/* close output */
	if (ofmt_ctx && !(ofmt->flags & AVFMT_NOFILE))
		avio_close(ofmt_ctx->pb);
	avformat_free_context(ofmt_ctx);
	if (ret < 0 && ret != AVERROR_EOF) {
		printf("Error occurred.\n");
		return -1;
	}
	return 0;
}

参考

雷神博客
https://blog.csdn.net/leixiaohua1020/article/details/39803457

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

基于FFmpeg的推流器(UDP推流) 的相关文章

  • 如何将 MP3 音频文件读入 numpy 数组/将 numpy 数组保存到 MP3?

    有没有办法从 MP3 音频文件中读取 写入 MP3 音频文件numpy具有类似 API 的数组scipy io wavfile read https docs scipy org doc scipy 0 14 0 reference gen
  • 致命错误:libavcodec/avcodec.h 没有这样的文件或目录编译终止

    我正在尝试使用 gcc 执行tutorial01 c 并且 gcc 和tutorial01 c 以及 libavcodec 和 libavformat 及其关联文件位于同一文件夹中 它给了我这个错误 致命错误 libavcodec avco
  • 使用 xuggle 将 mp3 转换为 wav 出现异常

    我正在尝试将 mp3 转换为 wav 代码在这里 String mp3 F work pic2talk38512 mp3 String wav F work pic2talk38512 wav TranscodeAudioAndVideo
  • 使用 Coldfusion 的 CFFILE 标签监控 FFMpeg 的进度日志

    我想学习如何使用 ColdFusion 中的 CFFILE 标签来读取文本文件的内容 就我而言 该文本文件是 FFMpeg 在对媒体文件进行转码时生成的进度日志 我想编写一个 ColdFusion 脚本 该脚本将定期轮询进度日志 直到日志表
  • FFMPEG波形透明,背景纯色

    我正在尝试使用 ffmpeg 生成波形 我希望背景为纯色 实际波形为透明 以下部分实现了我想要的 除了有黑色背景 我希望能够将其更改为任何颜色 但波形是透明的 我怎样才能用 ffmepg 实现这个目标 ffmpeg i input mp3
  • 尝试接收 UDP 多播时出现空指针异常

    在尝试了几次让简单的 UDP 多播接收器工作后 我感到很困惑 在我自己的代码无法按预期工作后 我尝试了 vertx 文档中发布的确切示例 DatagramSocket socket vertx createDatagramSocket ne
  • Xuggler 未转换 .webm 文件?

    我只是尝试使用 Xuggler 将 mov 文件转换为 webm 这应该可以工作 因为 FFMPEG 支持 webm 文件 这是我的代码 IMediaReader reader ToolFactory makeReader home use
  • ffmpeg 配置复杂过滤器时出错

    ffmpeg 命令存在一些问题 也许有人可以指出我正确的方向 我使用此链接来构建我的命令 那么问题 https stackoverflow com questions 7333232 how to concatenate two mp4 f
  • id3 图像编辑后播放 mp3 时遇到问题

    由于硬件限制 我们生产的软件试图确保导入到其库中的任何音频文件 准备复制到硬件上 都是可接受的比特率 最近 我们开始使用 FFmpeg 将许多不同的音频类型转换为 mp3 以便在我们的硬件上导入和使用它们 虽然转换工作正常并且 mp3 文件
  • FFMPEG 帧到 DirectX 表面

    给定一个指向 FFMPEG 的 AVFrame 的指针avcodec decode video 函数如何将图像复制到 DirectX 表面 假设我有一个指向适当大小的 DX X8R8G8B8 表面的指针 Thanks John 您可以使用
  • 从不同进程通过套接字 (UDP) 回复客户端

    我有一个服务器而不是 命令处理程序 进程 它通过 UDP 接收消息 并通过其发布的 API 无论该进程采用何种 IPC 机制 与该进程进行通信 从而将要做的工作委托给不同的进程 我们的系统有多个协作进程 然后 该 API 调用的结果会从命令
  • 以 Gif 形式在 Android 上以编程方式共享 WhatsApp 视频

    我如何将 mp4 视频文件转换为 WhatsApp gif 文件 在应用程序 UI 中简单显示为 gif 但内部是特定的 mp4 格式 以在 android 共享意图中使用 并被 Whatsapp 聊天应用程序识别为此类媒体 我搜索了很多
  • 将循环视频添加到声音 ffmpeg

    我开始使用 ffmpeg 这是我的第一个疑问 我有一个声音文件 example mp3 持续时间 1 分钟 我想添加一个循环视频 example mp4 x 秒持续时间 在这种情况下 我想生成 1 分钟的 mp4 视频并循环该视频 3 次
  • 用 C 语言进行非阻塞 udp 套接字编程:我能得到什么?

    我在理解从非阻塞 UDP 套接字返回什么recv recvfrom 时遇到问题 与 TCP 相比更具体一点 如果我错了 请纠正我 阻塞套接字 TCP 或 UDP 在缓冲区中有一些数据之前不会从 recv 返回 这可以是一定数量的字节 TCP
  • C#中图像制作视频的工作方式

    有人有已知的可靠方法来从一系列图像文件创建视频吗 在你因为我在发布问题之前没有寻找答案而对我进行批评之前 以及在你发出诸如 使用 FFMPEG 之类的简单消息之前 请阅读此消息的其余部分 我正在尝试从一系列图像 jpg bmp 等 创建视频
  • 图像序列到视频质量[关闭]

    Closed 这个问题是无关 help closed questions 目前不接受答案 我一直在尝试从一系列图像创建视频 当我使用建议的 ffmpeg 方法时 ffmpeg f image2 i image d jpg video mpg
  • FFMPEG:尝试从图像和音频创建 facebook 流时出现转换失败错误?

    目标是从图像和音频文件创建 Facebook 流 这是我的命令 ffmpeg re y loop 1 f image2 i maxresdefault jpg i audio loop mp3 ar 44100 b a 128k vcode
  • 如何获取视频时长(以秒为单位)? [复制]

    这个问题在这里已经有答案了 如何获取以秒为单位的视频时长 我尝试过的 ffmpeg i file flv 2 gt 1 grep Duration Duration 00 39 43 08 start 0 040000 bitrate 38
  • 使用 ImageMagick 有效地将线扫描图像拼接在一起

    我正在寻找线扫描相机的替代品 用于体育计时 或者更确切地说 用于需要确定位置的部分 我发现普通工业相机可以轻松与商业相机解决方案的速度相匹配 每秒 gt 1000 帧 对于我的需求来说 通常计时的准确性并不重要 重要的是运动员的相对位置 我
  • 为 Windows Phone 8 构建 ffmpeg

    我如何为 Windows Phone 8 arm 构建 ffmpeg 我找不到任何有关它的信息 我可以在 Windows Phone 8 中从 C 调用 h 264 硬件编码器 解码器吗 看来媒体基金会太有限了 谢谢 据我所知 由于缺少工具

随机推荐

  • c/c++中的struct和class的区别

    主要有两种情况 xff1a 1 C语言中的struct和c 43 43 中的class区别 2 c 43 43 中的struct和c 43 43 中的class的区别 下面分别介绍 xff1a 1 C语言中的struct和c 43 43 中
  • Linux应用层对串口的使用操作

    在Linux中串口作为字符设备 xff0c 设备节点在 dev 目录下 xff0c 使用普通的open xff0c close xff0c write和read等系统调用即可使用 这其中会涉及到一些串口的基本属性的设置 xff0c 如 波特
  • 给定两个字符串str1和str2,查找str2在str1中出现的位置

    给定string str1和string str2 xff0c 编写一个库函数 xff0c 返回str2在str1中的位置 如 xff1a str1为 34 ABCDLANCEXYZ 34 xff0c str2为 34 LANCE 34 x
  • 中国交通标志检测数据集

    版权声明 xff1a 本文为转发问 xff0c 原文见博客 https blog csdn net dong ma article details 84339007 中国交通标志检测数据集 xff08 CCTSDB xff09 来源于 A
  • CentOS 修改ls目录的颜色

    修改ls目录的颜色 linux系统默认目录颜色是蓝色的 xff0c 在黑背景下看不清楚 xff0c 可以通过以下2种方法修改ls查看的颜色 bash profile文件在用的根目录下 xff0c ls al可以看到 方法一 xff1a 1
  • Tiny210(S5PV210) U-BOOT(六)----DDR内存配置

    上次讲完了Nand Flash的低级初始化 xff0c 然后Nand Flash的操作主要是在board init f nand xff0c 中 xff0c 涉及到将代码从Nand Flash中copy到DDR中 xff0c 这个放到后面实
  • NAND FLASH命名规则

    基于网络的一个修订版 三星的pure nandflash xff08 就是不带其他模块只是nandflash存储芯片 xff09 的命名规则如下 xff1a 1 Memory K 2 NANDFlash 9 3 Small Classifi
  • s3c6410 DMA

    S3C6410中DMA操作步骤 xff1a 1 决定使用安全DMAC SDMAC 还是通用DMAC DMAC xff1b 2 开始相应DMAC的系统时钟 xff0c 并关闭另外一组的时钟 xff08 系统默认开启SDMA时钟 xff09 x
  • Visual Studio和VS Code的区别

    1 Visual Studio简介 xff1a 是一个集成开发环境 IDE xff0c 安装完成后就能直接用 xff0c 编译工具 xff0c 调试工具 xff0c 各个语言的开发工具 xff0c 都是已经配置好的 xff0c 开箱即用 适
  • 博客转移

    由于CSDN 文章不间断的会丢失图片 xff0c 然后逼格也不够高 xff0c 导致几年都没有写博客 xff0c 全部是记录至印象笔记中 xff0c 但是久了也不太好 xff0c 所以最近搞了一个自己的个人博客 xff0c 以后文章全部写至
  • 安装qt-everywhere-opensource-src-4.8.6

    1 下载 qt everywhere opensource src 4 8 6 http mirrors hust edu cn qtproject official releases qt 4 8 4 8 6 qt everywhere
  • CentOS6.5上安装qt-creator-opensource-linux-x86-3.1.2.run

    1 qt creator opensource linux x86 3 1 2 run的下载 wget http mirrors hustunique com qt official releases qtcreator 3 1 3 1 2
  • atoi()函数

    atoi 函数 原型 xff1a int atoi xff08 const char nptr xff09 用法 xff1a include lt stdlib h gt 功能 xff1a 将字符串转换成整型数 xff1b atoi 会扫描
  • ubuntu中printk打印信息

    1 设置vmware添加seria port 使用文件作为串口 2 启动ubuntu xff0c 修改 etc default grub GRUB CMDLINE LINUX DEFAULT 61 34 34 GRUB CMDLINE LI
  • 静态库、共享库、动态库概念?

    通常库分为 xff1a 静态库 共享库 xff0c 动态加载库 下面分别介绍 一 静态库 xff1a 1 概念 xff1a 静态库就是一些目标文件的集合 xff0c 以 a结尾 静态库在程序链接的时候使用 xff0c 链接器会将程序中使用
  • 链表——怎么写出正确的链表?

    链表 相比数组 xff0c 链表不需要一块连续的内存空间 xff0c 而是通过指针将一组零散的内存块串联起来使用 xff0c 而这里的内存块就叫做节点 xff0c 一般节点除了保存data还会保存下一个节点的地址也就是指针 单链表 头节点
  • 【STM32】STM32 变量存储在片内FLASH的指定位置

    在这里以STM32L4R5为例 xff08 官方出的DEMO板 xff09 xff0c 将变量存储在指定的片内FLASH地址 xff08 0x081F8000 xff09 一 MDK Keil软件操作 uint8 t version spa
  • 【STM32】 利用paho MQTT&WIFI 连接阿里云

    ST联合阿里云推出了云接入的相关培训 xff08 基于STM32的端到端物联网全栈开发 xff09 xff0c 所采用的的板卡为NUCLEO L4R5ZI板 xff0c 实现的主要功能为采集温湿度传感器上传到阿里云物联网平台 xff0c 并
  • 【STM32 】通过ST-LINK utility 实现片外FLASH的烧写

    目录 前言 一 例程参考及讲解 1 1 Loader Src c文件 1 2 Dev Inf c文件 二 程序修改 三 实测 参考 前言 在单片机的实际应用中 xff0c 通常会搭载一些片外FLASH芯片 xff0c 用于存储系统的一些配置
  • 基于FFmpeg的推流器(UDP推流)

    一 推流器对于输入输出文件无要求 1 输入文件可为网络流URL xff0c 可以实现转流器 2 将输入的文件改为回调函数 xff08 内存读取 xff09 的形式 xff0c 可以推送内存中的视频数据 3 将输入文件改为系统设备 xff08