feat(media): C1 转码 worker(独立进程消费 transcode_task,产出四档 HLS + 封面)
为什么:codex-研发任务清单阶段 C 第一项要求消费 transcode_task 产出多码率 HLS + 截图; 勘察发现除 worker 外还缺两件——TranscodeService.enqueue 没有任何调用方(队列永远空)、 media_asset.hls_url/poster_url 没人回写,所以一并补齐,已有能力(条件更新认领 / 3 次重试)直接复用。 - 新增 TranscodeRunner 端口 + FfmpegTranscodeRunner(每档一条 ffmpeg 出 VOD HLS + 手写 master.m3u8 + 抽封面 + ffprobe 读时长) - 新增 TranscodeWorker:claimNext → 转码 → 登记 media_rendition → 媒资 ready;失败记原因、第 3 次才落 FAILED 并把媒资置 failed - 存储统一走 MediaStorageService(新增 fileFor / objectKeyOf,含目录穿越校验),worker 不自己拼磁盘路径 - 队列隔离:app-api/admin-api 默认 worker-enabled=false,新增独立模块 fruitshorts-transcode-worker(随机端口) - MediaService 上传完成对视频素材入队并置 transcoding(图片仍直接 ready) - 实测抓到并修掉两个真问题:① scale 未加 force_divisible_by=2 时 854x480 算出奇数宽 853,libx264 拒绝转码 ② 只写 -hls_time 不强制关键帧时 8 秒片源只出 1 个分片,补 -force_key_frames 后按 6s 正确切分 - README 开发环境补 ffmpeg 9.0.2(只有 worker 需要) - 实测:mvn test 83 条全过、0 skipped(新增 worker 12 条,含真实 ffmpeg smoke); 端到端:正常源 SUCCESS + 4 档 rendition + 媒资 ready;坏源重试 3 次后 FAILED
This commit is contained in:
1 parent
1dc97b4bf6
commit
9f76302e53
15 files changed
+1136
-3
No files matched your search
+75
@@ -0,0 +1,75 @@
|
||||
// Author: fruit.com.cn
|
||||
|
||||
package com.fruitshorts.media.config;
|
||||
|
||||
import lombok.Data;
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 转码 worker 配置。
|
||||
*
|
||||
* <p>**默认关闭**(`worker-enabled=false`):`backend-design-phase1.md` §8.5 要求转码与在线服务隔离,
|
||||
* 所以 app-api / admin-api 绝不跑转码;要跑就单独起 `fruitshorts-transcode-worker` 进程
|
||||
* (那个模块的 yml 里把开关置 true)。
|
||||
*
|
||||
* <p>码率阶梯按 `backend-design-phase1.md` §3.1:360p/480p/720p/1080p。
|
||||
*/
|
||||
@Data
|
||||
@Component
|
||||
@ConfigurationProperties(prefix = "fruitshorts.media.transcode")
|
||||
public class TranscodeProperties {
|
||||
|
||||
/** 是否在本进程跑转码(默认 false,只有独立 worker 进程开)。 */
|
||||
private boolean workerEnabled = false;
|
||||
|
||||
/** 队列空时的轮询间隔(毫秒)。 */
|
||||
private long pollDelayMs = 5000L;
|
||||
|
||||
/** ffmpeg 可执行文件(生产建议绝对路径或容器内固定路径)。 */
|
||||
private String ffmpegPath = "ffmpeg";
|
||||
|
||||
/** ffprobe 可执行文件,用于读时长。 */
|
||||
private String ffprobePath = "ffprobe";
|
||||
|
||||
/** HLS 分片时长(秒)。 */
|
||||
private int segmentSeconds = 6;
|
||||
|
||||
/** 封面截图取视频第几秒。 */
|
||||
private int posterSecond = 1;
|
||||
|
||||
/** 单条 ffmpeg 的超时(秒):防止坏片源把 worker 卡死。 */
|
||||
private int timeoutSeconds = 1800;
|
||||
|
||||
/** 码率阶梯(默认四档,改这里不用改代码)。 */
|
||||
private List<Rung> ladder = List.of(
|
||||
new Rung("360p", 640, 360, 400, 64),
|
||||
new Rung("480p", 854, 480, 800, 64),
|
||||
new Rung("720p", 1280, 720, 1600, 96),
|
||||
new Rung("1080p", 1920, 1080, 3200, 128));
|
||||
|
||||
/** 一档码率。 */
|
||||
@Data
|
||||
public static class Rung {
|
||||
|
||||
/** 码率标识,写进 media_rendition.quality,也是产物目录名。 */
|
||||
private String quality;
|
||||
private int width;
|
||||
private int height;
|
||||
private int videoBitrateKbps;
|
||||
private int audioBitrateKbps;
|
||||
|
||||
public Rung() {
|
||||
}
|
||||
|
||||
public Rung(String quality, int width, int height, int videoBitrateKbps, int audioBitrateKbps) {
|
||||
this.quality = quality;
|
||||
this.width = width;
|
||||
this.height = height;
|
||||
this.videoBitrateKbps = videoBitrateKbps;
|
||||
this.audioBitrateKbps = audioBitrateKbps;
|
||||
}
|
||||
}
|
||||
}
|
||||
+60
@@ -29,6 +29,8 @@ public class MediaService {
|
||||
|
||||
private static final String STATUS_READY = "ready";
|
||||
private static final String STATUS_UPLOADED = "uploaded";
|
||||
private static final String STATUS_TRANSCODING = "transcoding";
|
||||
private static final String STATUS_FAILED = "failed";
|
||||
private static final String TASK_UPLOADING = "uploading";
|
||||
private static final String TASK_COMPLETED = "completed";
|
||||
private static final Set<String> IMAGE_EXTENSIONS =
|
||||
@@ -38,6 +40,7 @@ public class MediaService {
|
||||
private final MediaStorageService storageService;
|
||||
private final MediaAssetMapper mediaAssetMapper;
|
||||
private final MediaUploadTaskMapper mediaUploadTaskMapper;
|
||||
private final TranscodeService transcodeService;
|
||||
|
||||
public UploadInitRespVO init(UploadInitReqVO req, Long userId) {
|
||||
if (req.getFileSize() > properties.getMaxFileSize()) {
|
||||
@@ -121,6 +124,14 @@ public class MediaService {
|
||||
asset.setCreateBy(task.getCreateBy());
|
||||
mediaAssetMapper.insert(asset);
|
||||
|
||||
// 视频入转码队列(§7.2 流水线:合并校验 → 写 transcode_task);图片没有转码概念,直接 ready
|
||||
if (!isImage(task.getFileName())) {
|
||||
asset.setStatus(STATUS_TRANSCODING);
|
||||
asset.setTranscodeStatus(TranscodeService.STATUS_QUEUED);
|
||||
mediaAssetMapper.updateById(asset);
|
||||
transcodeService.enqueue(asset.getId(), 0L, 0L, publicUrl);
|
||||
}
|
||||
|
||||
task.setStatus(TASK_COMPLETED);
|
||||
task.setAssetId(asset.getId());
|
||||
task.setReceivedChunks(chunks);
|
||||
@@ -131,6 +142,55 @@ public class MediaService {
|
||||
return toResp(mediaAssetMapper.selectById(asset.getId()));
|
||||
}
|
||||
|
||||
/**
|
||||
* 转码开始:把媒资标成 transcoding。
|
||||
*
|
||||
* <p>由转码 worker 调用(worker 与上传在不同进程),所以这里是独立的小事务方法。
|
||||
*/
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public void markTranscoding(Long assetId) {
|
||||
updateAssetStatus(assetId, STATUS_TRANSCODING, TranscodeService.STATUS_RUNNING);
|
||||
}
|
||||
|
||||
/** 转码成功:写 hls_url / poster_url 并把状态推到 ready。 */
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public void markReady(Long assetId, String hlsUrl, String posterUrl, Integer durationSec) {
|
||||
MediaAsset asset = assetId == null ? null : mediaAssetMapper.selectById(assetId);
|
||||
if (asset == null) {
|
||||
return;
|
||||
}
|
||||
asset.setStatus(STATUS_READY);
|
||||
asset.setTranscodeStatus(TranscodeService.STATUS_SUCCESS);
|
||||
asset.setHlsUrl(hlsUrl == null ? "" : hlsUrl);
|
||||
asset.setPosterUrl(posterUrl == null ? "" : posterUrl);
|
||||
if (durationSec != null && durationSec > 0) {
|
||||
asset.setDurationSec(durationSec);
|
||||
}
|
||||
mediaAssetMapper.updateById(asset);
|
||||
}
|
||||
|
||||
/** 转码最终失败(重试耗尽):状态置 failed,原因留给运营在后台排查。 */
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public void markFailed(Long assetId, String reason) {
|
||||
MediaAsset asset = assetId == null ? null : mediaAssetMapper.selectById(assetId);
|
||||
if (asset == null) {
|
||||
return;
|
||||
}
|
||||
asset.setStatus(STATUS_FAILED);
|
||||
asset.setTranscodeStatus(TranscodeService.STATUS_FAILED);
|
||||
mediaAssetMapper.updateById(asset);
|
||||
}
|
||||
|
||||
private void updateAssetStatus(Long assetId, String status, String transcodeStatus) {
|
||||
MediaAsset asset = assetId == null ? null : mediaAssetMapper.selectById(assetId);
|
||||
if (asset == null) {
|
||||
return;
|
||||
}
|
||||
asset.setStatus(status);
|
||||
asset.setTranscodeStatus(transcodeStatus);
|
||||
mediaAssetMapper.updateById(asset);
|
||||
}
|
||||
|
||||
public MediaAssetRespVO get(Long id) {
|
||||
MediaAsset asset = id == null ? null : mediaAssetMapper.selectById(id);
|
||||
if (asset == null) {
|
||||
|
||||
+38
@@ -53,6 +53,44 @@ public class MediaStorageService {
|
||||
return root;
|
||||
}
|
||||
|
||||
/**
|
||||
* 把 objectKey 解析成**本地可写路径**:转码产物落地用它,避免各处在外面自己拼 `./data/uploads`。
|
||||
*
|
||||
* <p>切 OSS 时这里是唯一的替换点(改成"下载到临时目录 / 上传回对象存储"的适配)。
|
||||
* 同时做一次越权校验:objectKey 不允许跑出根目录。
|
||||
*/
|
||||
public Path fileFor(String objectKey) {
|
||||
if (objectKey == null || objectKey.isBlank()) {
|
||||
throw new ServiceException(ErrorCode.BAD_REQUEST, "objectKey 不能为空");
|
||||
}
|
||||
Path root = rootDir().toAbsolutePath().normalize();
|
||||
Path target = root.resolve(objectKey.replaceAll("^/+", "")).normalize();
|
||||
if (!target.startsWith(root)) {
|
||||
throw new ServiceException(ErrorCode.BAD_REQUEST, "非法的 objectKey:" + objectKey);
|
||||
}
|
||||
return target;
|
||||
}
|
||||
|
||||
/**
|
||||
* 把对外 URL 反解成 objectKey(`/files/xxx/yyy.mp4` → `xxx/yyy.mp4`,顺带去掉签名查询串)。
|
||||
* worker 拿到的 `transcode_task.source_url` 就是这种对外 URL。
|
||||
*/
|
||||
public String objectKeyOf(String publicUrl) {
|
||||
if (publicUrl == null || publicUrl.isBlank()) {
|
||||
return "";
|
||||
}
|
||||
String clean = publicUrl;
|
||||
int query = clean.indexOf('?');
|
||||
if (query >= 0) {
|
||||
clean = clean.substring(0, query);
|
||||
}
|
||||
String prefix = properties.getPublicPrefix();
|
||||
if (clean.startsWith(prefix)) {
|
||||
clean = clean.substring(prefix.length());
|
||||
}
|
||||
return clean.replaceAll("^/+", "");
|
||||
}
|
||||
|
||||
public Path chunkDir(String uploadId) {
|
||||
return rootDir().resolve("tmp").resolve(uploadId);
|
||||
}
|
||||
|
||||
+10
-3
@@ -33,7 +33,8 @@ public class TranscodeService {
|
||||
public static final String STATUS_RUNNING = "RUNNING";
|
||||
public static final String STATUS_SUCCESS = "SUCCESS";
|
||||
public static final String STATUS_FAILED = "FAILED";
|
||||
private static final int MAX_RETRY = 3;
|
||||
/** 失败重试上限(`backend-design-phase1.md` §7.2:失败重试 3 次并记录原因)。 */
|
||||
public static final int MAX_RETRY = 3;
|
||||
|
||||
private final TranscodeTaskMapper transcodeTaskMapper;
|
||||
private final MediaRenditionMapper mediaRenditionMapper;
|
||||
@@ -95,8 +96,13 @@ public class TranscodeService {
|
||||
transcodeTaskMapper.updateById(task);
|
||||
}
|
||||
|
||||
/** 失败重试最多 3 次,超过则停在 FAILED,由运营在后台看到并处理。 */
|
||||
public void fail(Long taskId, String errorMessage) {
|
||||
/**
|
||||
* 失败重试最多 3 次,超过则停在 FAILED,由运营在后台看到并处理。
|
||||
*
|
||||
* @return 这次失败之后任务的新状态(QUEUED = 还会重试;FAILED = 已放弃),
|
||||
* 调用方据此决定要不要把媒资也置为 failed
|
||||
*/
|
||||
public String fail(Long taskId, String errorMessage) {
|
||||
TranscodeTask task = getExisting(taskId);
|
||||
int retry = task.getRetryCount() == null ? 0 : task.getRetryCount();
|
||||
if (retry + 1 >= MAX_RETRY) {
|
||||
@@ -108,6 +114,7 @@ public class TranscodeService {
|
||||
task.setErrorMsg(errorMessage == null ? "" : errorMessage);
|
||||
task.setFinishedAt(LocalDateTime.now());
|
||||
transcodeTaskMapper.updateById(task);
|
||||
return task.getStatus();
|
||||
}
|
||||
|
||||
public List<MediaRendition> listRenditions(Long episodeId) {
|
||||
|
||||
+235
@@ -0,0 +1,235 @@
|
||||
// Author: fruit.com.cn
|
||||
|
||||
package com.fruitshorts.media.service.transcode;
|
||||
|
||||
import com.fruitshorts.common.exception.ErrorCode;
|
||||
import com.fruitshorts.common.exception.ServiceException;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Comparator;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
/**
|
||||
* 用本机 ffmpeg 产出多码率 HLS + 封面。
|
||||
*
|
||||
* <p>每档码率一条 ffmpeg 命令出 VOD 型 HLS 到 `<输出目录>/<quality>/`,
|
||||
* 再由本类写一个 `master.m3u8`(手写比 `var_stream_map` 可控,也不用依赖 ffmpeg 的 muxer 细节)。
|
||||
* 封面单独抽一帧 jpg。时长用 ffprobe 读,读不到就记 0(不因为探测失败就把整单判失败)。
|
||||
*
|
||||
* <p>**注意**:本实现需要"本地可写路径",也就是本地磁盘存储形态;
|
||||
* 将来切 OSS 时,这一层要改成"下载到临时目录 → 转码 → 上传",替换点就是 {@code MediaStorageService} 与这里。
|
||||
*/
|
||||
@Slf4j
|
||||
@Component
|
||||
public class FfmpegTranscodeRunner implements TranscodeRunner {
|
||||
|
||||
private static final String MASTER_PLAYLIST = "master.m3u8";
|
||||
private static final String VARIANT_PLAYLIST = "index.m3u8";
|
||||
private static final String POSTER_FILE = "poster.jpg";
|
||||
private static final int STDERR_TAIL = 800;
|
||||
|
||||
@Override
|
||||
public TranscodeResult run(TranscodeRequest request) {
|
||||
if (!Files.isReadable(request.sourceFile())) {
|
||||
throw new ServiceException(ErrorCode.DATA_NOT_FOUND,
|
||||
"源文件不存在或不可读:" + request.sourceFile());
|
||||
}
|
||||
createDirectories(request.outputDir());
|
||||
int durationSec = probeDuration(request);
|
||||
|
||||
List<ProducedRendition> renditions = new ArrayList<>(request.ladder().size());
|
||||
for (LadderRung rung : request.ladder()) {
|
||||
renditions.add(transcodeRung(request, rung));
|
||||
}
|
||||
writeMasterPlaylist(request, renditions);
|
||||
ProducedRendition poster = extractPoster(request);
|
||||
log.info("转码完成 task={}:{} 档 HLS + 封面,时长 {}s",
|
||||
request.taskId(), renditions.size(), durationSec);
|
||||
return new TranscodeResult(joinKey(request.objectKeyPrefix(), MASTER_PLAYLIST), renditions,
|
||||
poster.objectKey(), durationSec);
|
||||
}
|
||||
|
||||
private ProducedRendition transcodeRung(TranscodeRequest request, LadderRung rung) {
|
||||
String relativeDir = rung.quality() + "/";
|
||||
Path rungDir = request.outputDir().resolve(rung.quality());
|
||||
createDirectories(rungDir);
|
||||
List<String> command = List.of(
|
||||
request.ffmpegPath(), "-y",
|
||||
"-i", request.sourceFile().toString(),
|
||||
// 等比缩放到目标档位(不拉伸)。force_divisible_by=2 不能省:
|
||||
// 640x360 的源在 854x480 档会算出 853x480 这种奇数宽度,libx264 直接拒绝(width not divisible by 2)
|
||||
"-vf", "scale=" + rung.width() + ":" + rung.height()
|
||||
+ ":force_original_aspect_ratio=decrease:force_divisible_by=2",
|
||||
"-c:v", "libx264", "-preset", "veryfast",
|
||||
"-b:v", rung.videoBitrateKbps() + "k",
|
||||
// 强制在每个分片边界插关键帧:只写 -hls_time 的话,片源关键帧间隔大于分片时长时
|
||||
// 分片会被"并"成一个超长分片(实测 8 秒片源只出了 1 个分片),起播与拖动都会变差
|
||||
"-force_key_frames", "expr:gte(t,n_forced*" + request.segmentSeconds() + ")",
|
||||
"-c:a", "aac", "-b:a", rung.audioBitrateKbps() + "k",
|
||||
"-hls_time", String.valueOf(request.segmentSeconds()),
|
||||
"-hls_playlist_type", "vod",
|
||||
"-hls_segment_filename", rungDir.resolve("seg_%03d.ts").toString(),
|
||||
rungDir.resolve(VARIANT_PLAYLIST).toString());
|
||||
runProcess(command, request.timeoutSeconds(), "转码 " + rung.quality() + " 失败");
|
||||
|
||||
Path playlist = rungDir.resolve(VARIANT_PLAYLIST);
|
||||
if (!Files.exists(playlist)) {
|
||||
throw new ServiceException(ErrorCode.INTERNAL_ERROR,
|
||||
"ffmpeg 未产出播放列表:" + playlist);
|
||||
}
|
||||
return new ProducedRendition(rung.quality(), rung.width(), rung.height(),
|
||||
rung.videoBitrateKbps(), rung.audioBitrateKbps(),
|
||||
joinKey(request.objectKeyPrefix(), relativeDir + VARIANT_PLAYLIST),
|
||||
sizeOf(rungDir), countSegments(rungDir));
|
||||
}
|
||||
|
||||
/** 手写 master.m3u8:按带宽升序,把每档的 index.m3u8 串起来。 */
|
||||
private void writeMasterPlaylist(TranscodeRequest request, List<ProducedRendition> renditions) {
|
||||
StringBuilder body = new StringBuilder("#EXTM3U\n#EXT-X-VERSION:3\n");
|
||||
List<ProducedRendition> sorted = renditions.stream()
|
||||
.sorted(Comparator.comparingInt(ProducedRendition::videoBitrateKbps))
|
||||
.toList();
|
||||
for (ProducedRendition rendition : sorted) {
|
||||
int bandwidth = (rendition.videoBitrateKbps() + rendition.audioBitrateKbps()) * 1000;
|
||||
body.append("#EXT-X-STREAM-INF:BANDWIDTH=").append(bandwidth)
|
||||
.append(",RESOLUTION=").append(rendition.width()).append('x')
|
||||
.append(rendition.height()).append('\n')
|
||||
.append(rendition.quality()).append('/').append(VARIANT_PLAYLIST).append('\n');
|
||||
}
|
||||
Path master = request.outputDir().resolve(MASTER_PLAYLIST);
|
||||
try {
|
||||
Files.writeString(master, body.toString(), StandardCharsets.UTF_8);
|
||||
} catch (IOException ex) {
|
||||
throw new ServiceException(ErrorCode.INTERNAL_ERROR, "写 master.m3u8 失败:" + ex.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
private ProducedRendition extractPoster(TranscodeRequest request) {
|
||||
Path poster = request.outputDir().resolve(POSTER_FILE);
|
||||
List<String> command = List.of(
|
||||
request.ffmpegPath(), "-y",
|
||||
"-ss", String.valueOf(request.posterSecond()),
|
||||
"-i", request.sourceFile().toString(),
|
||||
"-frames:v", "1", "-q:v", "2",
|
||||
poster.toString());
|
||||
runProcess(command, request.timeoutSeconds(), "抽取封面失败");
|
||||
long size = 0L;
|
||||
try {
|
||||
if (Files.exists(poster)) {
|
||||
size = Files.size(poster);
|
||||
}
|
||||
} catch (IOException ignored) {
|
||||
// 封面大小只用于登记,读不到不影响转码结果
|
||||
}
|
||||
return new ProducedRendition("poster", 0, 0, 0, 0,
|
||||
joinKey(request.objectKeyPrefix(), POSTER_FILE), size, 1);
|
||||
}
|
||||
|
||||
private int probeDuration(TranscodeRequest request) {
|
||||
try {
|
||||
String output = runProcess(List.of(
|
||||
request.ffprobePath(), "-v", "error",
|
||||
"-show_entries", "format=duration",
|
||||
"-of", "default=noprint_wrappers=1:nokey=1",
|
||||
request.sourceFile().toString()), 60, "探测时长失败");
|
||||
return (int) Math.round(Double.parseDouble(output.trim()));
|
||||
} catch (Exception ex) {
|
||||
// 探测失败不阻断:时长只是登记信息,转码本身可能仍然成功
|
||||
log.warn("读取时长失败(task={}):{}", request.taskId(), ex.getMessage());
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 起进程并等结果;非 0 退出把输出尾部带进异常,方便定位是片源问题还是参数问题。
|
||||
*
|
||||
* <p>输出**重定向到临时文件**而不是直接读管道:直接 `readAllBytes()` 会阻塞到进程结束,
|
||||
* 那样 `waitFor(timeout)` 的超时就形同虚设,坏片源能把 worker 永久卡住。
|
||||
*/
|
||||
private String runProcess(List<String> command, int timeoutSeconds, String errorPrefix) {
|
||||
Path logFile = null;
|
||||
try {
|
||||
logFile = Files.createTempFile("fruitshorts-ffmpeg-", ".log");
|
||||
ProcessBuilder builder = new ProcessBuilder(command)
|
||||
.redirectErrorStream(true)
|
||||
.redirectOutput(logFile.toFile());
|
||||
Process process = builder.start();
|
||||
boolean finished = process.waitFor(timeoutSeconds, TimeUnit.SECONDS);
|
||||
if (!finished) {
|
||||
process.destroyForcibly();
|
||||
throw new ServiceException(ErrorCode.INTERNAL_ERROR,
|
||||
errorPrefix + ":超时(" + timeoutSeconds + "s)");
|
||||
}
|
||||
String output = Files.readString(logFile, StandardCharsets.UTF_8);
|
||||
if (process.exitValue() != 0) {
|
||||
throw new ServiceException(ErrorCode.INTERNAL_ERROR,
|
||||
errorPrefix + ":" + tail(output));
|
||||
}
|
||||
return output;
|
||||
} catch (ServiceException ex) {
|
||||
throw ex;
|
||||
} catch (IOException ex) {
|
||||
throw new ServiceException(ErrorCode.INTERNAL_ERROR,
|
||||
errorPrefix + ":无法执行 ffmpeg/ffprobe(" + ex.getMessage() + ")");
|
||||
} catch (InterruptedException ex) {
|
||||
Thread.currentThread().interrupt();
|
||||
throw new ServiceException(ErrorCode.INTERNAL_ERROR, errorPrefix + ":被中断");
|
||||
} finally {
|
||||
if (logFile != null) {
|
||||
try {
|
||||
Files.deleteIfExists(logFile);
|
||||
} catch (IOException ignored) {
|
||||
// 临时日志删不掉不是业务问题
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void createDirectories(Path path) {
|
||||
try {
|
||||
Files.createDirectories(path);
|
||||
} catch (IOException ex) {
|
||||
throw new ServiceException(ErrorCode.INTERNAL_ERROR, "创建产物目录失败:" + path);
|
||||
}
|
||||
}
|
||||
|
||||
private long sizeOf(Path dir) {
|
||||
try (Stream<Path> files = Files.walk(dir)) {
|
||||
return files.filter(Files::isRegularFile).mapToLong(path -> {
|
||||
try {
|
||||
return Files.size(path);
|
||||
} catch (IOException ex) {
|
||||
return 0L;
|
||||
}
|
||||
}).sum();
|
||||
} catch (IOException ex) {
|
||||
return 0L;
|
||||
}
|
||||
}
|
||||
|
||||
private int countSegments(Path dir) {
|
||||
try (Stream<Path> files = Files.list(dir)) {
|
||||
return (int) files.filter(path -> path.getFileName().toString().endsWith(".ts")).count();
|
||||
} catch (IOException ex) {
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
private String tail(String output) {
|
||||
String trimmed = output == null ? "" : output.trim();
|
||||
return trimmed.length() <= STDERR_TAIL ? trimmed : trimmed.substring(trimmed.length() - STDERR_TAIL);
|
||||
}
|
||||
|
||||
private String joinKey(String prefix, String relative) {
|
||||
String cleanPrefix = prefix == null ? "" : prefix.replaceAll("/+$", "");
|
||||
return cleanPrefix.isEmpty() ? relative : cleanPrefix + "/" + relative;
|
||||
}
|
||||
}
|
||||
+50
@@ -0,0 +1,50 @@
|
||||
// Author: fruit.com.cn
|
||||
|
||||
package com.fruitshorts.media.service.transcode;
|
||||
|
||||
import java.nio.file.Path;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 转码执行端口:把"调 ffmpeg 出多码率 HLS + 封面"封在一层后面。
|
||||
*
|
||||
* <p>这样做的好处是 worker 的逻辑(取任务 / 登记产物 / 推状态 / 重试)可以**不依赖 ffmpeg** 做单测,
|
||||
* 生产实现见 {@link FfmpegTranscodeRunner}。
|
||||
*/
|
||||
public interface TranscodeRunner {
|
||||
|
||||
/** 执行一次转码。失败时抛异常(异常消息会被写进 `transcode_task.error_msg`)。 */
|
||||
TranscodeResult run(TranscodeRequest request);
|
||||
|
||||
/** 一档码率。 */
|
||||
record LadderRung(String quality, int width, int height, int videoBitrateKbps, int audioBitrateKbps) {
|
||||
}
|
||||
|
||||
/**
|
||||
* 一次转码请求。
|
||||
*
|
||||
* @param sourceFile 源视频的**本地路径**(由 MediaStorageService 解析,worker 不自己拼路径)
|
||||
* @param outputDir 产物落地的本地目录
|
||||
* @param objectKeyPrefix 产物 objectKey 前缀,返回值里的 objectKey 基于它拼
|
||||
*/
|
||||
record TranscodeRequest(Long taskId, Path sourceFile, Path outputDir, String objectKeyPrefix,
|
||||
List<LadderRung> ladder, String ffmpegPath, String ffprobePath,
|
||||
int segmentSeconds, int posterSecond, int timeoutSeconds) {
|
||||
}
|
||||
|
||||
/** 一档产物。 */
|
||||
record ProducedRendition(String quality, int width, int height, int videoBitrateKbps,
|
||||
int audioBitrateKbps, String objectKey, long sizeBytes, int segmentCount) {
|
||||
}
|
||||
|
||||
/**
|
||||
* 转码产物。
|
||||
*
|
||||
* @param masterObjectKey HLS 主播放列表的 objectKey(客户端可播入口)
|
||||
* @param posterObjectKey 封面截图 objectKey
|
||||
* @param durationSec 视频时长(ffprobe 读出,0 表示读不到)
|
||||
*/
|
||||
record TranscodeResult(String masterObjectKey, List<ProducedRendition> renditions,
|
||||
String posterObjectKey, int durationSec) {
|
||||
}
|
||||
}
|
||||
+140
@@ -0,0 +1,140 @@
|
||||
// Author: fruit.com.cn
|
||||
|
||||
package com.fruitshorts.media.service.transcode;
|
||||
|
||||
import com.fruitshorts.media.config.TranscodeProperties;
|
||||
import com.fruitshorts.media.dal.entity.TranscodeTask;
|
||||
import com.fruitshorts.media.service.MediaService;
|
||||
import com.fruitshorts.media.service.MediaStorageService;
|
||||
import com.fruitshorts.media.service.TranscodeService;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
||||
import org.springframework.scheduling.annotation.Scheduled;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.nio.file.Path;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 转码 worker:消费 `transcode_task`,产出多码率 HLS + 封面。
|
||||
*
|
||||
* <p>跑法:**默认不在 app-api / admin-api 里跑**(`fruitshorts.media.transcode.worker-enabled=false`),
|
||||
* 要转码就单独起 `fruitshorts-transcode-worker`(`backend-design-phase1.md` §8.5 要求队列与在线服务隔离)。
|
||||
*
|
||||
* <p>并发安全靠 `TranscodeService.claimNext()` 的条件更新(`status=QUEUED` 才会被改成 `RUNNING`),
|
||||
* 多进程同时抢也只有一个能拿到;拿不到就下一轮再来。
|
||||
*
|
||||
* <p>失败重试 3 次(`TranscodeService.fail`),每次都把原因写进 `error_msg`;
|
||||
* 到第三次才落到 `FAILED`,同时把 `media_asset.status` 置 `failed`。
|
||||
*/
|
||||
@Slf4j
|
||||
@Component
|
||||
@RequiredArgsConstructor
|
||||
@ConditionalOnProperty(name = "fruitshorts.media.transcode.worker-enabled", havingValue = "true")
|
||||
public class TranscodeWorker {
|
||||
|
||||
private final TranscodeService transcodeService;
|
||||
private final MediaService mediaService;
|
||||
private final MediaStorageService storageService;
|
||||
private final TranscodeRunner transcodeRunner;
|
||||
private final TranscodeProperties properties;
|
||||
|
||||
/** 定时轮询:队列空就按 poll-delay 再来一轮;上一轮没跑完不会被下一轮叠加(fixedDelay)。 */
|
||||
@Scheduled(fixedDelayString = "${fruitshorts.media.transcode.poll-delay-ms:5000}")
|
||||
public void poll() {
|
||||
try {
|
||||
processOne();
|
||||
} catch (Exception ex) {
|
||||
// 轮询里不能让异常逃出去,否则调度线程会被取消,整个 worker 静默停摆
|
||||
log.error("转码轮询异常:{}", ex.getMessage(), ex);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 处理一条任务。
|
||||
*
|
||||
* @return true 表示确实领到并处理了一条;false 表示队列空(或没抢到)
|
||||
*/
|
||||
public boolean processOne() {
|
||||
TranscodeTask task = transcodeService.claimNext();
|
||||
if (task == null) {
|
||||
return false;
|
||||
}
|
||||
process(task);
|
||||
return true;
|
||||
}
|
||||
|
||||
/** 处理指定任务:转码成功 → 登记产物 + 资产就绪;失败 → 记原因并决定是否重试。 */
|
||||
public void process(TranscodeTask task) {
|
||||
long startedAt = System.currentTimeMillis();
|
||||
String objectKeyPrefix = outputPrefix(task);
|
||||
try {
|
||||
Path sourceFile = storageService.fileFor(storageService.objectKeyOf(task.getSourceUrl()));
|
||||
Path outputDir = storageService.fileFor(objectKeyPrefix);
|
||||
TranscodeRunner.TranscodeResult result = transcodeRunner.run(new TranscodeRunner.TranscodeRequest(
|
||||
task.getId(), sourceFile, outputDir, objectKeyPrefix, ladder(), properties.getFfmpegPath(),
|
||||
properties.getFfprobePath(), properties.getSegmentSeconds(), properties.getPosterSecond(),
|
||||
properties.getTimeoutSeconds()));
|
||||
|
||||
transcodeService.succeed(task.getId(), toRenditions(result));
|
||||
if (task.getMediaAssetId() != null && task.getMediaAssetId() > 0) {
|
||||
mediaService.markReady(task.getMediaAssetId(),
|
||||
storageService.toPublicUrl(result.masterObjectKey()),
|
||||
storageService.toPublicUrl(result.posterObjectKey()),
|
||||
result.durationSec());
|
||||
}
|
||||
log.info("转码成功 task={} asset={} 档数={} 耗时={}ms 产物前缀={}",
|
||||
task.getId(), task.getMediaAssetId(), result.renditions().size(),
|
||||
System.currentTimeMillis() - startedAt, objectKeyPrefix);
|
||||
} catch (Exception ex) {
|
||||
String reason = ex.getMessage() == null ? ex.getClass().getSimpleName() : ex.getMessage();
|
||||
int attempt = (task.getRetryCount() == null ? 0 : task.getRetryCount()) + 1;
|
||||
String status = transcodeService.fail(task.getId(), reason);
|
||||
if (TranscodeService.STATUS_FAILED.equals(status)
|
||||
&& task.getMediaAssetId() != null && task.getMediaAssetId() > 0) {
|
||||
mediaService.markFailed(task.getMediaAssetId(), reason);
|
||||
}
|
||||
log.error("转码失败 task={} 第 {}/{} 次尝试 耗时={}ms 结果={} 原因={}",
|
||||
task.getId(), attempt, TranscodeService.MAX_RETRY, System.currentTimeMillis() - startedAt,
|
||||
status, reason);
|
||||
}
|
||||
}
|
||||
|
||||
/** 产物 objectKey 前缀:`episode/transcoded/{taskId}`,与上传目录分开放,便于按前缀清理。 */
|
||||
private String outputPrefix(TranscodeTask task) {
|
||||
return "transcoded/" + task.getId();
|
||||
}
|
||||
|
||||
private List<TranscodeRunner.LadderRung> ladder() {
|
||||
List<TranscodeRunner.LadderRung> ladder = new ArrayList<>();
|
||||
for (TranscodeProperties.Rung rung : properties.getLadder()) {
|
||||
ladder.add(new TranscodeRunner.LadderRung(rung.getQuality(), rung.getWidth(), rung.getHeight(),
|
||||
rung.getVideoBitrateKbps(), rung.getAudioBitrateKbps()));
|
||||
}
|
||||
return ladder;
|
||||
}
|
||||
|
||||
private List<com.fruitshorts.media.dal.entity.MediaRendition> toRenditions(
|
||||
TranscodeRunner.TranscodeResult result) {
|
||||
List<com.fruitshorts.media.dal.entity.MediaRendition> renditions = new ArrayList<>();
|
||||
for (TranscodeRunner.ProducedRendition produced : result.renditions()) {
|
||||
com.fruitshorts.media.dal.entity.MediaRendition rendition =
|
||||
new com.fruitshorts.media.dal.entity.MediaRendition();
|
||||
rendition.setQuality(produced.quality());
|
||||
rendition.setFormat("HLS");
|
||||
rendition.setObjectKey(produced.objectKey());
|
||||
rendition.setPlayUrl(storageService.toPublicUrl(produced.objectKey()));
|
||||
rendition.setWidth(produced.width());
|
||||
rendition.setHeight(produced.height());
|
||||
rendition.setVideoBitrate(produced.videoBitrateKbps());
|
||||
rendition.setAudioBitrate(produced.audioBitrateKbps());
|
||||
rendition.setSizeBytes(produced.sizeBytes());
|
||||
rendition.setSegmentCount(produced.segmentCount());
|
||||
rendition.setDurationSec(result.durationSec());
|
||||
renditions.add(rendition);
|
||||
}
|
||||
return renditions;
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user