搭建 ffmpeg + nginx流媒体服务器,并用C++推流

目录

一、搭建流媒体服务器

二、C++推流代码


一、搭建流媒体服务器

mkdir ~/working

切换到~/working目录下

cd ~/working

获取nginx源码:

wget http://nginx.org/download/nginx-1.13.4.tar.gz

解压

tar xvf nginx-1.13.4.tar.gz

获取最新的nginx-rtmp源码

git clone https://github.com/arut/nginx-rtmp-module.git

切换到nginx目录

cd nginx-1.13.4

配置

./configure –with-http_ssl_module –with-http_stub_status_module –add-module=../nginx-rtmp-module

编译和安装配置有nginx-rtmp模块的nginx

make

sudo make install

# 注意如果make失败:

  那么就是需要装nginx的依赖包

    # 查看zlib是否安装
    dpkg -l | grep zlib
    # 解决依赖包openssl安装
    sudo apt-get install openssl libssl-dev
    # 解决依赖包pcre安装
    sudo apt-get install libpcre3 libpcre3-dev
    # 解决依赖包zlib安装
    sudo apt-get install zlib1g-dev

安装nginx初始化脚本

获取nginx初始化脚本

wget https://raw.github.com/JasonGiedymin/nginx-init-ubuntu/master/nginx

将脚本复制到/etc/init.d/目录下

sudo cp nginx /etc/init.d/

修改权限

sudo chmod +x /etc/init.d/nginx

使用update-rc.d进行启动项管理

sudo update-rc.d nginx defaults

创建目录结构

sudo mkdir /HLS

sudo mkdir /HLS/mobile

sudo mkdir /HLS/live

sudo mkdir /video_recordings

sudo chmod -R 777 /video_recordings

配置nginx

备份原来的nginx配置文件

sudo cp /usr/local/nginx/conf/nginx.conf /usr/local/nginx/conf/nginx.conf.back

sudo gedit /usr/local/nginx/conf/nginx.conf

往/usr/local/nginx/conf/nginx.conf添加以下内容

worker_processes 1;
error_log logs/error.log debug;
events {
worker_connections 1024;
}
rtmp {
server {
listen 1935;
allow play all;

#creates our “live” full-resolution HLS videostream from our incoming encoder stream and tells where to put the HLS video manifest and video fragments
application live {
allow play all;
live on;
record all;
record_path /video_recordings;
record_unique on;
hls on;
hls_nested on;
hls_path /HLS/live;
hls_fragment 10s;

#creates the downsampled or “trans-rated” mobile video stream as a 400kbps, 480×360 sized video
exec ffmpeg -i rtmp://192.168.1.104:1935/$app/$name -acodec copy -c:v libx264 -preset veryfast -profile:v baseline -vsync cfr -s 480×360 -b:v 400k -maxrate 400k -bufsize 400k -threads 0 -r 30 -f flv rtmp://192.168.1.104:1935/mobile/$;
}

#creates our “mobile” lower-resolution HLS videostream from the ffmpeg-created stream and tells where to put the HLS video manifest and video fragments
application mobile {
allow play all;
live on;
hls on;
hls_nested on;
hls_path /HLS/mobile;
hls_fragment 10s;
}

#allows you to play your recordings of your live streams using a URL like “rtmp://my-ip:1935/vod/filename.flv”
application vod {
play /video_recordings;
}
}
}

http {
include mime.types;
default_type application/octet-stream;

server {
listen 80;
server_name 192.168.1.104;

#creates the http-location for our full-resolution (desktop) HLS stream – “http://my-ip/live/my-stream-key/index.m3u8”
location /live {
types {
application/vnd.apple.mpegurl m3u8;
}
alias /HLS/live;
add_header Cache-Control no-cache;
}

#creates the http-location for our mobile-device HLS stream – “http://my-ip/mobile/my-stream-key/index.m3u8”
location /mobile {
types {
application/vnd.apple.mpegurl m3u8;
}
alias /HLS/mobile;
add_header Cache-Control no-cache;
}

#allows us to see how stats on viewers on our Nginx site using a URL like: “http://my-ip/stats”
location /stats {
stub_status;
}

}
}

启动nginx服务

sudo service nginx start

安装ffmpeg

sudo apt-get install ffmpeg

一.推流开始       (点播)

1。ffmpeg -re -i 01.mp4 -vcodec libx264 -acodec aac -strict -2 -f flv rtmp://192.168.32.137:1935/mobile/ha

/*将本地视频文件test.mp4转码推流到本地服务器*/

或者ffmpeg -re -i 01.mp4 -vcodec libx264 -acodec copy -f flv rtmp://192.168.32.137:1935/mobile/ha

2.在本机端打开vlc播放器

输入流地址rtmp://localhost/mobile/ha即可观看视频,不过本地播放有些卡顿,网络播放更卡

二  直播

1.将视频放到  /video_recordings 目录

使用VLC访问     vod是rtmp的application ,点播就可以了

  rtmp://192.168.32.137:1935/vod/2.flv

二、C++推流代码

若确实libavformat库,则sudo apt-get install libavformat-dev

编译c++文件:g++ main.cpp -o main -lavformat -lavcodec -lavutil

#include <stdio.h>

#define __STDC_CONSTANT_MACROS

extern "C"
{
#include <libavformat/avformat.h>
#include <libavutil/mathematics.h>
#include <libavutil/time.h>
};

int main(int argc, char* argv[])
{
	AVDictionary* opt = NULL;
	AVOutputFormat* ofmt = NULL;

	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 = "/mnt/hgfs/ubuntu_shared/20230411-174047.mp4";//mp4 file

	out_filename = "rtmp://192.168.75.128:1935/mobile/ha";//URL(Output URL)[RTMP]

	av_register_all();
	//Network
	avformat_network_init();
	//Input
	if ((ret = avformat_open_input(&ifmt_ctx, in_filename, 0, 0)) < 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, "flv", out_filename); //RTMP
	//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;
		}
		//Copy the settings of AVCodecContext
		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 |= AV_CODEC_FLAG_GLOBAL_HEADER;
	}
	//Dump Format------------------
	av_dump_format(ofmt_ctx, 0, out_filename, 1);
	//Open output URL
	if (!(ofmt->flags & AVFMT_NOFILE)) {
		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;
		}
	}
	//Write file header
	
	av_dict_set(&opt, "flvflags", "no_duration_filesize", 0);
	ret = avformat_write_header(ofmt_ctx, &opt);
	//ret = avformat_write_header(ofmt_ctx, NULL);
	if (ret < 0) {
		printf("Error occurred when opening output URL\n");
		goto end;
	}

	start_time = av_gettime();
	while (1) {
		AVStream* in_stream, * out_stream;
		//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;
			if (pts_time > now_time)
				av_usleep(pts_time - now_time);

		}

		in_stream = ifmt_ctx->streams[pkt.stream_index];
		out_stream = ofmt_ctx->streams[pkt.stream_index];
		/* copy packet */
		//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;
}

参考:

流媒体服务器搭建 ffmpeg + nginx - ZHANKR

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值