use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::sync::{Arc, LazyLock, Mutex};
use std::time::{Duration, Instant, UNIX_EPOCH};
use serde::{Deserialize, Serialize};
use sha2::{Digest as _, Sha256};
use crate::ffmpeg::{self, ClipInfo};
use crate::speech::Segment;
use crate::util::UnwrapPoison;
use super::MediaError;
const DIR: &str = "transcripts";
const VERSION: u32 = 2;
const PIECE: Duration = Duration::from_mins(5);
const PIECE_SLACK: f64 = 0.5;
const PIECES_PER_BATCH: usize = 12;
const TRANSCRIBE_TIMEOUT: Duration = Duration::from_mins(30);
const MAX_ENTRIES: usize = 256;
const PART_STALE: Duration = Duration::from_hours(1);
static IN_FLIGHT: LazyLock<Mutex<HashMap<PathBuf, Arc<tokio::sync::Mutex<()>>>>> =
LazyLock::new(|| Mutex::new(HashMap::new()));
pub(super) struct Transcribed {
pub(super) regions: Vec<Segment>,
pub(super) reached: f64,
pub(super) failure: Option<MediaError>,
}
pub(super) async fn regions(path: &Path, info: &ClipInfo) -> Transcribed {
let key = canonical(path).await;
let track = info.sound_length().as_secs_f64();
let mut cached = load(&key, info.bytes).await;
if let Some(done) = finished(&mut cached, track) {
return done;
}
let deadline = Instant::now() + TRANSCRIBE_TIMEOUT;
let Some(_flight) = single_flight(key.clone(), deadline).await else {
let reason = if crate::shutdown::aborting() {
MediaError::Stopping
} else {
MediaError::Busy
};
return unwaited(cached, track, reason);
};
cached = load(&key, info.bytes).await;
if let Some(done) = finished(&mut cached, track) {
return done;
}
if Instant::now() >= deadline {
return unwaited(cached, track, MediaError::Busy);
}
let (regions, from) = cached.map_or_else(
|| (Vec::new(), 0.0),
|cached| (cached.regions, cached.covered),
);
let mut transcribed = transcribe(path, info, &key, from, regions, deadline).await;
transcribed.reached = reached_of(transcribed.reached, track);
transcribed
}
fn unwaited(cached: Option<Entry>, track: f64, reason: MediaError) -> Transcribed {
let (regions, covered) = cached.map_or_else(
|| (Vec::new(), 0.0),
|cached| (cached.regions, cached.covered),
);
Transcribed {
regions,
reached: reached_of(covered, track),
failure: Some(reason),
}
}
fn reached_of(covered: f64, track: f64) -> f64 {
if covered >= track - PIECE_SLACK {
track
} else {
covered
}
}
fn transcribed(cached: Entry, track: f64) -> Transcribed {
Transcribed {
regions: cached.regions,
reached: reached_of(cached.covered, track),
failure: None,
}
}
struct Piece {
start: Duration,
length: Duration,
}
fn pieces(duration: Duration) -> Vec<Piece> {
let mut pieces = Vec::new();
let mut start = Duration::ZERO;
while start < duration {
let length = PIECE.min(duration.saturating_sub(start));
pieces.push(Piece { start, length });
start += PIECE;
}
pieces
}
fn remaining(pieces: Vec<Piece>, from: f64) -> Vec<Piece> {
pieces
.into_iter()
.filter(|piece| piece.start.as_secs_f64() >= from - PIECE_SLACK)
.collect()
}
async fn transcribe(
path: &Path,
info: &ClipInfo,
key: &Path,
from: f64,
mut regions: Vec<Segment>,
deadline: Instant,
) -> Transcribed {
let mut todo = remaining(pieces(info.sound_length()), from).into_iter();
tracing::debug!(
path = %path.display(),
pieces = todo.len(),
"Transcribing a sound track"
);
let mut reached = from;
loop {
let mut batch: Vec<(Piece, ffmpeg::Audio)> = Vec::new();
while batch.len() < PIECES_PER_BATCH && Instant::now() < deadline {
let Some(piece) = todo.next() else { break };
let extracted = tokio::time::timeout_at(
deadline.into(),
ffmpeg::extract_audio(path, Some((piece.start, piece.length))),
)
.await;
match extracted {
Ok(Ok(audio)) => batch.push((piece, audio)),
Ok(Err(error)) => {
let read = read_batch(&mut batch, key, info, &mut regions, deadline).await;
if let Some(failed) = read.failure {
tracing::warn!(
reason = %failed.message(),
"The pieces extracted before a decode failure could not be read"
);
}
return Transcribed {
regions,
reached: read.reached.unwrap_or(reached),
failure: Some(error.into()),
};
}
Err(_elapsed) => break,
}
}
if batch.is_empty() || Instant::now() >= deadline {
break;
}
let read = read_batch(&mut batch, key, info, &mut regions, deadline).await;
reached = read.reached.unwrap_or(reached);
if let Some(error) = read.failure {
return Transcribed {
regions,
reached,
failure: Some(error),
};
}
if read.cut || read.reached.is_none() {
break;
}
}
Transcribed {
regions,
reached,
failure: None,
}
}
struct Batch {
reached: Option<f64>,
cut: bool,
failure: Option<MediaError>,
}
async fn read_batch(
batch: &mut Vec<(Piece, ffmpeg::Audio)>,
key: &Path,
info: &ClipInfo,
regions: &mut Vec<Segment>,
deadline: Instant,
) -> Batch {
let files: Vec<(PathBuf, f64)> = batch
.iter()
.map(|(piece, audio)| (audio.path().to_path_buf(), piece.start.as_secs_f64()))
.collect();
let read = match crate::speech::transcribe_pieces(&files, deadline).await {
Ok(read) => read,
Err(error) => {
batch.clear();
let cut = error
.downcast_ref::<crate::speech::InferenceTimedOut>()
.is_some()
|| error.downcast_ref::<crate::speech::Interrupted>().is_some();
return Batch {
reached: None,
cut,
failure: (!cut).then(|| piece_failure(&error)),
};
}
};
let reached = read
.pieces
.checked_sub(1)
.and_then(|index| batch.get(index))
.map(|(piece, _)| (piece.start + piece.length).as_secs_f64());
batch.clear();
regions.extend(read.regions);
if let Some(reached) = reached {
store(key, info.bytes, reached, regions).await;
}
Batch {
reached,
cut: false,
failure: read.failure.as_ref().map(piece_failure),
}
}
fn piece_failure(error: &anyhow::Error) -> MediaError {
if error.downcast_ref::<crate::speech::Unreadable>().is_some() {
return MediaError::Undecodable;
}
MediaError::SoundTrack(error.root_cause().to_string())
}
#[derive(Serialize, Deserialize)]
struct Entry {
version: u32,
bytes: u64,
modified_ms: u64,
covered: f64,
regions: Vec<Segment>,
}
async fn load(path: &Path, bytes: u64) -> Option<Entry> {
let entry: Entry =
serde_json::from_slice(&tokio::fs::read(entry_path(path)?).await.ok()?).ok()?;
if entry.version != VERSION
|| entry.bytes != bytes
|| entry.modified_ms != modified_ms(path).await?
{
return None;
}
Some(entry)
}
fn finished(cached: &mut Option<Entry>, track: f64) -> Option<Transcribed> {
if !cached
.as_ref()
.is_some_and(|cached| cached.covered >= track - PIECE_SLACK)
{
return None;
}
cached.take().map(|cached| transcribed(cached, track))
}
async fn store(path: &Path, bytes: u64, covered: f64, regions: &[Segment]) {
if regions.is_empty() && covered <= 0.0 {
return;
}
let Some(entry) = entry_path(path) else {
return;
};
let Some(modified) = modified_ms(path).await else {
return;
};
let Ok(json) = serde_json::to_vec(&Entry {
version: VERSION,
bytes,
modified_ms: modified,
covered,
regions: regions.to_vec(),
}) else {
return;
};
let Some(dir) = entry.parent() else {
return;
};
if let Err(error) = tokio::fs::create_dir_all(dir).await {
tracing::warn!(%error, "The transcript cache directory could not be created");
return;
}
let temp = entry.with_extension(format!("{}.part", std::process::id()));
if let Err(error) = tokio::fs::write(&temp, &json).await {
tracing::warn!(%error, "A transcript could not be cached");
return;
}
if let Err(error) = tokio::fs::rename(&temp, &entry).await {
tracing::warn!(%error, "A transcript could not be cached");
let _ = tokio::fs::remove_file(&temp).await;
}
prune(dir, &entry).await;
}
async fn prune(dir: &Path, fresh: &Path) {
let Ok(mut entries) = tokio::fs::read_dir(dir).await else {
return;
};
let mut written: Vec<(std::time::SystemTime, PathBuf)> = Vec::new();
while let Ok(Some(entry)) = entries.next_entry().await {
let path = entry.path();
let Ok(modified) = entry.metadata().await.and_then(|meta| meta.modified()) else {
continue;
};
match path.extension().and_then(|ext| ext.to_str()) {
Some("json") if path != fresh => written.push((modified, path)),
Some("part") if modified.elapsed().is_ok_and(|age| age > PART_STALE) => {
let _ = tokio::fs::remove_file(&path).await;
}
_ => {}
}
}
if written.len() < MAX_ENTRIES {
return;
}
written.sort_unstable_by_key(|(modified, _)| *modified);
for (_, path) in written.iter().take(written.len() + 1 - MAX_ENTRIES) {
if let Err(error) = tokio::fs::remove_file(path).await {
tracing::warn!(path = %path.display(), %error, "A transcript entry could not be pruned");
}
}
}
fn entry_path(path: &Path) -> Option<PathBuf> {
let digest = crate::util::hex_string(&Sha256::digest(path.as_os_str().as_encoded_bytes()));
Some(cache_dir()?.join(format!("{digest}.json")))
}
#[cfg_attr(
test,
expect(clippy::unnecessary_wraps, reason = "the test root always resolves")
)]
fn cache_dir() -> Option<PathBuf> {
#[cfg(test)]
{
Some(crate::util::test::test_root().join(DIR))
}
#[cfg(not(test))]
{
crate::config::CONFIG
.try_storage_root()
.or_else(|| crate::config::default_config_dir().ok())
.map(|root| root.join(DIR))
}
}
async fn canonical(path: &Path) -> PathBuf {
tokio::fs::canonicalize(path)
.await
.unwrap_or_else(|_| path.to_path_buf())
}
async fn modified_ms(path: &Path) -> Option<u64> {
let modified = tokio::fs::metadata(path).await.ok()?.modified().ok()?;
u64::try_from(modified.duration_since(UNIX_EPOCH).ok()?.as_millis()).ok()
}
async fn single_flight(
key: PathBuf,
deadline: Instant,
) -> Option<tokio::sync::OwnedMutexGuard<()>> {
let lock = {
let mut in_flight = IN_FLIGHT.lock().unwrap_poison();
in_flight.retain(|_, lock| Arc::strong_count(lock) > 1);
Arc::clone(in_flight.entry(key).or_default())
};
let shutdown = crate::shutdown::shutdown_token();
tokio::select! {
guard = lock.lock_owned() => Some(guard),
() = tokio::time::sleep_until(deadline.into()) => None,
() = shutdown.cancelled() => None,
}
}
#[cfg(test)]
mod tests {
use super::*;
fn entry(covered: f64, regions: Vec<Segment>) -> Entry {
Entry {
version: VERSION,
bytes: 1024,
modified_ms: 0,
covered,
regions,
}
}
#[test]
fn a_track_is_cut_into_five_minute_pieces_carrying_their_offsets() {
let cut = pieces(Duration::from_secs(700));
let offsets: Vec<u64> = cut.iter().map(|p| p.start.as_secs()).collect();
assert_eq!(offsets, vec![0, 300, 600]);
assert_eq!(cut[2].length, Duration::from_secs(100));
assert_eq!(pieces(Duration::from_secs(600)).len(), 2);
assert!(pieces(Duration::ZERO).is_empty());
}
#[test]
fn a_finished_entry_is_not_read_again_and_a_partial_one_is_kept() {
let mut cached = Some(entry(300.0, Vec::new()));
assert!(finished(&mut cached, 700.0).is_none(), "700 s is not read");
assert_eq!(
cached.as_ref().map(|cached| cached.covered),
Some(300.0),
"the partial entry is what the next pass resumes from"
);
let mut cached = Some(entry(700.0, Vec::new()));
let done = finished(&mut cached, 700.0).expect("the track is read");
assert!((done.reached - 700.0).abs() < f64::EPSILON);
assert!(cached.is_none(), "a finished entry is consumed");
}
#[test]
fn a_pass_resumes_from_where_it_stopped() {
assert_eq!(remaining(pieces(Duration::from_secs(700)), 0.0).len(), 3);
assert_eq!(remaining(pieces(Duration::from_millis(400)), 0.0).len(), 1);
let resumed = remaining(pieces(Duration::from_secs(700)), 300.0);
assert_eq!(resumed[0].start, Duration::from_secs(300));
assert_eq!(resumed.len(), 2);
}
#[tokio::test]
async fn a_wait_that_outlives_its_own_bound_gives_up_on_the_cache() {
let key = PathBuf::from("/transcript-cache-test/clip.mp4");
let held = single_flight(key.clone(), Instant::now() + TRANSCRIBE_TIMEOUT)
.await
.expect("nothing holds this file");
assert!(
single_flight(key, Instant::now()).await.is_none(),
"a pass already running is not waited out past the reader's own bound"
);
drop(held);
let cached = unwaited(
Some(entry(
300.0,
vec![Segment {
start: 0.0,
end: 5.0,
text: Some("Hi.".to_string()),
label: None,
}],
)),
700.0,
MediaError::Busy,
);
assert_eq!(cached.regions.len(), 1, "the lines already read are kept");
assert!((cached.reached - 300.0).abs() < f64::EPSILON);
assert_eq!(cached.failure, Some(MediaError::Busy));
}
}