分享一个关于使用ffmpeg对mp4文件进行压缩切片为hls格式m3u8文件的命令行调用程序。
前提是已经安装了ffmpeg,安装过程就不再赘述了。
直接上代码
package xxxxx;
import cn.hutool.core.io.fileutil;
import cn.hutool.core.io.ioutil;
import com.czi.uavcloud.common.utils.stringutils;
import com.czi.uavcloud.fileprocess.utils.fileutils;
import lombok.extern.slf4j.slf4j;
import java.io.*;
import java.net.httpurlconnection;
import java.net.url;
import java.util.uuid;
/**
* 压缩切片处理器
*
* @author god_cvz
*/
@slf4j
public class videocompresshandle {
protected static final boolean windows = system.getproperty("os.name").startswith("windows");
protected static final string slash = windows ? "\\" : "/";
// 输出文件路径,可以自行修改
public static final string temp_folder_path = (windows ? "d:" : slash + "var") + slash + "tempvideocompress" + slash;
// 切片时长,默认5秒一个切片
private static final string default_hls_time = "5";
/**
* 从指定url下载视频并压缩切片为m3u8
*
* @param downloadurl 视频下载地址
*/
public static void compresswithurl(string downloadurl) {
string videofilepath = temp_folder_path + uuid.randomuuid() + slash + fileutil.getname(downloadurl);
// 下载视频至指定路径
try (bufferedinputstream bufferinput = new bufferedinputstream(getinputstreamfromurl(downloadurl));
fileoutputstream out = new fileoutputstream(videofilepath)) {
ioutil.copy(bufferinput, out);
} catch (exception e) {
e.printstacktrace();
}
compresswithlocal(videofilepath);
}
/**
* 从本地路径读取视频并压缩切片为m3u8
*
* @param videofilepath 本地视频地址
*/
public static void compresswithlocal(string videofilepath) {
// hutool工具返回的名称是带后缀的,入http://abc/123.mp4,返回的是123.mp4
string videoname = fileutil.getname(videofilepath);
// 创建临时文件夹目录
string tempfolderpath = temp_folder_path + uuid.randomuuid();
fileutil.mkdir(tempfolderpath);
if (!windows) {
try {
// 文件夹授权
asyncexecute(new string[]{"chmod", "777", "-r", tempfolderpath});
} catch (ioexception e) {
throw new runtimeexception(e);
}
}
// m3u8文件输出地址:/var/tempvideocompress/业务id/文件名/文件名.m3u8
string outputfolderpath = tempfolderpath + slash + videoname.split("\\.")[0];
fileutil.mkdir(outputfolderpath);
string m3u8filepath = outputfolderpath + slash + videoname.split("\\.")[0] + ".m3u8";
handle(tempfolderpath, videofilepath, m3u8filepath);
}
/**
* 从指定 url 下载资源并返回 inputstream
*
* @param urlstring 资源的 url 地址
* @return inputstream (需要调用方手动关闭)
* @throws ioexception 下载或连接失败时抛出异常
*/
public static inputstream getinputstreamfromurl(string urlstring) throws exception {
if (urlstring == null || urlstring.isempty()) {
throw new illegalargumentexception("url 不能为空");
}
log.info("[download] 开始下载文件:{}", urlstring);
long starttime = system.currenttimemillis();
try {
url url = new url(urlstring);
httpurlconnection connection = (httpurlconnection) url.openconnection();
connection.setrequestmethod("get");
connection.setconnecttimeout(10_000);
connection.setreadtimeout(15_000);
connection.setdoinput(true);
// 检查响应码
int responsecode = connection.getresponsecode();
if (responsecode != httpurlconnection.http_ok) {
throw new ioexception("下载失败,http 响应码:" + responsecode);
}
log.info("[download] 连接成功[{}],开始接收数据...", url);
inputstream inputstream = connection.getinputstream();
long endtime = system.currenttimemillis();
log.info("[download] 下载完成,用时 {} ms", (endtime - starttime));
return inputstream;
} catch (exception e) {
log.error("[download] 下载文件失败[{}], error:{}", urlstring, e.getmessage());
throw new exception("[download] 下载文件失败: " + e.getmessage());
}
}
public static void handle(string tempfolderpath, string videofilepath, string m3u8filepath) {
long starttime = system.currenttimemillis();
try {
// 压缩切片
log.info("[视频压缩切片]压缩切片文件");
ffmpegcompress(videofilepath, m3u8filepath);
// 需要上传的可以自己处理
// log.info("[视频压缩切片]上传切片目录文件:{}", videofilepath);
// uploadfolder(outputfolder);
} catch (exception e) {
log.info("[视频压缩切片]处理失败:{}", e.getmessage());
} finally {
long costtime = system.currenttimemillis() - starttime;
log.info("[视频压缩切片]总耗时:{}", costtime);
// log.info("[视频压缩切片]删除本地压缩包,释放空间:{}", tempfolderpath);
// fileutil.del(tempfolderpath);
}
}
/**
* 将mp4视频文件转码压缩为m3u8并切片
*
* @param inputfile
* @param outputfile
*/
public static void ffmpegcompress(string inputfile, string outputfile) {
ffmpegcompress(inputfile, outputfile, default_hls_time);
}
/**
* 将mp4视频文件转码压缩为m3u8并切片
*
* @param inputfile 待处理文件
* @param outputfile 输出的具体文件路径
*/
public static void ffmpegcompress(string inputfile, string outputfile, string hlstime) {
// 上级目录绝对路径
string absolutefolderpath = outputfile.substring(0, outputfile.indexof(fileutil.getname(outputfile)));
if (!fileutil.exist(absolutefolderpath)) {
fileutils.createdirifabsent(absolutefolderpath);
}
log.info("开始压缩转码文件:in:{},out:{},hlstime:{}", inputfile, outputfile, hlstime);
long starttime = system.currenttimemillis();
// linux的ffmpeg可执行文件放在/usr/bin/ffmpeg,可以自行修改
string cmd = windows ? "d:\\ffmpeg\\bin\\ffmpeg.exe" : "/usr/bin/ffmpeg";
string[] command = new string[]{cmd,
"-i", inputfile,
//多线程数
"-threads", "2",
//帧数
"-r", "25",
//码率
"-b:v", "3000k",
//分辨率
"-s", "1920x1080",
//ultrafast(转码速度最快,视频往往也最模糊)、superfast、veryfast、faster、fast、medium、slow、slower、veryslow、placebo这10个选项,从快到慢
"-preset", "ultrafast",
//视频画质级别 1-5
"-level", "3.0",
//从0开始
"-start_number", "0",
"-g", "50",
//设置编码器
"-codec:v", "h264",
//转码
"-f", "hls",
//每5秒切一个
"-hls_time", stringutils.isnotblank(hlstime) ? hlstime : default_hls_time,
//设置播放列表保存的最多条目,设置为0会保存所有切片信息,默认值为5
"-hls_list_size", "0",
outputfile};
try {
asyncexecute(command);
} catch (ioexception e) {
throw new runtimeexception(e);
}
log.info("压缩转码文件完成:{},耗时:{}", outputfile, system.currenttimemillis() - starttime);
}
/**
* 执行shell命令
*
* @param cmd
*/
public static integer asyncexecute(string[] cmd) throws ioexception {
return asyncexecute(cmd, null, null);
}
/**
* 执行shell命令(支持任务管理器)
*
* @param cmd 命令数组
* @param taskmanager 任务管理器,用于注册进程和检查取消状态
* @param taskid 任务id
*/
public static integer asyncexecute(string[] cmd, object taskmanager, long taskid) throws ioexception {
log.info("执行命令:{}", string.join(" ", cmd));
process process = new processbuilder(cmd)
// 合并错误流和标准流
.redirecterrorstream(true)
.start();
// 如果有任务管理器,注册进程
if (taskmanager != null && taskid != null) {
try {
// 使用反射调用 registerchildprocess 方法
taskmanager.getclass().getmethod("registerchildprocess", long.class, process.class)
.invoke(taskmanager, taskid, process);
} catch (exception e) {
log.warn("注册子进程失败: {}", e.getmessage());
}
}
try (bufferedreader reader = new bufferedreader(
new inputstreamreader(process.getinputstream()))) {
// 异步读取输出(防止阻塞)
thread outputthread = new thread(() -> {
try {
string line;
while ((line = reader.readline()) != null) {
system.out.println("[process] " + line);
// 检查任务是否被取消
if (taskmanager != null && taskid != null) {
try {
object context = taskmanager.getclass().getmethod("gettaskcontext", long.class)
.invoke(taskmanager, taskid);
if (context != null) {
boolean shouldstop = (boolean) context.getclass().getmethod("shouldstop")
.invoke(context);
if (shouldstop != null && shouldstop) {
log.info("检测到任务取消,停止读取进程输出,任务id: {}", taskid);
break;
}
}
} catch (exception e) {
// 忽略反射调用异常
}
}
}
} catch (ioexception e) {
system.err.println("输出流读取异常: " + e.getmessage());
}
});
outputthread.start();
// 等待进程完成,支持中断检查
int exitcode = waitforprocesswithcancellationcheck(process, taskmanager, taskid);
// 等待输出线程结束
outputthread.join(1000);
return exitcode;
} catch (interruptedexception e) {
log.info("进程执行被中断");
process.destroyforcibly();
throw new runtimeexception("进程执行被取消", e);
}
}
/**
* 等待进程完成,支持取消检查
*/
private static int waitforprocesswithcancellationcheck(process process, object taskmanager, long taskid) throws interruptedexception {
while (true) {
try {
// 检查线程是否被中断
if (thread.currentthread().isinterrupted()) {
log.info("检测到线程中断,正在终止进程...");
process.destroyforcibly();
throw new interruptedexception("任务被取消");
}
// 检查任务管理器中的任务状态
if (taskmanager != null && taskid != null) {
try {
object context = taskmanager.getclass().getmethod("gettaskcontext", long.class)
.invoke(taskmanager, taskid);
if (context != null) {
boolean shouldstop = (boolean) context.getclass().getmethod("shouldstop")
.invoke(context);
if (shouldstop != null && shouldstop) {
log.info("检测到任务取消请求,正在终止进程,任务id: {}", taskid);
process.destroyforcibly();
throw new interruptedexception("任务被取消");
}
}
} catch (exception e) {
// 忽略反射调用异常
}
}
// 非阻塞检查进程是否完成
if (process.isalive()) {
// 进程还在运行,等待一小段时间后再检查
thread.sleep(1000);
} else {
// 进程已完成,返回退出码
return process.exitvalue();
}
} catch (interruptedexception e) {
log.info("等待进程时被中断,正在强制终止进程...");
process.destroyforcibly();
throw e;
}
}
}
/**
* 上传切片文件目录
*
* @param folder
* @return
*/
public static void uploadfolder(string folder) {
// 切片文件上传至源文件同级目录下的一个同名文件夹
file[] files = fileutil.ls(folder);
if (files == null) {
return;
}
for (file file : files) {
uploadfile(file);
}
}
/**
* todo:自定义oss上传
*
* @param file
*/
private static void uploadfile(file file) {
try (fileinputstream fileinputstream = new fileinputstream(file)) {
} catch (filenotfoundexception e) {
log.error("读取文件报错");
} catch (ioexception e) {
throw new runtimeexception(e);
}
}
}
原视频文件:

切片后文件:

到此这篇关于springboot基于ffmpeg实现压缩视频切片为m3u8的文章就介绍到这了,更多相关springboot ffmpeg视频压缩内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论