简介
RTMPDump是一个用来处理RTMP流媒体的工具包,是一个C++的开源工程。而我们需要将Android平台下直接使用RTMPDump来进行RTMP推流,这里就涉及两个方便内容:第一,需要使用NDK对RTMPDump进行交叉编译。第二,如何在Android平台下使用RTMPDump。今天这篇文章主要是教会大家如何将RTMPDump移植到Android平台,让大家可以把代码跑起来看到直观的效果,至于具体RTMPDump的使用后面再详细介绍,当然网上也有很多教程,但第一步一般最容易把大家卡住,我就先和大家把第一步走好。
Linux使用ndk编译RTMPDump
网上对这一步有很多介绍,但我都没编出来,折磨了好久。但只要花时间,还是可以搞出来的,这里我详细介绍下,当然最后也会提供完成可用的源码。
编译环境
- CentOS Linux release 7.4.1708 (Core)
- 下载配置android sdk manager,下载ndk配置环境变量,参考Linux下Android构建环境
- gcc 、openssh等如果发现缺少依赖软件,直接用yum安装即可。
下载配置RTMPDump
RTMPDump直接到官网下载
我们直接下载最新的版本2.3
源码在librtmp文件夹下。然后我们新建一个文件夹rtmp后面用来进行编译:
新建一个jni目录,目录结构如上。然后将下载RTMPDump的头文件(.h)拷贝到include中,将.c文件拷贝到src中。如下图:
然后需要在jni目录下新建Android.mk和Application.mk文件
Android.mk
LOCAL_PATH := $(call my-dir)
include $(CLEAR_VARS)
LOCAL_MODULE := librtmp
LOCAL_SRC_FILES := \
src/amf.c \
src/hashswf.c \
src/log.c \
src/parseurl.c \
src/rtmp.c \
LOCAL_C_INCLUDES := $(LOCAL_PATH)/include
LOCAL_LDLIBS := -L$(SYSROOT)/usr/lib -llog
LOCAL_CFLAGS := -Wall -O2 -DSYS=posix -DNO_CRYPTO
TARGET_PLATFORM := android-23
### librtmp library ###
### shared library use the first line
### static library use the second line
### !!! only one line can be used !!! ###
include $(BUILD_SHARED_LIBRARY)
#include $(BUILD_STATIC_LIBRARY)
Application.mk
APP_ABI := all
到此就配置完成了在rtmp的根目录下执行
[root@MiWiFi-R2D-srv home]# ndk-build
当然你得把ndk配置到环境变量中
最后生成libs目录,这样so包就OK了,基本所有平台都支持
这里我给出编译项目地址 RtmpDump-Android,大家可以直接clone使用。当然已经编译好的动态库在libs下,大家可以直接使用。
Android平台下使用RTMPDump
前面我们已经把要使用的so编译出来了。接下来就是如何在Android平台下使用,这里还是在这个专题的同步项目中写代码FFmpegSample。本篇文章对应的代码是v1.4,大家一定注意版本。
设计RTMPDump的代码并不多。我把新增的文件标记出来:
- cpp/include下的librtmp就是我们在编译RTMPDump时候用到的头文件,这里直接copy过来即可。
- rtmp_handle.cpp 是真正业务实现的地方
- RtmpHandle.java 是提供native的调用入口
接下来讲具体集成流程:
第一步
将RTMPDump头文件copy到cpp/include下,在用动态库的时候头文件当然是必须的
第二步
将前面编译得到的librtmp.so复制到项目的jniLibs/armeabi目录下。注意:这里我测试使用的是arm机器,所以就直接使用armeabi下的so
第三步
修改CmakeList.txt
新增
add_library(rtmp SHARED IMPORTED)
set_target_properties(rtmp
PROPERTIES IMPORTED_LOCATION
${CMAKE_SOURCE_DIR}/src/main/jniLibs/${ANDROID_ABI}/librtmp.so)
修改链接库,添加rtmp
target_link_libraries( # Specifies the target library.
ffmpeg-handle
avcodec
avdevice
avfilter
avformat
avutil
swresample
swscale
rtmp
# Links the target library to the log library
# included in the NDK.
${log-lib} )
第四步
新建RtmpHandle.java
public class RtmpHandle {
public static RtmpHandle mInstance;
private RtmpHandle() {
}
public synchronized static RtmpHandle getInstance() {
if (mInstance == null) {
mInstance = new RtmpHandle();
}
return mInstance;
}
static {
System.loadLibrary("rtmp");
}
public native void pushFile(String path);
}
加载rtmp的库,提供native调用方法
第五步
新建rtmp_handle.cpp,加入jni的方法
extern "C"
JNIEXPORT void JNICALL
Java_com_wangheart_rtmpfile_rtmp_RtmpHandle_pushFile(JNIEnv *env, jobject instance, jstring path_) {
const char *path = env->GetStringUTFChars(path_, 0);
logw(path);
// TODO
publish_using_packet(path);
env->ReleaseStringUTFChars(path_, path);
}
而publish_using_packet(path);
方法调用就是真正的推流逻辑了。
第六步
在MainActivity.java中加一个按钮来触发推流
public void librmtp(View view) {
new Thread(){
@Override
public void run() {
super.run();
final String path = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "dongfengpo.flv";
File file = new File(path);
LogUtils.d(path + " " + file.exists());
RtmpHandle.getInstance().pushFile(path);
}
}.start();
}
既然是耗时操作,当然也是得开线程的。这里推送的文件是《东风破》——周杰伦,这个视频也是前面flv格式详解+实例剖析有用到过。
到这里移植基本完成,上一张完成图:
RTMPDump的使用细节后面文章我们再讨论。感谢大家关注!
//
// Created by eric on 2017/11/24.
//
//
// Created by eric on 2017/11/1.
//
#include <jni.h>
#include <string>
#include<android/log.h>
#include <exception>
//定义日志宏变量
#define logw(content) __android_log_write(ANDROID_LOG_WARN,"eric",content)
#define loge(content) __android_log_write(ANDROID_LOG_ERROR,"eric",content)
#define logd(content) __android_log_write(ANDROID_LOG_DEBUG,"eric",content)
extern "C" {
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#include "librtmp/rtmp_sys.h"
#include "librtmp/log.h"
#include <unistd.h>
#define HTON16(x) ((x>>8&0xff)|(x<<8&0xff00))
#define HTON24(x) ((x>>16&0xff)|(x<<16&0xff0000)|(x&0xff00))
#define HTON32(x) ((x>>24&0xff)|(x>>8&0xff00)|\
(x<<8&0xff0000)|(x<<24&0xff000000))
#define HTONTIME(x) ((x>>16&0xff)|(x<<16&0xff0000)|(x&0xff00)|(x&0xff000000))
}
#include <iostream>
using namespace std;
/*read 1 byte*/
int ReadU8(uint32_t *u8, FILE *fp) {
if (fread(u8, 1, 1, fp) != 1)
return 0;
return 1;
}
/*read 2 byte*/
int ReadU16(uint32_t *u16, FILE *fp) {
if (fread(u16, 2, 1, fp) != 1)
return 0;
*u16 = HTON16(*u16);
return 1;
}
/*read 3 byte*/
int ReadU24(uint32_t *u24, FILE *fp) {
if (fread(u24, 3, 1, fp) != 1)
return 0;
*u24 = HTON24(*u24);
return 1;
}
/*read 4 byte*/
int ReadU32(uint32_t *u32, FILE *fp) {
if (fread(u32, 4, 1, fp) != 1)
return 0;
*u32 = HTON32(*u32);
return 1;
}
/*read 1 byte,and loopback 1 byte at once*/
int PeekU8(uint32_t *u8, FILE *fp) {
if (fread(u8, 1, 1, fp) != 1)
return 0;
fseek(fp, -1, SEEK_CUR);
return 1;
}
/*read 4 byte and convert to time format*/
int ReadTime(uint32_t *utime, FILE *fp) {
if (fread(utime, 4, 1, fp) != 1)
return 0;
*utime = HTONTIME(*utime);
return 1;
}
int InitSockets() {
/* WORD version;
WSADATA wsaData;
version=MAKEWORD(2,2);
return (WSAStartup(version, &wsaData) == 0);*/
return 1;
}
void CleanupSockets() {
// WSACleanup();
}
//Publish using RTMP_SendPacket()
int publish_using_packet(const char *path) {
RTMP *rtmp = NULL;
RTMPPacket *packet = NULL;
uint32_t start_time = 0;
uint32_t now_time = 0;
//the timestamp of the previous frame
long pre_frame_time = 0;
long lasttime = 0;
int bNextIsKey = 1;
uint32_t preTagsize = 0;
//packet attributes
uint32_t type = 0;
uint32_t datalength = 0;
uint32_t timestamp = 0;
uint32_t streamid = 0;
FILE *fp = NULL;
fp = fopen(path, "rb");
if (!fp) {
RTMP_LogPrintf("Open File Error.\n");
CleanupSockets();
return -1;
}
/* set log level */
//RTMP_LogLevel loglvl=RTMP_LOGDEBUG;
//RTMP_LogSetLevel(loglvl);
if (!InitSockets()) {
RTMP_LogPrintf("Init Socket Err\n");
return -1;
}
rtmp = RTMP_Alloc();
RTMP_Init(rtmp);
//set connection timeout,default 30s
rtmp->Link.timeout = 5;
if (!RTMP_SetupURL(rtmp, "rtmp://192.168.31.127/live")) {
RTMP_Log(RTMP_LOGERROR, "SetupURL Err\n");
RTMP_Free(rtmp);
CleanupSockets();
return -1;
}
//if unable,the AMF command would be 'play' instead of 'publish'
RTMP_EnableWrite(rtmp);
if (!RTMP_Connect(rtmp, NULL)) {
RTMP_Log(RTMP_LOGERROR, "Connect Err\n");
RTMP_Free(rtmp);
CleanupSockets();
return -1;
}
if (!RTMP_ConnectStream(rtmp, 0)) {
RTMP_Log(RTMP_LOGERROR, "ConnectStream Err\n");
RTMP_Close(rtmp);
RTMP_Free(rtmp);
CleanupSockets();
return -1;
}
packet = (RTMPPacket *) malloc(sizeof(RTMPPacket));
RTMPPacket_Alloc(packet, 1024 * 64);
RTMPPacket_Reset(packet);
packet->m_hasAbsTimestamp = 0;
packet->m_nChannel = 0x04;
packet->m_nInfoField2 = rtmp->m_stream_id;
RTMP_LogPrintf("Start to send data ...\n");
//jump over FLV Header
fseek(fp, 9, SEEK_SET);
//jump over previousTagSizen
fseek(fp, 4, SEEK_CUR);
start_time = RTMP_GetTime();
while (1) {
//not quite the same as FLV spec
if (!ReadU8(&type, fp))
break;
if (!ReadU24(&datalength, fp))
break;
if (!ReadTime(×tamp, fp))
break;
if (!ReadU24(&streamid, fp))
break;
if (type != 0x08 && type != 0x09) {
//jump over non_audio and non_video frame,
//jump over next previousTagSizen at the same time
fseek(fp, datalength + 4, SEEK_CUR);
continue;
}
if (fread(packet->m_body, 1, datalength, fp) != datalength)
break;
packet->m_headerType = RTMP_PACKET_SIZE_LARGE;
packet->m_nTimeStamp = timestamp;
packet->m_packetType = type;
packet->m_nBodySize = datalength;
pre_frame_time = timestamp;
long delt = RTMP_GetTime() - start_time;
printf("%ld,%ld\n", pre_frame_time, (RTMP_GetTime() - start_time));
__android_log_print(ANDROID_LOG_WARN, "eric",
"%ld,%ld", pre_frame_time, (RTMP_GetTime() - start_time));
if (delt < pre_frame_time) {
usleep((pre_frame_time - delt)*1000);
}
if (!RTMP_IsConnected(rtmp)) {
RTMP_Log(RTMP_LOGERROR, "rtmp is not connect\n");
break;
}
if (!RTMP_SendPacket(rtmp, packet, 0)) {
RTMP_Log(RTMP_LOGERROR, "Send Error\n");
break;
}
if (!ReadU32(&preTagsize, fp))
break;
if (!PeekU8(&type, fp))
break;
if (type == 0x09) {
if (fseek(fp, 11, SEEK_CUR) != 0)
break;
if (!PeekU8(&type, fp)) {
break;
}
if (type == 0x17)
bNextIsKey = 1;
else
bNextIsKey = 0;
fseek(fp, -11, SEEK_CUR);
}
}
RTMP_LogPrintf("\nSend Data Over\n");
if (fp)
fclose(fp);
if (rtmp != NULL) {
RTMP_Close(rtmp);
RTMP_Free(rtmp);
rtmp = NULL;
}
if (packet != NULL) {
RTMPPacket_Free(packet);
free(packet);
packet = NULL;
}
CleanupSockets();
return 0;
}
int main(int argc, char *argv[]) {
//2 Methods:
// publish_using_packet();
//publish_using_write();
return 0;
}
extern "C"
JNIEXPORT void JNICALL
Java_com_wangheart_rtmpfile_rtmp_RtmpHandle_pushFile(JNIEnv *env, jobject instance, jstring path_) {
const char *path = env->GetStringUTFChars(path_, 0);
logw(path);
// TODO
publish_using_packet(path);
env->ReleaseStringUTFChars(path_, path);
}