ffmpeg, spawned and left to die like ffprobe, maps one subtitle stream and converts it to SRT under §15's sidecar name. Text formats become legal translation sources; bitmap tracks never extract.
170 lines
5.3 KiB
Rust
170 lines
5.3 KiB
Rust
//! Extracting an embedded text subtitle track to a sidecar SRT (§15).
|
|
//!
|
|
//! One `ffmpeg` invocation per track, spawned and left to die like `ffprobe`:
|
|
//! no long-lived process, nothing to clean up at rest. The output is forced
|
|
//! to SRT whatever the track's own format — `ass` and `mov_text` included —
|
|
//! because §15's sidecars and every translation backend downstream speak SRT.
|
|
|
|
use std::{
|
|
ffi::OsString,
|
|
path::{Path, PathBuf},
|
|
process::Stdio,
|
|
time::Duration,
|
|
};
|
|
|
|
use tokio::process::Command;
|
|
|
|
use crate::error::{Error, Result};
|
|
|
|
/// The binary invoked when nothing else is configured.
|
|
pub const DEFAULT_BINARY: &str = "ffmpeg";
|
|
|
|
/// How long one extraction may take. Generous: a full-length PGS-to-SRT
|
|
/// conversion of a 60 GB remux over a network mount is slow.
|
|
pub const DEFAULT_EXTRACTION_TIMEOUT: Duration = Duration::from_secs(300);
|
|
|
|
/// How much of `ffmpeg`'s stderr is kept in an error.
|
|
const STDERR_LIMIT: usize = 512;
|
|
|
|
/// Extracts embedded subtitle tracks.
|
|
#[derive(Clone, Debug)]
|
|
pub struct Extractor {
|
|
binary: OsString,
|
|
timeout: Duration,
|
|
}
|
|
|
|
impl Default for Extractor {
|
|
fn default() -> Self {
|
|
Self {
|
|
binary: DEFAULT_BINARY.into(),
|
|
timeout: DEFAULT_EXTRACTION_TIMEOUT,
|
|
}
|
|
}
|
|
}
|
|
|
|
impl Extractor {
|
|
/// An extractor that runs `ffmpeg` from `PATH`.
|
|
#[must_use]
|
|
pub fn new() -> Self {
|
|
Self::default()
|
|
}
|
|
|
|
/// Run a specific binary instead of whatever `PATH` resolves to.
|
|
#[must_use]
|
|
pub fn with_binary(mut self, binary: impl Into<OsString>) -> Self {
|
|
self.binary = binary.into();
|
|
self
|
|
}
|
|
|
|
/// Change how long one extraction may take.
|
|
#[must_use]
|
|
pub fn with_timeout(mut self, timeout: Duration) -> Self {
|
|
self.timeout = timeout;
|
|
self
|
|
}
|
|
|
|
/// Write one embedded subtitle track out as an SRT sidecar.
|
|
///
|
|
/// `subtitle_stream` is the track's position among the file's subtitle
|
|
/// streams — the index into `ProbedMedia::subtitle_tracks`, not the
|
|
/// container's absolute stream id. Only text codecs (`is_text`) extract;
|
|
/// asking for a bitmap track fails in `ffmpeg`, so callers decide from
|
|
/// [`SubtitleCodec::is_text`] first.
|
|
///
|
|
/// The write lands whole or not at all: `ffmpeg` writes beside the target
|
|
/// under a dot-name and the result is renamed into place, so Jellyfin
|
|
/// never sees a half-written sidecar.
|
|
///
|
|
/// # Errors
|
|
///
|
|
/// [`Error::Spawn`] when `ffmpeg` is not installed,
|
|
/// [`Error::Extract`] when it exits non-zero — which includes mapping a
|
|
/// stream that does not exist or carries bitmaps — and
|
|
/// [`Error::Timeout`] / [`Error::Io`] on the usual failures.
|
|
pub async fn extract_srt(
|
|
&self,
|
|
video: &Path,
|
|
subtitle_stream: usize,
|
|
destination: &Path,
|
|
) -> Result<()> {
|
|
if let Some(parent) = destination.parent() {
|
|
tokio::fs::create_dir_all(parent)
|
|
.await
|
|
.map_err(|source| Error::Io {
|
|
path: parent.to_path_buf(),
|
|
source,
|
|
})?;
|
|
}
|
|
|
|
let temp = partial_name(destination);
|
|
let result = self.run(video, subtitle_stream, &temp).await;
|
|
if result.is_err() {
|
|
let _ = tokio::fs::remove_file(&temp).await;
|
|
return result;
|
|
}
|
|
tokio::fs::rename(&temp, destination)
|
|
.await
|
|
.map_err(|source| Error::Io {
|
|
path: destination.to_path_buf(),
|
|
source,
|
|
})
|
|
}
|
|
|
|
/// Spawn `ffmpeg` and wait for it to die.
|
|
async fn run(&self, video: &Path, subtitle_stream: usize, temp: &Path) -> Result<()> {
|
|
let map = format!("0:s:{subtitle_stream}");
|
|
let mut command = Command::new(&self.binary);
|
|
command
|
|
.args(["-nostdin", "-v", "error", "-i"])
|
|
.arg(video)
|
|
.args(["-map", &map, "-c:s", "srt", "-f", "srt"])
|
|
.arg(temp)
|
|
.stdin(Stdio::null())
|
|
.stdout(Stdio::null())
|
|
.stderr(Stdio::piped())
|
|
.kill_on_drop(true);
|
|
|
|
let child = command.spawn().map_err(|source| Error::Spawn {
|
|
binary: self.binary.to_string_lossy().into_owned(),
|
|
source,
|
|
})?;
|
|
|
|
let output = match tokio::time::timeout(self.timeout, child.wait_with_output()).await {
|
|
Ok(output) => output.map_err(|source| Error::Io {
|
|
path: video.to_path_buf(),
|
|
source,
|
|
})?,
|
|
Err(_) => {
|
|
return Err(Error::Timeout {
|
|
path: video.to_path_buf(),
|
|
})
|
|
}
|
|
};
|
|
|
|
if output.status.success() {
|
|
return Ok(());
|
|
}
|
|
|
|
let stderr = String::from_utf8_lossy(&output.stderr)
|
|
.trim()
|
|
.chars()
|
|
.take(STDERR_LIMIT)
|
|
.collect();
|
|
Err(Error::Extract {
|
|
path: video.to_path_buf(),
|
|
stream: subtitle_stream,
|
|
status: output.status.code(),
|
|
stderr,
|
|
})
|
|
}
|
|
}
|
|
|
|
/// The dot-name `ffmpeg` writes before the rename into place.
|
|
fn partial_name(destination: &Path) -> PathBuf {
|
|
let mut name = destination.file_name().unwrap_or_default().to_os_string();
|
|
name.push(".partial");
|
|
let mut partial = destination.to_path_buf();
|
|
partial.set_file_name(name);
|
|
partial
|
|
}
|