A self-hosted media server and file management system
Vue ffmpegfile-serverjellyfinlaravelmediamedia-playermedia-servermediabrowsermediaservermusicmusic-librarymusic-playermusicplayerself-hostedvuejs
feat: subtitle extraction logic
aminnausin4be793ae3f3c
diff --git a/app/Http/Controllers/Api/V1/Metadata/SubtitleController.php b/app/Http/Controllers/Api/V1/Metadata/SubtitleController.phpnew file mode 100644index 00000000..34101d41--- /dev/null+++ b/app/Http/Controllers/Api/V1/Metadata/SubtitleController.php@@ -0,0 +1,33 @@+<?php++namespace App\Http\Controllers\Api\V1\Metadata;++use App\Http\Controllers\Controller;+use App\Models\Metadata;+use App\Services\Subtitles\SubtitleResolver;+use Illuminate\Http\Request;++class SubtitleController extends Controller {+ public function __construct(protected SubtitleResolver $subtitleResolver) {}++ /**+ * Look for a specified subtitle resource.+ *+ * Subtitle Extraction Process ->+ * Initially scan file, set subtitles_scanned_at time and make partially identifying subtitle rows in the subtitle table+ * then when requested by stream or file type, if the exact requested file matches an existing one, return that but if not probe again,+ * and for each found stream, extract it, write to a file and update the row in the subtitle file, and then convert it to the requested format and return that file+ * on subsequent requests, a matching file (usually vtt) will already exist and get returned directly+ */+ public function show(+ Request $request,+ Metadata $metadata,+ int $track = 2, // track number to specify file like 2.vtt or 3.vtt+ string $format = 'vtt'+ ) {+ // TODO: Log activity from request (requires future activity feature)+ return $this->subtitleResolver->resolveSubtitles($metadata, $track, $format);+ }++ // TODO: Add an API route that gets subtitles for a specific metadata or video row and cache the results. These are only used to determine the filepath used in the <track/>+}diff --git a/app/Services/Subtitles/Formats/SubtitleFormatStrategy.php b/app/Services/Subtitles/Formats/SubtitleFormatStrategy.phpnew file mode 100644index 00000000..2be5e263--- /dev/null+++ b/app/Services/Subtitles/Formats/SubtitleFormatStrategy.php@@ -0,0 +1,7 @@+<?php++namespace App\Services\Subtitles\Formats;++interface SubtitleFormatStrategy {+ public function convert(string $inputPath, string $outputPath): void;+}diff --git a/app/Services/Subtitles/Formats/VttStrategy.php b/app/Services/Subtitles/Formats/VttStrategy.phpnew file mode 100644index 00000000..eefac3ee--- /dev/null+++ b/app/Services/Subtitles/Formats/VttStrategy.php@@ -0,0 +1,22 @@+<?php++namespace App\Services\Subtitles\Formats;++use Illuminate\Support\Facades\Storage;+use Symfony\Component\Process\Process;++class VttStrategy implements SubtitleFormatStrategy {+ public function convert(string $inputPath, string $outputPath): void {+ $process = new Process([+ 'ffmpeg',+ '-y',+ '-i',+ Storage::disk('local')->path($inputPath),+ '-c:s',+ 'webvtt',+ Storage::disk('local')->path($outputPath),+ ]);++ $process->mustRun();+ }+}diff --git a/app/Services/Subtitles/SubtitleExtractor.php b/app/Services/Subtitles/SubtitleExtractor.phpnew file mode 100644index 00000000..47a75511--- /dev/null+++ b/app/Services/Subtitles/SubtitleExtractor.php@@ -0,0 +1,69 @@+<?php++namespace App\Services\Subtitles;++use App\Models\Metadata;+use App\Models\Subtitle;+use Illuminate\Support\Facades\Log;+use Illuminate\Support\Facades\Storage;+use Symfony\Component\Process\Process;++class SubtitleExtractor {+ public function extractStream(Metadata $metadata, Subtitle $subtitle) {+ try {+ $mediaPath = $metadata->video->path;+ $ext = $this->getExtentionFromCodec($subtitle['codec']);++ $outputPath = $this->getOutputDir($subtitle, $ext);++ $command = [+ 'ffmpeg',+ '-y',+ '-i',+ Storage::disk('public')->path($mediaPath), // Media is on public disk for now+ '-map',+ "0:$subtitle->track_id",+ Storage::disk('local')->path($outputPath),+ ];++ $process = new Process($command);+ $process->run();++ if (! $process->isSuccessful()) {+ throw new \Exception('Subtitles Failed: "' . implode(' ', $command) . '"');+ }++ $subtitle->update([+ 'path' => $outputPath,+ 'format' => $ext,+ ]);++ return $outputPath;+ } catch (\Throwable $th) {+ Log::error('Unable to get file subtitles', ['error' => $th->getMessage()]);+ throw $th;+ }+ }++ /**+ * Get the relative output path given the subtitle and file extention+ */+ private function getOutputDir(Subtitle $subtitle, string $ext) {+ $outDir = "data/media/{$subtitle->metadata_uuid}/subtitles"; // Relative output directory+ Storage::disk('local')->makeDirectory($outDir); // Ensure directory exists++ return "{$outDir}/{$subtitle->track_id}.{$ext}"; // Add track.ext to get final output address+ }++ private function getExtentionFromCodec(string $codec): string {+ return match ($codec) {+ 'subrip' => 'srt',+ 'ass' => 'ass',+ 'ssa' => 'ssa',+ 'webvtt' => 'vtt',+ 'hdmv_pgs_subtitle' => 'sup',+ 'dvd_subtitle' => 'sub',+ default => 'bin',+ };+ }+}diff --git a/app/Services/Subtitles/SubtitleFormatter.php b/app/Services/Subtitles/SubtitleFormatter.phpnew file mode 100644index 00000000..45e2f0f3--- /dev/null+++ b/app/Services/Subtitles/SubtitleFormatter.php@@ -0,0 +1,27 @@+<?php++namespace App\Services\Subtitles;++use App\Services\Subtitles\Formats\VttStrategy;+use Illuminate\Support\Facades\Storage;++class SubtitleFormatter {+ public function convert(string $input, string $output, string $format): string {+ if (! Storage::disk('local')->exists($input)) {+ throw new \RuntimeException("Input file not found: {$input}");+ }++ $strategy = match ($format) {+ 'vtt' => new VttStrategy,+ default => throw new \InvalidArgumentException('Unsupported format'),+ };++ $strategy->convert($input, $output);++ if (! Storage::disk('local')->exists($output)) {+ throw new \RuntimeException("Conversion failed: {$output} not created");+ }++ return $output;+ }+}diff --git a/app/Services/Subtitles/SubtitleResolver.php b/app/Services/Subtitles/SubtitleResolver.phpnew file mode 100644index 00000000..74651cc7--- /dev/null+++ b/app/Services/Subtitles/SubtitleResolver.php@@ -0,0 +1,49 @@+<?php++namespace App\Services\Subtitles;++use App\Models\Metadata;+use Illuminate\Support\Facades\Response;+use Illuminate\Support\Facades\Storage;+use Symfony\Component\HttpFoundation\BinaryFileResponse;++class SubtitleResolver {+ public function __construct(protected SubtitleExtractor $extractor, protected SubtitleFormatter $formatter) {}++ public function resolveSubtitles(Metadata $metadata, int $track, string $format): BinaryFileResponse {+ $subtitle = $metadata->subtitles()->where('track_id', $track)->firstOrFail(); // 404 on no result++ $format = ltrim(strtolower($format), '.');+ $requestedPath = "data/media/{$subtitle->metadata_uuid}/subtitles/{$track}.{$format}";++ if ($this->fileExists($requestedPath)) {+ return Response::file(+ Storage::disk('local')->path($requestedPath)+ );+ }++ if (! $subtitle->path || ! $this->fileExists($subtitle->path)) {+ $this->extractor->extractStream($metadata, $subtitle); // Native format subtitle file (usually srt)+ $subtitle->refresh();+ }++ $nativePath = $subtitle->path;+ $convertedPath = $this->formatter->convert(+ $nativePath,+ $requestedPath,+ $format+ );++ if (! $this->fileExists($convertedPath)) {+ abort(500);+ }++ return Response::file(+ Storage::disk('local')->path($convertedPath)+ );+ }++ private function fileExists(string $path): bool {+ return Storage::disk('local')->exists($path);+ }+}