Medlar/crates/core/src/stream/mod.rs

509 lines
22 KiB
Rust

//! Streams: HLS and DASH in pieces that are joined, RTSP and MMS recorded through ffmpeg. Nothing is converted.
//!
//! Copy protection is recognised and refused. The only keys used are those a list hands to everyone (AES-128).
mod dash;
pub mod ffmpeg;
mod fetch;
mod hls;
mod join;
mod list;
mod record;
mod tape;
#[cfg(test)]
mod fuzz;
pub use ffmpeg::Tools;
pub use list::{Choice, Found, Kind, Pick, Variant};
use crate::disk::{self, PartialFile, blocking};
use crate::http::{Client, Error, Monitor, Options, PartState, PartView, Result, Shared, Snapshot, Source, Stop, safe_name, stopped};
use crate::model::{ErrorKind, Part, Task, TaskId};
use crate::store::Store;
use fetch::{Feed, Net, Want};
use list::Media;
use std::collections::VecDeque;
use std::io;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::sync::atomic::{AtomicU64, Ordering};
use std::time::Duration;
use tape::{Head, Tape, Track};
use tokio::task::JoinSet;
use tokio::time::Instant;
use url::Url;
/// Pieces that are downloaded at once.
const PARALLEL: u32 = 4;
/// Ending of what ffmpeg is making, after that of the unfinished file.
const JOINING: &str = ".join";
fn odd(what: &str) -> Error {
Error::BadReply(format!("stream: {what}"))
}
fn drm() -> Error {
Error::conn(ErrorKind::Drm)
}
fn disk_error(e: io::Error) -> Error {
Error::Disk(e.into())
}
/// Links that ffmpeg has to open.
pub(crate) fn recorded(url: &Url) -> bool {
matches!(url.scheme(), "rtsp" | "mms" | "mmsh" | "mmst")
}
/// What kind of stream a link is, if it is one. `mime` is what the server called it, if that is known.
pub fn kind(url: &Url, mime: Option<&str>) -> Option<Kind> {
if recorded(url) {
return Some(if url.scheme() == "rtsp" { Kind::Rtsp } else { Kind::Mms });
}
if !matches!(url.scheme(), "http" | "https") {
return None;
}
let path = url.path().to_ascii_lowercase();
match mime.map(str::to_ascii_lowercase).as_deref() {
Some("application/vnd.apple.mpegurl" | "application/x-mpegurl" | "audio/mpegurl" | "audio/x-mpegurl") if !path.ends_with(".m3u") => Some(Kind::Hls),
Some("application/dash+xml") => Some(Kind::Dash),
_ if path.ends_with(".m3u8") => Some(Kind::Hls),
_ if path.ends_with(".mpd") => Some(Kind::Dash),
_ => None,
}
}
/// Of a task, as far as it is known.
pub fn kind_of(task: &Task) -> Option<Kind> {
kind(&Url::parse(&task.url).ok()?, task.mime.as_deref())
}
/// What there is to choose from. Nothing is known of a stream that ffmpeg has to open.
pub async fn probe(client: &Client, source: &Source, stop: &mut Stop) -> Result<Found> {
if let Some(kind) = kind(&source.url, None).filter(|k| matches!(k, Kind::Rtsp | Kind::Mms)) {
return Ok(Found { kind, live: true, duration: None, videos: vec![], audios: vec![] });
}
let net = Net::plain(client, source);
let mut opened = net.open(stop).await?;
// A master list doesn't say whether what it leads to goes on.
if opened.found.kind == Kind::Hls && opened.media.is_none() {
let first = opened.found.videos.first().cloned().ok_or_else(|| odd("no variants"))?;
opened.media = net.refresh(&None, &[first], stop).await?.pop();
}
if let Some(media) = &opened.media {
opened.found.live = !media.ended;
opened.found.duration = media.ended.then(|| media.segments.iter().map(|s| s.seconds).sum());
}
Ok(opened.found)
}
/// What a download of a stream needs to know.
pub struct Request<'a> {
pub id: TaskId,
pub source: Source,
pub choice: Choice,
pub tools: &'a Tools,
pub options: &'a Options,
}
/// Starts or continues the task and returns the finished file. Doesn't touch the task's state. A stream that goes on ends with
/// `monitor.finish`, or at the limits of the choice; stopping it keeps what is there, to go on later.
pub async fn download(shared: &Shared, request: Request<'_>, monitor: &Monitor, mut stop: Stop) -> Result<PathBuf> {
let Request { id, source, choice, tools, options } = request;
let ffmpeg = tools.ffmpeg()?.to_path_buf();
let store = &shared.store;
let (task, parts) = run(store, move |s| Ok((s.task(id)?, s.parts(id)?))).await?;
let partial = {
let (folder, name) = (task.folder.clone(), task.name.clone());
let begun = !parts.is_empty();
blocking(move || if begun { PartialFile::reopen(&folder, &name) } else { Ok(None) }).await?
};
let done: u64 = parts.iter().map(|p| p.done).sum();
let mut tape = None;
let mut empty = None;
match partial {
Some(file) if Tape::is(&file).await? => {
let file = Arc::new(file);
match Tape::open(file.clone(), done).await? {
Some(found) => tape = Some(found),
// Killed before anything of it was safe.
None if done == 0 => empty = Some(file),
None => return Err(Error::Changed),
}
}
Some(file) if done == 0 && file.size()? == 0 => empty = Some(Arc::new(file)),
// Joined already, and then interrupted.
Some(file) if file.size()? > 0 => return finish(store, id, file).await,
Some(_) => return Err(Error::Missing),
None if done > 0 => {
let path = task.folder.join(&task.name);
let whole = parts.iter().all(|p| p.end == Some(p.start + p.done));
if whole && path.symlink_metadata().is_ok_and(|m| m.is_file() && m.len() == done) {
return Ok(path);
}
return Err(Error::Missing);
}
None => {}
}
let mut meter = Meter::new(store.clone(), id, options);
let finishing = *monitor.finishing().borrow();
let kind = kind_of(&task).unwrap_or(Kind::Hls);
let mut job = Work { shared, task: &task, options, choice: &choice, monitor, ffmpeg: &ffmpeg };
let mut tape = match tape {
// The user wants what there is.
Some(tape) if finishing && tape.head.live && !tape.records.is_empty() => tape,
tape if matches!(kind, Kind::Rtsp | Kind::Mms) => {
let mut tape = match tape {
Some(tape) => tape,
None => job.create(empty, Head { live: true, tracks: vec![Track { id: String::new(), total: None }] }, &source.url, false).await?,
};
let result = record::record(&ffmpeg, &shared.client, &source, &choice, &mut tape, &mut meter, monitor, &mut stop).await;
meter.save(&tape).await?;
result?;
tape
}
tape => {
let net = Arc::new(Net::new(shared, &source, options, monitor, meter.received.clone()));
job.pieces(net, tape, empty, &mut meter, &mut stop).await?
}
};
meter.save(&tape).await?;
let file = job.join(&mut tape, &mut stop).await?;
drop(tape);
finish(store, id, file).await
}
async fn run<T: Send + 'static>(store: &Arc<Store>, work: impl FnOnce(&Store) -> Result<T> + Send + 'static) -> Result<T> {
let store = store.clone();
blocking(move || work(&store)).await
}
/// Gives a joined file its name.
async fn finish(store: &Arc<Store>, id: TaskId, file: PartialFile) -> Result<PathBuf> {
let matroska = file.read_at(4, 0).await.is_ok_and(|start| start == [0x1a, 0x45, 0xdf, 0xa3]);
run(store, move |store| {
let size = file.size()?;
store.save_parts(id, vec![Part { start: 0, end: Some(size), done: size }])?;
let task = store.task(id)?;
let (stem, ext) = crate::http::name::split(&task.name);
// The format that was asked for could not hold it.
let name = match ext {
Some(ext) if matroska && !matches!(join::muxer(ext), Some(join::ANYTHING | "webm")) => format!("{stem}.mkv"),
_ => task.name.clone(),
};
file.finish(&name, size, |name| {
let name = name.to_string();
store.edit_task(id, move |task| (task.name, task.size) = (name, Some(size)))?;
Ok(())
})
})
.await
}
struct Work<'a> {
shared: &'a Shared,
task: &'a Task,
options: &'a Options,
choice: &'a Choice,
monitor: &'a Monitor,
ffmpeg: &'a Path,
}
impl Work<'_> {
/// A new tape, under a free name.
async fn create(&self, empty: Option<Arc<PartialFile>>, head: Head, url: &Url, sound: bool) -> Result<Tape> {
let file = match empty {
Some(file) => {
file.clear()?;
file
}
None => {
let wanted = name(&self.task.name, url, if sound { "m4a" } else { "mp4" });
let (id, folder) = (self.task.id, self.task.folder.clone());
let file = run(&self.shared.store, move |store| {
let _names = disk::names();
let (file, name) = PartialFile::create(&folder, &wanted, &store.used_names(&folder, id)?)?;
store.edit_task(id, move |task| task.name = name)?;
store.save_parts(id, vec![Part { start: 0, end: None, done: 0 }])?;
Ok(file)
});
Arc::new(file.await?)
}
};
Tape::create(file, head).await
}
/// Downloads the pieces of a list, until it ends or is told to.
async fn pieces(&mut self, net: Arc<Net>, tape: Option<Tape>, empty: Option<Arc<PartialFile>>, meter: &mut Meter, stop: &mut Stop) -> Result<Tape> {
let opened = net.open(stop).await?;
let picked = opened.found.pick(self.choice).ok_or(Error::because(ErrorKind::Media, "error.media.choice"))?;
let sound = !picked.iter().any(|p| opened.found.videos.contains(p));
let is_master = opened.media.is_none() && opened.manifest.is_none();
let root = if is_master { None } else { Some(opened.found.kind) };
let mut media = match (&opened.manifest, opened.media) {
(Some(manifest), _) => picked.iter().map(|v| manifest.media(v, fetch::now())).collect::<Result<Vec<_>>>()?,
(None, Some(media)) => vec![media],
(None, None) => net.refresh(&root, &picked, stop).await?,
};
for m in &mut media {
net.split(m, stop).await?;
}
let live = media.iter().any(|m| !m.ended);
if media.iter().any(|m| m.segments.is_empty()) && !live {
return Err(odd("no segments"));
}
let total = |m: &Media| (!live).then_some(m.segments.len() as u64);
let head = Head { live, tracks: picked.iter().zip(&media).map(|(v, m)| Track { id: v.id.clone(), total: total(m) }).collect() };
let mut tape = match tape {
Some(tape) => {
// A recording may have ended meanwhile.
let same = if tape.head.live { tape.head.tracks.iter().map(|t| &t.id).eq(head.tracks.iter().map(|t| &t.id)) } else { tape.head == head };
if !same {
return Err(Error::Changed);
}
tape
}
None => self.create(empty, head, &net.source.url, sound).await?,
};
let live = tape.head.live;
meter.whole = (!live).then(|| media.iter().flat_map(|m| &m.segments).map(|s| (s.seconds * 1000.0) as u64).sum());
let mut feeds: Vec<Feed> = (0..picked.len() as u32).map(|track| Feed::new(track, &tape, self.choice.seconds)).collect();
let mut queue: VecDeque<Want> = VecDeque::new();
let mut ended = add(&mut feeds, &media, live, &mut queue);
// Picture and sound side by side.
queue.make_contiguous().sort_by_key(|w| w.place);
let (mut running, mut lists) = (JoinSet::new(), JoinSet::new());
let mut finish = self.monitor.finishing();
let cap = self.monitor.cap();
let (mut failed, mut silent) = (None, 0);
let mut pace = wait_of(&media, false);
let mut look = Instant::now() + pace;
loop {
let full = live && self.choice.bytes.is_some_and(|most| tape.end >= most);
if failed.is_some() || full {
queue.clear();
}
ended |= full;
let width = (*cap.borrow()).min(net.width()).min(self.monitor.flow().connections()).max(1) as usize;
while running.len() < width && let Some(want) = queue.pop_front() {
let (net, mut stop) = (net.clone(), stop.clone());
running.spawn(async move {
let got = net.piece(&want, &mut stop).await;
(want, got)
});
}
if running.is_empty() && queue.is_empty() {
if ended || failed.is_some() {
break;
}
net.rest();
}
if live && !ended && failed.is_none() && lists.is_empty() && Instant::now() >= look {
let (net, picked, mut stop) = (net.clone(), picked.clone(), stop.clone());
lists.spawn(async move { net.refresh(&root, &picked, &mut stop).await });
}
tokio::select! {
biased;
_ = stopped(stop) => {
failed = Some(Error::Stopped);
break;
}
_ = stopped(&mut finish), if live && !ended => {
ended = true;
queue.clear();
}
Some(got) = running.join_next() => match got {
Ok((want, Ok(data))) => tape.append(want.record, &data).await?,
// It is gone already, the rest goes on.
Ok((_, Err(Error::Status { code: 404 | 410, .. }))) if live => {}
Ok((_, Err(e))) => failed = failed.or(Some(e)),
Err(e) => std::panic::resume_unwind(e.into_panic()),
},
Some(list) = lists.join_next() => match list {
Ok(Ok(now)) => {
silent = 0;
let changed = now.iter().zip(&media).any(|(a, b)| a.segments.last() != b.segments.last());
media = now;
pace = wait_of(&media, !changed);
ended |= add(&mut feeds, &media, live, &mut queue);
look = Instant::now() + pace;
}
Ok(Err(Error::Stopped)) => {}
// The end of many.
Ok(Err(Error::Status { code: 404 | 410, .. })) if !tape.records.is_empty() => ended = true,
Ok(Err(e)) => {
silent += 1;
if silent >= self.options.tries || !fetch::passing(&e) {
failed = failed.or(Some(e));
}
look = Instant::now() + pace;
}
Err(e) => std::panic::resume_unwind(e.into_panic()),
},
_ = tokio::time::sleep(meter.tick()) => {}
}
meter.look(&tape, running.len() as u32, self.monitor).await?;
}
// Ends the requests, not what is on the tape.
running.shutdown().await;
meter.save(&tape).await?;
meter.show(&tape, 0, self.monitor);
match failed {
Some(e) => Err(e),
None => Ok(tape),
}
}
/// The joined file takes the place of the tape.
async fn join(&self, tape: &mut Tape, stop: &mut Stop) -> Result<PartialFile> {
let from = tape.file.path().to_path_buf();
let mut to = from.clone().into_os_string();
to.push(JOINING);
let to = PathBuf::from(to);
let ext = self.shared.store.task(self.task.id)?.name;
let muxer = crate::http::name::split(&ext).1.and_then(join::muxer).unwrap_or(join::ANYTHING);
join::join(self.ffmpeg, tape, muxer, &to, stop).await?;
blocking(move || {
std::fs::rename(&to, &from).map_err(disk_error)?;
PartialFile::hold(from)?.ok_or(Error::Missing)
})
.await
}
}
/// Puts what is new in the queue. True when there will be no more.
fn add(feeds: &mut [Feed], media: &[Media], live: bool, queue: &mut VecDeque<Want>) -> bool {
let mut over = true;
for (feed, media) in feeds.iter_mut().zip(media) {
feed.take(media, live, queue);
over &= media.ended || feed.full();
}
over
}
/// Until the next look at lists that grow.
fn wait_of(media: &[Media], same: bool) -> Duration {
let pace = media.iter().map(|m| m.pace).fold(60.0, f64::min);
Duration::from_secs_f64(if same { pace / 2.0 } else { pace })
}
/// Names that say nothing.
const PLAIN: &[&str] = &["master", "index", "playlist", "manifest", "chunklist", "main", "stream", "live", "video", "prog_index", "media"];
/// The name for a stream without one, with an ending for what it becomes.
fn name(given: &str, url: &Url, ext: &str) -> String {
let given = safe_name(given).filter(|n| !n.is_empty());
let mut words: Vec<String> = url.path_segments().into_iter().flatten().rev().filter_map(decoded).collect();
words.extend(url.host_str().and_then(safe_name));
let stem = |n: &str| n.rsplit_once('.').filter(|(s, e)| !s.is_empty() && matches!(e.to_ascii_lowercase().as_str(), "m3u8" | "m3u" | "mpd" | "sdp")).map_or(n.to_string(), |(s, _)| s.to_string());
let telling = words.iter().map(|w| stem(w)).find(|w| !PLAIN.contains(&w.to_ascii_lowercase().as_str()));
let name = given.map(|n| stem(&n)).filter(|n| !PLAIN.contains(&n.to_ascii_lowercase().as_str())).or(telling).unwrap_or_else(|| "stream".into());
match crate::http::name::split(&name).1.and_then(join::muxer) {
Some(_) => name,
None => safe_name(&format!("{name}.{ext}")).unwrap_or_else(|| format!("stream.{ext}")),
}
}
fn decoded(segment: &str) -> Option<String> {
safe_name(&percent_encoding::percent_decode_str(segment).decode_utf8_lossy())
}
/// What others see of it, and what is safe on disk.
struct Meter {
store: Arc<Store>,
id: TaskId,
received: Arc<AtomicU64>,
/// Milliseconds of all tracks, when that is known.
whole: Option<u64>,
tick: Duration,
checkpoint: Duration,
saved: (u64, Instant),
shown: (u64, Instant),
speed: f64,
}
impl Meter {
fn new(store: Arc<Store>, id: TaskId, options: &Options) -> Meter {
let now = Instant::now();
let (tick, checkpoint) = (options.tick, options.checkpoint);
Meter { store, id, received: Arc::default(), whole: None, tick, checkpoint, saved: (0, now), shown: (0, now), speed: 0.0 }
}
fn tick(&self) -> Duration {
self.tick
}
fn came(&self, n: u64) {
self.received.fetch_add(n, Ordering::Relaxed);
}
async fn look(&mut self, tape: &Tape, connections: u32, monitor: &Monitor) -> Result<()> {
if self.shown.1.elapsed() >= self.tick {
self.show(tape, connections, monitor);
}
if self.saved.1.elapsed() >= self.checkpoint {
self.save(tape).await?;
}
Ok(())
}
fn show(&mut self, tape: &Tape, connections: u32, monitor: &Monitor) {
let received = self.received.load(Ordering::Relaxed);
let dt = self.shown.1.elapsed().as_secs_f64().max(0.001);
let now = received.saturating_sub(self.shown.0) as f64 / dt;
self.speed = self.speed * 0.7 + now * 0.3;
self.shown = (received, Instant::now());
// Its size is a guess from how long it is, so that there is something to show.
let here: u64 = tape.records.iter().map(|r| u64::from(r.ms)).sum();
let size = self.whole.filter(|_| here > 0).map(|whole| (tape.end as f64 * (whole as f64 / here as f64).max(1.0)) as u64);
let state = if connections > 0 { PartState::Running } else { PartState::Waiting };
let part = PartView { id: 0, start: 0, end: size, done: tape.end, state, speed: self.speed, fails: 0 };
let shot = Snapshot { size, parts: vec![part], connections, wanted: connections, received, speed: self.speed, ..Default::default() };
monitor.publish(shot, vec![], std::iter::empty());
}
/// Data first, then the record of it.
async fn save(&mut self, tape: &Tape) -> Result<()> {
let (end, file, id) = (tape.end, tape.file.clone(), self.id);
if self.saved.0 != end {
run(&self.store, move |store| {
file.sync()?;
Ok(store.save_parts(id, vec![Part { start: 0, end: None, done: end }])?)
})
.await?;
}
self.saved = (end, Instant::now());
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn kinds() {
let of = |url: &str, mime| kind(&Url::parse(url).unwrap(), mime);
assert_eq!(of("https://h/a/Master.M3U8?x=1", None), Some(Kind::Hls));
assert_eq!(of("https://h/a", Some("application/vnd.apple.mpegURL")), Some(Kind::Hls));
assert_eq!(of("https://h/a.mpd", None), Some(Kind::Dash));
assert_eq!(of("rtsp://h/a", None), Some(Kind::Rtsp));
assert_eq!(of("mms://h/a.wmv", None), Some(Kind::Mms));
for (url, mime) in [("https://h/songs.m3u", Some("audio/x-mpegurl")), ("https://h/a.mp4", Some("video/mp4")), ("ftp://h/a.m3u8", None)] {
assert_eq!(of(url, mime), None, "{url}");
}
}
#[test]
fn names() {
let of = |given: &str, url: &str| name(given, &Url::parse(url).unwrap(), "mp4");
assert_eq!(of("", "https://h/my%20film/master.m3u8?t=1"), "my film.mp4");
assert_eq!(of("", "https://h/film.m3u8"), "film.mp4");
assert_eq!(of("", "https://h.org/index.m3u8"), "h.org.mp4");
assert_eq!(of("index.m3u8", "https://h.org/a/index.m3u8"), "a.mp4");
assert_eq!(of("Mine.mkv", "https://h/x.m3u8"), "Mine.mkv");
assert_eq!(of("Part 1.5", "https://h/x.m3u8"), "Part 1.5.mp4");
assert_eq!(of("../../x", "rtsp://h/cam"), "x.mp4");
}
}