音视频实践学习

本文目录

概述

还是先从最简单的搞起来,先从最基本的视频推流开始,要知道在电脑上使用ffmpeg完成推流,简直不要太简单,直接使用ffmpeg的推流命令即可,今天想在android平台实践一下,具体操作大家也可以看看雷神的博客。

ffmpeg -re -i input.mp4 -vcodec copy -f flv rtmp://192.168.1.102:1935/onzhou/live

配置环境

操作系统: ubuntu 16.05

注意: ffmpeg库的编译使用的是android-ndk-r10e版本,使用高版本编译会报错。

而android-studio工程中配合cmake使用的版本则是android-ndk-r16b版本

image

新建工程ffmpeg-single-streamer

image

build.gradle配置比较简单,可以参考之前的文章

新建CMakeLists.txt文件,配置如下

cmake_minimum_required(VERSION 3.4.1)

add_library(ffmpeg-streamer

SHARED

src/main/cpp/ffmpeg_streamer.c)

find_library(log-lib

log)

#获取上级目录

get_filename_component(PARENT_DIR ${CMAKE_SOURCE_DIR} PATH)

set(LIBRARY_DIR ${PARENT_DIR}/ffmpeg-single)

set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=gnu++11")

set(CMAKE_VERBOSE_MAKEFILE on)

add_library(ffmpeg-single

SHARED

IMPORTED)

set_target_properties(ffmpeg-single

PROPERTIES IMPORTED_LOCATION

${LIBRARY_DIR}/libs/${ANDROID_ABI}/libffmpeg.so

)

#头文件

include_directories(${LIBRARY_DIR}/libs/${ANDROID_ABI}/include)

target_link_libraries(ffmpeg-streamer ffmpeg-single ${log-lib})

新建NowStreamer.java文件

package com.onzhou.ffmpeg.streamer;

public class NowStreamer {

static {

System.loadLibrary("ffmpeg");

System.loadLibrary("ffmpeg-streamer");

}

public native int startPublish(String input, String output);

}

在src/main/cpp目录新建源文件ffmpeg_streamer.c

#include

#include

#include

#include "libavcodec/avcodec.h"

#include "libavformat/avformat.h"

#include "libavfilter/avfilter.h"

#include "libavutil/log.h"

#ifdef ANDROID

#include

#include

#define LOG_TAG "NowStreamer"

#define LOGE(format, ...) __android_log_print(ANDROID_LOG_ERROR, LOG_TAG, format, ##__VA_ARGS__)

#define LOGI(format, ...) __android_log_print(ANDROID_LOG_INFO, LOG_TAG, format, ##__VA_ARGS__)

#else

#define LOGE(format, ...) printf(LOG_TAG format "\n", ##__VA_ARGS__)

#define LOGI(format, ...) printf(LOG_TAG format "\n", ##__VA_ARGS__)

#endif

//输出日志

void log_callback(void *ptr, int level, const char *fmt, va_list vl) {

//写入日志文件

FILE *fp = fopen("/storage/emulated/0/av_log.txt", "a+");

if (fp) {

vfprintf(fp, fmt, vl);

fflush(fp);

fclose(fp);

}

//LOGE(fmt, vl);

}

JNIEXPORT jint JNICALL Java_com_onzhou_ffmpeg_streamer_NowStreamer_startPublish

