211 lines
7.5 KiB
JavaScript
211 lines
7.5 KiB
JavaScript
"use strict";
|
|
// transcoder.ts
|
|
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
if (k2 === undefined) k2 = k;
|
|
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
desc = { enumerable: true, get: function() { return m[k]; } };
|
|
}
|
|
Object.defineProperty(o, k2, desc);
|
|
}) : (function(o, m, k, k2) {
|
|
if (k2 === undefined) k2 = k;
|
|
o[k2] = m[k];
|
|
}));
|
|
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
|
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
}) : function(o, v) {
|
|
o["default"] = v;
|
|
});
|
|
var __importStar = (this && this.__importStar) || (function () {
|
|
var ownKeys = function(o) {
|
|
ownKeys = Object.getOwnPropertyNames || function (o) {
|
|
var ar = [];
|
|
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
|
|
return ar;
|
|
};
|
|
return ownKeys(o);
|
|
};
|
|
return function (mod) {
|
|
if (mod && mod.__esModule) return mod;
|
|
var result = {};
|
|
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
|
|
__setModuleDefault(result, mod);
|
|
return result;
|
|
};
|
|
})();
|
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
const child_process_1 = require("child_process");
|
|
const fs = __importStar(require("fs/promises"));
|
|
const path = __importStar(require("path"));
|
|
const client_1 = require("@prisma/client");
|
|
const prisma = new client_1.PrismaClient();
|
|
// -----------------------------
|
|
// Configuration
|
|
// -----------------------------
|
|
const UPLOADS_DIR = process.env.UPLOADS_DIR || "/uploads";
|
|
const ORIGINALS_DIR = path.join(UPLOADS_DIR, "videos");
|
|
const HLS_ROOT = path.join(UPLOADS_DIR, "hls");
|
|
// Safer bitrate ladder for education content
|
|
const HLS_PRESETS = [
|
|
{ name: "1080p", width: 1920, height: 1080, bitrate: "3500k", maxrate: "4000k" },
|
|
{ name: "720p", width: 1280, height: 720, bitrate: "1800k", maxrate: "2000k" },
|
|
{ name: "480p", width: 854, height: 480, bitrate: "900k", maxrate: "1000k" },
|
|
];
|
|
// -----------------------------
|
|
// Utilities
|
|
// -----------------------------
|
|
async function fileExists(p) {
|
|
try {
|
|
await fs.access(p);
|
|
return true;
|
|
}
|
|
catch {
|
|
return false;
|
|
}
|
|
}
|
|
function runFFmpeg(args) {
|
|
return new Promise((resolve, reject) => {
|
|
const ffmpeg = (0, child_process_1.spawn)("ffmpeg", args, { stdio: "inherit" });
|
|
ffmpeg.on("close", (code) => {
|
|
if (code === 0)
|
|
resolve();
|
|
else
|
|
reject(new Error(`FFmpeg exited with code ${code}`));
|
|
});
|
|
});
|
|
}
|
|
async function probeResolution(input) {
|
|
return new Promise((resolve, reject) => {
|
|
const ffprobe = (0, child_process_1.spawn)("ffprobe", [
|
|
"-v", "error",
|
|
"-select_streams", "v:0",
|
|
"-show_entries", "stream=width,height",
|
|
"-of", "csv=s=x:p=0",
|
|
input,
|
|
]);
|
|
let output = "";
|
|
ffprobe.stdout.on("data", (data) => {
|
|
output += data.toString();
|
|
});
|
|
ffprobe.on("close", (code) => {
|
|
if (code !== 0)
|
|
return reject(new Error("ffprobe failed"));
|
|
const [width, height] = output.trim().split("x").map(Number);
|
|
resolve({ width, height });
|
|
});
|
|
});
|
|
}
|
|
// -----------------------------
|
|
// HLS Creation
|
|
// -----------------------------
|
|
async function createVariant(input, outputDir, preset) {
|
|
const segmentPattern = path.join(outputDir, `${preset.name}_%03d.ts`);
|
|
const playlistPath = path.join(outputDir, `${preset.name}.m3u8`);
|
|
const args = [
|
|
"-y",
|
|
"-i", input,
|
|
"-c:v", "libx264",
|
|
"-preset", "medium",
|
|
"-profile:v", "main",
|
|
"-crf", "20",
|
|
"-vf", `scale=w=${preset.width}:h=${preset.height}:force_original_aspect_ratio=decrease`,
|
|
"-b:v", preset.bitrate,
|
|
"-maxrate", preset.maxrate,
|
|
"-bufsize", "4000k",
|
|
"-c:a", "aac",
|
|
"-b:a", "128k",
|
|
"-f", "hls",
|
|
"-hls_time", "6",
|
|
"-hls_playlist_type", "vod",
|
|
"-hls_segment_filename", segmentPattern,
|
|
playlistPath,
|
|
];
|
|
console.log(`[HLS] Creating ${preset.name}`);
|
|
await runFFmpeg(args);
|
|
}
|
|
async function createMasterPlaylist(outputDir, variants) {
|
|
const lines = [
|
|
"#EXTM3U",
|
|
"#EXT-X-VERSION:3",
|
|
];
|
|
for (const variant of variants) {
|
|
const preset = HLS_PRESETS.find(p => p.name === variant);
|
|
const bandwidth = parseInt(preset.maxrate.replace("k", "")) * 1000;
|
|
lines.push(`#EXT-X-STREAM-INF:BANDWIDTH=${bandwidth},RESOLUTION=${preset.width}x${preset.height}`);
|
|
lines.push(`${preset.name}.m3u8`);
|
|
}
|
|
await fs.writeFile(path.join(outputDir, "master.m3u8"), lines.join("\n"));
|
|
}
|
|
// -----------------------------
|
|
// Transcode One Video
|
|
// -----------------------------
|
|
async function transcodeVideo(videoId) {
|
|
console.log(`\n[Transcoding] ${videoId}`);
|
|
const inputPath = path.join(ORIGINALS_DIR, `${videoId}.mp4`);
|
|
const finalDir = path.join(HLS_ROOT, videoId);
|
|
const tempDir = path.join(HLS_ROOT, `${videoId}.tmp`);
|
|
if (!(await fileExists(inputPath))) {
|
|
throw new Error(`Original file not found: ${inputPath}`);
|
|
}
|
|
if (await fileExists(finalDir)) {
|
|
console.log(`[Skip] HLS already exists`);
|
|
return;
|
|
}
|
|
await fs.mkdir(tempDir, { recursive: true });
|
|
const { width, height } = await probeResolution(inputPath);
|
|
const allowedVariants = HLS_PRESETS.filter(p => p.width <= width && p.height <= height);
|
|
if (allowedVariants.length === 0) {
|
|
throw new Error("No suitable HLS variants for source resolution");
|
|
}
|
|
for (const preset of allowedVariants) {
|
|
await createVariant(inputPath, tempDir, preset);
|
|
}
|
|
await createMasterPlaylist(tempDir, allowedVariants.map(p => p.name));
|
|
// Atomic rename
|
|
await fs.rename(tempDir, finalDir);
|
|
console.log(`[Done] ${videoId}`);
|
|
}
|
|
// -----------------------------
|
|
// Main Batch Worker
|
|
// -----------------------------
|
|
async function main() {
|
|
console.log("[Transcoder] Starting batch run");
|
|
await fs.mkdir(HLS_ROOT, { recursive: true });
|
|
const videos = await prisma.video.findMany({
|
|
where: { transcodingStatus: "uploaded" },
|
|
});
|
|
if (videos.length === 0) {
|
|
console.log("[Transcoder] Nothing to process");
|
|
return;
|
|
}
|
|
console.log(`[Transcoder] Found ${videos.length} videos`);
|
|
for (const video of videos) {
|
|
try {
|
|
// Atomically lock job
|
|
await prisma.video.update({
|
|
where: { id: video.id },
|
|
data: { transcodingStatus: "processing" },
|
|
});
|
|
await transcodeVideo(video.id);
|
|
await prisma.video.update({
|
|
where: { id: video.id },
|
|
data: { transcodingStatus: "transcoded" },
|
|
});
|
|
}
|
|
catch (err) {
|
|
console.error(`[Error] ${video.id}`, err);
|
|
await prisma.video.update({
|
|
where: { id: video.id },
|
|
data: { transcodingStatus: "failed" },
|
|
});
|
|
}
|
|
}
|
|
await prisma.$disconnect();
|
|
console.log("[Transcoder] Batch complete");
|
|
}
|
|
main().catch(async (err) => {
|
|
console.error("[Fatal]", err);
|
|
await prisma.$disconnect();
|
|
process.exit(1);
|
|
});
|
|
//# sourceMappingURL=index.js.map
|