Skip to content

Commit

Permalink
perf: 视频转码适配nvidia显卡
Browse files Browse the repository at this point in the history
  • Loading branch information
jamebal committed Apr 29, 2024
1 parent 627e5b3 commit 3cafa69
Showing 1 changed file with 71 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -238,6 +238,12 @@ private void videoToM3U8(String fileId, String username, String relativePath, St
"-hls_segment_filename", Paths.get(videoCacheDir, fileId + "-%03d.ts").toString(),
outputPath
);
// 检测是硬件加速
processBuilder = checkHardwareAcceleration(fileId, processBuilder, fileAbsolutePath, bitrate, videoCacheDir, outputPath);

// 打印ffmpeg命令
processBuilder.command().forEach(command -> System.out.println(command + " \\"));

processBuilder.redirectErrorStream(true);
Process process = processBuilder.start();
boolean pushMessage = false;
Expand Down Expand Up @@ -272,6 +278,71 @@ private void videoToM3U8(String fileId, String username, String relativePath, St
}
}

private ProcessBuilder checkHardwareAcceleration(String fileId, ProcessBuilder processBuilder, Path fileAbsolutePath, int bitrate, String videoCacheDir, String outputPath) {
if (checkCUDA() && checkNVENC()) {
// 使用CUDA硬件加速和NVENC编码器
processBuilder = new ProcessBuilder(
Constants.FFMPEG,
"-hwaccel", "cuda",
"-hwaccel_output_format", "cuda",
"-i", fileAbsolutePath.toString(),
"-vf", "scale_cuda=-2:" + 720,
"-c:v", "h264_nvenc",
"-b:v", bitrate + "k",
"-preset", "medium",
"-profile:v", "main",
"-level", "4.0",
"-start_number", "0",
"-hls_time", "10",
"-hls_list_size", "0",
"-g", "48",
"-sc_threshold", "0",
"-f", "hls",
"-hls_segment_filename", Paths.get(videoCacheDir, fileId + "-%03d.ts").toString(),
outputPath
);
}
return processBuilder;
}

/**
* 检测是否支持cuda硬件加速
*/
private boolean checkCUDA() {
try {
Process process = Runtime.getRuntime().exec("ffmpeg -hwaccels");
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
if (line.contains("cuda")) {
return true;
}
}
} catch (IOException e) {
log.error(e.getMessage(), e);
}
return false;
}

/**
* 检测是否支持nvenc编码器
*/
private boolean checkNVENC() {
try {
Process process = Runtime.getRuntime().exec("ffmpeg -hide_banner -encoders | grep nvenc");
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
if (line.contains("nvenc")) {
return true;
}
}
} catch (IOException e) {
log.error(e.getMessage(), e);
}
return false;
}

/**
* 判断是否需要转码
* @param videoInfo 视频信息
Expand Down

0 comments on commit 3cafa69

Please sign in to comment.