From d26c59ee2655e55f4829eb9c0cabb8520579bd62 Mon Sep 17 00:00:00 2001 From: astar76 Date: Wed, 25 Nov 2026 13:18:25 -0600 Subject: [PATCH] S012: HLS, DASH, RTSP and MMS Co-Authored-By: Claude Opus 5.5 --- Cargo.lock | 3 + crates/core/Cargo.toml | 5 +- crates/core/lang/en.json | 10 + crates/core/src/error.rs | 3 + crates/core/src/http/mod.rs | 9 +- crates/core/src/http/monitor.rs | 16 +- crates/core/src/http/piece.rs | 74 +++ crates/core/src/lib.rs | 1 + crates/core/src/manager/actor.rs | 31 ++ crates/core/src/manager/mod.rs | 4 +- crates/core/src/model.rs | 6 + crates/core/src/stream/dash.rs | 479 ++++++++++++++++++++ crates/core/src/stream/fetch.rs | 388 ++++++++++++++++ crates/core/src/stream/ffmpeg.rs | 306 +++++++++++++ crates/core/src/stream/hls.rs | 304 +++++++++++++ crates/core/src/stream/join.rs | 163 +++++++ crates/core/src/stream/list.rs | 156 +++++++ crates/core/src/stream/mod.rs | 507 +++++++++++++++++++++ crates/core/src/stream/record.rs | 223 +++++++++ crates/core/src/stream/tape.rs | 174 +++++++ crates/core/tests/stream.rs | 750 +++++++++++++++++++++++++++++++ docs/RECOVERY.md | 3 + 22 files changed, 3608 insertions(+), 7 deletions(-) create mode 100644 crates/core/src/http/piece.rs create mode 100644 crates/core/src/stream/dash.rs create mode 100644 crates/core/src/stream/fetch.rs create mode 100644 crates/core/src/stream/ffmpeg.rs create mode 100644 crates/core/src/stream/hls.rs create mode 100644 crates/core/src/stream/join.rs create mode 100644 crates/core/src/stream/list.rs create mode 100644 crates/core/src/stream/mod.rs create mode 100644 crates/core/src/stream/record.rs create mode 100644 crates/core/src/stream/tape.rs create mode 100644 crates/core/tests/stream.rs diff --git a/Cargo.lock b/Cargo.lock index d43965f..e62fe95 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2768,9 +2768,11 @@ dependencies = [ name = "medlar-core" version = "0.1.0" dependencies = [ + "aes", "arc-swap", "base64 0.23.1", "bytes", + "cbc", "chrono", "dirs", "fastrand", @@ -2785,6 +2787,7 @@ dependencies = [ "rcgen", "regex", "reqwest", + "roxmltree 0.21.2", "rusqlite", "russh", "russh-sftp", diff --git a/crates/core/Cargo.toml b/crates/core/Cargo.toml index 99fdc61..d3deb28 100644 --- a/crates/core/Cargo.toml +++ b/crates/core/Cargo.toml @@ -6,9 +6,11 @@ license.workspace = true description = "Medlar's engine, store and settings" [dependencies] +aes = "0.9" arc-swap = "1.9.5" base64 = "0.23" bytes = "1.10" +cbc = "0.2" chrono = { version = "0.4", default-features = false, features = ["clock", "std"] } dirs = "6" futures-lite = "2.6" @@ -19,6 +21,7 @@ log = { workspace = true, features = ["std"] } md-5 = "0.11.0" percent-encoding = "2.3.2" regex = { version = "1", default-features = false, features = ["std", "unicode-case", "unicode-perl"] } +roxmltree = "0.21" # Pinned: D-017. reqwest = { version = "=0.13.5", default-features = false, features = ["rustls-no-provider", "socks"] } # ring, as everywhere else: aws-lc-rs would be a second one. @@ -32,7 +35,7 @@ rustls-platform-verifier = "0.7.1" serde.workspace = true serde_json.workspace = true sha2 = "0.11.1" -tokio = { version = "1.54.1", features = ["rt-multi-thread", "macros", "sync", "time", "net", "io-util"] } +tokio = { version = "1.54.1", features = ["rt-multi-thread", "macros", "sync", "time", "net", "io-util", "process"] } tokio-rustls = { version = "0.26", default-features = false } tower-service = "0.3" url = "2" diff --git a/crates/core/lang/en.json b/crates/core/lang/en.json index ac5627c..5a652cc 100644 --- a/crates/core/lang/en.json +++ b/crates/core/lang/en.json @@ -270,6 +270,16 @@ "error.wrong_content.why": "{server} sent a web page instead of the file. The link may be old, or need a login.", "error.no_resume": "Can't be continued", "error.no_resume.why": "{server} no longer sends the rest of a file, only all of it. What is here was kept.", + "error.tool": "A program is missing", + "error.tool.why": "A program this download needs is not on this computer. Install it, then try again.", + "error.tool.ffmpeg": "Streams need the program ffmpeg, which is not on this computer. Install it, then try again.", + "error.drm": "Copy protected", + "error.drm.why": "{server} sends this stream with copy protection. Medlar does not get around it, so nothing was downloaded.", + "error.media": "Stream can't be saved", + "error.media.why": "ffmpeg could not make a file of what {server} sent.", + "error.media.choice": "{server} no longer offers the chosen quality or language.", + "error.media.empty": "{server} sent no sound or picture.", + "error.proxy.stream": "The stream from {server} can't go through the proxy, and Medlar does not connect without it.", "error.disk_full": "Disk is full", "error.disk_full.why": "There is not enough space in {folder}. The download goes on when there is.", "error.read_only": "Disk is read-only", diff --git a/crates/core/src/error.rs b/crates/core/src/error.rs index ed066d8..7017aee 100644 --- a/crates/core/src/error.rs +++ b/crates/core/src/error.rs @@ -102,6 +102,9 @@ impl ErrorKind { Tls => (Serious, Retry::Never, Fix::TryAgain), Disk => (Serious, later(30, 600), Fix::ChangeFolder), List => (Serious, later(30, 600), Fix::TryAgain), + Drm => (Blocked, Retry::Never, Fix::EditLink), + Tool => (Blocked, Retry::Never, Fix::TryAgain), + Media => (Serious, Retry::Never, Fix::TryAgain), Crashed => (Serious, Retry::Never, Fix::TryAgain), } } diff --git a/crates/core/src/http/mod.rs b/crates/core/src/http/mod.rs index 953c736..272180c 100644 --- a/crates/core/src/http/mod.rs +++ b/crates/core/src/http/mod.rs @@ -5,6 +5,7 @@ mod fetch; mod monitor; pub(crate) mod name; mod parts; +mod piece; mod probe; pub use download::{Options, Shared, download}; @@ -13,6 +14,7 @@ pub(crate) use fetch::same_body; pub use fetch::{Link, OVERLAP, compare, fetch, same_bytes}; pub use monitor::{Monitor, PartEvent, PartId, PartState, PartView, Snapshot}; pub use name::safe as safe_name; +pub(crate) use piece::piece; pub use probe::{Probe, probe}; use crate::model::ErrorKind; @@ -20,7 +22,7 @@ use crate::sftp::HostKeys; use crate::site::{Access, same_site}; use crate::tls::Trust; use crate::transport::{Remote, Way}; -use crate::{disk, redact, store}; +use crate::{disk, redact, store, stream}; use reqwest::header::{self, HeaderMap, HeaderName, HeaderValue}; pub(crate) use reqwest::Response; use reqwest::{RequestBuilder, StatusCode, redirect}; @@ -209,7 +211,7 @@ impl Source { pub fn new(url: &str) -> Result { let url = Url::parse(url).map_err(|_| Error::Link)?; let remote = Remote::of(&url).map(Arc::new); - if !(remote.is_some() || matches!(url.scheme(), "http" | "https")) || url.host_str().is_none_or(str::is_empty) { + if !(remote.is_some() || matches!(url.scheme(), "http" | "https") || stream::recorded(&url)) || url.host_str().is_none_or(str::is_empty) { return Err(Error::Link); } Ok(Source { url, headers: HeaderMap::new(), access: None, remote }) @@ -270,6 +272,9 @@ impl Source { if let Some(remote) = &self.remote { return remote.respond(client, self, range).await; } + if stream::recorded(&self.url) { + return Err(Error::Link); + } let mut here = self.clone(); for _ in 0..=HOPS { let request = |client: &Client, headers: &HeaderMap| -> RequestBuilder { diff --git a/crates/core/src/http/monitor.rs b/crates/core/src/http/monitor.rs index 8c670b1..7e32173 100644 --- a/crates/core/src/http/monitor.rs +++ b/crates/core/src/http/monitor.rs @@ -66,6 +66,7 @@ pub struct Monitor { events: broadcast::Sender, state: Mutex<(Snapshot, Vec>)>, flow: Arc, + finish: watch::Sender, } impl Monitor { @@ -75,7 +76,7 @@ impl Monitor { } pub fn with_flow(cap: u32, flow: Flow) -> Monitor { - Monitor { cap: watch::Sender::new(cap), events: broadcast::Sender::new(1024), state: Mutex::default(), flow: Arc::new(flow) } + Monitor { cap: watch::Sender::new(cap), events: broadcast::Sender::new(1024), state: Mutex::default(), flow: Arc::new(flow), finish: watch::Sender::new(false) } } /// The limits that count for it. @@ -88,6 +89,15 @@ impl Monitor { self.cap.send_replace(cap); } + /// What has no end of its own ends here, and is made a whole file of. + pub fn finish(&self) { + self.finish.send_replace(true); + } + + pub(crate) fn finishing(&self) -> watch::Receiver { + self.finish.subscribe() + } + pub fn subscribe(&self) -> broadcast::Receiver { self.events.subscribe() } @@ -103,12 +113,12 @@ impl Monitor { shot } - pub(super) fn cap(&self) -> watch::Receiver { + pub(crate) fn cap(&self) -> watch::Receiver { self.cap.subscribe() } /// The snapshot first: whoever sees the events finds them in it. - pub(super) fn publish(&self, shot: Snapshot, parts: Vec>, events: impl Iterator) { + pub(crate) fn publish(&self, shot: Snapshot, parts: Vec>, events: impl Iterator) { *self.state.lock().unwrap() = (shot, parts); for e in events { // Nobody has to listen. diff --git a/crates/core/src/http/piece.rs b/crates/core/src/http/piece.rs new file mode 100644 index 0000000..a935081 --- /dev/null +++ b/crates/core/src/http/piece.rs @@ -0,0 +1,74 @@ +//! Something small, whole and in memory: lists, keys and pieces of streams. + +use super::*; +use crate::limit::Flow; +use std::sync::atomic::{AtomicU64, Ordering}; + +#[derive(Debug)] +pub(crate) struct Piece { + /// Where the redirects ended. + pub url: Url, + pub mime: Option, + pub body: Vec, +} + +/// Fails when it is larger than `most`. `range` is the first byte and the one after the last. Adds to `received` what comes. +pub(crate) async fn piece( + client: &Client, + source: &Source, + range: Option<(u64, u64)>, + most: u64, + flow: &Flow, + received: &AtomicU64, + stop: &mut Stop, +) -> Result { + let asked = range.map(|(first, end)| format!("bytes={first}-{}", end - 1)); + let mut response = source.get(client, asked, None, stop).await?; + let headers = response.headers(); + let expected = match (range, response.status()) { + (None, StatusCode::OK) => content_length(headers), + (Some((first, end)), StatusCode::PARTIAL_CONTENT) => { + let got = ContentRange::of(headers).filter(|r| r.first == first && r.last < end); + let got = got.ok_or_else(|| Error::BadReply("another range than asked for".into()))?; + if got.last + 1 < end && got.total.is_none_or(|total| got.last + 1 < total) { + return Err(Error::BadReply("less than asked for".into())); + } + Some(got.len()) + } + (Some(_), StatusCode::OK) => return Err(Error::RangeIgnored), + _ => return Err(status_error(&response)), + }; + let url = response.url().clone(); + check_encoding(headers, &url)?; + let too_large = || Error::BadReply(format!("larger than {most}")); + if expected.is_some_and(|n| n > most) { + return Err(too_large()); + } + let mime = name::mime(headers); + let mut body = Vec::with_capacity(expected.unwrap_or(0) as usize); + let work = async { + let cut = |e: reqwest::Error, got| if e.is_timeout() { e.into() } else { Error::Cut { got, expected } }; + while let Some(chunk) = client.wait(async { response.chunk().await.map_err(|e| cut(e, body.len() as u64)) }).await? { + let mut rest = &chunk[..]; + while !rest.is_empty() { + let (now, later) = rest.split_at(flow.take(rest.len() as u64).await as usize); + body.extend_from_slice(now); + received.fetch_add(now.len() as u64, Ordering::Relaxed); + rest = later; + } + if body.len() as u64 > most { + return Err(too_large()); + } + } + Ok(()) + }; + tokio::select! { + biased; + _ = stopped(stop) => return Err(Error::Stopped), + done = work => done?, + } + match expected { + Some(n) if n != body.len() as u64 => Err(Error::Cut { got: body.len() as u64, expected }), + _ => Ok(Piece { url, mime, body }), + } +} diff --git a/crates/core/src/lib.rs b/crates/core/src/lib.rs index 6aaae21..415ae11 100644 --- a/crates/core/src/lib.rs +++ b/crates/core/src/lib.rs @@ -30,6 +30,7 @@ pub mod site; pub mod snapshot; pub mod speed; pub mod store; +pub mod stream; pub mod strings; pub mod tls; mod transport; diff --git a/crates/core/src/manager/actor.rs b/crates/core/src/manager/actor.rs index 20bfdc4..603a84b 100644 --- a/crates/core/src/manager/actor.rs +++ b/crates/core/src/manager/actor.rs @@ -20,6 +20,7 @@ use crate::settings::Limits; use crate::snapshot::{Counters, Line, Log, Snapshot, TaskView, Totals}; use crate::speed::{History, Meter}; use crate::store::{self, Store}; +use crate::stream::{self, Tools}; use crate::{adopt, disk, host, redact, site, strings, tr}; use arc_swap::ArcSwap; use std::collections::{BTreeMap, BTreeSet, HashMap, VecDeque}; @@ -108,6 +109,8 @@ struct Entry { connections: u32, wanted: u32, resumable: Option, + /// Its next run ends a stream at once. + finish: bool, meter: Meter, history: Arc, /// Bytes of the second that isn't over. @@ -135,6 +138,7 @@ impl Entry { connections: 0, wanted: 0, resumable: None, + finish: false, meter: Meter::default(), history: Arc::default(), second: 0, @@ -556,6 +560,7 @@ impl Actor { } Command::Resume(_) => result = self.resume(id), Command::Pause(_) => result = self.hold(id), + Command::Finish(_) => result = self.finish(id), Command::Stop(_) => { result = self.hold(id).and_then(|()| { if matches!(state, Done | Gone) { @@ -874,6 +879,25 @@ impl Actor { } } + /// Ends a stream: now, or in a run of its own when it doesn't run. + fn finish(&mut self, id: TaskId) -> Result<()> { + let e = &self.entries[&id]; + if stream::kind_of(&e.task).is_none() || matches!(e.task.state, State::Checking | State::Finishing | State::Done | State::Gone) { + return Ok(()); + } + match &e.work { + Some(Work::Run(run)) if e.task.state == State::Running => run.monitor.finish(), + _ => { + self.entry(id).finish = true; + self.resume(id)?; + self.forces += 1; + self.entry(id).forced = self.forces; + self.choose = true; + } + } + Ok(()) + } + /// Takes a running one's place away. fn suspend(&mut self, id: TaskId) { if self.entries[&id].task.state == State::Running { @@ -959,11 +983,18 @@ impl Actor { flow.set(task.speed_limit); let monitor = Arc::new(Monitor::with_flow(unlimited(self.config.limits.parts_per_download), flow)); let run = Run { stop, monitor: monitor.clone(), since: Instant::now(), received: 0, known: false, had: self.entries[&id].downloaded }; + if std::mem::take(&mut self.entry(id).finish) { + monitor.finish(); + } let (shared, options, to) = (self.config.shared.clone(), self.config.options.clone(), self.to.clone()); let sites = self.config.sites.clone(); self.runtime().spawn(async move { let work = tokio::spawn(async move { let source = site::source(sites.as_ref(), &task, &stopped).await?; + if stream::kind_of(&task).is_some() { + let request = stream::Request { id, source, choice: Default::default(), tools: &Tools::find(), options: &options }; + return stream::download(&shared, request, &monitor, stopped).await; + } download(&shared, id, source, &options, &monitor, stopped).await }); let result = match work.await { diff --git a/crates/core/src/manager/mod.rs b/crates/core/src/manager/mod.rs index acbc018..88b8ea4 100644 --- a/crates/core/src/manager/mod.rs +++ b/crates/core/src/manager/mod.rs @@ -98,6 +98,8 @@ pub enum Command { Pause(TaskId), /// Back in line, also after a failure. Resume(TaskId), + /// What goes on until it is stopped, like a live stream, ends here: what there is becomes the file. + Finish(TaskId), /// Pauses it and puts it last. Stop(TaskId), /// Can be undone for `Config::undo`, and until the program ends. @@ -131,7 +133,7 @@ impl Command { use Command::*; match self { Add(_) | Adopt { .. } => None, - Start(id) | Pause(id) | Resume(id) | Stop(id) | Restore(id) | Redownload(id) | KeepBoth(id) | AwaitLink(id) => Some(*id), + Start(id) | Pause(id) | Resume(id) | Stop(id) | Finish(id) | Restore(id) | Redownload(id) | KeepBoth(id) | AwaitLink(id) => Some(*id), Remove { id, .. } | Move { id, .. } | Rename { id, .. } | Edit { id, .. } | Continue { id, .. } => Some(*id), } } diff --git a/crates/core/src/model.rs b/crates/core/src/model.rs index d3d8ee1..15c0a3e 100644 --- a/crates/core/src/model.rs +++ b/crates/core/src/model.rs @@ -129,6 +129,12 @@ named_enum!( Killed = "killed", /// Waits for a link from its page. Link = "link", + /// A program that is needed is not on this computer. + Tool = "tool", + /// Copy protection, which is never worked around. + Drm = "drm", + /// Sound and picture that can't be made a file of. + Media = "media", Crashed = "crashed", } ); diff --git a/crates/core/src/stream/dash.rs b/crates/core/src/stream/dash.rs new file mode 100644 index 0000000..8649e52 --- /dev/null +++ b/crates/core/src/stream/dash.rs @@ -0,0 +1,479 @@ +//! DASH manifests (ISO/IEC 23009-1): those that are whole, and simple ones that grow. + +use super::list::*; +use super::{drm, odd}; +use crate::http::Result; +use roxmltree::{Document, Node}; +use url::Url; + +/// More than any film has. Numbers in a manifest must not make us count for ever. +const MOST: u64 = 200_000; +/// Pieces taken of a file that has all in one. +pub(super) const CHUNK: u64 = 4 << 20; + +#[derive(Debug)] +pub(super) struct Manifest { + pub found: Found, + periods: Vec, + pace: f64, + /// Seconds since 1970. + begins: Option, + depth: Option, +} + +#[derive(Debug)] +struct Period { + start: f64, + length: Option, + sets: Vec, +} + +#[derive(Debug)] +struct Rendition { + variant: Variant, + /// Not video. + sound: bool, + base: Url, + segments: Segments, +} + +#[derive(Debug)] +enum Segments { + Template { init: Option, media: String, number: u64, end_number: Option, scale: f64, each: Option, times: Vec<(u64, u64)>, offset: u64 }, + List { init: Option, media: Vec, seconds: f64 }, + Whole, +} + +pub(super) fn parse(text: &str, base: &Url) -> Result { + let doc = Document::parse(text.trim_start_matches('\u{feff}')).map_err(|_| odd("manifest"))?; + let mpd = doc.root_element(); + if mpd.tag_name().name() != "MPD" { + return Err(odd("no manifest")); + } + // Widevine, PlayReady, FairPlay, ClearKey: all announce themselves like this. + if doc.descendants().any(|n| n.tag_name().name() == "ContentProtection") { + return Err(drm()); + } + let live = mpd.attribute("type") == Some("dynamic"); + let length = mpd.attribute("mediaPresentationDuration").and_then(seconds); + let base = base_url(mpd, base)?; + let mut periods: Vec = vec![]; + for p in children(mpd, "Period") { + if p.attributes().any(|a| a.name() == "href") { + return Err(odd("a period elsewhere")); + } + let own = p.attribute("start").and_then(seconds); + let start = own.or_else(|| periods.last().map_or(Some(0.0), |l| Some(l.start + l.length?))).ok_or_else(|| odd("period"))?; + if let Some(last) = periods.last_mut().filter(|l| l.length.is_none()) { + last.length = Some(start - last.start); + } + let mut period = Period { start, length: p.attribute("duration").and_then(seconds), sets: vec![] }; + let base = base_url(p, &base)?; + for set in children(p, "AdaptationSet") { + let base = base_url(set, &base)?; + for r in children(set, "Representation") { + period.sets.extend(rendition(p, set, r, &base)?); + } + } + periods.push(period); + } + if let Some(last) = periods.last_mut().filter(|l| l.length.is_none() && !live) { + last.length = length.map(|n| n - last.start); + } + let first = periods.iter().find(|p| !p.sets.is_empty()).ok_or_else(|| odd("no streams"))?; + let mut found = Found { kind: Kind::Dash, live, duration: length.filter(|_| !live), videos: vec![], audios: vec![] }; + for r in &first.sets { + let list = if r.sound { &mut found.audios } else { &mut found.videos }; + if !list.iter().any(|v| v.id == r.variant.id) { + list.push(r.variant.clone()); + } + } + sort(&mut found.videos); + sort(&mut found.audios); + Ok(Manifest { + found, + periods, + pace: mpd.attribute("minimumUpdatePeriod").and_then(seconds).unwrap_or(4.0).clamp(0.5, 60.0), + begins: mpd.attribute("availabilityStartTime").and_then(date), + depth: mpd.attribute("timeShiftBufferDepth").and_then(seconds), + }) +} + +fn children<'a, 'b: 'a>(node: Node<'a, 'b>, name: &'static str) -> impl Iterator> { + node.children().filter(move |n| n.tag_name().name() == name) +} + +fn child<'a, 'b: 'a>(node: Node<'a, 'b>, name: &'static str) -> Option> { + children(node, name).next() +} + +/// The first of several: the others are the same on other servers. +fn base_url(node: Node, base: &Url) -> Result { + match child(node, "BaseURL").and_then(|b| b.text()) { + Some(text) => web(base, text).ok_or_else(|| odd("base")), + None => Ok(base.clone()), + } +} + +/// None for what is neither picture nor sound. +fn rendition(period: Node, set: Node, r: Node, base: &Url) -> Result> { + let either = |name| r.attribute(name).or(set.attribute(name)); + let mime = either("mimeType").or(set.attribute("contentType")).unwrap_or_default(); + let sound = match mime.split('/').next() { + Some("video") => false, + Some("audio") => true, + _ => return Ok(None), + }; + // Pictures for the seek bar. + if children(set, "EssentialProperty").chain(children(r, "EssentialProperty")).any(|p| p.attribute("schemeIdUri").is_some_and(|s| s.contains("trick"))) { + return Ok(None); + } + let number = |name| either(name).and_then(|n| n.parse::().ok()); + let id = r.attribute("id").unwrap_or_default().to_string(); + let bandwidth = r.attribute("bandwidth").and_then(|b| b.parse().ok()).unwrap_or(0); + let main = children(set, "Role").any(|role| role.attribute("value") == Some("main")); + let variant = Variant { + bandwidth, + size: number("width").zip(number("height")), + codecs: either("codecs").unwrap_or_default().to_string(), + language: set.attribute("lang").map(String::from), + preferred: sound && main, + ..Variant::new(id) + }; + let base = base_url(r, base)?; + let levels = [r, set, period]; + let template: Vec = levels.iter().filter_map(|n| child(*n, "SegmentTemplate")).collect(); + let list: Vec = levels.iter().filter_map(|n| child(*n, "SegmentList")).collect(); + fn attr<'a>(nodes: &[Node<'a, 'a>], name: &str) -> Option<&'a str> { + nodes.iter().find_map(|n| n.attribute(name)) + } + let segments = if !template.is_empty() { + let int = |name, or| attr(&template, name).map_or(Some(or), |n| n.parse().ok()).ok_or_else(|| odd("template")); + let times = template.iter().find_map(|n| child(*n, "SegmentTimeline")).map(|t| timeline(t, period)).transpose()?; + let each = attr(&template, "duration").and_then(|d| d.parse().ok()).filter(|d| *d > 0); + if each.is_none() && times.is_none() { + return Err(odd("template")); + } + let scale: u64 = int("timescale", 1)?; + Segments::Template { + init: attr(&template, "initialization").map(|t| fill(t, &variant, 0, 0)).transpose()?, + media: attr(&template, "media").ok_or_else(|| odd("template"))?.to_string(), + number: int("startNumber", 1)?, + end_number: attr(&template, "endNumber").and_then(|n| n.parse().ok()), + scale: scale.max(1) as f64, + each: each.filter(|_| times.is_none()), + times: times.unwrap_or_default(), + offset: int("presentationTimeOffset", 0)?, + } + } else if !list.is_empty() { + let piece = |link: Option<&str>, range: Option<&str>| -> Result { + let url = link.map_or(Some(base.clone()), |l| web(&base, l)).ok_or_else(|| odd("link"))?; + Ok(Piece { url, range: range.map(|r| byte_range(r).ok_or_else(|| odd("range"))).transpose()? }) + }; + let init = list.iter().find_map(|n| child(*n, "Initialization")); + let media = list.iter().map(|n| children(*n, "SegmentURL").collect::>()).find(|m| !m.is_empty()).unwrap_or_default(); + let scale = attr(&list, "timescale").and_then(|n| n.parse().ok()).filter(|n: &f64| *n > 0.0).unwrap_or(1.0); + Segments::List { + init: init.map(|i| piece(i.attribute("sourceURL"), i.attribute("range"))).transpose()?, + media: media.iter().map(|m| piece(m.attribute("media"), m.attribute("mediaRange"))).collect::>()?, + seconds: attr(&list, "duration").and_then(|n| n.parse::().ok()).unwrap_or(0.0) / scale, + } + } else { + Segments::Whole + }; + Ok(Some(Rendition { variant, sound, base, segments })) +} + +/// Start and length of each. +fn timeline(node: Node, period: Node) -> Result> { + let mut times: Vec<(u64, u64)> = vec![]; + let entries: Vec = children(node, "S").collect(); + let mut t = 0u64; + for (i, s) in entries.iter().enumerate() { + let int = |name| s.attribute(name).and_then(|n| n.parse::().ok()); + let d = int("d").filter(|d| *d > 0).ok_or_else(|| odd("timeline"))?; + t = int("t").unwrap_or(t); + let more = match s.attribute("r").map(|r| r.parse::()) { + None => 0, + Some(Ok(r)) if r >= 0 => r as u64, + // Up to the next one, or the end of the period. + Some(Ok(_)) => { + let next = entries.get(i + 1).and_then(|n| n.attribute("t")).and_then(|n| n.parse::().ok()); + let scale = node.parent_element().and_then(|p| p.attribute("timescale")).and_then(|n| n.parse::().ok()).unwrap_or(1.0); + let of_period = || Some((period.attribute("duration").and_then(seconds)? * scale) as u64 + entries[0].attribute("t").and_then(|t| t.parse().ok()).unwrap_or(0)); + let end = next.or_else(of_period).ok_or_else(|| odd("timeline"))?; + end.saturating_sub(t).div_ceil(d).saturating_sub(1) + } + Some(Err(_)) => return Err(odd("timeline")), + }; + if more >= MOST || times.len() as u64 + more >= MOST { + return Err(odd("timeline")); + } + for _ in 0..=more { + times.push((t, d)); + t = t.checked_add(d).ok_or_else(|| odd("timeline"))?; + } + } + Ok(times) +} + +/// `$Number%05d$` and the like. +fn fill(template: &str, v: &Variant, number: u64, time: u64) -> Result { + let mut out = String::new(); + let mut rest = template; + while let Some((before, after)) = rest.split_once('$') { + out += before; + let (name, after) = after.split_once('$').ok_or_else(|| odd("template"))?; + rest = after; + let (name, format) = name.split_once('%').unwrap_or((name, "")); + let width: usize = match format.strip_suffix('d') { + Some(w) => w.parse().ok().filter(|w| *w <= 32).ok_or_else(|| odd("template"))?, + None => 0, + }; + match name { + "" => out.push('$'), + "RepresentationID" => out += &v.id, + "Number" => out += &format!("{number:0width$}"), + "Time" => out += &format!("{time:0width$}"), + "Bandwidth" => out += &format!("{:0width$}", v.bandwidth), + _ => return Err(odd("template")), + } + } + Ok(out + rest) +} + +fn byte_range(text: &str) -> Option<(u64, u64)> { + let (first, last) = text.split_once('-')?; + let (first, last): (u64, u64) = (first.trim().parse().ok()?, last.trim().parse().ok()?); + (first <= last).then_some((first, last.checked_add(1)?)) +} + +/// `P1DT2H3M4.5S` +fn seconds(text: &str) -> Option { + let (days, time) = text.trim().strip_prefix('P')?.split_once('T').unwrap_or((text.trim().strip_prefix('P')?, "")); + let mut total = 0.0; + for (text, units) in [(days, &[('D', 86400.0)][..]), (time, &[('H', 3600.0), ('M', 60.0), ('S', 1.0)])] { + let mut digits = String::new(); + for c in text.chars() { + if c.is_ascii_digit() || c == '.' { + digits.push(c); + } else { + let unit = units.iter().find(|(u, _)| *u == c)?.1; + total += std::mem::take(&mut digits).parse::().ok()? * unit; + } + } + } + Some(total) +} + +fn date(text: &str) -> Option { + let parsed = chrono::DateTime::parse_from_rfc3339(text).or_else(|_| chrono::DateTime::parse_from_rfc3339(&format!("{text}Z"))).ok()?; + Some(parsed.timestamp_millis() as f64 / 1000.0) +} + +impl Manifest { + /// `now` in seconds since 1970. + pub fn media(&self, variant: &Variant, now: f64) -> Result { + let live = self.found.live; + let sound = self.found.audios.iter().any(|a| a.id == variant.id); + let mut media = Media { ended: !live, pace: self.pace, ..Media::default() }; + for period in &self.periods { + let Some(r) = period.closest(variant, sound) else { continue }; + // The start tells periods apart, also when old ones are dropped from the manifest. + let stretch = (period.start * 1000.0) as u64; + if matches!(r.segments, Segments::Whole) { + if self.periods.len() > 1 || live { + return Err(odd("several files")); + } + media.whole = Some(r.base.clone()); + return Ok(media); + } + media.segments.extend(r.expand(period, stretch, live.then(|| self.window(period, now)).flatten())?); + } + if media.segments.len() as u64 > MOST { + return Err(odd("too many")); + } + if !live { + // The place in the list is what stays. + for (i, s) in media.segments.iter_mut().enumerate() { + (s.seq, s.next) = (i as u64, i as u64 + 1); + } + } + Ok(media) + } + + /// What of a growing period is there: from and to, in seconds since its start. + fn window(&self, period: &Period, now: f64) -> Option<(f64, f64)> { + let to = now - self.begins? - period.start; + let to = period.length.map_or(to, |n| to.min(n)); + Some((self.depth.map_or(0.0, |d| (to - d).max(0.0)), to)) + } +} + +impl Period { + /// The same one, or what comes next to it. + fn closest(&self, variant: &Variant, sound: bool) -> Option<&Rendition> { + let same = self.sets.iter().find(|r| r.variant.id == variant.id && r.sound == sound); + let mut fit: Vec<&Rendition> = self.sets.iter().filter(|r| r.sound == sound).collect(); + fit.sort_by_key(|r| (r.variant.language != variant.language, r.variant.bandwidth.abs_diff(variant.bandwidth))); + same.or(fit.first().copied()) + } +} + +impl Rendition { + fn expand(&self, period: &Period, stretch: u64, window: Option<(f64, f64)>) -> Result> { + let segment = |seq, next, seconds, piece, init: &Option| Segment { stretch, seq, next, seconds, piece, key: None, init: init.clone(), init_key: None }; + match &self.segments { + Segments::Whole => Ok(vec![]), + Segments::List { init, media, seconds } => { + let numbered = media.iter().enumerate().map(|(i, p)| (i as u64, p)); + Ok(numbered.map(|(i, p)| segment(i, i + 1, *seconds, p.clone(), init)).collect()) + } + Segments::Template { init, media, number, end_number, scale, each, times, offset } => { + let at = |number, time| -> Result { + let url = web(&self.base, &fill(media, &self.variant, number, time)?).ok_or_else(|| odd("link"))?; + Ok(Piece { url, range: None }) + }; + let init = match init { + Some(link) => Some(Piece { url: web(&self.base, link).ok_or_else(|| odd("link"))?, range: None }), + None => None, + }; + let Some(each) = each else { + let numbered = times.iter().zip(*number..); + return numbered.map(|(&(t, d), n)| Ok(segment(t, t + d, d as f64 / scale, at(n, t)?, &init))).collect(); + }; + let long = *each as f64 / scale; + let (from, to) = match window { + // Only those that are whole. + Some((from, to)) => ((from / long).ceil().max(0.0) as u64, (to / long).floor().max(0.0) as u64), + None => (0, (period.length.ok_or_else(|| odd("period"))? / long - 1e-6).ceil().max(0.0) as u64), + }; + let to = end_number.map_or(to, |e| to.min((e + 1).saturating_sub(*number))); + if to.saturating_sub(from) > MOST { + return Err(odd("too many")); + } + (from..to).map(|i| Ok(segment(i, i + 1, long, at(number + i, offset + i * each)?, &init))).collect() + } + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::http::Error; + use crate::model::ErrorKind; + + fn base() -> Url { + Url::parse("https://h/a/m.mpd").unwrap() + } + + fn manifest(text: &str) -> Manifest { + parse(text, &base()).unwrap() + } + + fn paths(m: &Media) -> Vec<&str> { + m.segments.iter().map(|s| s.piece.url.path()).collect() + } + + const NUMBERED: &str = r#" + + + sound/ + + "#; + + #[test] + fn templates() { + let m = manifest(NUMBERED); + assert_eq!(m.found.duration, Some(9.5)); + let picked = m.found.pick(&Choice::default()).unwrap(); + assert_eq!(picked.iter().map(|v| v.id.as_str()).collect::>(), ["high", "s"]); + let video = m.media(&picked[0], 0.0).unwrap(); + assert!(video.ended); + assert_eq!(paths(&video), ["/a/high/001.m4s", "/a/high/002.m4s", "/a/high/003.m4s"]); + assert_eq!(video.segments[0].init.as_ref().unwrap().url.path(), "/a/high/i.mp4"); + let sound = m.media(&picked[1], 0.0).unwrap(); + assert_eq!(paths(&sound), ["/a/sound/5$.m4s", "/a/sound/45$.m4s", "/a/sound/85$.m4s"]); + assert_eq!(sound.segments[2].seconds, 1.5); + let small = Choice { max_height: Some(480), audio: Pick::None, ..Choice::default() }; + assert_eq!(m.found.pick(&small).unwrap()[0].id, "low"); + } + + #[test] + fn lists_and_single_files() { + let m = manifest( + r#"v.mp4 + + a.mp4"#, + ); + let v = m.media(&m.found.videos[0], 0.0).unwrap(); + assert_eq!(v.segments[0].piece.range, Some((10, 20))); + assert_eq!(paths(&v), ["/a/v.mp4", "/a/x.mp4"]); + assert_eq!(v.segments[0].init.as_ref().unwrap().range, Some((0, 10))); + assert_eq!(m.media(&m.found.audios[0], 0.0).unwrap().whole.unwrap().path(), "/a/a.mp4"); + } + + #[test] + fn periods_follow_each_other() { + let set = |id: &str| format!(r#""#); + let m = manifest(&format!( + r#"{}{}"#, + set("a"), + set("b") + )); + let v = m.media(&m.found.videos[0], 0.0).unwrap(); + assert_eq!(paths(&v), ["/a/a1", "/a/a2", "/a/b1", "/a/b2", "/a/b3"]); + assert_eq!(v.segments.iter().map(|s| (s.stretch, s.seq)).collect::>(), [(0, 0), (0, 1), (4000, 2), (4000, 3), (4000, 4)]); + } + + #[test] + fn growing_ones() { + let m = manifest( + r#" + "#, + ); + assert!(m.found.live); + let v = m.media(&m.found.videos[0], 121.0).unwrap(); + assert!(!v.ended); + assert_eq!(paths(&v), ["/a/8", "/a/9"], "those of the last 6 seconds that are whole"); + } + + #[test] + fn protected_ones_are_refused() { + for uuid in ["edef8ba9-79d6-4ace-a3c8-27dcd51d21ed", "9a04f079-9840-4286-ab92-e65be0885f95", "94ce86fb-07ff-4f43-adb8-93d2fa968ca2"] { + let text = NUMBERED.replace("", &format!(r#""#)); + assert!(matches!(parse(&text, &base()), Err(Error::Conn { kind: ErrorKind::Drm, .. }))); + } + } + + #[test] + fn nonsense_is_no_manifest() { + let with = |inner: &str| format!(r#"{inner}"#); + let media = |text: &str| parse(text, &base()).and_then(|m| m.media(&m.found.videos[0].clone(), 0.0)); + for text in [ + "", + "", + "", + r#"]>&a;"#, + &with(r#""#), + &with(r#""#), + &with(r#""#), + &with(r#""#), + &with(r#""#), + &with(r#""#), + &with(r#"file:///etc/"#), + ] { + assert!(matches!(media(text), Err(Error::BadReply(_))), "{text}"); + } + } + + #[test] + fn times() { + assert_eq!(seconds("P1DT2H3M4.5S"), Some(86400.0 + 7200.0 + 180.0 + 4.5)); + assert_eq!(seconds("PT0S"), Some(0.0)); + assert_eq!(seconds("5"), None); + assert_eq!(date("1970-01-01T00:00:01"), Some(1.0)); + assert_eq!(date("1970-01-01T01:00:01.5+01:00"), Some(1.5)); + } +} diff --git a/crates/core/src/stream/fetch.rs b/crates/core/src/stream/fetch.rs new file mode 100644 index 0000000..1bc9802 --- /dev/null +++ b/crates/core/src/stream/fetch.rs @@ -0,0 +1,388 @@ +//! Lists and pieces from the server, and which pieces are still wanted. + +use super::list::*; +use super::tape::{Record, Tape}; +use super::{PARALLEL, dash, drm, hls, odd}; +use crate::host::{self, Hosts, Member, Permit}; +use crate::http::{self, Client, Error, Monitor, Options, Result, Shared, Source, Stop, stopped}; +use crate::limit::{Flow, Group}; +use crate::model::HostProfile; +use crate::store::Store; +use aes::cipher::block_padding::Pkcs7; +use aes::cipher::{BlockModeDecrypt, KeyIvInit}; +use std::collections::{HashMap, HashSet, VecDeque}; +use std::sync::atomic::{AtomicU32, AtomicU64, Ordering}; +use std::sync::{Arc, Mutex}; +use std::time::{Duration, Instant}; +use url::Url; + +const MOST_LIST: u64 = 32 << 20; +/// Held in memory. +const MOST_PIECE: u64 = 256 << 20; +/// What a growing list is joined at, from its end. +const FROM_END: usize = 3; + +pub(super) fn now() -> f64 { + crate::model::now() as f64 / 1000.0 +} + +/// Worth another try. +pub(super) fn passing(e: &Error) -> bool { + match e { + Error::Net(_) | Error::Idle | Error::Cut { .. } => true, + Error::Status { code, .. } => matches!(code, 408 | 425 | 429 | 500..=599), + _ => false, + } +} + +pub(super) struct Opened { + pub found: Found, + pub manifest: Option, + /// The link itself was the list of one variant. + pub media: Option, +} + +/// One download's way to its servers. +pub(super) struct Net { + client: Client, + pub source: Source, + options: Options, + flow: Arc, + received: Arc, + places: Option, + width: AtomicU32, + /// Held while one is asked for: the others wait for it. + keys: tokio::sync::Mutex>, +} + +/// Connections are shared with the other downloads. +struct Places { + hosts: Arc, + store: Arc, + members: Mutex>>, + /// Connections between two pieces. + idle: Mutex>, +} + +impl Net { + pub fn new(shared: &Shared, source: &Source, options: &Options, monitor: &Monitor, received: Arc) -> Net { + let places = Places { hosts: shared.hosts.clone(), store: shared.store.clone(), members: Mutex::default(), idle: Mutex::default() }; + Net { + client: shared.client.clone(), + source: source.clone(), + options: options.clone(), + flow: monitor.flow().clone(), + received, + places: Some(places), + width: AtomicU32::new(PARALLEL), + keys: tokio::sync::Mutex::default(), + } + } + + /// For a look at what there is. + pub fn plain(client: &Client, source: &Source) -> Net { + Net { + client: client.clone(), + source: source.clone(), + options: Options { tries: 1, ..Options::default() }, + flow: Arc::new(Flow::free()), + received: Arc::default(), + places: None, + width: AtomicU32::new(1), + keys: tokio::sync::Mutex::default(), + } + } + + /// As many pieces at once as the server stands. + pub fn width(&self) -> u32 { + self.width.load(Ordering::Relaxed) + } + + async fn text(&self, url: &Url, stop: &mut Stop) -> Result<(Url, String)> { + let at = if *url == self.source.url { self.source.clone() } else { self.source.at(url) }; + let got = http::piece(&self.client, &at, None, MOST_LIST, &self.flow, &AtomicU64::new(0), stop).await?; + if got.mime.as_deref() == Some("text/html") { + return Err(Error::Page); + } + Ok((got.url, String::from_utf8_lossy(&got.body).into_owned())) + } + + pub async fn open(&self, stop: &mut Stop) -> Result { + let (base, text) = self.text(&self.source.url, stop).await?; + if text.trim_start_matches('\u{feff}').trim_start().starts_with('<') { + let manifest = dash::parse(&text, &base)?; + return Ok(Opened { found: manifest.found.clone(), manifest: Some(manifest), media: None }); + } + Ok(match hls::parse(&text, &base)? { + hls::List::Master(found) => Opened { found, manifest: None, media: None }, + hls::List::Media(media) => { + let only = Variant { url: Some(self.source.url.clone()), ..Variant::new(String::new()) }; + let found = Found { kind: Kind::Hls, live: !media.ended, duration: None, videos: vec![only], audios: vec![] }; + Opened { found, manifest: None, media: Some(media) } + } + }) + } + + /// The lists of the variants, as they are now. `root` is the kind of the first link, unless it is a list of lists. + pub async fn refresh(&self, root: &Option, variants: &[Variant], stop: &mut Stop) -> Result> { + if *root == Some(Kind::Dash) { + let (base, text) = self.text(&self.source.url, stop).await?; + let manifest = dash::parse(&text, &base)?; + return variants.iter().map(|v| manifest.media(v, now())).collect(); + } + let mut media = vec![]; + for v in variants { + let (base, text) = self.text(v.url.as_ref().ok_or_else(|| odd("link"))?, stop).await?; + match hls::parse(&text, &base)? { + hls::List::Media(m) => media.push(m), + hls::List::Master(_) => return Err(odd("a list of lists in a list")), + } + } + Ok(media) + } + + /// A single file is taken in pieces too. + pub async fn split(&self, media: &mut Media, stop: &mut Stop) -> Result<()> { + let Some(url) = media.whole.take() else { return Ok(()) }; + let probe = http::probe(&self.client, &self.source.at(&url), stop).await?; + let size = probe.version.size.filter(|n| probe.ranges && *n > 0); + let ranges: Vec> = match size { + Some(size) => (0..size.div_ceil(dash::CHUNK)).map(|i| Some((i * dash::CHUNK, ((i + 1) * dash::CHUNK).min(size)))).collect(), + None => vec![None], + }; + let each = |(i, range): (usize, Option<(u64, u64)>)| Segment { + stretch: 0, + seq: i as u64, + next: i as u64 + 1, + // Not known, but the same for all. + seconds: range.map_or(1.0, |(a, b)| (b - a) as f64 / dash::CHUNK as f64), + piece: Piece { url: url.clone(), range }, + key: None, + init: None, + init_key: None, + }; + media.segments = ranges.into_iter().enumerate().map(each).collect(); + media.ended = true; + Ok(()) + } + + /// Tries again where that may help. + pub async fn piece(&self, want: &Want, stop: &mut Stop) -> Result> { + let mut data = self.get(&want.piece, MOST_PIECE, stop).await?; + if let Some(key) = &want.key { + let bytes = self.key(&key.url, stop).await?; + let plain = cbc::Decryptor::::new(&bytes.into(), &key.iv.into()).decrypt_padded::(&mut data); + let n = plain.map_err(|_| odd("the key does not fit"))?.len(); + data.truncate(n); + } + if want.record.init && [b"pssh", b"encv", b"enca"].iter().any(|name| data.windows(4).any(|w| w == *name)) { + return Err(drm()); + } + Ok(data) + } + + async fn key(&self, url: &Url, stop: &mut Stop) -> Result<[u8; 16]> { + let mut keys = self.keys.lock().await; + if let Some(key) = keys.get(url) { + return Ok(*key); + } + let got = self.get(&Piece { url: url.clone(), range: None }, 1 << 10, stop).await?; + let key: [u8; 16] = got.try_into().map_err(|_| odd("no key"))?; + keys.insert(url.clone(), key); + Ok(key) + } + + async fn get(&self, piece: &Piece, most: u64, stop: &mut Stop) -> Result> { + let mut fails = 0; + loop { + let permit = self.permit(&piece.url, stop).await?; + let got = http::piece(&self.client, &self.source.at(&piece.url), piece.range, most, &self.flow, &self.received, stop).await; + let e = match got { + Ok(got) => { + self.back(&piece.url, permit); + return Ok(got.body); + } + Err(e) => e, + }; + drop(permit); + fails += 1; + if !passing(&e) || fails >= self.options.tries { + return Err(e); + } + let mut wait = self.options.backoff.saturating_mul(1 << (fails - 1).min(10)).min(self.options.max_wait); + if let Error::Status { code, retry_after } = &e { + if matches!(code, 429 | 503) { + let _ = self.width.try_update(Ordering::Relaxed, Ordering::Relaxed, |n| (n > 1).then_some(n - 1)); + } + match retry_after { + Some(asked) if *asked > self.options.max_wait => return Err(e), + Some(asked) => wait = wait.max(*asked), + None => {} + } + } + tokio::select! { + _ = stopped(stop) => return Err(Error::Stopped), + _ = tokio::time::sleep(wait) => {} + } + } + } + + /// A place for a connection to the host of `url`. + async fn permit(&self, url: &Url, stop: &mut Stop) -> Result> { + let Some(places) = &self.places else { return Ok(None) }; + let host = host::key(url); + { + let mut idle = places.idle.lock().unwrap(); + idle.retain(|(_, permit)| !permit.revoked()); + if let Some(i) = idle.iter().position(|(h, _)| *h == host) { + return Ok(Some(idle.swap_remove(i).1)); + } + // It goes to others meanwhile. + idle.clear(); + } + let member = places.members.lock().unwrap().get(&host).cloned(); + let member = match member { + Some(member) => member, + None => { + let (store, asked) = (places.store.clone(), host.clone()); + let known: HostProfile = super::run(&store, move |s| Ok(s.host(&asked)?)).await?.unwrap_or_default(); + let at = self.source.at(url); + places.hosts.set_host_cap(&host, at.max_connections().or(known.max_connections)); + self.flow.put_limited(Group::Host(host.clone()), at.speed_limit().or(known.speed_limit)); + places.members.lock().unwrap().entry(host.clone()).or_insert_with(|| Arc::new(places.hosts.join(&host))).clone() + } + }; + loop { + if let Some(permit) = member.open(self.width(), self.flow.weight(), Instant::now()) { + return Ok(Some(permit)); + } + tokio::select! { + _ = stopped(stop) => return Err(Error::Stopped), + _ = tokio::time::sleep(Duration::from_millis(50)) => {} + } + } + } + + /// The connection can bring the next one. + fn back(&self, url: &Url, permit: Option) { + if let (Some(places), Some(permit)) = (&self.places, permit) + && !permit.revoked() + { + places.idle.lock().unwrap().push((host::key(url), permit)); + } + } + + /// Nothing is wanted for a while. + pub fn rest(&self) { + if let Some(places) = &self.places { + places.idle.lock().unwrap().clear(); + for member in places.members.lock().unwrap().values() { + member.wants(0, self.flow.weight()); + } + } + } +} + +/// A piece to download, and where it belongs. +pub(super) struct Want { + pub record: Record, + pub piece: Piece, + pub key: Option, + /// Seconds from the start, in milliseconds: tracks go on side by side. + pub place: u64, +} + +/// What of one track is wanted. +pub(super) struct Feed { + track: u32, + group: u32, + /// The last one: its stretch and number, and the number that should follow. + last: Option<(u64, u64, u64)>, + /// What the group starts with. None: not known any more. + init: Option>, + have: HashSet<(bool, u32, u64)>, + /// How often the numbers of a growing list began anew. + epoch: u64, + taken: u64, + most: Option, +} + +const EPOCH: u32 = 48; + +impl Feed { + pub fn new(track: u32, tape: &Tape, seconds: Option) -> Feed { + let mine = || tape.records.iter().filter(|r| r.track == track); + let last = mine().filter(|r| !r.init).max_by_key(|r| (r.stretch, r.seq)); + Feed { + track, + group: mine().map(|r| r.group).max().unwrap_or(0), + last: last.map(|r| (r.stretch, r.seq, r.seq + 1)), + init: None, + have: mine().map(|r| (r.init, r.group, r.seq)).collect(), + epoch: last.map_or(0, |r| r.stretch >> EPOCH), + taken: tape.length(track), + most: seconds.filter(|_| tape.head.live).map(|s| s * 1000), + } + } + + pub fn full(&self) -> bool { + self.most.is_some_and(|most| self.taken >= most) + } + + pub fn take(&mut self, media: &Media, live: bool, queue: &mut VecDeque) { + if !live { + return self.all(media, queue); + } + let first = self.last.is_none(); + if let (Some((stretch, seq, _)), Some(end)) = (self.last, media.segments.last()) + && (end.stretch + (self.epoch << EPOCH), end.seq + media.segments.len() as u64) < (stretch, seq) + { + self.epoch += 1; + } + let skip = if first && !media.from_start && !media.ended { media.segments.len().saturating_sub(FROM_END) } else { 0 }; + for s in &media.segments[skip..] { + if self.full() { + return; + } + let stretch = s.stretch + (self.epoch << EPOCH); + if self.last.is_some_and(|(st, seq, _)| (stretch, s.seq) <= (st, seq)) { + continue; + } + let follows = self.last.is_none_or(|(st, _, next)| st == stretch && next == s.seq) && self.init.as_ref().is_none_or(|i| *i == s.init); + if !follows { + self.group += 1; + } + let fresh = !follows || first && !self.have.contains(&(true, self.group, 0)); + self.want(s, stretch, fresh, queue); + self.last = Some((stretch, s.seq, s.next)); + self.init = Some(s.init.clone()); + self.taken += (s.seconds * 1000.0) as u64; + } + } + + /// The same groups each time. + fn all(&mut self, media: &Media, queue: &mut VecDeque) { + let mut before: Option<&Segment> = None; + let (mut group, mut place) = (0, 0); + for s in &media.segments { + let fresh = before.is_none_or(|b| b.stretch != s.stretch || b.init != s.init); + group += u32::from(fresh && before.is_some()); + self.group = group; + let at = queue.len(); + self.want(s, s.stretch, fresh && !self.have.contains(&(true, group, 0)), queue); + queue.range_mut(at..).for_each(|w| w.place = place); + place += (s.seconds * 1000.0) as u64; + before = Some(s); + } + } + + fn want(&mut self, s: &Segment, stretch: u64, fresh: bool, queue: &mut VecDeque) { + let record = Record { track: self.track, group: self.group, init: false, stretch, seq: s.seq, ms: (s.seconds * 1000.0) as u32, at: 0, len: 0 }; + if fresh && let Some(init) = &s.init { + queue.push_back(Want { record: Record { init: true, seq: 0, ms: 0, ..record }, piece: init.clone(), key: s.init_key.clone(), place: 0 }); + } + if self.have.insert((false, self.group, s.seq)) { + queue.push_back(Want { record, piece: s.piece.clone(), key: s.key.clone(), place: 0 }); + } + } +} diff --git a/crates/core/src/stream/ffmpeg.rs b/crates/core/src/stream/ffmpeg.rs new file mode 100644 index 0000000..23a6068 --- /dev/null +++ b/crates/core/src/stream/ffmpeg.rs @@ -0,0 +1,306 @@ +//! The ffmpeg that is on this computer: finding it, running it, stopping it. +//! +//! It gets lists of arguments, never a shell. What must not be seen among the arguments goes through its standard input. + +use crate::http::{Error, Result}; +use crate::model::ErrorKind; +use crate::redact; +use std::collections::VecDeque; +use std::ffi::{OsStr, OsString}; +use std::fmt; +use std::io; +use std::path::{Path, PathBuf}; +use std::process::Stdio; +use std::sync::{Arc, Mutex}; +use std::time::Duration; +use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader}; +use tokio::process::{Child, ChildStdout, Command}; +use tokio::sync::watch; +use tokio::task::JoinHandle; + +/// Lines of its log that are kept. +const TAIL: usize = 40; +/// Longer ones are cut. +const LINE: u64 = 4096; + +/// Programs that other people make. +#[derive(Debug, Clone, Default)] +pub struct Tools { + pub ffmpeg: Option, +} + +impl Tools { + /// Next to Medlar first, then where programs are. + pub fn find() -> Tools { + let beside = std::env::current_exe().ok().and_then(|exe| Some(exe.parent()?.to_path_buf())); + let path = std::env::var_os("PATH").unwrap_or_default(); + Tools { ffmpeg: find("ffmpeg", beside.as_deref(), &path) } + } + + pub fn ffmpeg(&self) -> Result<&Path> { + self.ffmpeg.as_deref().ok_or(Error::because(ErrorKind::Tool, "error.tool.ffmpeg")) + } +} + +fn find(name: &str, beside: Option<&Path>, path: &OsStr) -> Option { + let runs = |p: &PathBuf| p.is_absolute() && p.is_file() && rustix::fs::access(p, rustix::fs::Access::EXEC_OK).is_ok(); + beside.map(Path::to_path_buf).into_iter().chain(std::env::split_paths(path)).map(|dir| dir.join(name)).find(runs) +} + +#[derive(Debug, Clone, Copy, Default, PartialEq)] +pub struct Progress { + /// Where in the recording or film it is. + pub time: Duration, + /// Bytes written. + pub bytes: u64, +} + +/// What to run. Use `input` for links: it says which protocols may follow. +#[derive(Default)] +pub struct Job { + args: Vec, + stdin: Option>, + output: bool, +} + +/// Without what goes to its standard input. +impl fmt::Debug for Job { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "{:?}", self.args) + } +} + +impl Job { + pub fn new() -> Job { + let mut job = Job::default(); + job.args(["-hide_banner", "-nostdin", "-nostats", "-loglevel", "warning", "-progress", "pipe:2", "-y"]); + job + } + + pub fn arg(&mut self, arg: impl AsRef) -> &mut Job { + self.args.push(arg.as_ref().into()); + self + } + + pub fn args>(&mut self, args: impl IntoIterator) -> &mut Job { + self.args.extend(args.into_iter().map(|a| a.as_ref().into())); + self + } + + /// With the protocols it may use, also through what it finds in there. + pub fn input(&mut self, protocols: &str, input: impl AsRef) -> &mut Job { + self.args(["-protocol_whitelist", protocols, "-i"]).arg(input) + } + + /// What it reads as `pipe:0`. + pub fn stdin(&mut self, bytes: impl Into>) -> &mut Job { + self.stdin = Some(bytes.into()); + self + } + + /// The file it makes. `muxer` is ffmpeg's name of the format. + pub fn file(&mut self, muxer: &str, path: &Path) -> &mut Job { + let mut url = OsString::from("file:"); + url.push(path); + self.args(["-f", muxer]).arg(url) + } + + /// What it makes is read from `Running::output`. + pub fn pipe(&mut self, muxer: &str) -> &mut Job { + self.output = true; + self.args(["-f", muxer, "pipe:1"]) + } + + #[cfg(test)] + pub(super) fn script(&self) -> Option<&[u8]> { + self.stdin.as_deref() + } + + pub fn start(self, ffmpeg: &Path) -> Result { + let mut command = Command::new(ffmpeg); + command.args(&self.args).env("AV_LOG_FORCE_NOCOLOR", "1").process_group(0).kill_on_drop(true); + // The user's proxy is never passed on by accident. + for name in ["http_proxy", "https_proxy", "HTTPS_PROXY", "all_proxy", "ALL_PROXY"] { + command.env_remove(name); + } + command.stdin(if self.stdin.is_some() { Stdio::piped() } else { Stdio::null() }); + command.stdout(if self.output { Stdio::piped() } else { Stdio::null() }).stderr(Stdio::piped()); + let mut child = command.spawn().map_err(|e| { + log::warn!("{} does not start: {e}", ffmpeg.display()); + Error::because(ErrorKind::Tool, "error.tool.ffmpeg") + })?; + if let (Some(mut stdin), Some(bytes)) = (child.stdin.take(), self.stdin) { + // It may end without reading all of it. + tokio::spawn(async move { drop(stdin.write_all(&bytes).await) }); + } + let (progress, seen) = watch::channel(Progress::default()); + let tail = Arc::new(Mutex::new(VecDeque::new())); + let stderr = child.stderr.take().expect("it is piped"); + let reader = tokio::spawn(listen(stderr, progress, tail.clone())); + Ok(Running { output: child.stdout.take(), child, seen, tail, reader }) + } +} + +/// Reads to the end, so that it never waits for us. +async fn listen(stderr: impl tokio::io::AsyncRead + Unpin, progress: watch::Sender, tail: Arc>>) { + let mut lines = BufReader::new(stderr); + let mut line = vec![]; + let mut now = Progress::default(); + loop { + line.clear(); + let mut short = tokio::io::AsyncReadExt::take(&mut lines, LINE); + match short.read_until(b'\n', &mut line).await { + Ok(0) | Err(_) => return, + Ok(_) => {} + } + let text = String::from_utf8_lossy(&line); + let text = text.trim(); + if text.is_empty() { + continue; + } + if now.read(text) { + if text.starts_with("progress=") { + progress.send_replace(now); + } + continue; + } + let mut tail = tail.lock().unwrap(); + if tail.len() == TAIL { + tail.pop_front(); + } + tail.push_back(redact::text(text)); + } +} + +impl Progress { + /// Whether the line is one of its reports. + fn read(&mut self, line: &str) -> bool { + let Some((key, value)) = line.split_once('=') else { return false }; + let value = value.trim(); + match key { + "out_time_us" => self.time = value.parse().map_or(self.time, Duration::from_micros), + "total_size" => self.bytes = value.parse().unwrap_or(self.bytes), + "frame" | "fps" | "bitrate" | "out_time_ms" | "out_time" | "dup_frames" | "drop_frames" | "speed" | "progress" => {} + _ => return key.starts_with("stream_") && key.ends_with("_q"), + } + true + } +} + +/// Killed when it is dropped. +#[derive(Debug)] +pub struct Running { + pub output: Option, + child: Child, + seen: watch::Receiver, + tail: Arc>>, + reader: JoinHandle<()>, +} + +/// How it failed. +#[derive(Debug)] +pub struct Failed { + /// The end of its log, without secrets. + pub tail: Vec, +} + +impl Running { + pub fn progress(&self) -> watch::Receiver { + self.seen.clone() + } + + /// Asks it to end what it makes properly. `end` tells when it did. + pub fn finish(&self) { + let pid = self.child.id().and_then(|id| rustix::process::Pid::from_raw(id.cast_signed())); + if let Some(pid) = pid { + let _ = rustix::process::kill_process(pid, rustix::process::Signal::INT); + } + } + + pub async fn kill(mut self) { + let _ = self.child.kill().await; + } + + /// Waits for its end. Read all of `output` before. + pub async fn end(&mut self) -> io::Result> { + drop(self.output.take()); + let status = self.child.wait().await?; + let _ = tokio::time::timeout(Duration::from_secs(1), &mut self.reader).await; + if status.success() { + return Ok(Ok(())); + } + let tail: Vec = self.tail.lock().unwrap().iter().cloned().collect(); + log::debug!("ffmpeg failed ({status}): {}", tail.join(" / ")); + Ok(Err(Failed { tail })) + } +} + +impl Failed { + pub fn says(&self, what: &str) -> bool { + self.tail.iter().any(|line| line.contains(what)) + } + + /// What its messages mean. They themselves are for the log only. + pub fn error(&self) -> Error { + use ErrorKind::*; + let known = [ + ("No space left", DiskFull), + ("401 Unauthorized", Login), + ("403 Forbidden", Forbidden), + ("404 Not Found", NotFound), + ("Connection refused", Refused), + ("timed out", Timeout), + ("Failed to resolve", Dns), + ("No route to host", Unreachable), + ("Network is unreachable", Unreachable), + ]; + let Some((_, kind)) = known.iter().find(|(text, _)| self.says(text)) else { return Error::conn(Media) }; + match kind { + DiskFull => Error::Disk(io::Error::from(io::ErrorKind::StorageFull).into()), + Login => Error::conn(Login), + Forbidden => Error::because(Forbidden, "error.forbidden.plain"), + NotFound => Error::because(NotFound, "error.not_found.plain"), + kind => Error::conn(*kind), + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn programs_are_found() { + let dir = tempfile::tempdir().unwrap(); + let here = dir.path().join("tool"); + assert_eq!(find("tool", None, dir.path().as_os_str()), None); + std::fs::write(&here, "").unwrap(); + assert_eq!(find("tool", None, dir.path().as_os_str()), None, "it can't be run"); + rustix::fs::chmod(&here, rustix::fs::Mode::RWXU).unwrap(); + assert_eq!(find("tool", None, dir.path().as_os_str()).as_ref(), Some(&here)); + assert_eq!(find("tool", Some(dir.path()), OsStr::new("")).as_ref(), Some(&here)); + // Never from the current folder. + assert_eq!(find("tool", None, OsStr::new(".:")), None); + assert!(matches!(Tools::default().ffmpeg(), Err(Error::Conn { kind: ErrorKind::Tool, .. }))); + } + + #[test] + fn reports_are_told_from_messages() { + let mut p = Progress::default(); + for line in ["frame=10", "out_time_us=2500000", "out_time=00:00:02.500000", "total_size=77", "speed=1x", "stream_0_0_q=-1.0", "out_time_us=N/A"] { + assert!(p.read(line), "{line}"); + } + assert_eq!(p, Progress { time: Duration::from_millis(2500), bytes: 77 }); + assert!(!p.read("Error opening a=b")); + assert!(!p.read("Invalid data found")); + } + + #[test] + fn its_messages_are_understood() { + let of = |text: &str| Failed { tail: vec!["x".into(), text.into()] }.error(); + assert!(matches!(of("Server returned 401 Unauthorized (authorization failed)"), Error::Conn { kind: ErrorKind::Login, .. })); + assert!(matches!(of("rtsp://h: Connection refused"), Error::Conn { kind: ErrorKind::Refused, .. })); + assert!(matches!(of("av_interleaved_write_frame(): No space left on device"), Error::Disk(_))); + assert!(matches!(of("something else"), Error::Conn { kind: ErrorKind::Media, .. })); + } +} diff --git a/crates/core/src/stream/hls.rs b/crates/core/src/stream/hls.rs new file mode 100644 index 0000000..9e6ebf3 --- /dev/null +++ b/crates/core/src/stream/hls.rs @@ -0,0 +1,304 @@ +//! HLS lists (RFC 8216). + +use super::list::*; +use super::{drm, odd}; +use crate::http::Result; +use std::collections::HashMap; +use url::Url; + +pub(super) enum List { + Master(Found), + Media(Media), +} + +pub(super) fn parse(text: &str, base: &Url) -> Result { + let text = text.trim_start_matches('\u{feff}'); + if !text.trim_start().starts_with("#EXTM3U") { + return Err(odd("no list of streams")); + } + if text.lines().any(|l| l.starts_with("#EXT-X-STREAM-INF:")) { master(text, base).map(List::Master) } else { media(text, base).map(List::Media) } +} + +fn tag<'a>(line: &'a str, name: &str) -> Option<&'a str> { + line.strip_prefix(name)?.strip_prefix(':').map(str::trim) +} + +/// `A=1,B="x,y"` +fn attributes(text: &str) -> HashMap<&str, &str> { + let mut found = HashMap::new(); + let mut rest = text; + while let Some((name, after)) = rest.split_once('=') { + let (value, after) = match after.strip_prefix('"').and_then(|a| a.split_once('"')) { + Some((value, after)) => (value, after.split_once(',').map_or("", |(_, a)| a)), + None => after.split_once(',').unwrap_or((after, "")), + }; + found.insert(name.trim(), value.trim()); + rest = after; + } + found +} + +/// Keys that the list itself offers are fine, anything else is copy protection. +fn check_key(a: &HashMap<&str, &str>) -> Result { + let format = a.get("KEYFORMAT").copied().unwrap_or("identity"); + match a.get("METHOD").copied() { + Some("NONE") => Ok(false), + Some("AES-128") if format == "identity" => Ok(true), + _ => Err(drm()), + } +} + +fn check_protection(line: &str) -> Result<()> { + if let Some(a) = tag(line, "#EXT-X-SESSION-KEY") { + check_key(&attributes(a))?; + } + // Adobe's. + if line.starts_with("#EXT-X-FAXS-CM") { Err(drm()) } else { Ok(()) } +} + +fn master(text: &str, base: &Url) -> Result { + let mut found = Found { kind: Kind::Hls, live: false, duration: None, videos: vec![], audios: vec![] }; + let mut info: Option> = None; + for line in text.lines().map(str::trim) { + check_protection(line)?; + if let Some(a) = tag(line, "#EXT-X-STREAM-INF") { + info = Some(attributes(a)); + } else if let Some(a) = tag(line, "#EXT-X-MEDIA") { + let a = attributes(a); + let text = |name| a.get(name).map(|v: &&str| v.to_string()); + // Without a link it is in the video. + let Some(url) = a.get("URI").filter(|_| a.get("TYPE") == Some(&"AUDIO")) else { continue }; + let Some(url) = web(base, url) else { continue }; + let (group, name) = (text("GROUP-ID").unwrap_or_default(), text("NAME").unwrap_or_default()); + let id = format!("{group}/{name}/{}", text("LANGUAGE").unwrap_or_default()); + found.audios.push(Variant { + language: text("LANGUAGE"), + name: Some(name), + sound: Some(group), + preferred: a.get("DEFAULT") == Some(&"YES"), + url: Some(url), + ..Variant::new(id) + }); + } else if !line.is_empty() && !line.starts_with('#') + && let Some(a) = info.take() + { + let Some(url) = web(base, line) else { continue }; + let bandwidth = a.get("BANDWIDTH").and_then(|b| b.parse().ok()).unwrap_or(0); + let size = a.get("RESOLUTION").and_then(|r| r.split_once('x')).and_then(|(w, h)| Some((w.parse().ok()?, h.parse().ok()?))); + let (w, h) = size.unwrap_or_default(); + found.videos.push(Variant { + bandwidth, + size, + codecs: a.get("CODECS").map(|c| c.to_string()).unwrap_or_default(), + sound: a.get("AUDIO").map(|g| g.to_string()), + url: Some(url), + ..Variant::new(format!("{w}x{h}@{bandwidth}")) + }); + } + } + // A video whose sound has no link of its own has it inside. + for v in &mut found.videos { + v.sound = v.sound.take().filter(|g| found.audios.iter().any(|a| a.sound.as_ref() == Some(g))); + } + sort(&mut found.videos); + // The same again on another server. + found.videos.dedup_by(|b, a| a.id == b.id && a.sound == b.sound && a.codecs == b.codecs); + if found.videos.is_empty() { Err(odd("no variants")) } else { Ok(found) } +} + +fn media(text: &str, base: &Url) -> Result { + let mut media = Media { pace: 6.0, ..Media::default() }; + let (mut seq, mut breaks) = (0u64, 0u64); + let (mut key, mut init, mut seconds, mut range, mut gap) = (None::<(Url, Option<[u8; 16]>)>, None, 0.0, None, false); + let mut init_key = None; + // Where the last range of each file ended. + let mut ends: HashMap = HashMap::new(); + for line in text.lines().map(str::trim) { + check_protection(line)?; + if let Some(n) = tag(line, "#EXT-X-TARGETDURATION") { + media.pace = n.parse::().ok().filter(|n| n.is_finite()).unwrap_or(media.pace).clamp(0.5, 60.0); + } else if let Some(n) = tag(line, "#EXT-X-MEDIA-SEQUENCE") { + seq = n.parse().map_err(|_| odd("sequence"))?; + } else if let Some(n) = tag(line, "#EXT-X-DISCONTINUITY-SEQUENCE") { + breaks = n.parse().map_err(|_| odd("sequence"))?; + } else if line == "#EXT-X-DISCONTINUITY" { + breaks += 1; + } else if line == "#EXT-X-ENDLIST" { + media.ended = true; + } else if line == "#EXT-X-GAP" { + gap = true; + } else if let Some(kind) = tag(line, "#EXT-X-PLAYLIST-TYPE") { + media.from_start = kind == "EVENT"; + } else if let Some(a) = tag(line, "#EXT-X-KEY") { + let a = attributes(a); + key = if check_key(&a)? { + let url = a.get("URI").and_then(|u| web(base, u)).ok_or_else(|| odd("key"))?; + Some((url, a.get("IV").map(|iv| parse_iv(iv).ok_or_else(|| odd("iv"))).transpose()?)) + } else { + None + }; + } else if let Some(a) = tag(line, "#EXT-X-MAP") { + let a = attributes(a); + let url = a.get("URI").and_then(|u| web(base, u)).ok_or_else(|| odd("map"))?; + let range = match a.get("BYTERANGE") { + Some(text) => Some(byte_range(text, 0).ok_or_else(|| odd("range"))?), + None => None, + }; + init = Some(Piece { url, range }); + // RFC 8216 4.3.2.5: an encrypted one has to say its IV. + init_key = key.clone().map(|(url, iv)| Key { url, iv: iv.unwrap_or_default() }); + } else if let Some(text) = tag(line, "#EXTINF") { + seconds = text.split(',').next().and_then(|s| s.trim().parse().ok()).filter(|s: &f64| s.is_finite() && *s >= 0.0).unwrap_or(0.0); + } else if let Some(text) = tag(line, "#EXT-X-BYTERANGE") { + range = Some(text.to_string()); + } else if !line.is_empty() && !line.starts_with('#') { + let url = web(base, line).ok_or_else(|| odd("link"))?; + let range = match range.take() { + Some(text) => Some(byte_range(&text, ends.get(&url).copied().unwrap_or(0)).ok_or_else(|| odd("range"))?), + None => None, + }; + if let Some((_, end)) = range { + ends.insert(url.clone(), end); + } + let key = key.clone().map(|(url, iv)| Key { url, iv: iv.unwrap_or(u128::from(seq).to_be_bytes()) }); + if !std::mem::take(&mut gap) { + let piece = Piece { url, range }; + media.segments.push(Segment { stretch: breaks, seq, next: seq.wrapping_add(1), seconds, piece, key, init: init.clone(), init_key: init_key.clone() }); + } + seq = seq.checked_add(1).ok_or_else(|| odd("sequence"))?; + } + } + if media.ended { + // Servers count these as they like; the place in the list is what stays. + for (i, s) in media.segments.iter_mut().enumerate() { + (s.seq, s.next) = (i as u64, i as u64 + 1); + } + } + Ok(media) +} + +/// `length[@start]` +fn byte_range(text: &str, after: u64) -> Option<(u64, u64)> { + let (len, start) = match text.split_once('@') { + Some((len, start)) => (len, start.trim().parse().ok()?), + None => (text, after), + }; + let len: u64 = len.trim().parse().ok().filter(|n| *n > 0)?; + Some((start, start.checked_add(len)?)) +} + +fn parse_iv(text: &str) -> Option<[u8; 16]> { + let hex = text.strip_prefix("0x").or(text.strip_prefix("0X"))?; + Some(u128::from_str_radix(hex, 16).ok()?.to_be_bytes()) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::http::Error; + use crate::model::ErrorKind; + + fn base() -> Url { + Url::parse("https://h/a/list.m3u8?t=1").unwrap() + } + + fn list(text: &str) -> Media { + match parse(text, &base()) { + Ok(List::Media(m)) => m, + _ => panic!("no media list: {text}"), + } + } + + fn found(text: &str) -> Found { + match parse(text, &base()) { + Ok(List::Master(f)) => f, + _ => panic!("no master list: {text}"), + } + } + + fn refused(text: &str) -> bool { + matches!(parse(text, &base()), Err(Error::Conn { kind: ErrorKind::Drm, .. })) + } + + #[test] + fn variants_and_sound() { + let f = found( + "#EXTM3U\n#EXT-X-MEDIA:TYPE=AUDIO,GROUP-ID=\"a\",NAME=\"English, plain\",LANGUAGE=\"en\",URI=\"en.m3u8\"\n\ + #EXT-X-MEDIA:TYPE=AUDIO,GROUP-ID=\"a\",NAME=\"Deutsch\",LANGUAGE=\"de\",DEFAULT=YES,URI=\"de.m3u8\"\n\ + #EXT-X-MEDIA:TYPE=AUDIO,GROUP-ID=\"in\",NAME=\"x\"\n\ + #EXT-X-STREAM-INF:BANDWIDTH=100,RESOLUTION=640x360,CODECS=\"avc1,mp4a\",AUDIO=\"a\"\nlow.m3u8\n\ + #EXT-X-STREAM-INF:BANDWIDTH=300,RESOLUTION=1920x1080,AUDIO=\"a\"\nhigh.m3u8\n\ + #EXT-X-STREAM-INF:BANDWIDTH=300,RESOLUTION=1920x1080,AUDIO=\"a\"\nhttps://other/high.m3u8\n\ + #EXT-X-STREAM-INF:BANDWIDTH=200,RESOLUTION=1280x720,AUDIO=\"in\"\nmid.m3u8\n", + ); + let ids: Vec<&str> = f.videos.iter().map(|v| v.id.as_str()).collect(); + assert_eq!(ids, ["1920x1080@300", "1280x720@200", "640x360@100"]); + assert_eq!(f.audios[0].name.as_deref(), Some("English, plain")); + let picked = |choice: Choice| f.pick(&choice).map(|v| v.into_iter().map(|v| v.url.unwrap().path().to_string()).collect::>()); + assert_eq!(picked(Choice::default()).unwrap(), ["/a/high.m3u8", "/a/de.m3u8"]); + assert_eq!(picked(Choice { max_height: Some(720), ..Choice::default() }).unwrap(), ["/a/mid.m3u8"], "its sound is inside"); + assert_eq!(picked(Choice { max_height: Some(100), ..Choice::default() }).unwrap()[0], "/a/low.m3u8"); + let english = Pick::One(f.audios[0].id.clone()); + assert_eq!(picked(Choice { video: Pick::None, audio: english, ..Choice::default() }).unwrap(), ["/a/en.m3u8"]); + assert_eq!(picked(Choice { video: Pick::One("gone".into()), ..Choice::default() }), None); + } + + #[test] + fn segments() { + let m = list( + "#EXTM3U\n#EXT-X-TARGETDURATION:4\n#EXT-X-MEDIA-SEQUENCE:7\n#EXT-X-MAP:URI=\"i.mp4\",BYTERANGE=\"10@5\"\n\ + #EXTINF:3.5,title\n#EXT-X-BYTERANGE:100@20\nall.m4s\n#EXTINF:4,\n#EXT-X-BYTERANGE:50\nall.m4s\n\ + #EXT-X-DISCONTINUITY\n#EXT-X-GAP\n#EXTINF:4,\nnone.m4s\n#EXTINF:1,\n../x.m4s\n", + ); + assert!(!m.ended && !m.from_start); + assert_eq!(m.pace, 4.0); + let seen: Vec<_> = m.segments.iter().map(|s| (s.stretch, s.seq, s.seconds, s.piece.url.path(), s.piece.range)).collect(); + assert_eq!(seen, [(0, 7, 3.5, "/a/all.m4s", Some((20, 120))), (0, 8, 4.0, "/a/all.m4s", Some((120, 170))), (1, 10, 1.0, "/x.m4s", None)]); + assert_eq!(m.segments[0].init.as_ref().unwrap().range, Some((5, 15))); + } + + #[test] + fn keys() { + let m = list( + "#EXTM3U\n#EXT-X-MEDIA-SEQUENCE:5\n#EXT-X-KEY:METHOD=AES-128,URI=\"k\"\n#EXTINF:1,\na\n\ + #EXT-X-KEY:METHOD=AES-128,URI=\"k2\",IV=0x0102\n#EXTINF:1,\nb\n#EXT-X-KEY:METHOD=NONE\n#EXTINF:1,\nc\n#EXT-X-ENDLIST\n", + ); + let iv = |n: u128| n.to_be_bytes(); + assert_eq!(m.segments[0].key.as_ref().unwrap().iv, iv(5), "the sequence number of the server"); + assert_eq!(m.segments[1].key.as_ref().unwrap().iv, iv(0x102)); + assert_eq!(m.segments[2].key, None); + assert_eq!(m.segments[2].seq, 2); + } + + #[test] + fn protected_ones_are_refused() { + for key in [ + "METHOD=SAMPLE-AES,URI=\"skd://x\",KEYFORMAT=\"com.apple.streamingkeydelivery\"", + "METHOD=SAMPLE-AES,URI=\"k\"", + "METHOD=SAMPLE-AES-CTR,URI=\"data:x\",KEYFORMAT=\"urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed\"", + "METHOD=AES-128,URI=\"k\",KEYFORMAT=\"com.microsoft.playready\"", + "METHOD=ISO-23001-7,URI=\"k\"", + ] { + assert!(refused(&format!("#EXTM3U\n#EXT-X-KEY:{key}\n#EXTINF:1,\na\n")), "{key}"); + assert!(refused(&format!("#EXTM3U\n#EXT-X-SESSION-KEY:{key}\n#EXT-X-STREAM-INF:BANDWIDTH=1\na\n")), "{key}"); + } + assert!(refused("#EXTM3U\n#EXT-X-FAXS-CM:URI=\"x\"\n#EXTINF:1,\na\n")); + } + + #[test] + fn nonsense_is_no_list() { + let bad = |text: &str| matches!(parse(text, &base()), Err(Error::BadReply(_))); + for text in [ + "", + "", + "#EXTM3U\n#EXTINF:1,\nfile:///etc/passwd\n", + "#EXTM3U\n#EXT-X-KEY:METHOD=AES-128,URI=\"file:///k\"\n#EXTINF:1,\na\n", + "#EXTM3U\n#EXT-X-BYTERANGE:x\na\n", + "#EXTM3U\n#EXT-X-BYTERANGE:18446744073709551615@5\na\n", + "#EXTM3U\n#EXT-X-MEDIA-SEQUENCE:18446744073709551615\n#EXTINF:1,\na\n", + "#EXTM3U\n#EXT-X-STREAM-INF:BANDWIDTH=1\n", + ] { + assert!(bad(text), "{text}"); + } + } +} diff --git a/crates/core/src/stream/join.rs b/crates/core/src/stream/join.rs new file mode 100644 index 0000000..adc72ce --- /dev/null +++ b/crates/core/src/stream/join.rs @@ -0,0 +1,163 @@ +//! Makes one file of all that arrived, without changing sound or picture. +//! +//! ffmpeg reads the pieces from sockets that only this user can open, so that they need no second place on disk. + +use super::ffmpeg::{Job, Running}; +use super::disk_error; +use super::tape::{Record, Tape}; +use crate::disk::{PartialFile, blocking}; +use crate::http::{Error, Result, Stop, stopped}; +use crate::model::ErrorKind; +use std::io; +use std::os::unix::fs::DirBuilderExt; +use std::path::{Path, PathBuf}; +use std::sync::Arc; +use std::sync::atomic::{AtomicU32, Ordering}; +use tokio::io::AsyncWriteExt; +use tokio::net::UnixListener; +use tokio::task::JoinSet; + +/// What streams are made of. Keeps pieces from pretending to be lists that lead to other files. +const FORMATS: &str = "mpegts,mov,mp4,m4a,3gp,3g2,mj2,matroska,webm,aac,ac3,eac3,mp3,flac,ogg,asf,concat"; +const BLOCK: u64 = 1 << 20; + +/// Gone with everything in it when dropped. +struct Sockets { + dir: PathBuf, + serving: JoinSet<()>, + next: u32, +} + +impl Sockets { + fn new() -> io::Result { + static NEXT: AtomicU32 = AtomicU32::new(0); + let base = std::env::var_os("XDG_RUNTIME_DIR").map(PathBuf::from).filter(|d| d.is_dir()).unwrap_or_else(std::env::temp_dir); + loop { + let name = format!("medlar-{}-{}", std::process::id(), NEXT.fetch_add(1, Ordering::Relaxed)); + let dir = base.join(name); + match std::fs::DirBuilder::new().mode(0o700).create(&dir) { + Ok(()) => return Ok(Sockets { dir, serving: JoinSet::new(), next: 0 }), + // Left by one that was killed, with the same number. + Err(e) if e.kind() == io::ErrorKind::AlreadyExists => continue, + Err(e) => return Err(e), + } + } + } + + /// The address of a socket that gives out what `pieces` say, once. + fn serve(&mut self, what: Served) -> Result { + let path = self.dir.join(self.next.to_string()); + self.next += 1; + let listener = UnixListener::bind(&path).map_err(disk_error)?; + self.serving.spawn(async move { + let Ok((mut to, _)) = listener.accept().await else { return }; + let sent = match what { + Served::Text(text) => to.write_all(text.as_bytes()).await.map_err(disk_error), + Served::Pieces(file, pieces) => send(&file, &pieces, &mut to).await, + }; + if let Err(e) = sent { + log::debug!("joining: {e:?}"); + } + let _ = to.shutdown().await; + }); + Ok(format!("unix:{}", path.display())) + } +} + +impl Drop for Sockets { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.dir); + } +} + +enum Served { + Text(String), + Pieces(Arc, Vec), +} + +async fn send(file: &PartialFile, pieces: &[Record], to: &mut (impl AsyncWriteExt + Unpin)) -> Result<()> { + for p in pieces { + let mut at = p.at; + while at < p.at + p.len { + let n = BLOCK.min(p.at + p.len - at); + to.write_all(&file.read_at(n as usize, at).await?).await.map_err(disk_error)?; + at += n; + } + } + Ok(()) +} + +/// ffmpeg's name for the format a file name asks for. +pub(super) fn muxer(ext: &str) -> Option<&'static str> { + Some(match ext.to_ascii_lowercase().as_str() { + "mp4" | "m4v" => "mp4", + "m4a" => "ipod", + "mkv" | "mka" => "matroska", + "webm" => "webm", + "mov" => "mov", + "ts" => "mpegts", + _ => return None, + }) +} + +/// What holds anything. +pub(super) const ANYTHING: &str = "matroska"; + +/// Writes `to`, in the format of `muxer` or, where that can't hold it, in `ANYTHING`. Nothing is left there when it fails. +pub(super) async fn join(ffmpeg: &Path, tape: &Tape, muxer: &str, to: &Path, stop: &mut Stop) -> Result<()> { + let mut result = once(ffmpeg, tape, muxer, to, stop).await; + if muxer != ANYTHING && matches!(result, Err(Error::Conn { kind: ErrorKind::Media, .. })) { + log::debug!("{muxer} can't hold it"); + result = once(ffmpeg, tape, ANYTHING, to, stop).await; + } + if result.is_err() { + let _ = std::fs::remove_file(to); + } + result +} + +async fn once(ffmpeg: &Path, tape: &Tape, muxer: &str, to: &Path, stop: &mut Stop) -> Result<()> { + let mut sockets = Sockets::new().map_err(disk_error)?; + let tracks: Vec>> = (0..tape.head.tracks.len() as u32).map(|t| tape.groups(t)).filter(|g| !g.is_empty()).collect(); + if tracks.is_empty() { + return Err(Error::because(ErrorKind::Media, "error.media.empty")); + } + let single = tracks.iter().all(|groups| groups.len() == 1); + let mut job = Job::new(); + for (i, groups) in tracks.iter().enumerate() { + let mut addresses = vec![]; + for group in groups { + addresses.push(sockets.serve(Served::Pieces(tape.file.clone(), group.clone()))?); + } + // Their clocks are the same one. + if i > 0 && single { + job.args(["-isync", "0"]); + } + job.args(["-format_whitelist", FORMATS]); + match &addresses[..] { + [one] => job.input("unix", one), + many => { + let list = many.iter().map(|a| format!("file '{a}'\n")).collect::(); + let list = sockets.serve(Served::Text(format!("ffconcat version 1.0\n{list}")))?; + job.args(["-f", "concat", "-safe", "0"]).input("unix", list) + } + }; + } + match tracks.len() { + 1 => job.args(["-map", "0:v?", "-map", "0:a?"]), + _ => job.args(["-map", "0:v?", "-map", "1:a?"]), + }; + job.args(["-c", "copy"]).file(muxer, to); + let mut running = job.start(ffmpeg)?; + ended(&mut running, stop).await?; + let to = to.to_path_buf(); + blocking(move || std::fs::File::open(to).and_then(|f| f.sync_all()).map_err(disk_error)).await +} + +async fn ended(running: &mut Running, stop: &mut Stop) -> Result<()> { + tokio::select! { + biased; + _ = stopped(stop) => Err(Error::Stopped), + end = running.end() => end?.map_err(|failed| failed.error()), + } +} diff --git a/crates/core/src/stream/list.rs b/crates/core/src/stream/list.rs new file mode 100644 index 0000000..317a381 --- /dev/null +++ b/crates/core/src/stream/list.rs @@ -0,0 +1,156 @@ +//! What lists of streams have in common. + +use serde::{Deserialize, Serialize}; +use url::Url; + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +pub enum Kind { + Hls, + Dash, + Rtsp, + Mms, +} + +/// What can be downloaded from a link. +#[derive(Debug, Clone)] +pub struct Found { + pub kind: Kind, + /// Goes on until it is stopped. + pub live: bool, + /// Seconds. + pub duration: Option, + /// Best first. With sound in them, unless they name their `sound`. + pub videos: Vec, + /// Sound that comes on its own. Best first. + pub audios: Vec, +} + +/// One quality or language. +#[derive(Debug, Clone, PartialEq)] +pub struct Variant { + /// Stays the same when the list is read again. + pub id: String, + /// Bits per second. + pub bandwidth: u64, + pub size: Option<(u32, u32)>, + pub codecs: String, + pub language: Option, + pub name: Option, + /// The group of `audios` that goes with it, or the one it is in. + pub sound: Option, + /// The one to take when none is asked for. + pub preferred: bool, + /// Where its own list is (HLS). + pub(super) url: Option, +} + +impl Variant { + pub(super) fn new(id: String) -> Variant { + Variant { id, bandwidth: 0, size: None, codecs: String::new(), language: None, name: None, sound: None, preferred: false, url: None } + } +} + +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub enum Pick { + #[default] + Best, + None, + /// `Variant::id` + One(String), +} + +/// What the user chose of a stream. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(default)] +pub struct Choice { + pub video: Pick, + pub audio: Pick, + /// The best that is no higher, for `Pick::Best`. + pub max_height: Option, + /// A recording ends by itself after so many seconds or bytes. + pub seconds: Option, + pub bytes: Option, +} + +impl Found { + /// What to download. None when the choice doesn't fit, or there is nothing. + pub(super) fn pick(&self, choice: &Choice) -> Option> { + let by_id = |from: &[Variant], id: &str| from.iter().find(|v| v.id == id).cloned(); + let video = match &choice.video { + Pick::None => None, + Pick::One(id) => Some(by_id(&self.videos, id)?), + Pick::Best => { + let fits = |v: &&Variant| choice.max_height.is_none_or(|max| v.size.is_none_or(|(_, h)| h <= max)); + self.videos.iter().find(fits).or(self.videos.last()).cloned() + } + }; + let audio = match &choice.audio { + Pick::None => None, + Pick::One(id) => Some(by_id(&self.audios, id)?), + Pick::Best => { + let group = video.as_ref().and_then(|v| v.sound.as_ref()); + // A video that names no group has its sound in it, unless there is none of it (DASH). + let apart = self.kind == Kind::Dash || video.is_none(); + let fits = |a: &&Variant| apart || (group.is_some() && a.sound.as_ref() == group); + let best = self.audios.iter().filter(fits); + best.clone().find(|a| a.preferred).or(best.clone().next()).cloned() + } + }; + let picked: Vec = video.into_iter().chain(audio).collect(); + (!picked.is_empty()).then_some(picked) + } +} + +/// A piece of a file, or all of it. +#[derive(Debug, Clone, PartialEq, Eq)] +pub(super) struct Piece { + pub url: Url, + /// First byte and the one after the last. + pub range: Option<(u64, u64)>, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub(super) struct Key { + pub url: Url, + pub iv: [u8; 16], +} + +#[derive(Debug, Clone, PartialEq)] +pub(super) struct Segment { + /// Pieces with the same one can be put together as they are. + pub stretch: u64, + pub seq: u64, + /// The `seq` of the one after it. + pub next: u64, + pub seconds: f64, + pub piece: Piece, + pub key: Option, + /// Comes before all others of the stretch. + pub init: Option, + pub init_key: Option, +} + +/// One variant, as its list is now. +#[derive(Debug, Clone, Default)] +pub(super) struct Media { + pub segments: Vec, + /// There will be no more. + pub ended: bool, + /// All since the start, though it goes on. + pub from_start: bool, + /// Seconds between two looks. + pub pace: f64, + /// All of it is in one file. + pub whole: Option, +} + +/// Lists may lead to the web only. +pub(super) fn web(base: &Url, link: &str) -> Option { + let url = base.join(link.trim()).ok()?; + (matches!(url.scheme(), "http" | "https") && url.has_host()).then_some(url) +} + +/// Best first: the higher picture, then more bits. +pub(super) fn sort(variants: &mut [Variant]) { + variants.sort_by_key(|v| std::cmp::Reverse((v.size.map_or(0, |(_, h)| h), v.bandwidth))); +} diff --git a/crates/core/src/stream/mod.rs b/crates/core/src/stream/mod.rs new file mode 100644 index 0000000..c11fb00 --- /dev/null +++ b/crates/core/src/stream/mod.rs @@ -0,0 +1,507 @@ +//! 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; + +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 { + 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(&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 { + 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 { + 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(store: &Arc, work: impl FnOnce(&Store) -> Result + Send + 'static) -> Result { + let store = store.clone(); + blocking(move || work(&store)).await +} + +/// Gives a joined file its name. +async fn finish(store: &Arc, id: TaskId, file: PartialFile) -> Result { + 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>, head: Head, url: &Url, sound: bool) -> Result { + 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, tape: Option, empty: Option>, meter: &mut Meter, stop: &mut Stop) -> Result { + 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::>>()?, + (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 = (0..picked.len() as u32).map(|track| Feed::new(track, &tape, self.choice.seconds)).collect(); + let mut queue: VecDeque = 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 { + 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) -> 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 = 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 { + 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, + id: TaskId, + received: Arc, + /// Milliseconds of all tracks, when that is known. + whole: Option, + tick: Duration, + checkpoint: Duration, + saved: (u64, Instant), + shown: (u64, Instant), + speed: f64, +} + +impl Meter { + fn new(store: Arc, 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"); + } +} diff --git a/crates/core/src/stream/record.rs b/crates/core/src/stream/record.rs new file mode 100644 index 0000000..be46fac --- /dev/null +++ b/crates/core/src/stream/record.rs @@ -0,0 +1,223 @@ +//! Streams that ffmpeg has to receive itself: RTSP and MMS. + +use super::ffmpeg::Job; +use super::list::Choice; +use super::tape::{Record, Tape}; +use super::{Meter, disk_error, odd}; +use crate::auth::Login; +use crate::http::{Error, Monitor, Result, Source, Stop, Client, stopped}; +use crate::model::ErrorKind; +use std::path::Path; +use std::time::Duration; +use tokio::io::AsyncReadExt; +use tokio::time::{Instant, timeout}; +use url::Url; + +/// What ffmpeg writes is kept in pieces of this size, or of a second. +const PIECE: usize = 256 << 10; +const EVERY: Duration = Duration::from_secs(1); +/// Nothing comes for so long: the stream is gone. +const SILENCE: Duration = Duration::from_secs(20); +/// For ffmpeg to end properly when the download is paused. +const GRACE: Duration = Duration::from_millis(800); + +/// Where to ask, in this order. +fn addresses(url: &Url) -> Vec<(String, &'static str)> { + let with = |scheme: &str| format!("{scheme}{}", &url.as_str()[url.scheme().len()..]); + let (http, tcp) = ((with("mmsh"), "mmsh,http,tcp"), (with("mmst"), "mmst,tcp")); + match url.scheme() { + "rtsp" => vec![(url.to_string(), "rtsp,rtp,udp,tcp")], + "mmsh" => vec![http], + "mmst" => vec![tcp], + // The old name for both. Its own port is that of the second. + _ if url.port() == Some(1755) => vec![tcp, http], + _ => vec![http, tcp], + } +} + +/// A login must not be among the arguments, where everyone can read them. +fn input(job: &mut Job, address: &str, protocols: &str, login: Option<&Login>) -> Result<()> { + let wait = &SILENCE.as_micros().to_string()[..]; + let options = if address.starts_with("rtsp:") { &[("rtsp_flags", "prefer_tcp"), ("timeout", wait)][..] } else { &[] }; + let Some(login) = login else { + for (name, value) in options { + job.arg(format!("-{name}")).arg(value); + } + job.input(protocols, address); + return Ok(()); + }; + let encode = |text: &str| percent_encoding::utf8_percent_encode(text, percent_encoding::NON_ALPHANUMERIC).to_string(); + let (scheme, rest) = address.split_once("://").ok_or(Error::Link)?; + let with = format!("{scheme}://{}:{}@{rest}", encode(&login.user), encode(&login.password)).replace('\'', r"'\''"); + if with.contains(['\n', '\r']) { + return Err(Error::Link); + } + let options: String = options.iter().map(|(name, value)| format!("option {name} {value}\n")).collect(); + job.args(["-f", "concat", "-safe", "0"]).input(&format!("pipe,{protocols}"), "pipe:0"); + job.stdin(format!("ffconcat version 1.0\nfile '{with}'\n{options}")); + Ok(()) +} + +/// Adds to the tape until the stream ends, a limit is reached or `monitor.finish` is called. +#[allow(clippy::too_many_arguments)] +pub(super) async fn record( + ffmpeg: &Path, + client: &Client, + source: &Source, + choice: &Choice, + tape: &mut Tape, + meter: &mut Meter, + monitor: &Monitor, + stop: &mut Stop, +) -> Result<()> { + let way = tokio::select! { + _ = stopped(stop) => return Err(Error::Stopped), + way = source.way(client) => way?, + }; + // Straight to the server would show it who asks. + if way.proxy.is_some() { + return Err(Error::because(ErrorKind::Proxy, "error.proxy.stream")); + } + let had = tape.records.len(); + let mut first = None; + for (address, protocols) in addresses(&source.url) { + let mut job = Job::new(); + input(&mut job, &address, protocols, way.login.as_ref())?; + let result = run(ffmpeg, job, choice, tape, meter, monitor, stop).await; + use ErrorKind::{Login, Dns, Tool}; + let other_way = match &result { + Err(Error::Conn { kind, .. }) => !matches!(kind, Login | Dns | Tool), + Err(Error::Idle) => true, + _ => false, + }; + if !other_way || tape.records.len() > had { + return result; + } + first = first.or(result.err()); + } + Err(first.unwrap_or(Error::Link)) +} + +async fn run(ffmpeg: &Path, mut job: Job, choice: &Choice, tape: &mut Tape, meter: &mut Meter, monitor: &Monitor, stop: &mut Stop) -> Result<()> { + let had = tape.length(0); + let full = |tape: &Tape| choice.bytes.is_some_and(|most| tape.records.iter().map(|r| r.len).sum::() >= most); + if let Some(seconds) = choice.seconds { + let left = (seconds * 1000).saturating_sub(had); + if left == 0 { + return Ok(()); + } + job.args(["-t", &format!("{}ms", left)]); + } + if full(tape) { + return Ok(()); + } + job.args(["-map", "0:v?", "-map", "0:a?", "-c", "copy", "-flush_packets", "1"]).pipe("matroska"); + let mut running = job.start(ffmpeg)?; + let mut output = running.output.take().ok_or_else(|| odd("no output"))?; + let group = tape.records.iter().map(|r| r.group + 1).max().unwrap_or(0); + let progress = running.progress(); + let mut finish = monitor.finishing(); + let (mut seq, mut ms, mut buf) = (0u64, 0u64, Vec::with_capacity(PIECE)); + let (mut asked, mut paused, mut since, mut came) = (false, false, Instant::now(), Instant::now()); + let mut kill_at = None; + loop { + let mut chunk = [0; 16 << 10]; + let read = tokio::select! { + biased; + _ = stopped(stop), if !paused => { + paused = true; + running.finish(); + kill_at = Some(Instant::now() + GRACE); + None + } + _ = stopped(&mut finish), if !asked && !paused => { + asked = true; + running.finish(); + kill_at = Some(Instant::now() + SILENCE); + None + } + n = output.read(&mut chunk) => Some(n.map_err(disk_error)?), + _ = tokio::time::sleep(meter.tick()) => None, + }; + if let Some(n) = read { + let mut rest = &chunk[..n]; + while !rest.is_empty() { + // What is here is kept, whatever the limits say. + let n = tokio::select! { + biased; + _ = stopped(stop), if !paused => rest.len(), + n = monitor.flow().take(rest.len() as u64) => n as usize, + }; + buf.extend_from_slice(&rest[..n]); + meter.came(n as u64); + rest = &rest[n..]; + } + came = Instant::now(); + } + let over = read == Some(0); + if !buf.is_empty() && (over || buf.len() >= PIECE || since.elapsed() >= EVERY) { + let now = progress.borrow().time.as_millis() as u64; + // The end of the last report comes late. + let record = Record { track: 0, group, init: false, stretch: u64::from(group), seq, ms: now.saturating_sub(ms) as u32, at: 0, len: 0 }; + tape.append(record, &buf).await?; + (seq, ms, since) = (seq + 1, ms.max(now), Instant::now()); + buf.clear(); + if full(tape) && !asked && !paused { + asked = true; + running.finish(); + kill_at = Some(Instant::now() + SILENCE); + } + } + meter.look(tape, 1, monitor).await?; + if over { + break; + } + let late = kill_at.is_some_and(|at| Instant::now() >= at); + if late || (!asked && !paused && came.elapsed() > SILENCE + EVERY) { + running.kill().await; + if !buf.is_empty() { + let record = Record { track: 0, group, init: false, stretch: u64::from(group), seq, ms: 0, at: 0, len: 0 }; + tape.append(record, &buf).await?; + } + return if paused { Err(Error::Stopped) } else if asked { Ok(()) } else { Err(Error::Idle) }; + } + } + let end = timeout(GRACE, running.end()).await; + if paused { + return Err(Error::Stopped); + } + if asked { + return Ok(()); + } + match end { + Ok(Ok(Ok(()))) if seq > 0 => Ok(()), + Ok(Ok(Ok(()))) => Err(Error::because(ErrorKind::Media, "error.media.empty")), + Ok(Ok(Err(failed))) if seq == 0 => Err(failed.error()), + Ok(Err(e)) => Err(disk_error(e)), + _ => Err(Error::Cut { got: tape.end, expected: None }), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn where_to_ask() { + let of = |url: &str| addresses(&Url::parse(url).unwrap()).into_iter().map(|a| a.0).collect::>(); + assert_eq!(of("rtsp://h:8554/a?b"), ["rtsp://h:8554/a?b"]); + assert_eq!(of("mms://h/a.wmv"), ["mmsh://h/a.wmv", "mmst://h/a.wmv"]); + assert_eq!(of("mms://h:1755/a"), ["mmst://h:1755/a", "mmsh://h:1755/a"]); + } + + #[test] + fn logins_stay_off_the_arguments() { + let login = Login { user: "me@x".into(), password: "S3CRET'\n".into() }; + let mut job = Job::new(); + input(&mut job, "rtsp://h/it's", "rtsp,tcp", Some(&login)).unwrap(); + let shown = format!("{job:?}"); + let script = String::from_utf8(job.script().unwrap().to_vec()).unwrap(); + assert!(script.contains(r"file 'rtsp://me%40x:S3CRET%27%0A@h/it'\''s'"), "{script}"); + assert!(!shown.contains("S3CRET"), "{shown}"); + } +} diff --git a/crates/core/src/stream/tape.rs b/crates/core/src/stream/tape.rs new file mode 100644 index 0000000..69cff3d --- /dev/null +++ b/crates/core/src/stream/tape.rs @@ -0,0 +1,174 @@ +//! The unfinished file of a stream: what arrived, in the order it arrived, with what belongs where. +//! +//! One file, so that moving, renaming and binning it is the same as for any other download. + +use crate::disk::PartialFile; +use crate::http::Result; +use serde::{Deserialize, Serialize}; +use std::sync::Arc; + +const MAGIC: &[u8; 8] = b"MedlarS1"; +const RECORD: u64 = 48; +const MARK: u32 = 0x4d64_6c52; + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub(super) struct Head { + pub live: bool, + /// What it is of, to notice when the server has another one now. + pub tracks: Vec, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub(super) struct Track { + pub id: String, + /// Segments. None while it grows. + pub total: Option, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(super) struct Record { + pub track: u32, + /// Put together as they are. + pub group: u32, + pub init: bool, + pub stretch: u64, + pub seq: u64, + /// Length of the recording in it, in milliseconds. + pub ms: u32, + pub at: u64, + pub len: u64, +} + +#[derive(Debug)] +pub(super) struct Tape { + pub file: Arc, + pub head: Head, + pub records: Vec, + /// Where the next one goes. + pub end: u64, +} + +impl Tape { + /// Whether the file is one. An empty one may become one. + pub async fn is(file: &PartialFile) -> Result { + Ok(file.size()? >= MAGIC.len() as u64 && file.read_at(MAGIC.len(), 0).await? == MAGIC) + } + + pub async fn create(file: Arc, head: Head) -> Result { + let text = serde_json::to_vec(&head).expect("plain data"); + let mut buf = MAGIC.to_vec(); + buf.extend((text.len() as u32).to_le_bytes()); + buf.extend(text); + let end = buf.len() as u64; + file.write_at(buf, end as usize, 0).await?; + Ok(Tape { file, head, records: vec![], end }) + } + + /// `safe` is how much of it was safe on disk. What came after may be half there: it is written over. + /// None when even the head is not whole. + pub async fn open(file: Arc, safe: u64) -> Result> { + let safe = safe.min(file.size()?); + let start = MAGIC.len() as u64 + 4; + if safe < start { + return Ok(None); + } + let len = file.read_at(4, start - 4).await?; + let len = u64::from(u32::from_le_bytes(len.try_into().expect("four"))); + if safe < start + len { + return Ok(None); + } + let Ok(head) = serde_json::from_slice(&file.read_at(len as usize, start).await?) else { return Ok(None) }; + let mut tape = Tape { file, head, records: vec![], end: start + len }; + while tape.end + RECORD <= safe { + let bytes = tape.file.read_at(RECORD as usize, tape.end).await?; + let Some(record) = Record::read(&bytes, tape.end + RECORD).filter(|r| r.at.checked_add(r.len).is_some_and(|end| end <= safe)) else { break }; + tape.end = record.at + record.len; + tape.records.push(record); + } + Ok(Some(tape)) + } + + /// `at` and `len` are filled in. + pub async fn append(&mut self, mut record: Record, data: &[u8]) -> Result<()> { + (record.at, record.len) = (self.end + RECORD, data.len() as u64); + let mut buf = record.bytes(); + buf.extend_from_slice(data); + let n = buf.len(); + self.file.write_at(buf, n, self.end).await?; + self.end += n as u64; + self.records.push(record); + Ok(()) + } + + /// The groups of a track, each in order with what comes first at its start. + pub fn groups(&self, track: u32) -> Vec> { + let mut mine: Vec = self.records.iter().copied().filter(|r| r.track == track).collect(); + mine.sort_by_key(|r| (r.group, !r.init, r.seq)); + mine.dedup_by_key(|r| (r.group, r.init, r.seq)); + let groups = mine.chunk_by(|a, b| a.group == b.group).map(<[Record]>::to_vec); + groups.filter(|g| g.iter().any(|r| !r.init)).collect() + } + + /// Milliseconds of the track. + pub fn length(&self, track: u32) -> u64 { + self.records.iter().filter(|r| r.track == track).map(|r| u64::from(r.ms)).sum() + } +} + +impl Record { + fn bytes(&self) -> Vec { + let mut b = Vec::with_capacity(RECORD as usize + self.len as usize); + for n in [MARK, self.track, self.group, u32::from(self.init), self.ms, 0] { + b.extend(n.to_le_bytes()); + } + for n in [self.stretch, self.seq, self.len] { + b.extend(n.to_le_bytes()); + } + b + } + + fn read(b: &[u8], at: u64) -> Option { + let small = |i: usize| u32::from_le_bytes(b[i * 4..i * 4 + 4].try_into().expect("four")); + let big = |i: usize| u64::from_le_bytes(b[24 + i * 8..32 + i * 8].try_into().expect("eight")); + (small(0) == MARK).then(|| Record { track: small(1), group: small(2), init: small(3) == 1, ms: small(4), stretch: big(0), seq: big(1), at, len: big(2) }) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::collections::HashSet; + + fn record(track: u32, group: u32, init: bool, seq: u64) -> Record { + Record { track, group, init, stretch: 0, seq, ms: 500, at: 0, len: 0 } + } + + #[tokio::test] + async fn goes_on_after_a_torn_end() { + let dir = tempfile::tempdir().unwrap(); + let (file, name) = PartialFile::create(dir.path(), "a.mp4", &HashSet::new()).unwrap(); + assert!(!Tape::is(&file).await.unwrap()); + let head = Head { live: false, tracks: vec![Track { id: "v".into(), total: Some(3) }] }; + let mut tape = Tape::create(Arc::new(file), head.clone()).await.unwrap(); + for (r, data) in [(record(0, 1, false, 5), "two"), (record(0, 0, false, 1), "one"), (record(0, 0, true, 0), "i"), (record(1, 0, true, 0), "only")] { + tape.append(r, data.as_bytes()).await.unwrap(); + } + let (whole, records) = (tape.end, tape.records.clone()); + tape.append(record(0, 1, false, 6), &[7; 1000]).await.unwrap(); + let end = tape.end; + drop(tape); + let file = Arc::new(PartialFile::reopen(dir.path(), &name).unwrap().unwrap()); + assert!(Tape::is(&file).await.unwrap()); + for safe in [whole, whole + 10, end - 1] { + let tape = Tape::open(file.clone(), safe).await.unwrap().unwrap(); + assert_eq!((tape.end, &tape.records, &tape.head), (whole, &records, &head)); + } + assert!(Tape::open(file.clone(), 5).await.unwrap().is_none()); + let tape = Tape::open(file, end).await.unwrap().unwrap(); + assert_eq!(tape.records.len(), 5); + let order: Vec> = tape.groups(0).iter().map(|g| g.iter().map(|r| (r.init, r.seq)).collect()).collect(); + assert_eq!(order, [vec![(true, 0), (false, 1)], vec![(false, 5), (false, 6)]]); + assert!(tape.groups(1).is_empty()); + assert_eq!(tape.length(0), 2000); + } +} diff --git a/crates/core/tests/stream.rs b/crates/core/tests/stream.rs new file mode 100644 index 0000000..24a94f4 --- /dev/null +++ b/crates/core/tests/stream.rs @@ -0,0 +1,750 @@ +//! Streams: HLS and DASH in pieces, RTSP and MMS through ffmpeg. The fixtures are made by ffmpeg, the results looked at by ffprobe. + +use medlar_core::auth::Login; +use medlar_core::host::{Caps, Hosts}; +use medlar_core::http::{ClientOptions, Error, Monitor, Options, Shared, Source, client}; +use medlar_core::model::*; +use medlar_core::net_state::Bus; +use medlar_core::secret::{Secret, Secrets}; +use medlar_core::settings::Settings; +use medlar_core::site::Sites; +use medlar_core::store::Store; +use medlar_core::stream::{self, Choice, Pick, Request, Tools}; +use medlar_testserver::{Faults, TestServer}; +use std::io::{BufRead, BufReader, Read, Write}; +use std::net::{TcpListener, TcpStream}; +use std::path::{Path, PathBuf}; +use std::process::Command; +use std::sync::{Arc, Mutex}; +use std::time::{Duration, Instant}; +use tokio::sync::watch; +use tokio::task::JoinHandle; +use tokio::time::sleep; + +type Result = std::result::Result; + +/// Seconds of the fixtures. +const LENGTH: f64 = 6.0; + +fn ms(n: u64) -> Duration { + Duration::from_millis(n) +} + +fn ffmpeg(dir: &Path, args: &[&str]) { + let out = Command::new("/usr/bin/ffmpeg").current_dir(dir).args(["-y", "-nostdin", "-loglevel", "error"]).args(args).output().unwrap(); + assert!(out.status.success(), "{args:?}: {}", String::from_utf8_lossy(&out.stderr)); +} + +/// Picture and sound of `LENGTH` seconds. +fn input<'a>(to: &[&'a str]) -> Vec<&'a str> { + let mut args = vec!["-f", "lavfi", "-i", "testsrc=size=160x120:rate=10:duration=6", "-f", "lavfi", "-i", "sine=440:duration=6"]; + args.extend(["-c:v", "libx264", "-preset", "ultrafast", "-g", "10", "-c:a", "aac"]); + args.extend(to); + args +} + +struct Bench { + server: TestServer, + media: PathBuf, + dir: tempfile::TempDir, + shared: Shared, + options: Options, + sites: Option>, +} + +struct Going { + stop: watch::Sender, + monitor: Arc, + work: JoinHandle>, +} + +impl Going { + async fn end(self) -> Result { + tokio::time::timeout(Duration::from_secs(60), self.work).await.expect("it ends").unwrap() + } + + async fn stop(self) { + self.stop.send_replace(true); + assert!(matches!(self.end().await, Err(Error::Stopped))); + } + + /// Bytes that are here. + fn here(&self) -> u64 { + self.monitor.snapshot().parts.iter().map(|p| p.done).sum() + } +} + +impl Bench { + async fn new() -> Bench { + let server = TestServer::start().await; + server.build_media().await.unwrap(); + let media = std::env::temp_dir().join(format!("medlar-testserver-{}-{}", std::process::id(), server.port())); + let dir = tempfile::tempdir().unwrap(); + let shared = Bench::shared(dir.path()); + let options = Options { tick: ms(25), tries: 3, backoff: ms(20), max_wait: ms(1500), checkpoint: ms(50), ..Options::default() }; + Bench { server, media, dir, shared, options, sites: None } + } + + fn shared(dir: &Path) -> Shared { + let store = Arc::new(Store::open(&dir.join("medlar.db")).unwrap()); + let client = client(&ClientOptions { idle_timeout: ms(2000), ..ClientOptions::default() }).unwrap(); + Shared { client, store, hosts: Hosts::new(Caps { burst: 1000, per_second: 1000.0, ..Caps::default() }) } + } + + /// Runs ffmpeg where the server has its files. + fn make(&self, to: &[&str]) { + ffmpeg(&self.media, &input(to)); + } + + fn write(&self, name: &str, text: &str) { + // Whole or not at all, as it is read meanwhile. + std::fs::write(self.media.join("new"), text).unwrap(); + std::fs::rename(self.media.join("new"), self.media.join(name)).unwrap(); + } + + fn read(&self, name: &str) -> String { + std::fs::read_to_string(self.media.join(name)).unwrap() + } + + fn url(&self, name: &str) -> String { + self.server.url(&format!("/media/{name}")) + } + + fn add(&self, url: &str, name: &str) -> TaskId { + let task = Task { url: url.into(), name: name.into(), folder: self.dir.path().join("files"), ..Task::default() }; + self.shared.store.add_task(task).unwrap() + } + + async fn go(&self, id: TaskId, choice: Choice) -> Going { + self.go_with(id, choice, Arc::new(Monitor::new(16))).await + } + + async fn go_with(&self, id: TaskId, choice: Choice, monitor: Arc) -> Going { + let task = self.shared.store.task(id).unwrap(); + let source = match &self.sites { + Some(sites) => sites.source(&task).await.unwrap(), + None => Source::new(&task.url).unwrap(), + }; + let (stop, stopped) = watch::channel(false); + let (shared, options, seen) = (self.shared.clone(), self.options.clone(), monitor.clone()); + let work = tokio::spawn(async move { + let request = Request { id, source, choice, tools: &Tools::find(), options: &options }; + stream::download(&shared, request, &seen, stopped).await + }); + Going { stop, monitor, work } + } + + async fn get(&self, name: &str, choice: Choice) -> Result { + let id = self.add(&self.url(name), ""); + self.go(id, choice).await.end().await + } + + /// Nothing is left but the files themselves. + fn clean(&self, files: usize) { + let names: Vec<_> = std::fs::read_dir(self.dir.path().join("files")).unwrap().map(|e| e.unwrap().file_name()).collect(); + assert_eq!(names.len(), files, "{names:?}"); + } +} + +async fn until(what: &str, is: impl Fn() -> bool) { + let end = Instant::now() + Duration::from_secs(30); + while !is() { + assert!(Instant::now() < end, "never {what}"); + sleep(ms(10)).await; + } +} + +struct Seen { + seconds: f64, + format: String, + /// Kinds of streams and their names. + codecs: Vec, + packets: u64, +} + +fn look(file: &Path) -> Seen { + let args = ["-v", "error", "-count_packets", "-show_entries", "format=duration,format_name:stream=codec_name,nb_read_packets", "-of", "flat"]; + let out = Command::new("/usr/bin/ffprobe").args(args).arg(file).output().unwrap(); + let text = String::from_utf8(out.stdout).unwrap(); + assert!(out.status.success() && out.stderr.is_empty(), "{}", String::from_utf8_lossy(&out.stderr)); + let pairs: Vec<(String, String)> = text.lines().filter_map(|l| l.split_once('=')).map(|(k, v)| (k.into(), v.trim_matches('"').into())).collect(); + let all = |end: &str| pairs.iter().filter(|(k, _)| k.ends_with(end)).map(|(_, v)| v.clone()).collect::>(); + Seen { + seconds: all("format.duration")[0].parse().unwrap(), + format: all("format_name")[0].clone(), + codecs: all("codec_name"), + packets: all("nb_read_packets").iter().map(|n| n.parse::().unwrap()).sum(), + } +} + +/// All of it is there, and decodes without a complaint. +fn check(file: &Path, seconds: f64, codecs: &[&str]) -> Seen { + let seen = look(file); + assert!((seen.seconds - seconds).abs() < 0.2, "{} s instead of {seconds}", seen.seconds); + assert_eq!(seen.codecs, codecs); + let out = Command::new("/usr/bin/ffmpeg").args(["-nostdin", "-v", "error", "-i"]).arg(file).args(["-f", "null", "-"]).output().unwrap(); + assert!(out.stderr.is_empty(), "{}", String::from_utf8_lossy(&out.stderr)); + seen +} + +fn kind_of(result: Result) -> ErrorKind { + match result { + Err(Error::Conn { kind, .. }) => kind, + other => panic!("{other:?}"), + } +} + +const HLS: &[&str] = &["-f", "hls", "-hls_time", "1", "-hls_list_size", "0", "-hls_segment_filename", "h%d.ts", "h.m3u8"]; + +#[tokio::test(flavor = "multi_thread")] +async fn hls_whole() { + let b = Bench::new().await; + b.make(HLS); + let file = b.get("h.m3u8", Choice::default()).await.unwrap(); + assert_eq!(file.file_name().unwrap(), "h.mp4"); + check(&file, LENGTH, &["h264", "aac"]); + let task = b.shared.store.tasks().unwrap().remove(0); + assert_eq!((task.name.as_str(), task.size), ("h.mp4", Some(file.metadata().unwrap().len()))); + b.clean(1); + // Every piece was asked for once. + for i in 0..6 { + assert_eq!(b.server.requests_for(&format!("/media/h{i}.ts")).len(), 1); + } +} + +#[tokio::test(flavor = "multi_thread")] +async fn hls_variants_and_sound_apart() { + let b = Bench::new().await; + let streams = ["-map", "0:v", "-map", "0:v", "-map", "1:a", "-s:v:0", "160x120", "-s:v:1", "320x240", "-f", "hls", "-hls_time", "1", "-hls_list_size", "0"]; + let out = ["-hls_segment_type", "fmp4", "-var_stream_map", "v:0,agroup:a v:1,agroup:a a:0,agroup:a,language:en,default:yes", "-master_pl_name", "m.m3u8"]; + let names = ["-hls_fmp4_init_filename", "init%v.mp4", "-hls_segment_filename", "v%v_%d.m4s", "v%v.m3u8"]; + b.make(&[&streams[..], &out, &names].concat()); + let (_stop, mut stopped) = watch::channel(false); + let found = stream::probe(&b.shared.client, &Source::new(&b.url("m.m3u8")).unwrap(), &mut stopped).await.unwrap(); + assert_eq!(found.videos.iter().map(|v| v.size.unwrap().1).collect::>(), [240, 120]); + assert_eq!((found.audios.len(), found.live), (1, false)); + assert!((found.duration.unwrap() - LENGTH).abs() < 0.2); + + let file = b.get("m.m3u8", Choice::default()).await.unwrap(); + check(&file, LENGTH, &["h264", "aac"]); + assert!(b.server.requests_for("/media/v0_0.m4s").is_empty(), "the best one only"); + let file = b.get("m.m3u8", Choice { max_height: Some(120), audio: Pick::None, ..Choice::default() }).await.unwrap(); + check(&file, LENGTH, &["h264"]); + let file = b.get("m.m3u8", Choice { video: Pick::None, ..Choice::default() }).await.unwrap(); + assert_eq!(file.extension().unwrap(), "m4a"); + check(&file, LENGTH, &["aac"]); + let gone = Choice { video: Pick::One("x".into()), ..Choice::default() }; + assert_eq!(kind_of(b.get("m.m3u8", gone).await), ErrorKind::Media); + b.clean(3); +} + +#[tokio::test(flavor = "multi_thread")] +async fn hls_with_keys_and_ranges() { + let b = Bench::new().await; + std::fs::write(b.media.join("k.bin"), b"0123456789abcdef").unwrap(); + b.write("k.info", "k.bin\nk.bin\n"); + b.make(&["-hls_key_info_file", "k.info", "-hls_flags", "periodic_rekey", "-f", "hls", "-hls_time", "1", "-hls_list_size", "0", "-hls_segment_filename", "e%d.ts", "e.m3u8"]); + assert!(b.read("e.m3u8").contains("METHOD=AES-128")); + check(&b.get("e.m3u8", Choice::default()).await.unwrap(), LENGTH, &["h264", "aac"]); + assert_eq!(b.server.requests_for("/media/k.bin").len(), 1, "a key is asked for once"); + + b.make(&["-hls_flags", "single_file", "-f", "hls", "-hls_time", "1", "-hls_list_size", "0", "r.m3u8"]); + assert!(b.read("r.m3u8").contains("#EXT-X-BYTERANGE")); + check(&b.get("r.m3u8", Choice::default()).await.unwrap(), LENGTH, &["h264", "aac"]); + + std::fs::write(b.media.join("k.bin"), b"another key here").unwrap(); + let e = b.get("e.m3u8", Choice::default()).await.unwrap_err(); + assert!(matches!(e, Error::BadReply(_) | Error::Conn { kind: ErrorKind::Media, .. }), "{e:?}"); +} + +#[tokio::test(flavor = "multi_thread")] +async fn hls_with_a_break() { + let b = Bench::new().await; + b.make(HLS); + let list = b.read("h.m3u8"); + let (head, pieces) = list.split_at(list.find("#EXTINF").unwrap()); + let pieces = pieces.replace("#EXT-X-ENDLIST\n", ""); + // The same again, with the clock back at its start. + b.write("twice.m3u8", &format!("{head}{pieces}#EXT-X-DISCONTINUITY\n{pieces}#EXT-X-ENDLIST\n")); + let file = b.get("twice.m3u8", Choice::default()).await.unwrap(); + let seen = look(&file); + assert!((seen.seconds - 2.0 * LENGTH).abs() < 0.3, "{}", seen.seconds); + assert_eq!(seen.codecs, ["h264", "aac"]); +} + +#[tokio::test(flavor = "multi_thread")] +async fn dash_whole() { + let b = Bench::new().await; + for (name, args) in [ + ("t.mpd", &["-use_template", "1", "-use_timeline", "1"][..]), + ("n.mpd", &["-use_template", "1", "-use_timeline", "0"]), + ("l.mpd", &["-use_template", "0", "-use_timeline", "0"]), + ("s.mpd", &["-single_file", "1"]), + ] { + let sets = ["-f", "dash", "-seg_duration", "1", "-adaptation_sets", "id=0,streams=v id=1,streams=a"]; + let prefix = name.split('.').next().unwrap(); + let (init, media) = (format!("{prefix}i$RepresentationID$.m4s"), format!("{prefix}c$RepresentationID$-$Number%05d$.m4s")); + b.make(&[&sets[..], args, &["-init_seg_name", &init, "-media_seg_name", &media, name]].concat()); + let file = b.get(name, Choice::default()).await.unwrap_or_else(|e| panic!("{name}: {e:?}\n{}", b.read(name))); + check(&file, LENGTH, &["h264", "aac"]); + } + // All in one file, taken in ranges. + b.write( + "one.mpd", + r#" + one.mp4"#, + ); + b.make(&["-an", "-movflags", "frag_keyframe+empty_moov+default_base_moof", "one.mp4"]); + check(&b.get("one.mpd", Choice::default()).await.unwrap(), LENGTH, &["h264"]); +} + +#[tokio::test(flavor = "multi_thread")] +async fn dash_that_grows() { + let b = Bench::new().await; + b.make(&["-an", "-f", "dash", "-seg_duration", "1", "-use_timeline", "0", "g.mpd"]); + let set = r#""#; + let list = |n: u32, kind: &str| { + let times: String = (0..n).map(|t| format!(r#""#)).collect(); + format!(r#"{set}{times}"#) + }; + b.write("grow.mpd", &list(3, "dynamic")); + let id = b.add(&b.url("grow.mpd"), ""); + let going = b.go(id, Choice::default()).await; + for n in 4..=6 { + until("asked for the next", || b.server.requests_for(&format!("/media/chunk-stream0-{:05}.m4s", n - 1)).len() == 1).await; + b.write("grow.mpd", &list(n, if n == 6 { "static" } else { "dynamic" })); + } + check(&going.end().await.unwrap(), LENGTH, &["h264"]); +} + +#[tokio::test(flavor = "multi_thread")] +async fn live_until_finished() { + let b = Bench::new().await; + b.make(HLS); + let whole = b.read("h.m3u8"); + let pieces: Vec<&str> = whole[whole.find("#EXTINF").unwrap()..].split_inclusive(".ts\n").take(6).collect(); + let window = |from: usize, to: usize| format!("#EXTM3U\n#EXT-X-TARGETDURATION:1\n#EXT-X-MEDIA-SEQUENCE:{from}\n{}", pieces[from..to].concat()); + b.write("live.m3u8", &window(0, 4)); + let id = b.add(&b.url("live.m3u8"), ""); + let got = |i: usize| b.server.requests_for(&format!("/media/h{i}.ts")).len() == 1; + let going = b.go(id, Choice::default()).await; + until("at the end of the list", || got(3)).await; + assert!(!got(0), "it joins near the end"); + // Paused, while the stream goes on. + until("kept", || going.here() > 2_000).await; + sleep(ms(300)).await; + going.stop().await; + b.write("live.m3u8", &window(2, 5)); + let going = b.go(id, Choice::default()).await; + until("what came meanwhile", || got(4)).await; + b.write("live.m3u8", &window(3, 6)); + until("the next", || got(5)).await; + sleep(ms(300)).await; + going.monitor.finish(); + check(&going.end().await.unwrap(), 5.0, &["h264", "aac"]); + for i in 1..6 { + assert!(got(i), "{i} once"); + } + b.clean(1); + + // A limit ends it too, and so does the list. + b.write("live.m3u8", &window(0, 4)); + let file = b.get("live.m3u8", Choice { seconds: Some(2), ..Choice::default() }).await.unwrap(); + check(&file, 2.0, &["h264", "aac"]); + let id = b.add(&b.url("live.m3u8"), "over"); + let going = b.go(id, Choice::default()).await; + until("under way", || going.here() > 2_000).await; + b.write("live.m3u8", &(window(0, 6) + "#EXT-X-ENDLIST\n")); + check(&going.end().await.unwrap(), 5.0, &["h264", "aac"]); + + // Finished while it was paused: what there is. + b.write("live.m3u8", &window(0, 4)); + let id = b.add(&b.url("live.m3u8"), "paused"); + let going = b.go(id, Choice::default()).await; + until("recorded", || going.here() > 2_000 && going.monitor.snapshot().connections == 0).await; + going.stop().await; + let monitor = Arc::new(Monitor::new(16)); + monitor.finish(); + b.write("live.m3u8", "gone"); + check(&b.go_with(id, Choice::default(), monitor).await.end().await.unwrap(), 3.0, &["h264", "aac"]); +} + +#[tokio::test(flavor = "multi_thread")] +async fn goes_on_after_a_restart() { + let mut b = Bench::new().await; + b.make(HLS); + b.server.set_faults("/media/h*", Faults { latency_ms: Some(150), ..Faults::default() }); + let id = b.add(&b.url("h.m3u8"), ""); + let going = b.go(id, Choice::default()).await; + until("begun", || going.here() > 2_000).await; + going.stop().await; + // Another program start. + b.shared = Bench::shared(b.dir.path()); + let parts = b.shared.store.parts(id).unwrap(); + assert!(parts[0].done > 0 && parts[0].end.is_none()); + b.server.clear_all_faults(); + b.server.clear_log(); + let file = b.go(id, Choice::default()).await.end().await.unwrap(); + check(&file, LENGTH, &["h264", "aac"]); + let again = (0..6).filter(|i| b.server.requests_for(&format!("/media/h{i}.ts")).len() == 1).count(); + assert!(again < 6, "nothing that was here is asked for again"); + b.clean(1); + // Killed after the end, before the list knew. + assert_eq!(b.go(id, Choice::default()).await.end().await.unwrap(), file); + + // Killed between the joining and the name. + let id = b.add(&b.url("h.m3u8"), "x.mp4"); + b.shared.store.save_parts(id, vec![Part { start: 0, end: None, done: 5000 }]).unwrap(); + std::fs::copy(&file, medlar_core::disk::partial_path(&b.dir.path().join("files"), "x.mp4")).unwrap(); + b.server.clear_log(); + let file = b.go(id, Choice::default()).await.end().await.unwrap(); + assert_eq!(file.file_name().unwrap(), "x.mp4"); + check(&file, LENGTH, &["h264", "aac"]); + assert!(b.server.log().is_empty()); +} + +#[tokio::test(flavor = "multi_thread")] +async fn another_list_is_not_mixed_in() { + let b = Bench::new().await; + b.make(HLS); + b.server.set_faults("/media/h*", Faults { latency_ms: Some(150), ..Faults::default() }); + let id = b.add(&b.url("h.m3u8"), ""); + let going = b.go(id, Choice::default()).await; + until("begun", || going.here() > 2_000).await; + going.stop().await; + let list = b.read("h.m3u8"); + b.write("h.m3u8", &list.replacen("#EXTINF", "#EXTINF:1,\nh0.ts\n#EXTINF", 1)); + assert!(matches!(b.go(id, Choice::default()).await.end().await, Err(Error::Changed))); +} + +#[tokio::test(flavor = "multi_thread")] +async fn pieces_are_tried_again() { + let b = Bench::new().await; + b.make(HLS); + b.server.set_faults("/media/h1.ts", Faults { status: Some(503), status_count: Some(2), ..Faults::default() }); + b.server.set_faults("/media/h2.ts", Faults { status: Some(500), status_count: Some(1), ..Faults::default() }); + let id = b.add(&b.url("h.m3u8"), ""); + let going = b.go(id, Choice::default()).await; + check(&going.end().await.unwrap(), LENGTH, &["h264", "aac"]); + assert_eq!(b.server.requests_for("/media/h1.ts").len(), 3); + + // One that never comes: the others are kept. + b.server.set_faults("/media/h3.ts", Faults { cut_after: Some(1000), ..Faults::default() }); + let id = b.add(&b.url("h.m3u8"), "two.mkv"); + let e = b.go(id, Choice::default()).await.end().await.unwrap_err(); + assert!(matches!(e, Error::Cut { .. }), "{e:?}"); + b.server.clear_all_faults(); + b.server.clear_log(); + let file = b.go(id, Choice::default()).await.end().await.unwrap(); + assert!(check(&file, LENGTH, &["h264", "aac"]).format.contains("matroska")); + assert!(b.server.requests_for("/media/h0.ts").is_empty()); + + for (status, wanted) in [(404, 404), (403, 403)] { + b.server.set_faults("/media/h3.ts", Faults::status(status)); + let e = b.get("h.m3u8", Choice::default()).await.unwrap_err(); + assert!(matches!(e, Error::Status { code, .. } if code == wanted), "{e:?}"); + } + let e = b.get("no.m3u8", Choice::default()).await.unwrap_err(); + assert!(matches!(e, Error::Status { code: 404, .. }), "{e:?}"); +} + +#[tokio::test(flavor = "multi_thread")] +async fn protected_and_false_ones() { + let b = Bench::new().await; + b.make(HLS); + let protected = "#EXT-X-KEY:METHOD=SAMPLE-AES,URI=\"skd://k\",KEYFORMAT=\"com.apple.streamingkeydelivery\"\n#EXTINF"; + let list = b.read("h.m3u8"); + b.write("fair.m3u8", &list.replacen("#EXTINF", protected, 1)); + assert_eq!(kind_of(b.get("fair.m3u8", Choice::default()).await), ErrorKind::Drm); + b.make(&["-an", "-encryption_scheme", "cenc-aes-ctr", "-encryption_key", "00112233445566778899aabbccddeeff", "-encryption_kid", "00112233445566778899aabbccddeeff", "-movflags", "frag_keyframe+empty_moov", "enc.mp4"]); + b.write("wide.mpd", r#""#); + assert_eq!(kind_of(b.get("wide.mpd", Choice::default()).await), ErrorKind::Drm); + // The list doesn't say so, but the piece does. + b.write("quiet.m3u8", "#EXTM3U\n#EXT-X-MAP:URI=\"enc.mp4\"\n#EXTINF:6,\nenc.mp4\n#EXT-X-ENDLIST\n"); + assert_eq!(kind_of(b.get("quiet.m3u8", Choice::default()).await), ErrorKind::Drm); + // Lists that pretend to be pieces don't get ffmpeg to open anything. + let secret = b.dir.path().join("secret.ts"); + std::fs::copy(b.media.join("h0.ts"), &secret).unwrap(); + let evil = [ + format!("#EXTM3U\n#EXT-X-TARGETDURATION:1\n#EXTINF:1,\nfile://{}\n#EXT-X-ENDLIST\n", secret.display()), + format!("ffconcat version 1.0\nfile '{}'\n", secret.display()), + format!("#EXTM3U\n#EXTINF:1,\n{}\n#EXT-X-ENDLIST\n", b.url("h5.ts")), + ]; + for text in evil { + b.write("evil.ts", &text); + for list in ["#EXTM3U\n#EXTINF:1,\nevil.ts\n#EXT-X-ENDLIST\n", "#EXTM3U\n#EXTINF:1,\nevil.ts\n#EXT-X-DISCONTINUITY\n#EXTINF:1,\nevil.ts\n#EXT-X-ENDLIST\n"] { + b.write("evil.m3u8", list); + assert_eq!(kind_of(b.get("evil.m3u8", Choice::default()).await), ErrorKind::Media, "{text}"); + } + } + assert!(b.server.requests_for("/media/h5.ts").is_empty()); + // No ffmpeg: nothing is downloaded. + let id = b.add(&b.url("h.m3u8"), ""); + let (_stop, stopped) = watch::channel(false); + let request = Request { id, source: Source::new(&b.url("h.m3u8")).unwrap(), choice: Choice::default(), tools: &Tools::default(), options: &b.options }; + b.server.clear_log(); + assert_eq!(kind_of(stream::download(&b.shared, request, &Monitor::new(1), stopped).await), ErrorKind::Tool); + assert!(b.server.log().is_empty()); +} + +/// A server of one RTSP stream: a tone, 50 packets a second, in real time. +struct Rtsp { + port: u16, + heard: Arc>>, +} + +impl Rtsp { + /// Ends after `seconds`, if any are given. + fn start(login: Option<&'static str>, seconds: Option) -> Rtsp { + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let port = listener.local_addr().unwrap().port(); + let heard = Arc::new(Mutex::new(vec![])); + let log = heard.clone(); + std::thread::spawn(move || { + for conn in listener.incoming() { + let (conn, log) = (conn.unwrap(), log.clone()); + std::thread::spawn(move || drop(Rtsp::serve(conn, login, seconds, &log))); + } + }); + Rtsp { port, heard } + } + + fn serve(conn: TcpStream, login: Option<&str>, seconds: Option, log: &Mutex>) -> std::io::Result<()> { + let mut out = conn.try_clone()?; + let mut lines = BufReader::new(conn).lines(); + loop { + let mut head: Vec = vec![]; + loop { + match lines.next() { + Some(Ok(line)) if line.is_empty() => break, + Some(Ok(line)) => head.push(line), + _ => return Ok(()), + } + } + let Some(request) = head.first() else { continue }; + log.lock().unwrap().push(request.clone()); + let of = |name: &str| head.iter().find_map(|l| l.strip_prefix(name)).map(str::to_string); + let seq = of("CSeq: ").unwrap_or_default(); + if login.is_some_and(|l| of("Authorization: Basic ").as_deref() != Some(l)) { + write!(out, "RTSP/1.0 401 Unauthorized\r\nCSeq: {seq}\r\nWWW-Authenticate: Basic realm=\"cam\"\r\n\r\n")?; + continue; + } + let sdp = "v=0\r\no=- 0 0 IN IP4 127.0.0.1\r\ns=x\r\nt=0 0\r\nm=audio 0 RTP/AVP 0\r\na=control:track1\r\n"; + let more = match request.split(' ').next().unwrap_or_default() { + "OPTIONS" => "Public: DESCRIBE, SETUP, PLAY, TEARDOWN\r\n\r\n".into(), + "DESCRIBE" => format!("Content-Type: application/sdp\r\nContent-Length: {}\r\n\r\n{sdp}", sdp.len()), + "SETUP" => "Transport: RTP/AVP/TCP;unicast;interleaved=0-1\r\nSession: 1\r\n\r\n".into(), + _ => "Session: 1\r\n\r\n".into(), + }; + write!(out, "RTSP/1.0 200 OK\r\nCSeq: {seq}\r\n{more}")?; + if request.starts_with("PLAY") { + let mut out = out.try_clone()?; + std::thread::spawn(move || { + let start = Instant::now(); + for n in 0u32.. { + if seconds.is_some_and(|s| f64::from(n) >= s * 50.0) { + return out.shutdown(std::net::Shutdown::Both); + } + let mut packet = vec![b'$', 0, 0, 172, 0x80, 0]; + packet.extend((n as u16).to_be_bytes()); + packet.extend((n * 160).to_be_bytes()); + packet.extend([0, 0, 0, 1]); + packet.extend([if n % 2 == 0 { 0x90 } else { 0x10 }; 160]); + out.write_all(&packet)?; + std::thread::sleep((ms(20) * (n + 1)).saturating_sub(start.elapsed())); + } + Ok(()) + }); + } + } + } + + fn url(&self) -> String { + format!("rtsp://127.0.0.1:{}/cam", self.port) + } +} + +#[tokio::test(flavor = "multi_thread")] +async fn rtsp_is_recorded() { + let b = Bench::new().await; + let server = Rtsp::start(None, None); + // Until it is told to end, with a pause. + let id = b.add(&server.url(), ""); + let going = b.go(id, Choice::default()).await; + until("recording", || going.here() > 10_000).await; + going.stop().await; + let before = b.shared.store.parts(id).unwrap()[0].done; + let going = b.go(id, Choice::default()).await; + until("recording again", || going.here() > before + 15_000).await; + going.monitor.finish(); + let file = going.end().await.unwrap(); + // Not one of the formats mp4 can hold. + assert_eq!(file.file_name().unwrap(), "cam.mkv"); + let seen = look(&file); + assert_eq!(seen.codecs, ["pcm_mulaw"]); + // 8000 bytes a second. + assert!(seen.seconds > 2.5 && seen.seconds < 20.0, "{}", seen.seconds); + + let timed = b.add(&server.url(), "timed"); + let file = b.go(timed, Choice { seconds: Some(2), ..Choice::default() }).await.end().await.unwrap(); + assert!((look(&file).seconds - 2.0).abs() < 0.3, "{}", look(&file).seconds); + let sized = b.add(&server.url(), "sized"); + let file = b.go(sized, Choice { bytes: Some(8_000), ..Choice::default() }).await.end().await.unwrap(); + let size = file.metadata().unwrap().len(); + assert!(size > 7_000 && size < 60_000, "{size}"); + // It ends by itself. + let short = Rtsp::start(None, Some(1.5)); + let id = b.add(&short.url(), "short"); + let file = b.go(id, Choice::default()).await.end().await.unwrap(); + assert!((look(&file).seconds - 1.5).abs() < 0.3, "{}", look(&file).seconds); + b.clean(4); + // Nobody there. + let gone = b.add(&format!("rtsp://127.0.0.1:{}/x", TcpListener::bind("127.0.0.1:0").unwrap().local_addr().unwrap().port()), ""); + assert_eq!(kind_of(b.go(gone, Choice::default()).await.end().await), ErrorKind::Refused); +} + +#[tokio::test(flavor = "multi_thread")] +async fn rtsp_logins_are_not_seen() { + let mut b = Bench::new().await; + // us%er:p'w x + let server = Rtsp::start(Some("dXMlZXI6cCd3IHg="), None); + let secrets = Arc::new(Secrets::new(Bus::Off)); + let settings = Settings { proxy: "direct".into(), ..Settings::default() }; + let sites = Sites::new(ClientOptions::default(), &settings, secrets.clone(), Bus::Off).unwrap(); + let login = Login { user: "us%er".into(), password: "p'w x".into() }; + let secret = Secret { home: Some(server.url()), login: Some(login), ..Secret::default() }; + let _ = secrets.save("cam", "cam", &secret).await; + b.sites = Some(sites.clone()); + let id = b.add(&server.url(), ""); + assert_eq!(kind_of(b.go(id, Choice::default()).await.end().await), ErrorKind::Login); + b.shared.store.edit_task(id, |t| t.secret = Some("cam".into())).unwrap(); + let going = b.go(id, Choice::default()).await; + until("recording", || going.here() > 5_000).await; + let mine: Vec = children().into_iter().filter(|args| args.contains(&format!(":{}/", server.port)) || args.contains("pipe:0")).collect(); + assert!(!mine.is_empty()); + assert!(mine.iter().all(|args| !args.contains("er:") && !args.contains("p%27w") && !args.contains("p'w")), "{mine:?}"); + going.monitor.finish(); + assert_eq!(look(&going.end().await.unwrap()).codecs, ["pcm_mulaw"]); + + // Never around a proxy. + server.heard.lock().unwrap().clear(); + sites.set(&Settings { proxy: "socks5://127.0.0.1:9".into(), proxy_bypass: vec![], ..Settings::default() }); + let id = b.add(&server.url(), ""); + assert_eq!(kind_of(b.go(id, Choice::default()).await.end().await), ErrorKind::Proxy); + assert!(server.heard.lock().unwrap().is_empty()); +} + +/// The arguments of our child processes. +fn children() -> Vec { + let me = std::process::id(); + let mut found = vec![]; + for entry in std::fs::read_dir("/proc").unwrap().flatten() { + let stat = std::fs::read_to_string(entry.path().join("stat")).unwrap_or_default(); + let parent = stat.rsplit(')').next().and_then(|s| s.split_whitespace().nth(1)).and_then(|p| p.parse::().ok()); + if parent == Some(me) { + found.push(std::fs::read_to_string(entry.path().join("cmdline")).unwrap_or_default().replace('\0', " ")); + } + } + found +} + +/// MMS over HTTP: the header, then the packets of an ASF file. +fn mms_server(asf: Vec) -> u16 { + let long = |at: usize| u64::from_le_bytes(asf[at..at + 8].try_into().unwrap()) as usize; + let header = long(16) + 50; + let end = long(16) + long(long(16) + 16); + let packets: Vec> = asf[header..end].chunks(3200).map(<[u8]>::to_vec).collect(); + let header = asf[..header].to_vec(); + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let port = listener.local_addr().unwrap().port(); + let chunk = |kind: u8, n: u32, data: &[u8]| { + let len = (data.len() as u16 + 8).to_le_bytes(); + [&[b'$', kind][..], &len, &n.to_le_bytes(), &[0, 0x0c], &len, data].concat() + }; + std::thread::spawn(move || { + for conn in listener.incoming() { + let mut conn = conn.unwrap(); + let mut head = vec![]; + let mut byte = [0]; + while !head.ends_with(b"\r\n\r\n") && conn.read(&mut byte).unwrap_or(0) == 1 { + head.push(byte[0]); + } + let text = String::from_utf8_lossy(&head).into_owned(); + let _ = conn.write_all(b"HTTP/1.0 200 OK\r\nContent-Type: application/x-mms-framed\r\nPragma: client-id=1\r\n\r\n"); + let _ = conn.write_all(&chunk(b'H', 0, &header)); + if text.contains("xPlayStrm=1") { + for (i, p) in packets.iter().enumerate() { + let _ = conn.write_all(&chunk(b'D', i as u32, p)); + } + let _ = conn.write_all(&[b'$', b'E', 4, 0, 0, 0, 0, 0]); + } + } + }); + port +} + +#[tokio::test(flavor = "multi_thread")] +async fn mms_is_recorded() { + let b = Bench::new().await; + ffmpeg(&b.media, &["-f", "lavfi", "-i", "testsrc=size=160x120:rate=10:duration=6", "-f", "lavfi", "-i", "sine=440:duration=6", "-c:v", "wmv2", "-c:a", "wmav2", "-f", "asf", "a.wmv"]); + let port = mms_server(std::fs::read(b.media.join("a.wmv")).unwrap()); + let id = b.add(&format!("mms://127.0.0.1:{port}/a.wmv"), ""); + let file = b.go(id, Choice::default()).await.end().await.unwrap(); + let seen = look(&file); + assert!((seen.seconds - LENGTH).abs() < 0.3, "{}", seen.seconds); + assert_eq!(seen.codecs, ["wmv2", "wmav2"]); + assert!(seen.packets > 60); +} + +#[tokio::test(flavor = "multi_thread")] +async fn the_manager_knows_streams() { + use medlar_core::manager::{Bin, Command, Config, Manager}; + use medlar_core::settings::Limits; + let b = Bench::new().await; + b.make(HLS); + let limits = Limits { speed: 0, max_active: 4, max_connections: 32, parts_per_download: 4, connections_per_host: 16 }; + let dir = tempfile::tempdir().unwrap(); + let mut config = Config::new(Bench::shared(dir.path()), limits); + (config.options, config.bin, config.tick) = (b.options.clone(), Bin::at(dir.path().join("Trash")), ms(20)); + let manager = Manager::open(config).unwrap(); + let add = async |url: String| { + let task = Task { url, folder: dir.path().join("files"), ..Task::default() }; + manager.send(Command::Add(Box::new(task))).await.unwrap() + }; + let view = |id| manager.snapshot().get(id).unwrap().clone(); + let state = async |id, state| until(&format!("{state:?}"), || view(id).state() == state).await; + + let film = add(b.url("h.m3u8")).await; + state(film, State::Done).await; + assert_eq!(view(film).task.name, "h.mp4"); + check(&dir.path().join("files/h.mp4"), LENGTH, &["h264", "aac"]); + assert_eq!(view(film).size, Some(dir.path().join("files/h.mp4").metadata().unwrap().len())); + + // Live: paused, moved with what there is, and ended. + let list = b.read("h.m3u8").replace("#EXT-X-ENDLIST\n", ""); + b.write("live.m3u8", &list); + let live = add(b.url("live.m3u8")).await; + until("recorded", || view(live).downloaded > 2_000 && view(live).connections == 0).await; + manager.send(Command::Pause(live)).await.unwrap(); + state(live, State::Paused).await; + manager.send(Command::Rename { id: live, name: "mine.mp4".into() }).await.unwrap(); + manager.send(Command::Finish(live)).await.unwrap(); + state(live, State::Done).await; + check(&dir.path().join("files/mine.mp4"), 3.0, &["h264", "aac"]); + + let camera = Rtsp::start(None, None); + let cam = add(camera.url()).await; + until("recording", || view(cam).downloaded > 10_000).await; + manager.send(Command::Finish(cam)).await.unwrap(); + state(cam, State::Done).await; + assert_eq!(view(cam).task.name, "cam.mkv"); + + b.write("fair.m3u8", "#EXTM3U\n#EXT-X-KEY:METHOD=SAMPLE-AES,URI=\"skd://k\"\n#EXTINF:1,\nh0.ts\n"); + let fair = add(b.url("fair.m3u8")).await; + state(fair, State::Failed).await; + let error = view(fair).task.error.clone().unwrap(); + assert_eq!(error.kind, Some(ErrorKind::Drm)); + assert!(error.detail.starts_with("Copy protected"), "{}", error.detail); + manager.send(Command::Finish(fair)).await.unwrap(); + manager.close(); +} diff --git a/docs/RECOVERY.md b/docs/RECOVERY.md index d91df29..cfaa154 100644 --- a/docs/RECOVERY.md +++ b/docs/RECOVERY.md @@ -38,6 +38,9 @@ Title and text: `error.` and `error..why` in the catalogue; button: | `changed` | File changed on the server | blocked | no | Choose (`choose`) | | `no_resume` | Can't be continued | blocked | no | Choose (`choose`) | | `killed` | Interrupted | passing | no | Resume (`resume`) | +| `drm` | Copy protected | blocked | no | Edit link (`edit_link`) | +| `tool` | A program is missing | blocked | no | Try again (`try_again`) | +| `media` | Stream can't be saved | serious | no | Try again (`try_again`) | | `tls` | Secure connection failed | serious | no | Try again (`try_again`) | | `disk` | Disk error | serious | later 30–600 s | Change folder (`change_folder`) | | `list` | Download list not saved | serious | later 30–600 s | Try again (`try_again`) |