20 modularize the code to split up large classes (#21)
* MODULARIZE ClipService by introducing CompressionService, MetadataService, and ThumbnailService * ADD deleteClip functionality to ClipController
This commit is contained in:
@@ -0,0 +1,46 @@
|
||||
package com.ddf.vodsystem.services.media;
|
||||
|
||||
import com.ddf.vodsystem.dto.CommandOutput;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStreamReader;
|
||||
import java.util.List;
|
||||
import java.util.function.Consumer;
|
||||
|
||||
public class CommandRunner {
|
||||
public static CommandOutput run(List<String> command, Consumer<String> onOutput) throws IOException, InterruptedException {
|
||||
ProcessBuilder processBuilder = new ProcessBuilder(command);
|
||||
processBuilder.redirectErrorStream(true);
|
||||
|
||||
Process process = processBuilder.start();
|
||||
CommandOutput commandOutput = new CommandOutput();
|
||||
|
||||
// Read the output and error streams
|
||||
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
|
||||
String line;
|
||||
while ((line = reader.readLine()) != null) {
|
||||
commandOutput.addLine(line);
|
||||
if (onOutput != null) {
|
||||
onOutput.accept(line);
|
||||
}
|
||||
}
|
||||
|
||||
int exitCode = process.waitFor();
|
||||
commandOutput.setExitCode(exitCode);
|
||||
|
||||
if (exitCode != 0) {
|
||||
throw new IOException("Command failed with exit code " + exitCode + ": " + String.join("\n", commandOutput.getOutput()));
|
||||
}
|
||||
|
||||
return commandOutput;
|
||||
}
|
||||
|
||||
public static CommandOutput run(List<String> command) throws IOException, InterruptedException {
|
||||
return run(command, null);
|
||||
}
|
||||
|
||||
private CommandRunner() {
|
||||
// Private constructor to prevent instantiation
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,123 @@
|
||||
package com.ddf.vodsystem.services.media;
|
||||
|
||||
import com.ddf.vodsystem.dto.ProgressTracker;
|
||||
import com.ddf.vodsystem.dto.VideoMetadata;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
@Service
|
||||
public class CompressionService {
|
||||
private static final Logger logger = LoggerFactory.getLogger(CompressionService.class);
|
||||
|
||||
private static final float AUDIO_RATIO = 0.15f;
|
||||
private static final float MAX_AUDIO_BITRATE = 128f;
|
||||
private static final float BITRATE_MULTIPLIER = 0.9f;
|
||||
private final Pattern timePattern = Pattern.compile("out_time_ms=(\\d+)");
|
||||
|
||||
public void compress(File inputFile, File outputFile, VideoMetadata videoMetadata, ProgressTracker progress) throws IOException, InterruptedException {
|
||||
logger.info("Compressing video from {} to {}", inputFile.getAbsolutePath(), outputFile.getAbsolutePath());
|
||||
|
||||
float length = videoMetadata.getEndPoint() - videoMetadata.getStartPoint();
|
||||
List<String> command = buildCommand(inputFile, outputFile, videoMetadata);
|
||||
CommandRunner.run(command, line -> setProgress(line, progress, length));
|
||||
}
|
||||
|
||||
private void setProgress(String line, ProgressTracker progress, float length) {
|
||||
Matcher matcher = timePattern.matcher(line);
|
||||
if (matcher.find()) {
|
||||
float timeInMs = Float.parseFloat(matcher.group(1)) / 1000000f;
|
||||
progress.setProgress(timeInMs / length);
|
||||
}
|
||||
}
|
||||
|
||||
private List<String> buildFilters(Float fps, Integer width, Integer height) {
|
||||
List<String> command = new ArrayList<>();
|
||||
command.add("-vf");
|
||||
|
||||
List<String> filters = new ArrayList<>();
|
||||
|
||||
if (fps != null) {
|
||||
logger.info("Frame rate set to {}", fps);
|
||||
filters.add("fps=" + fps);
|
||||
}
|
||||
|
||||
if (!(width == null && height == null)) {
|
||||
logger.info("Scaling video to width: {}, height: {}", width, height);
|
||||
String w = (width != null) ? width.toString() : "-1";
|
||||
String h = (height != null) ? height.toString() : "-1";
|
||||
filters.add("scale=" + w + ":" + h);
|
||||
}
|
||||
|
||||
logger.info("Adding video filters");
|
||||
command.add(String.join(",", filters));
|
||||
return command;
|
||||
}
|
||||
|
||||
private List<String> buildBitrate(Float length, Float fileSize) {
|
||||
List<String> command = new ArrayList<>();
|
||||
|
||||
float bitrate = ((fileSize * 8) / length) * BITRATE_MULTIPLIER;
|
||||
float audioBitrate = bitrate * AUDIO_RATIO;
|
||||
float videoBitrate;
|
||||
|
||||
if (audioBitrate > MAX_AUDIO_BITRATE) {
|
||||
audioBitrate = MAX_AUDIO_BITRATE;
|
||||
videoBitrate = bitrate - MAX_AUDIO_BITRATE;
|
||||
} else {
|
||||
videoBitrate = bitrate * (1 - AUDIO_RATIO);
|
||||
}
|
||||
|
||||
command.add("-b:v");
|
||||
command.add(videoBitrate + "k");
|
||||
command.add("-b:a");
|
||||
command.add(audioBitrate + "k");
|
||||
|
||||
return command;
|
||||
}
|
||||
|
||||
private List<String> buildInputs(File inputFile, Float startPoint, Float length) {
|
||||
List<String> command = new ArrayList<>();
|
||||
|
||||
command.add("-ss");
|
||||
command.add(startPoint.toString());
|
||||
|
||||
command.add("-i");
|
||||
command.add(inputFile.getAbsolutePath());
|
||||
|
||||
command.add("-t");
|
||||
command.add(Float.toString(length));
|
||||
|
||||
return command;
|
||||
}
|
||||
|
||||
private List<String> buildCommand(File inputFile, File outputFile, VideoMetadata videoMetadata) {
|
||||
List<String> command = new ArrayList<>();
|
||||
command.add("ffmpeg");
|
||||
command.add("-progress");
|
||||
command.add("pipe:1");
|
||||
command.add("-y");
|
||||
|
||||
Float length = videoMetadata.getEndPoint() - videoMetadata.getStartPoint();
|
||||
command.addAll(buildInputs(inputFile, videoMetadata.getStartPoint(), length));
|
||||
|
||||
if (videoMetadata.getFps() != null || videoMetadata.getWidth() != null || videoMetadata.getHeight() != null) {
|
||||
command.addAll(buildFilters(videoMetadata.getFps(), videoMetadata.getWidth(), videoMetadata.getHeight()));
|
||||
}
|
||||
|
||||
if (videoMetadata.getFileSize() != null) {
|
||||
command.addAll(buildBitrate(length, videoMetadata.getFileSize()));
|
||||
}
|
||||
|
||||
// Output file
|
||||
command.add(outputFile.getAbsolutePath());
|
||||
return command;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,146 @@
|
||||
package com.ddf.vodsystem.services.media;
|
||||
|
||||
import com.ddf.vodsystem.dto.CommandOutput;
|
||||
import com.ddf.vodsystem.dto.VideoMetadata;
|
||||
import com.ddf.vodsystem.exceptions.FFMPEGException;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.util.List;
|
||||
|
||||
@Service
|
||||
public class MetadataService {
|
||||
private static final Logger logger = LoggerFactory.getLogger(MetadataService.class);
|
||||
|
||||
public VideoMetadata getVideoMetadata(File file) {
|
||||
logger.info("Getting metadata for file {}", file.getAbsolutePath());
|
||||
|
||||
List<String> command = List.of(
|
||||
"ffprobe",
|
||||
"-v", "quiet",
|
||||
"-print_format", "json",
|
||||
"-show_format", "-select_streams",
|
||||
"v:0", "-show_entries", "stream=duration,width,height,r_frame_rate:format=size,duration",
|
||||
"-i", file.getAbsolutePath()
|
||||
);
|
||||
|
||||
ObjectMapper mapper = new ObjectMapper();
|
||||
StringBuilder outputBuilder = new StringBuilder();
|
||||
|
||||
try {
|
||||
CommandOutput output = CommandRunner.run(command);
|
||||
|
||||
for (String line : output.getOutput()) {
|
||||
outputBuilder.append(line);
|
||||
}
|
||||
|
||||
JsonNode node = mapper.readTree(outputBuilder.toString());
|
||||
return parseVideoMetadata(node);
|
||||
} catch (IOException | InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
throw new FFMPEGException("Error while getting video metadata: " + e);
|
||||
}
|
||||
}
|
||||
|
||||
public void normalizeVideoMetadata(VideoMetadata inputFileMetadata, VideoMetadata outputFileMetadata) {
|
||||
if (outputFileMetadata.getStartPoint() == null) {
|
||||
outputFileMetadata.setStartPoint(0f);
|
||||
}
|
||||
|
||||
if (outputFileMetadata.getEndPoint() == null) {
|
||||
outputFileMetadata.setEndPoint(inputFileMetadata.getEndPoint());
|
||||
}
|
||||
}
|
||||
|
||||
private VideoMetadata parseVideoMetadata(JsonNode node) {
|
||||
VideoMetadata metadata = new VideoMetadata();
|
||||
metadata.setStartPoint(0f);
|
||||
|
||||
JsonNode streamNode = extractStreamNode(node);
|
||||
|
||||
metadata.setEndPoint(extractDuration(streamNode));
|
||||
metadata.setWidth(getWidth(streamNode));
|
||||
metadata.setHeight(getHeight(streamNode));
|
||||
metadata.setFps(extractFps(streamNode));
|
||||
|
||||
JsonNode formatNode = extractFormatNode(node);
|
||||
metadata.setFileSize(extractFileSize(formatNode));
|
||||
extractEndPointFromFormat(metadata, formatNode);
|
||||
|
||||
return metadata;
|
||||
}
|
||||
|
||||
private JsonNode extractStreamNode(JsonNode node) {
|
||||
JsonNode streamNode = node.path("streams").get(0);
|
||||
if (streamNode == null || streamNode.isMissingNode()) {
|
||||
throw new FFMPEGException("ffprobe streams missing");
|
||||
}
|
||||
return streamNode;
|
||||
}
|
||||
|
||||
private Float extractDuration(JsonNode streamNode) {
|
||||
if (streamNode.has("duration")) {
|
||||
return Float.valueOf(streamNode.get("duration").asText());
|
||||
}
|
||||
|
||||
throw new FFMPEGException("ffprobe duration missing");
|
||||
}
|
||||
|
||||
private Integer getWidth(JsonNode streamNode) {
|
||||
if (streamNode.has("width")) {
|
||||
return streamNode.get("width").asInt();
|
||||
}
|
||||
|
||||
throw new FFMPEGException("ffprobe width missing");
|
||||
}
|
||||
|
||||
private Integer getHeight(JsonNode streamNode) {
|
||||
if (streamNode.has("height")) {
|
||||
return streamNode.get("height").asInt();
|
||||
}
|
||||
|
||||
throw new FFMPEGException("ffprobe height missing");
|
||||
}
|
||||
|
||||
private JsonNode extractFormatNode(JsonNode node) {
|
||||
JsonNode formatNode = node.path("format");
|
||||
return (formatNode != null && !formatNode.isMissingNode()) ? formatNode : null;
|
||||
}
|
||||
|
||||
private Float extractFileSize(JsonNode formatNode) {
|
||||
if (formatNode != null && formatNode.has("size")) {
|
||||
return Float.parseFloat(formatNode.get("size").asText());
|
||||
}
|
||||
|
||||
throw new FFMPEGException("ffprobe file size missing");
|
||||
}
|
||||
|
||||
private void extractEndPointFromFormat(VideoMetadata metadata, JsonNode formatNode) {
|
||||
if (formatNode != null && formatNode.has("duration") && metadata.getEndPoint() == null) {
|
||||
metadata.setEndPoint(Float.parseFloat(formatNode.get("duration").asText()));
|
||||
}
|
||||
}
|
||||
|
||||
private Float extractFps(JsonNode streamNode) {
|
||||
if (streamNode.has("r_frame_rate")) {
|
||||
String fpsFraction = streamNode.get("r_frame_rate").asText();
|
||||
|
||||
if (fpsFraction.contains("/")) {
|
||||
String[] parts = fpsFraction.split("/");
|
||||
double numerator = Float.parseFloat(parts[0]);
|
||||
double denominator = Float.parseFloat(parts[1]);
|
||||
if (denominator != 0) {
|
||||
return (float) (numerator / denominator);
|
||||
}
|
||||
} else {
|
||||
return Float.valueOf(fpsFraction); // Handle cases like "25" directly
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
package com.ddf.vodsystem.services.media;
|
||||
|
||||
import com.ddf.vodsystem.dto.CommandOutput;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.util.List;
|
||||
|
||||
@Service
|
||||
public class ThumbnailService {
|
||||
private static final Logger logger = LoggerFactory.getLogger(ThumbnailService.class);
|
||||
|
||||
public CommandOutput createThumbnail(File inputFile, File outputFile, Float timeInVideo) throws IOException, InterruptedException {
|
||||
logger.info("Creating thumbnail at {} seconds", timeInVideo);
|
||||
|
||||
List<String> command = List.of(
|
||||
"ffmpeg",
|
||||
"-ss", timeInVideo.toString(),
|
||||
"-i", inputFile.getAbsolutePath(),
|
||||
"-frames:v", "1",
|
||||
outputFile.getAbsolutePath()
|
||||
);
|
||||
|
||||
return CommandRunner.run(command);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user