使用JavaCV和FFmpeg进行H264视频编码
上次成功通过FFmpeg采集摄像头的YUV数据,这次针对上一次的程序进行了改造,使用H264编码采集后的数据。
(传送门) JavaCV FFmpeg采集摄像头YUV数据
其他关于JavaCV的文章,可以通过下面的链接查看:
JavaCV-开发系列文章汇总篇(https://www.cnblogs.com/itqn/p/14696221.html)
采集摄像头数据是一个解码过程,而将采集后的数据进行H264编码则是编码过程,如图:
从上图可以看出,编码过程,数据流是从AVFrame流向AVPacket,而解码过程正好相反,数据流是从AVPacket流向AVFrame。
javacpp-ffmpeg依赖:
<dependency>
<groupId>org.bytedeco.javacpp-presets</groupId>
<artifactId>ffmpeg</artifactId>
<version>${ffmpeg.version}</version>
</dependency>
FFmpeg编码的过程是解码的逆过程,不过主线流程是类似的,如下图:
基本上主要的步骤都是:
- 查找编码/解码器
- 打开编码/解码器
- 进行编码/解码
在FFmpeg的demo流程中其实还有创建流avformat_new_stream()
,写入头部信息avformat_write_header()
和尾部信息av_write_trailer()
等操作,这里只是将YUV数据编码成H264裸流,所以可以暂时不需要考虑这些操作。
将采集视频流数据进行H264编码的整体流程主要有以下几个步骤:
- 采集视频帧
- 将视频帧转化为YUV420P格式
- 构建H264编码器
- 对视频帧进行编码
采集视频帧
采集视频流中的视频帧在上一次采集YUV数据的时候已经实现了,主要是从AVFormatContext中用av_read_frame()
读取视频数据并进行解码(avcodec_decode_video2()
),实现代码如下:
public AVFrame grab() throws FFmpegException {
if (av_read_frame(pFormatCtx, pkt) >= 0 && pkt.stream_index() == videoIdx) {
ret = avcodec_decode_video2(pCodecCtx, pFrame, got, pkt);
if (ret < 0) {
throw new FFmpegException(ret, "avcodec_decode_video2 解码失败");
}
if (got[0] != 0) {
return videoConverter.scale(pFrame);
}
av_packet_unref(pkt);
}
return null;
}
这样通过grab()方法就可以获取到视频流中的视频帧了。
将视频帧转化为YUV420P格式
在进行H264编码之前一定要确保视频帧是YUV420P格式的,所以必须对采集到的视频帧做一次转化,用到的是FFmpeg的SwsContext
组件,下面的VideoConverter
是对SwsContext
封装的组件,内部实现了AVFrame的填充及SwsContext
的初始化,使用方式如下:
// 1. 创建VideoConverter,指定转化格式为AV_PIX_FMT_YUV420P
videoConverter = VideoConverter.create(videoWidth, videoHeight, pCodecCtx.pix_fmt(),
videoWidth, videoHeight, AV_PIX_FMT_YUV420P);
// 2. 对视频帧进行转化
videoConverter.scale(pFrame);
VideoConvert的scale方式,实际上也是调用了SwsContext的scale方法:
sws_scale(swsContext, new PointerPointer<>(pFrame), pFrame.linesize(),
0, srcSliceH, new PointerPointer<>(avFrame), avFrame.linesize());
构建H264编码器
进行H264编码之前需要构建H264编码器,根据上面的流程图利用avcodec_find_encoder()
和avcodec_alloc_context3()
实现编码器的创建和参数配置,最后用avcodec_open()
打开编码器,完整的初始化代码如下:
public static VideoH264Encoder create(int width, int height, int fps, Map<String, String> opts)
throws FFmpegException {
VideoH264Encoder h = new VideoH264Encoder();
// 查找H264编码器
h.pCodec = avcodec_find_encoder(AV_CODEC_ID_H264);
if (h.pCodec == null) {
throw new FFmpegException("初始化 AV_CODEC_ID_H264 编码器失败");
}
// 初始化编码器信息
h.pCodecCtx = avcodec_alloc_context3(h.pCodec);
h.pCodecCtx.codec_id(AV_CODEC_ID_H264);
h.pCodecCtx.codec_type(AVMEDIA_TYPE_VIDEO);
h.pCodecCtx.pix_fmt(AV_PIX_FMT_YUV420P);
h.pCodecCtx.width(width);
h.pCodecCtx.height(height);
h.pCodecCtx.time_base().num(1);
h.pCodecCtx.time_base().den(fps);
// 其他参数设置
AVDictionary dictionary = new AVDictionary();
opts.forEach((k, v) -> {
avutil.av_dict_set(dictionary, k, v, 0);
});
h.ret = avcodec_open2(h.pCodecCtx, h.pCodec, dictionary);
if (h.ret < 0) {
throw new FFmpegException(h.ret, "avcodec_open2 编码器打开失败");
}
h.pkt = new AVPacket();
return h;
}
参数说明
width:视频的宽度
height:视频的高度
fps:视频的帧率
opts:编码器的其他参数设置
对视频帧进行编码
编码器构建完成后就可以对视频帧进行编码了,入参为AVFrame,出参为byte[](这里也可以是AVPacket,由于需要将H264裸流写入文件,这里直接返回byte数组)
public byte[] encode(AVFrame avFrame) throws FFmpegException {
if (avFrame == null) {
return null;
}
byte[] bf = null;
try {
avFrame.format(pCodecCtx.pix_fmt());
avFrame.width(pCodecCtx.width());
avFrame.height(pCodecCtx.height());
ret = avcodec_encode_video2(pCodecCtx, pkt, avFrame, got);
if (ret < 0) {
throw new FFmpegException(ret, "avcodec_encode_video2 编码失败");
}
if (got[0] != 0) {
bf = new byte[pkt.size()];
pkt.data().get(bf);
}
av_packet_unref(pkt);
} catch (Exception e) {
throw new FFmpegException(e.getMessage());
}
return bf;
}
最后只需要调整一下上一次的主程序,将读取YUV数据的部分,调整为将AVFrame丢进编码器,拉取byte数组即可。
public static void main(String[] args) throws FFmpegException, IOException, InterruptedException {
int fps = 25;
avdevice_register_all();
av_register_all();
VideoGrabber g = new VideoGrabber();
g.open("Integrated Camera");
VideoH264Encoder encoder = VideoH264Encoder.create(g.getVideoWidth(), g.getVideoHeight(), fps);
OutputStream fos = new FileOutputStream("yuv420p.h264");
for (int i = 0; i < 200; i++) {
AVFrame avFrame = g.grab();
byte[] buf = encoder.encode(avFrame);
if (buf != null) {
fos.write(buf);
}
Thread.sleep(1000 / fps);
}
fos.flush();
fos.close();
encoder.release();
g.close();
}
最终采集效果(H264裸流)可以用VLC播放:
这里对比一下,同样的200帧YUV数据和H264数据的大小,相差还是很大的。
=========================================================
H264编码源码可关注公众号 “HiIT青年” 发送 “ffmpeg-h264” 获取。(如果没有收到回复,可能是你之前取消过关注。)
关注公众号,阅读更多文章。
推荐阅读
-
使用JavaCPP和FFmpeg进行流媒体编码与图像处理
-
使用JavaCV和FFmpeg进行H264视频编码
-
实战教程:使用FFmpeg解析H264视频编码
-
Java 使用 ffmpeg 进行视频格式转换、音频和视频合并、播放和截图
-
微信 "扫一扫 "物联网,全面揭秘 "扫一扫 "背后的扫盲技术!-1.1 扫一扫感知物体是做什么的? 1.1 微信扫一扫是做什么的? 扫一扫识物是指以图片或视频(商品图片:鞋/包/美妆/服饰/家电/玩具/图书/食品/珠宝/家具/其他商品)为输入媒介,挖掘微信内容生态中的有价值信息(电商+百科+资讯,如图1所示),并展示给用户。这里的电商基本涵盖了微信小程序覆盖上亿SKU的全量优质电商,可以支持用户货比N家并直接下单购买,百科和资讯则聚合了微信内的头部自媒体如搜狗、搜搜、百度等,向用户展示和分享拍摄商品相关的内容资讯。 图 1 扫一扫识别功能示意图 欢迎大家更新iOS新版微信→扫一扫→识货,亲自体验,也欢迎大家通过识货界面的反馈按钮向我们提交反馈意见。 扫一扫识物实景图展示 1.2 扫一扫识物有哪些使用场景? 扫一扫识物的目的是为用户访问微信内部生态内容开辟一个新窗口,以用户扫图片为输入形式,为用户提供微信生态内容中的百科、资讯、电商等作为展示页面。除了用户熟悉的扫一扫操作外,我们还将进一步拓展长按操作,让用户更方便地进行扫一扫操作。"扫一扫知事 "的落地场景主要涵盖三大部分: a. 科普知识: a.科普知识。用户通过扫一扫,可以在微信生态圈中获取该对象的百科、资讯等常识或趣闻,帮助用户更好地了解该对象; b.购物场景。同样的搜索功能支持用户看到喜欢的商品立即检索到微信小程序电商中的同款商品,支持用户即扫即购; c.广告场景。扫一扫识别物体可以辅助公众号文章、视频更好地理解其中蕴含的图片信息,从而更好地投放匹配广告,提高点击率。 1.3 Sweep Sense 为 Sweep 家族带来了哪些新技术? 对于扫一扫来说,大家耳熟能详的应该就是扫一扫二维码、扫一扫小程序码、扫一扫条形码、扫一扫翻译了。无论是各种形式的编码还是文字字符,都可以看作是图片的一种特定编码形式,而物的识别则是对自然场景图片的识别,这对于扫一扫家族来说是一个质的飞跃,我们希望从物的识别入手,进一步拓展扫一扫对自然场景图片的理解能力,比如扫酒、扫车、扫植物、扫人脸等服务,如下图3所示。 图 3 Sweep 家族
-
使用 ffmpeg 和 mencoder 进行 java 视频转码
-
腾讯视频直播 02-推流-美颜滤镜 同样,腾讯云提供了 setBeautyFilter 方法来设置美颜风格、磨皮程度、美白程度和泛红程度 //style 磨皮风格:0:平滑 1:自然 2:朦胧 //美容级别:0-9。值为 0 时关闭美颜效果。默认值:0,关闭美颜效果。 //美白级别:取值 0-9。值为 0 时,将关闭美白效果。默认值:0,关闭美白效果。 //ruddyLevel:取值范围为 0-9。值为 0 时关闭美白效果。默认值:0,关闭美白效果。 public boolean setBeautyFilter(int style, int beautyLevel, int whiteningLevel, int ruddyLevel);; public boolean setBeautyFilter(int style, int beautyLevel, int whiteningLevel, int ruddyLevel) 滤镜 setFilter 方法可以设置滤镜效果,滤镜本身是一个直方图文件。setSpecialRatio 方法可以设置滤镜的程度,从 0 到 1,越大滤镜效果越明显,默认值为 0.5。 Bitmap bitmap = BitmapUtils.decodeResource(getResources, R.drawable.langman); if (mLivePusher) if (mLivePusher ! = null) { mLivePusher.setFilter(bmp); } 控制摄像头 腾讯云 sdk 默认为前置摄像头(可以通过修改 TXLivePushConfig 的配置函数 setFrontCamera 来修改默认值),调用一次 switchCamera 就切换一次,注意切换摄像头前要确保 TXLivePushConfig 和 TXLivePusher 对象已经初始化。 mLivePushConfig.setFrontCamera(true); // 默认前置摄像头。 mLivePusher.switchCamera; //切换摄像头。 ⑦ 设置徽标水印 腾讯视频云目前支持两种设置水印的方式:一种是在流媒体 SDK 中设置水印,原理是在 SDK 中对视频进行编码前在画面中设置水印。另一种方式是在云端设置水印,即由云端解析视频并添加水印标识。 建议使用 SDK 添加水印,因为在云端添加水印会有问题。下面是添加水印的 SDK 介绍: //设置视频水印 mLivePushConfig.setWatermark(BitmapFactory.decodeResource(getResources,R.drawable.watermark), 10, 10); // 最后两个参数是视频的水印。 //最后两个参数是水印位置的 X 轴和 Y 轴坐标。 mLivePusher.setConfig(mLivePushConfig); 如果需要对水印图像的位置进行模型适配,则需要调用水印规范化接口。 /设置视频水印 mLivePushConfig.setWatermark(mBitmap, 0.02f, 0.05f, 0.2f); //参数为水印图像。 //参数包括水印图像的位图、水印位置的 X 轴坐标、水印位置的 Y 轴坐标和水印宽度。后三个参数的范围是 [0,1]。 // 最后两个参数是水印位置的 X 轴坐标和 Y 轴坐标。 mLivePusher.setConfig(mLivePushConfig); TXLivePushConfig 中的 setHardwareAcceleration 方法可以启用或禁用硬件编码。 if (mHWVideoEncode){ if (mLivePushConfig ! = null) { if (Build.VERSION.SDK_INT < 18){ Toast.makeText(getApplicationContext, "Hardware acceleration failed, current phone API level is too low (min 18)"、 Toast.LENGTH_SHORT).show; mHWVideoEncode = false; } } } } mLivePushConfig.setHardwareAcceleration(mHWVideoEncode ? TXLiveConstants.ENCODE_VIDEO_HARDWARE : TXLiveConstants.ENCODE_VIDEO_SOFTWARE); mLivePusher.setConfig(mLivePushConfig); // 如果您不确定何时启用硬件加速,建议将其设置为 ENCODE_VIDEO_AUTO。 // 默认情况下启用软件编码,但如果手机的 CPU 使用率超过 80% 或帧速率为 10,SDK 将自动切换到硬件编码。 ⑨ 后台推流 在常规模式下,一旦应用程序进入后台,摄像头捕捉数据的能力就会被 Android 禁用,这意味着 SDK 无法继续捕捉和编码音频和视频数据。如果我们什么都不做,故事就会按照下面的脚本发展: 阶段 1(背景剪切后 10 秒 ->)- CDN 无法将视频流传输给观众,因为没有数据,观众看到的是主帧。 阶段 2(10 秒-> 70 秒)--观众一方的播放器因无法接收到直播流而退出,房间里空无一人。 第 3 阶段(70 秒后)--服务器直接断开了推送流媒体的 RTMP 链接,主播需要重新打开直播才能继续。 主播可能只是短暂地接了一个紧急电话,但各云提供商的安全措施会迫使主播的直播提前结束。 1) 设置 setPauseFlag 在开始推流之前,使用 TXLivePushConfig 的 setPauseImg 接口设置一个等待图像,其含义建议为 "主播将暂时离开,稍后再回来"。
-
使用 FFmpeg 开发音频和视频流 (III) - 将视频 YUV 格式编码为 H264
-
使用JavaCV与FFmpeg进行视频压缩操作指南
-
使用FFmpeg和NVIDIA GPU进行视频硬件编码与解码的实验探究