(JNIEnv *env, jobject obj, jstring input_jstr, jstring output_jstr) {

AVOutputFormat *ofmt = NULL;

AVFormatContext *ifmt_ctx = NULL, *ofmt_ctx = NULL;

AVPacket pkt;

int ret, i;

char input_str[500] = {0};

char output_str[500] = {0};

char info[1000] = {0};

sprintf(input_str, "%s", (*env)->GetStringUTFChars(env, input_jstr, NULL));

sprintf(output_str, "%s", (*env)->GetStringUTFChars(env, output_jstr, NULL));

//日志回调写入文件

av_log_set_callback(log_callback);

av_register_all();

//网络初始化

avformat_network_init();

//Input

if ((ret = avformat_open_input(&ifmt_ctx, input_str, 0, 0)) < 0) {

LOGE("Could not open input file.");

goto end;

}

if ((ret = avformat_find_stream_info(ifmt_ctx, 0)) < 0) {

LOGE("Failed to retrieve input stream information");

goto end;

}

int videoindex = -1;

for (i = 0; i < ifmt_ctx->nb_streams; i++)

if (ifmt_ctx->streams[i]->codec->codec_type == AVMEDIA_TYPE_VIDEO) {

videoindex = i;

break;

}

//Output

avformat_alloc_output_context2(&ofmt_ctx, NULL, "flv", output_str); //RTMP

//avformat_alloc_output_context2(&ofmt_ctx, NULL, "mpegts", output_str);//UDP

if (!ofmt_ctx) {

LOGE("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) {

LOGE("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) {

LOGE("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;

}

//Open output URL

if (!(ofmt->flags & AVFMT_NOFILE)) {

ret = avio_open(&ofmt_ctx->pb, output_str, AVIO_FLAG_WRITE);

if (ret < 0) {

LOGE("Could not open output URL '%s'", output_str);

goto end;

}

}

//Write file header

ret = avformat_write_header(ofmt_ctx, NULL);

if (ret < 0) {

LOGE("Error occurred when opening output URL\n");

goto end;

}

int frame_index = 0;

int64_t 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,

AV_ROUND_NEAR_INF | AV_ROUND_PASS_MINMAX);

pkt.dts = av_rescale_q_rnd(pkt.dts, in_stream->time_base, out_stream->time_base,

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) {

LOGE("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) {

LOGE("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) {

LOGE("Error occurred.\n");

return -1;

}

return 0;

}

推流服务器的搭建,可以参考之前的文章

public void onStartClick(View view) {

if (nowStreamer == null) {

nowStreamer = new NowStreamer();

}

if (publishDisposable == null) {

publishDisposable = Schedulers.newThread().scheduleDirect(new Runnable() {

@Override

public void run() {

//推流本地的一个mp4文件

final File intputVideo = new File(getExternalFilesDir(null), "input.mp4");

nowStreamer.startPublish(intputVideo.getAbsolutePath(), PUBLISH_ADDRESS);

}

});

}

}

编译打包运行,开始推流,我们在局域网中使用vlc播放器,打开网络串流

rtmp://192.168.1.102:1935/onzhou/live

image

android推流局域网,android全平台基于ffmpeg解码本地MP4视频推流到RTMP服务器相关推荐

  1. android全平台基于ffmpeg解码本地MP4视频推流到RTMP服务器

    音视频实践学习 android全平台编译ffmpeg以及x264与fdk-aac实践 ubuntu下使用nginx和nginx-rtmp-module配置直播推流服务器 android全平台编译ffm ...

  2. EasyDarwin+FFmpeg实现本地音视频推流

    所需 EasyDarwin 用作流媒体转发服务器 FFmpeg 用于转码及推流 步骤 1. 安装 EasyDarwin,下载地址 2. 解压后如图: 有两种方法运行 (1) 运行 EasyDarwin ...

  3. QT软件开发-基于FFMPEG设计录屏与rtsp、rtmp推流软件(支持桌面与摄像头)(一)

    QT软件开发-基于FFMPEG设计录屏与rtsp.rtmp推流软件(支持桌面与摄像头)(一) https://xiaolong.blog.csdn.net/article/details/126954 ...

  4. QT软件开发-基于FFMPEG设计录屏与rtsp、rtmp推流软件(支持桌面与摄像头)(四)

    QT软件开发-基于FFMPEG设计录屏与rtsp.rtmp推流软件(支持桌面与摄像头)(一) https://xiaolong.blog.csdn.net/article/details/126954 ...

  5. 网络直播平台搭建中直播协议和视频推流

    网络直播平台搭建中直播协议和视频推流 直播协议 流媒体分为直播和点播.通常来说点播使用的都是HTTP协议,直播主要用的是RTMP, HLS, HTTP-FLV等.近年来直播协议也有新发展如DASH,但 ...

  6. 音视频开发之旅(34) - 基于FFmpeg实现简单的视频解码器

    目录 FFmpeg解码过程流程图和关键的数据结构 mp4通过FFmpeg解码YUV裸视频数据 遇到的问题 资料 收获 一.FFmpeg解码过程流程图和关键的数据结构 FFmpeg解码涉及的知识点比较多 ...

  7. 音视频开发(二十七):基于FFmpeg实现简单的视频解码器

    目录 FFmpeg解码过程流程图和关键的数据结构 mp4通过FFmpeg解码YUV裸视频数据 一.FFmpeg解码过程流程图和关键的数据结构 FFmpeg解码涉及的知识点比较多,很容易被函数和结构体搞 ...

  8. Jrtplib发送视频文件 + FFMPEG解码+VFW播放视频 (回调方式)

    在上篇文章<Jrtplib收发H264文件 + FFMPEG解码+VFW播放视频> 里,我们采用的模式是发送端读取本地H264文件, 把完整的Naul(包含起始码) 逐个发送给接收端,接收 ...

  9. 编译Android下可用的全平台FFmpeg(包含libx264与libfdk-aac)

    请尊重原创,转载请注明出处:http://blog.csdn.net/mabeijianxi/article/details/74544879 源码或工具版本: ndk :r14 FFmpeg 版本: ...

最新文章

  1. 什么是原码、反码、补码?什么是按位与?范围数字按位与!
  2. PL/SQL 按日期查询问题
  3. 进程间通信 IPC 的本地过程调用 LPC(Local Procedure Call)和远程过程调用 RPC(Remote Procedure Call)
  4. torch.argmax()函数
  5. 简述ospf的工作原理_简述洛氏硬度计的工作原理及应用领域
  6. leetcode 131. Palindrome Partitioning | 131. 分割回文串(递归解法)
  7. arduino使用oled代码_实用!Arduino平台最强大的“显卡”驱动:Adafruit GFX 图形库8000字详细使用指南...
  8. PyTorch基础(part2)
  9. mysql逗号分隔函数_mysql split 函数(用逗号分隔)的实现
  10. java 删除压缩zip文件_从ZIP存档中删除文件,而无需在Java或Python中解压缩 - java...
  11. 苹果官宣!iOS 16正式定档了 刘海屏MacBook Air或亮相
  12. android adb移植到arm,android-ndk – 为arm处理器构建android adb
  13. android java项目源码_Android项目源码本站第三个知乎app项目
  14. SQLyog详细安装教程
  15. 谷歌大脑新工作:把注意力放在MLP上!
  16. 植物大战僵尸的简单修改
  17. 安卓9:Android studio模拟器屏幕翻转、旋转屏幕的解决办法
  18. android 打开wifi并链接到制定ip,在安卓WiFi-Direct连接中获取对等设备IP地址的方法及设备与流程...
  19. 一步步学习k8s(二)
  20. 亚马逊云计算平台---------AWS(一)

热门文章

  1. vue:时间选择器自定义时间可选范围
  2. MySQL使用什么关键字添加唯一约束_MySQL使用____关键字添加唯一约束。
  3. DOC命令删除文件和文件夹
  4. 没有重复的数据在insert 时:ORA-00001:违反唯一约束条件
  5. 交流弱信号放大电路的设计
  6. 图片去底色怎么处理?图片去底色的方法
  7. c语言考试程序设计模板,期末考试C语言程序设计
  8. 个人或企业开发一款app需要多少钱?
  9. python龟速爬取整本小说
  10. 前端笔记--微信小程序(原生)