Merge remote-tracking branch 'origin/main' into worktree-agent-a3fe67eb0bcf4cbce
Browse files at this commit13 changed files +2095 -103
- crates/app/src/main.rs +237 -10
- crates/engine/src/audio.rs +117 -3
- crates/engine/src/decode.rs +1 -1
- crates/engine/src/edith.rs +7 -4
- crates/engine/src/export.rs +250 -1
- crates/engine/src/limiter.rs +91 -1
- crates/engine/src/mux.rs +142 -1
- crates/engine/src/playback.rs +457 -76
- crates/engine/src/project.rs +66 -3
- crates/engine/tests/export_subs.rs +295 -0
- crates/engine/tests/invalidation.rs +308 -0
- crates/engine/tests/mixed_fps.rs +109 -0
- crates/engine/tests/playback.rs +15 -3
crates/app/src/main.rsmodified+237 -10
| @@ -430,6 +430,7 @@ struct Picker { | |||
| 430 | #[derive(Clone, Copy, PartialEq, Eq, Debug)] | 430 | #[derive(Clone, Copy, PartialEq, Eq, Debug)] |
| 431 | enum Pick { | 431 | enum Pick { |
| 432 | Resolution, | 432 | Resolution, |
| 433 | + Fps, | ||
| 433 | Fit(Lane, usize), | 434 | Fit(Lane, usize), |
| 434 | /// What the export's *sound* is coded at. Opened from the card's Sound row, | 435 | /// What the export's *sound* is coded at. Opened from the card's Sound row, |
| 435 | /// which is the only place it means anything. | 436 | /// which is the only place it means anything. |
| @@ -439,9 +440,13 @@ enum Pick { | |||
| 439 | /// One value a list offers, carrying everything picking it needs -- so a click | 440 | /// One value a list offers, carrying everything picking it needs -- so a click |
| 440 | /// goes straight to the value rather than to a position in a list that was | 441 | /// goes straight to the value rather than to a position in a list that was |
| 441 | /// built somewhere else. | 442 | /// built somewhere else. |
| 442 | -#[derive(Clone, Copy, PartialEq, Eq, Debug)] | 443 | +/// `Eq` is off it for the rate: a frame rate is the `f64` the engine is told, |
| 444 | +/// bit for bit (23.976023976... is not 23.976), and nothing here keys a map on a | ||
| 445 | +/// choice -- comparing two is all a list row ever does. | ||
| 446 | +#[derive(Clone, Copy, PartialEq, Debug)] | ||
| 443 | enum Choice { | 447 | enum Choice { |
| 444 | Size(u32, u32), | 448 | Size(u32, u32), |
| 449 | + Fps(f64), | ||
| 445 | Fit(Lane, usize, FitPolicy), | 450 | Fit(Lane, usize, FitPolicy), |
| 446 | AudioRate(u32), | 451 | AudioRate(u32), |
| 447 | } | 452 | } |
| @@ -622,6 +627,23 @@ fn typed(key: &str) -> Option<char> { | |||
| 622 | /// them, which is what makes the trip round come back to where it started. | 627 | /// them, which is what makes the trip round come back to where it started. |
| 623 | const RESOLUTIONS: [(u32, u32); 4] = [(3840, 2160), (1920, 1080), (1280, 720), (854, 480)]; | 628 | const RESOLUTIONS: [(u32, u32); 4] = [(3840, 2160), (1920, 1080), (1280, 720), (854, 480)]; |
| 624 | 629 | ||
| 630 | +/// The project frame rates the list offers, slowest first: the rates footage is | ||
| 631 | +/// actually shot and delivered at, the NTSC ones written as the ratios they are | ||
| 632 | +/// (`24000/1001`, not `23.976`) -- the engine conforms the timeline to the very | ||
| 633 | +/// number it is handed, so a rate rounded here would be a rate no timescale can | ||
| 634 | +/// name. The media's own is cycled in beside them | ||
| 635 | +/// ([`frame_rate_ladder`]), which is what keeps the way back on the list. | ||
| 636 | +const FRAME_RATES: [f64; 8] = [ | ||
| 637 | + 24_000. / 1001., | ||
| 638 | + 24., | ||
| 639 | + 25., | ||
| 640 | + 30_000. / 1001., | ||
| 641 | + 30., | ||
| 642 | + 50., | ||
| 643 | + 60_000. / 1001., | ||
| 644 | + 60., | ||
| 645 | +]; | ||
| 646 | + | ||
| 625 | /// How far a band may be pushed either way, in dB. The engine clamps nothing | 647 | /// How far a band may be pushed either way, in dB. The engine clamps nothing |
| 626 | /// here -- it will filter whatever it is given -- so this is a UI decision: | 648 | /// here -- it will filter whatever it is given -- so this is a UI decision: |
| 627 | /// past about this a peaking band stops sounding like tone and starts sounding | 649 | /// past about this a peaking band stops sounding like tone and starts sounding |
| @@ -1696,6 +1718,23 @@ impl Player { | |||
| 1696 | cx.notify(); | 1718 | cx.notify(); |
| 1697 | } | 1719 | } |
| 1698 | 1720 | ||
| 1721 | + /// The project cut at another rate: the list names one and this is where it | ||
| 1722 | + /// happens, the way [`apply_resolution`](Self::apply_resolution) is for a | ||
| 1723 | + /// size. The whole timeline is conformed to it by the engine | ||
| 1724 | + /// ([`PlaybackSession::set_frame_rate`]) -- same seconds, same footage -- | ||
| 1725 | + /// and the rate the app itself counts frames in follows, since every | ||
| 1726 | + /// timecode, ruler mark and step key here is measured in it. | ||
| 1727 | + fn apply_frame_rate(&mut self, fps: f64, cx: &mut Context<Self>) { | ||
| 1728 | + if let Some(session) = &mut self.session | ||
| 1729 | + && session.set_frame_rate(fps) | ||
| 1730 | + { | ||
| 1731 | + self.fps = session.meta().frame_rate; | ||
| 1732 | + self.notice = Some(format!("PROJECT: {} fps", fps_label(fps)).into()); | ||
| 1733 | + self.reset_after_reseek(); | ||
| 1734 | + } | ||
| 1735 | + cx.notify(); | ||
| 1736 | + } | ||
| 1737 | + | ||
| 1699 | /// Opens a choice list on a setting, where it was asked for. One floating | 1738 | /// Opens a choice list on a setting, where it was asked for. One floating |
| 1700 | /// thing at a time: the click that opens it is the click that closes | 1739 | /// thing at a time: the click that opens it is the click that closes |
| 1701 | /// whatever menu it was opened from. | 1740 | /// whatever menu it was opened from. |
| @@ -1713,6 +1752,7 @@ impl Player { | |||
| 1713 | self.picker = None; | 1752 | self.picker = None; |
| 1714 | match choice { | 1753 | match choice { |
| 1715 | Choice::Size(w, h) => self.apply_resolution(w, h, cx), | 1754 | Choice::Size(w, h) => self.apply_resolution(w, h, cx), |
| 1755 | + Choice::Fps(fps) => self.apply_frame_rate(fps, cx), | ||
| 1716 | Choice::Fit(lane, idx, fit) => self.apply_fit(lane, idx, fit, cx), | 1756 | Choice::Fit(lane, idx, fit) => self.apply_fit(lane, idx, fit, cx), |
| 1717 | // The same field the row's key steps, set outright: a list picks a | 1757 | // The same field the row's key steps, set outright: a list picks a |
| 1718 | // value, it does not step to one. | 1758 | // value, it does not step to one. |
| @@ -1734,6 +1774,7 @@ impl Player { | |||
| 1734 | Pick::Resolution => { | 1774 | Pick::Resolution => { |
| 1735 | resolution_choices(session.resolution(), session.native_resolution()) | 1775 | resolution_choices(session.resolution(), session.native_resolution()) |
| 1736 | } | 1776 | } |
| 1777 | + Pick::Fps => fps_choices(session.meta().frame_rate, session.native_frame_rate()), | ||
| 1737 | Pick::Fit(lane, idx) => { | 1778 | Pick::Fit(lane, idx) => { |
| 1738 | fit_choices(lane, idx, session.fit_of(lane, idx), session.resolution()) | 1779 | fit_choices(lane, idx, session.fit_of(lane, idx), session.resolution()) |
| 1739 | } | 1780 | } |
| @@ -2043,8 +2084,11 @@ impl Player { | |||
| 2043 | /// ceiling by the same, and the switch either way (a ring of two, like the | 2084 | /// ceiling by the same, and the switch either way (a ring of two, like the |
| 2044 | /// silence card's unit row). | 2085 | /// silence card's unit row). |
| 2045 | /// | 2086 | /// |
| 2046 | - /// Every one of them goes through the session, so it reseeks: what the ear | 2087 | + /// Every one of them goes through the session, which hands it straight to |
| 2047 | - /// hears while the arrow is held is the mix that is being set. | 2088 | + /// the running mixer: what the ear hears while the arrow is held is the mix |
| 2089 | + /// that is being set, and nothing is rebuilt to make that true -- no reseek, | ||
| 2090 | + /// so no `reset_after_reseek` and no blink in the picture behind the card | ||
| 2091 | + /// ([`engine::PlaybackSession::set_lane_gain_db`]). | ||
| 2048 | fn nudge_mix(&mut self, steps: i32, cx: &mut Context<Self>) { | 2092 | fn nudge_mix(&mut self, steps: i32, cx: &mut Context<Self>) { |
| 2049 | let lanes = self.mix_lanes(); | 2093 | let lanes = self.mix_lanes(); |
| 2050 | let Some(session) = self.session.as_mut() else { | 2094 | let Some(session) = self.session.as_mut() else { |
| @@ -4165,8 +4209,13 @@ impl Player { | |||
| 4165 | if self.export.is_some() { | 4209 | if self.export.is_some() { |
| 4166 | return; | 4210 | return; |
| 4167 | } | 4211 | } |
| 4168 | - let settings = | 4212 | + let mut settings = |
| 4169 | export_settings(self.quality, self.custom_mbps, self.format, self.audio_kbps); | 4213 | export_settings(self.quality, self.custom_mbps, self.format, self.audio_kbps); |
| 4214 | + // The track the library has picked is the one that travels -- the same | ||
| 4215 | + // row the overlay draws, so the file carries what was watched. Set here | ||
| 4216 | + // rather than inside `export_settings`, which the card also calls for | ||
| 4217 | + // the *estimate* and which nothing else needs a subtitle for. | ||
| 4218 | + settings.subtitles = Some(self.sub_track); | ||
| 4170 | let Some(session) = &mut self.session else { | 4219 | let Some(session) = &mut self.session else { |
| 4171 | self.notice = Some("NOTHING TO EXPORT — open a file first".into()); | 4220 | self.notice = Some("NOTHING TO EXPORT — open a file first".into()); |
| 4172 | cx.notify(); | 4221 | cx.notify(); |
| @@ -5279,11 +5328,17 @@ impl Player { | |||
| 5279 | /// `None` -- no element at all -- while the toggle is off, with no track | 5328 | /// `None` -- no element at all -- while the toggle is off, with no track |
| 5280 | /// picked, and between cues: the picture is what this window is for, and a | 5329 | /// picked, and between cues: the picture is what this window is for, and a |
| 5281 | /// permanent empty band across it would be in the way of exactly that. | 5330 | /// permanent empty band across it would be in the way of exactly that. |
| 5331 | + /// | ||
| 5332 | + /// The cues are the *timeline's* ([`PlaybackSession::timeline_cues`]) and | ||
| 5333 | + /// not the track's own: on a cut timeline an embedded track's cues ride the | ||
| 5334 | + /// pictures they belong to, and this is the same map the export writes the | ||
| 5335 | + /// file with -- so what is read here is what the file says. | ||
| 5282 | fn subtitle_overlay(&self, at: f64) -> Option<impl IntoElement + use<>> { | 5336 | fn subtitle_overlay(&self, at: f64) -> Option<impl IntoElement + use<>> { |
| 5283 | if !self.subs_on { | 5337 | if !self.subs_on { |
| 5284 | return None; | 5338 | return None; |
| 5285 | } | 5339 | } |
| 5286 | - let cues = cues_at(&self.subtitle_track()?.cues, at); | 5340 | + let mapped = self.session.as_ref()?.timeline_cues(self.sub_track); |
| 5341 | + let cues = cues_at(&mapped, at); | ||
| 5287 | if cues.is_empty() { | 5342 | if cues.is_empty() { |
| 5288 | return None; | 5343 | return None; |
| 5289 | } | 5344 | } |
| @@ -5599,6 +5654,30 @@ impl Player { | |||
| 5599 | this.open_picker(Pick::Resolution, event.position(), cx) | 5654 | this.open_picker(Pick::Resolution, event.position(), cx) |
| 5600 | }), | 5655 | }), |
| 5601 | )) | 5656 | )) |
| 5657 | + // The rate every clip is counted in, which is also the rate | ||
| 5658 | + // the export is written at -- the other half of "the project | ||
| 5659 | + // is not the media", and the one the panel could only ever | ||
| 5660 | + // read out before. A click opens the rates with this one | ||
| 5661 | + // marked; picking one conforms the whole timeline to it. | ||
| 5662 | + .child(control( | ||
| 5663 | + "fps", | ||
| 5664 | + None, | ||
| 5665 | + match self.session.is_some() { | ||
| 5666 | + true => format!("{} fps", fps_label(self.fps)), | ||
| 5667 | + false => "Rate".to_string(), | ||
| 5668 | + }, | ||
| 5669 | + match self.session.is_some() { | ||
| 5670 | + true => format!( | ||
| 5671 | + "click to pick a frame rate — the project is cut at {} fps", | ||
| 5672 | + fps_label(self.fps) | ||
| 5673 | + ), | ||
| 5674 | + false => "the project's frame rate — open a file first".to_string(), | ||
| 5675 | + }, | ||
| 5676 | + live, | ||
| 5677 | + cx.listener(|this, event: &ClickEvent, _, cx| { | ||
| 5678 | + this.open_picker(Pick::Fps, event.position(), cx) | ||
| 5679 | + }), | ||
| 5680 | + )) | ||
| 5602 | // How much of the timeline the panel below is showing -- | 5681 | // How much of the timeline the panel below is showing -- |
| 5603 | // beside the resolution, since neither of them edits | 5682 | // beside the resolution, since neither of them edits |
| 5604 | // anything: they are both what is being looked at. The | 5683 | // anything: they are both what is being looked at. The |
| @@ -6453,6 +6532,27 @@ impl Player { | |||
| 6453 | })); | 6532 | })); |
| 6454 | } | 6533 | } |
| 6455 | list.push(r.into_any_element()); | 6534 | list.push(r.into_any_element()); |
| 6535 | + // What happens to the picked subtitle track, in one line: it is written | ||
| 6536 | + // into the file, or the reason it is not. Nothing to pick here -- which | ||
| 6537 | + // track is the library's row and the container is the format row above | ||
| 6538 | + // -- so the row says and does not answer, like the machine lines below. | ||
| 6539 | + list.push( | ||
| 6540 | + entry( | ||
| 6541 | + ("subtitles", 0), | ||
| 6542 | + "", | ||
| 6543 | + "Subtitles".into(), | ||
| 6544 | + self.session | ||
| 6545 | + .as_ref() | ||
| 6546 | + .map_or_else( | ||
| 6547 | + || "none".into(), | ||
| 6548 | + |s| s.planned_subtitles(self.format, Some(self.sub_track)), | ||
| 6549 | + ) | ||
| 6550 | + .into(), | ||
| 6551 | + false, | ||
| 6552 | + false, | ||
| 6553 | + ) | ||
| 6554 | + .into_any_element(), | ||
| 6555 | + ); | ||
| 6456 | let destination = entry( | 6556 | let destination = entry( |
| 6457 | ("destination", 0), | 6557 | ("destination", 0), |
| 6458 | "d", | 6558 | "d", |
| @@ -8298,7 +8398,17 @@ impl Player { | |||
| 8298 | ), | 8398 | ), |
| 8299 | } | 8399 | } |
| 8300 | .into(); | 8400 | .into(); |
| 8301 | - let cues: Vec<(f32, f32)> = track.cues.iter().map(|cue| cue_box(scale, cue)).collect(); | 8401 | + // Where the cues are on *this* timeline and not in the file they came |
| 8402 | + // from ([`PlaybackSession::timeline_cues`]) -- the same map the plate | ||
| 8403 | + // over the picture and the export both go through, which is what keeps | ||
| 8404 | + // a mark under the take it is spoken over after a cut. | ||
| 8405 | + let cues: Vec<(f32, f32)> = self | ||
| 8406 | + .session | ||
| 8407 | + .as_ref()? | ||
| 8408 | + .timeline_cues(self.sub_track) | ||
| 8409 | + .iter() | ||
| 8410 | + .map(|cue| cue_box(scale, cue)) | ||
| 8411 | + .collect(); | ||
| 8302 | Some( | 8412 | Some( |
| 8303 | div() | 8413 | div() |
| 8304 | .flex_none() | 8414 | .flex_none() |
| @@ -10035,6 +10145,53 @@ fn resolution_choices(current: (u32, u32), native: (u32, u32)) -> Vec<ChoiceRow> | |||
| 10035 | .collect() | 10145 | .collect() |
| 10036 | } | 10146 | } |
| 10037 | 10147 | ||
| 10148 | +/// Every project frame rate on offer, slowest first: [`FRAME_RATES`] with the | ||
| 10149 | +/// media's own cycled in at its place by speed, so a project already cut at a | ||
| 10150 | +/// listed rate does not see it twice and the media's own rate -- the one a | ||
| 10151 | +/// project moved off it has no other way back to -- is always there. | ||
| 10152 | +/// [`resolution_ladder`]'s rule, for the other setting the project has of its | ||
| 10153 | +/// own. | ||
| 10154 | +fn frame_rate_ladder(native: f64) -> Vec<f64> { | ||
| 10155 | + let mut rates = FRAME_RATES.to_vec(); | ||
| 10156 | + // Bit for bit: 23.976023976... is not 23.976, and a rate that read as | ||
| 10157 | + // "already listed" when it is not would take the media's own off the list. | ||
| 10158 | + if !rates.contains(&native) { | ||
| 10159 | + let at = rates | ||
| 10160 | + .iter() | ||
| 10161 | + .position(|&fps| fps > native) | ||
| 10162 | + .unwrap_or(rates.len()); | ||
| 10163 | + rates.insert(at, native); | ||
| 10164 | + } | ||
| 10165 | + rates | ||
| 10166 | +} | ||
| 10167 | + | ||
| 10168 | +/// The rate list's rows: every rung of the ladder, the media's own said so, and | ||
| 10169 | +/// the one in force marked. Named as a person writes a rate ([`fps_label`]), | ||
| 10170 | +/// with what it is for beside it -- short, or the row loses its tail to the | ||
| 10171 | +/// truncation the resolution list already met. | ||
| 10172 | +fn fps_choices(current: f64, native: f64) -> Vec<ChoiceRow> { | ||
| 10173 | + frame_rate_ladder(native) | ||
| 10174 | + .into_iter() | ||
| 10175 | + .map(|fps| { | ||
| 10176 | + ( | ||
| 10177 | + Choice::Fps(fps), | ||
| 10178 | + format!("{} fps", fps_label(fps)).into(), | ||
| 10179 | + match fps == native { | ||
| 10180 | + true => "the media's own".to_string(), | ||
| 10181 | + // The rates that are a ratio are the ones nobody can tell | ||
| 10182 | + // from their neighbour by the label alone. | ||
| 10183 | + false => match (fps - fps.round()).abs() < 0.001 { | ||
| 10184 | + true => String::new(), | ||
| 10185 | + false => "NTSC".to_string(), | ||
| 10186 | + }, | ||
| 10187 | + } | ||
| 10188 | + .into(), | ||
| 10189 | + fps == current, | ||
| 10190 | + ) | ||
| 10191 | + }) | ||
| 10192 | + .collect() | ||
| 10193 | +} | ||
| 10194 | + | ||
| 10038 | /// The fit list's rows: all four policies against the canvas they place a | 10195 | /// The fit list's rows: all four policies against the canvas they place a |
| 10039 | /// picture on, since the word alone ("fill") says nothing about the size it is | 10196 | /// picture on, since the word alone ("fill") says nothing about the size it is |
| 10040 | /// filling -- which is the very thing the notice says after a stroke. | 10197 | /// filling -- which is the very thing the notice says after a stroke. |
| @@ -10212,6 +10369,10 @@ fn export_settings( | |||
| 10212 | // badly, which is a thing about the machine and not about the output -- | 10369 | // badly, which is a thing about the machine and not about the output -- |
| 10213 | // `VE_SW_ENC` already says it, and to the whole run rather than once. | 10370 | // `VE_SW_ENC` already says it, and to the whole run rather than once. |
| 10214 | force_sw: false, | 10371 | force_sw: false, |
| 10372 | + // The picked track is put on by `start_export`, which is the only | ||
| 10373 | + // caller that writes a file; the rest of them are asking about the | ||
| 10374 | + // bitrate and the format. | ||
| 10375 | + subtitles: None, | ||
| 10215 | } | 10376 | } |
| 10216 | } | 10377 | } |
| 10217 | 10378 | ||
| @@ -11638,7 +11799,8 @@ mod tests { | |||
| 11638 | containers, | 11799 | containers, |
| 11639 | enable, envelope, eq_card_w, eq_freq, eq_freq_label, eq_spectrum, eq_x, eq_y, | 11800 | enable, envelope, eq_card_w, eq_freq, eq_freq_label, eq_spectrum, eq_x, eq_y, |
| 11640 | estimated_mb, export_path, export_settings, format_key, | 11801 | estimated_mb, export_path, export_settings, format_key, |
| 11641 | - format_line, format_refusal, fps_label, frac_along, frac_down, frame_at, histogram, | 11802 | + format_line, format_refusal, fps_choices, fps_label, frac_along, frac_down, frame_at, |
| 11803 | + frame_rate_ladder, histogram, | ||
| 11642 | inserted_band, is_bare_modifier, is_project, keymap, keys_filter, keys_rows, lanes_h, | 11804 | inserted_band, is_bare_modifier, is_project, keymap, keys_filter, keys_rows, lanes_h, |
| 11643 | marked, menu_at, next_audio_kbps, next_container, normalise, nothing_to_play, panel_h, project_path, | 11805 | marked, menu_at, next_audio_kbps, next_container, normalise, nothing_to_play, panel_h, project_path, |
| 11644 | retarget, scrub_due, show_label, silence_rate, snap_cue, snap_marks, snapped, | 11806 | retarget, scrub_due, show_label, silence_rate, snap_cue, snap_marks, snapped, |
| @@ -11647,7 +11809,8 @@ mod tests { | |||
| 11647 | whole_take, window_title, | 11809 | whole_take, window_title, |
| 11648 | }; | 11810 | }; |
| 11649 | use super::{ | 11811 | use super::{ |
| 11650 | - Choice, ETA_SPAN, Edge, FITS, LaneKind, PPS_DEFAULT, RESOLUTIONS, Repeat, Scale, View, | 11812 | + Choice, ETA_SPAN, Edge, FITS, FRAME_RATES, LaneKind, PPS_DEFAULT, RESOLUTIONS, Repeat, |
| 11813 | + Scale, View, | ||
| 11651 | ZOOM_MAX_SECONDS, ZOOM_MIN_FRAMES, ZOOM_STEP, audio_rate_choices, clock, eta_secs, file_name, file_uri, | 11814 | ZOOM_MAX_SECONDS, ZOOM_MIN_FRAMES, ZOOM_STEP, audio_rate_choices, clock, eta_secs, file_name, file_uri, |
| 11652 | fit_choices, landing, lane_refuses, library_rows, live_idx, next_fit, next_resolution, | 11815 | fit_choices, landing, lane_refuses, library_rows, live_idx, next_fit, next_resolution, |
| 11653 | note_progress, px_along, | 11816 | note_progress, px_along, |
| @@ -14584,10 +14747,35 @@ mod tests { | |||
| 14584 | assert!(fits[2].3, "the clip's own policy is not marked"); | 14747 | assert!(fits[2].3, "the clip's own policy is not marked"); |
| 14585 | assert!(fits[0].2.contains("1920x1080"), "{}", fits[0].2); | 14748 | assert!(fits[0].2.contains("1920x1080"), "{}", fits[0].2); |
| 14586 | 14749 | ||
| 14750 | + // The rate list, the other setting the project has of its own: every | ||
| 14751 | + // rate on offer, the media's own cycled in at its place by speed and | ||
| 14752 | + // said so, and the one the timeline is cut at marked. The value carried | ||
| 14753 | + // is the `f64` the engine conforms to, not the rounded label -- 23.976 | ||
| 14754 | + // is not 24000/1001, and a rate the timescales cannot name is refused. | ||
| 14755 | + let ntsc = 24_000. / 1001.; | ||
| 14756 | + let rates = frame_rate_ladder(25.); | ||
| 14757 | + assert_eq!(rates.len(), FRAME_RATES.len(), "25 is already on the list"); | ||
| 14758 | + let odd = frame_rate_ladder(48.); | ||
| 14759 | + assert_eq!(odd[5], 48., "the media's own, in its place by speed"); | ||
| 14760 | + assert_eq!(odd.len(), FRAME_RATES.len() + 1); | ||
| 14761 | + let fps = fps_choices(ntsc, 48.); | ||
| 14762 | + assert_eq!(fps.len(), odd.len()); | ||
| 14763 | + assert_eq!(fps.iter().filter(|(.., picked)| *picked).count(), 1); | ||
| 14764 | + assert_eq!(fps[0].0, Choice::Fps(ntsc), "the ratio, not 23.976"); | ||
| 14765 | + assert_eq!(fps[0].1.as_ref(), "23.976 fps"); | ||
| 14766 | + assert!(fps[0].3, "the rate in force is not marked"); | ||
| 14767 | + assert!(fps[5].2.contains("the media's own"), "{}", fps[5].2); | ||
| 14768 | + for (.., detail, _) in &fps { | ||
| 14769 | + assert!(detail.chars().count() < 26, "{detail} loses its tail"); | ||
| 14770 | + } | ||
| 14771 | + | ||
| 14587 | // The open list fits the floor the menus are measured against: the | 14772 | // The open list fits the floor the menus are measured against: the |
| 14588 | - // longest of them is the resolution ladder, and it hangs at the pointer | 14773 | + // longest of them is the rate ladder with an odd rate cycled in, and it |
| 14589 | - // with every row on screen. Rows are click targets (WCAG 2.5.8). | 14774 | + // hangs at the pointer with every row on screen. Rows are click targets |
| 14775 | + // (WCAG 2.5.8). | ||
| 14590 | assert!(MENU_ROW_H >= HIT_MIN); | 14776 | assert!(MENU_ROW_H >= HIT_MIN); |
| 14777 | + assert!(odd.len() > ladder.len(), "the longest list moved"); | ||
| 14778 | + assert!(MENU_PAD * 2. + odd.len() as f32 * MENU_ROW_H <= 360.); | ||
| 14591 | let tall = MENU_PAD * 2. + ladder.len() as f32 * MENU_ROW_H; | 14779 | let tall = MENU_PAD * 2. + ladder.len() as f32 * MENU_ROW_H; |
| 14592 | assert!(tall <= 360., "the list is taller than the floor"); | 14780 | assert!(tall <= 360., "the list is taller than the floor"); |
| 14593 | assert_eq!( | 14781 | assert_eq!( |
| @@ -15171,6 +15359,45 @@ mod tests { | |||
| 15171 | }; | 15359 | }; |
| 15172 | assert!(subtitle_detail(&refused).contains("pictures")); | 15360 | assert!(subtitle_detail(&refused).contains("pictures")); |
| 15173 | assert!(cues_at(&refused.cues, 1.).is_empty()); | 15361 | assert!(cues_at(&refused.cues, 1.).is_empty()); |
| 15362 | + | ||
| 15363 | + // ...and what the plate and the strip draw after a *cut*: the timeline's | ||
| 15364 | + // own clock, asked of the engine through the very map an export writes | ||
| 15365 | + // the file with (`PlaybackSession::timeline_cues`), so the preview and | ||
| 15366 | + // the file cannot drift apart. The numbers are the export's own | ||
| 15367 | + // (`export::a_subtitle_file_beside_the_media_keeps_the_timelines_own_ | ||
| 15368 | + // clock`): 0.5s..2.5s rippled out of a five-second timeline leaves | ||
| 15369 | + // three seconds, which clips the second cue and takes the third away | ||
| 15370 | + // altogether -- while the track itself still holds all three, which is | ||
| 15371 | + // exactly why the drawing may not read them straight. | ||
| 15372 | + let lanes = session.lanes(); | ||
| 15373 | + session | ||
| 15374 | + .cut_regions(&[(15, 60)], &lanes) | ||
| 15375 | + .expect("cut 0.5s..2.5s out"); | ||
| 15376 | + assert_eq!(session.timeline_duration(), 3.0); | ||
| 15377 | + assert_eq!(session.subtitles()[0].cues.len(), 3, "the track is untouched"); | ||
| 15378 | + let mapped = session.timeline_cues(0); | ||
| 15379 | + assert_eq!( | ||
| 15380 | + mapped | ||
| 15381 | + .iter() | ||
| 15382 | + .map(|c| (c.start_us, c.end_us)) | ||
| 15383 | + .collect::<Vec<_>>(), | ||
| 15384 | + vec![(500_000, 1_500_000), (2_000_000, 3_000_000)] | ||
| 15385 | + ); | ||
| 15386 | + // The overlay's own two lines, at the same moments as above. | ||
| 15387 | + let drawn = |t: f64| -> Vec<String> { | ||
| 15388 | + cues_at(&mapped, t) | ||
| 15389 | + .into_iter() | ||
| 15390 | + .map(|c| c.text.clone()) | ||
| 15391 | + .collect() | ||
| 15392 | + }; | ||
| 15393 | + assert_eq!(drawn(0.7), ["first line"]); | ||
| 15394 | + assert_eq!(drawn(2.5), ["second line\nwith a break"]); | ||
| 15395 | + assert!( | ||
| 15396 | + drawn(4.2).is_empty(), | ||
| 15397 | + "a cue past the cut end is drawn where the file writes none" | ||
| 15398 | + ); | ||
| 15399 | + // ...and the strip's: the second cue is one second wide now, not 1.25. | ||
| 15400 | + assert_eq!(cue_box(scale, &mapped[1]), (80., 40.)); | ||
| 15174 | } | 15401 | } |
| 15175 | 15402 | ||
| 15176 | #[test] | 15403 | #[test] |
crates/engine/src/audio.rsmodified+117 -3
| @@ -28,7 +28,9 @@ | |||
| 28 | use std::fs::File; | 28 | use std::fs::File; |
| 29 | use std::io::BufReader; | 29 | use std::io::BufReader; |
| 30 | use std::path::{Path, PathBuf}; | 30 | use std::path::{Path, PathBuf}; |
| 31 | +use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; | ||
| 31 | use std::sync::mpsc::{Receiver, SyncSender, sync_channel}; | 32 | use std::sync::mpsc::{Receiver, SyncSender, sync_channel}; |
| 33 | +use std::sync::{Arc, Mutex}; | ||
| 32 | use std::thread; | 34 | use std::thread; |
| 33 | 35 | ||
| 34 | use mp4::{AudioObjectType, ChannelConfig, MediaType, Mp4Reader, Mp4Track, TrackType}; | 36 | use mp4::{AudioObjectType, ChannelConfig, MediaType, Mp4Reader, Mp4Track, TrackType}; |
| @@ -152,6 +154,67 @@ pub struct StreamInfo { | |||
| 152 | pub decodable: bool, | 154 | pub decodable: bool, |
| 153 | } | 155 | } |
| 154 | 156 | ||
| 157 | +/// The mix settings a *running* mixer reads: what each lane is turned by on its | ||
| 158 | +/// way into the sum and the ceiling the sum comes out through, both swappable | ||
| 159 | +/// while the stream plays. | ||
| 160 | +/// | ||
| 161 | +/// This is what keeps a fader off the reseek path. Everything else a timeline | ||
| 162 | +/// says lives inside a decode worker -- a segment's window, its curve, its rate | ||
| 163 | +/// -- and can only be changed by rebuilding it, which is a flush, a re-open and | ||
| 164 | +/// a hole in the sound. These two live at the sum, where nothing is decoded, so | ||
| 165 | +/// the mixer can pick them up between one block and the next: an arrow key held | ||
| 166 | +/// down on a fader moves the level and nothing else moves at all. | ||
| 167 | +/// | ||
| 168 | +/// One of these belongs to one mixer thread. [`is_live`](MixControls::is_live) | ||
| 169 | +/// is what says whether a mixer is actually reading it -- a single lane at | ||
| 170 | +/// unity with the limiter off is not mixed at all | ||
| 171 | +/// ([`AudioSession::open_mixed_streams_master`]), and a caller that finds this | ||
| 172 | +/// dead has to reopen the stream to be heard. | ||
| 173 | +pub struct MixControls { | ||
| 174 | + /// Bumped by every change; the mixer reloads when the number it last saw | ||
| 175 | + /// is not this one, so an unchanged mix costs one relaxed load per block. | ||
| 176 | + version: AtomicU64, | ||
| 177 | + /// The lane amplitudes and the limiter, together: they are set together and | ||
| 178 | + /// a mixer that read half of one change and half of the next would be | ||
| 179 | + /// mixing a state nobody asked for. | ||
| 180 | + state: Mutex<(Vec<f32>, Limiter)>, | ||
| 181 | + /// A mixer thread has these; see the type docs. | ||
| 182 | + live: AtomicBool, | ||
| 183 | +} | ||
| 184 | + | ||
| 185 | +impl MixControls { | ||
| 186 | + pub fn new(gains: Vec<f32>, limiter: Limiter) -> Arc<Self> { | ||
| 187 | + Arc::new(Self { | ||
| 188 | + version: AtomicU64::new(0), | ||
| 189 | + state: Mutex::new((gains, limiter)), | ||
| 190 | + live: AtomicBool::new(false), | ||
| 191 | + }) | ||
| 192 | + } | ||
| 193 | + | ||
| 194 | + /// Hands the running mixer a new mix. Cheap enough for a key repeat: a lock | ||
| 195 | + /// held for a `Vec` swap and an atomic. | ||
| 196 | + pub fn set(&self, gains: Vec<f32>, limiter: Limiter) { | ||
| 197 | + *self.state.lock().unwrap() = (gains, limiter); | ||
| 198 | + self.version.fetch_add(1, Ordering::Release); | ||
| 199 | + } | ||
| 200 | + | ||
| 201 | + /// Whether a mixer thread is reading this at all. | ||
| 202 | + pub fn is_live(&self) -> bool { | ||
| 203 | + self.live.load(Ordering::Acquire) | ||
| 204 | + } | ||
| 205 | + | ||
| 206 | + /// The mix, if it has moved since `seen`. `None` -- the every-block case -- | ||
| 207 | + /// takes no lock. | ||
| 208 | + fn changed(&self, seen: &mut u64) -> Option<(Vec<f32>, Limiter)> { | ||
| 209 | + let now = self.version.load(Ordering::Acquire); | ||
| 210 | + if now == *seen { | ||
| 211 | + return None; | ||
| 212 | + } | ||
| 213 | + *seen = now; | ||
| 214 | + Some(self.state.lock().unwrap().clone()) | ||
| 215 | + } | ||
| 216 | +} | ||
| 217 | + | ||
| 155 | pub struct AudioSession; | 218 | pub struct AudioSession; |
| 156 | 219 | ||
| 157 | impl AudioSession { | 220 | impl AudioSession { |
| @@ -497,6 +560,26 @@ impl AudioSession { | |||
| 497 | speeds: &[Vec<Option<crate::project::Stretch>>], | 560 | speeds: &[Vec<Option<crate::project::Stretch>>], |
| 498 | gains: &[f32], | 561 | gains: &[f32], |
| 499 | limiter: Limiter, | 562 | limiter: Limiter, |
| 563 | + ) -> crate::Result<Option<(AudioMeta, Receiver<AudioChunk>)>> { | ||
| 564 | + Self::open_mixed_streams_live(sources, lanes, eqs, speeds, gains, limiter, None) | ||
| 565 | + } | ||
| 566 | + | ||
| 567 | + /// [`open_mixed_streams_master`](Self::open_mixed_streams_master) with the | ||
| 568 | + /// mix left *reachable*: `live` is the handle the mixer picks its gains and | ||
| 569 | + /// its limiter off between blocks, so a fader moved while the stream plays | ||
| 570 | + /// is heard without the stream being rebuilt ([`MixControls`]). | ||
| 571 | + /// | ||
| 572 | + /// `gains`/`limiter` still say what it starts as -- they are what decides | ||
| 573 | + /// whether there is a mixer at all -- and the handle is marked live only | ||
| 574 | + /// when there is one. An export passes `None`: nothing can move under it. | ||
| 575 | + pub fn open_mixed_streams_live( | ||
| 576 | + sources: &[(PathBuf, usize)], | ||
| 577 | + lanes: &[Vec<(Option<usize>, f64, f64)>], | ||
| 578 | + eqs: &[Vec<Option<EqParams>>], | ||
| 579 | + speeds: &[Vec<Option<crate::project::Stretch>>], | ||
| 580 | + gains: &[f32], | ||
| 581 | + limiter: Limiter, | ||
| 582 | + live: Option<&Arc<MixControls>>, | ||
| 500 | ) -> crate::Result<Option<(AudioMeta, Receiver<AudioChunk>)>> { | 583 | ) -> crate::Result<Option<(AudioMeta, Receiver<AudioChunk>)>> { |
| 501 | let [first, rest @ ..] = lanes else { | 584 | let [first, rest @ ..] = lanes else { |
| 502 | return Ok(None); | 585 | return Ok(None); |
| @@ -540,12 +623,20 @@ impl AudioSession { | |||
| 540 | let mut gains = gains.to_vec(); | 623 | let mut gains = gains.to_vec(); |
| 541 | gains.resize(lanes.len(), 1.0); | 624 | gains.resize(lanes.len(), 1.0); |
| 542 | // Built here, off the thread that will run it, where the rate is known. | 625 | // Built here, off the thread that will run it, where the rate is known. |
| 543 | - let limiter = limiter | 626 | + let state = limiter |
| 544 | .is_active() | 627 | .is_active() |
| 545 | .then(|| LimiterState::new(&limiter, meta.sample_rate, channels)); | 628 | .then(|| LimiterState::new(&limiter, meta.sample_rate, channels)); |
| 629 | + // Marked before the spawn rather than inside it: a caller asks this the | ||
| 630 | + // moment the open returns, and a flag set on the far thread would still | ||
| 631 | + // read dead. | ||
| 632 | + let live = live.map(|live| { | ||
| 633 | + live.live.store(true, Ordering::Release); | ||
| 634 | + live.clone() | ||
| 635 | + }); | ||
| 636 | + let rate = meta.sample_rate; | ||
| 546 | thread::Builder::new() | 637 | thread::Builder::new() |
| 547 | .name("audio-mix".into()) | 638 | .name("audio-mix".into()) |
| 548 | - .spawn(move || mix(&rxs, channels, &gains, limiter, &tx))?; | 639 | + .spawn(move || mix(&rxs, channels, gains, state, rate, live.as_deref(), &tx))?; |
| 549 | Ok(Some((meta, rx))) | 640 | Ok(Some((meta, rx))) |
| 550 | } | 641 | } |
| 551 | 642 | ||
| @@ -2124,10 +2215,15 @@ struct Worker { | |||
| 2124 | fn mix( | 2215 | fn mix( |
| 2125 | rxs: &[Receiver<AudioChunk>], | 2216 | rxs: &[Receiver<AudioChunk>], |
| 2126 | channels: usize, | 2217 | channels: usize, |
| 2127 | - gains: &[f32], | 2218 | + mut gains: Vec<f32>, |
| 2128 | mut limiter: Option<LimiterState>, | 2219 | mut limiter: Option<LimiterState>, |
| 2220 | + rate: u32, | ||
| 2221 | + controls: Option<&MixControls>, | ||
| 2129 | tx: &SyncSender<AudioChunk>, | 2222 | tx: &SyncSender<AudioChunk>, |
| 2130 | ) { | 2223 | ) { |
| 2224 | + // The version of the mix these gains and this limiter came from; see the | ||
| 2225 | + // reload at the head of the loop. | ||
| 2226 | + let mut seen = 0; | ||
| 2131 | let mut pending: Vec<Vec<f32>> = rxs.iter().map(|_| Vec::new()).collect(); | 2227 | let mut pending: Vec<Vec<f32>> = rxs.iter().map(|_| Vec::new()).collect(); |
| 2132 | let mut live: Vec<bool> = rxs.iter().map(|_| true).collect(); | 2228 | let mut live: Vec<bool> = rxs.iter().map(|_| true).collect(); |
| 2133 | // Numbering follows lane 0, whose first chunk says where it starts. | 2229 | // Numbering follows lane 0, whose first chunk says where it starts. |
| @@ -2135,6 +2231,24 @@ fn mix( | |||
| 2135 | let mut emitted = 0; | 2231 | let mut emitted = 0; |
| 2136 | let mut out: Vec<f32> = Vec::new(); | 2232 | let mut out: Vec<f32> = Vec::new(); |
| 2137 | loop { | 2233 | loop { |
| 2234 | + // A mix moved while the stream plays, picked up between two blocks: | ||
| 2235 | + // the levels change at a block boundary and nothing else changes at | ||
| 2236 | + // all -- no flush, no re-open, no hole. The limiter is *retuned* rather | ||
| 2237 | + // than rebuilt, so its delay line keeps running and the sample count | ||
| 2238 | + // the master clock is made of does not move ([`LimiterState::retune`]). | ||
| 2239 | + if let Some((next, params)) = controls.and_then(|c| c.changed(&mut seen)) { | ||
| 2240 | + gains = next; | ||
| 2241 | + gains.resize(rxs.len(), 1.0); | ||
| 2242 | + match limiter.as_mut() { | ||
| 2243 | + Some(state) => state.retune(¶ms), | ||
| 2244 | + // First time it has ever been switched in on this stream: the | ||
| 2245 | + // one that swallows nothing, for the count's sake. | ||
| 2246 | + None if params.is_active() => { | ||
| 2247 | + limiter = Some(LimiterState::engaged(¶ms, rate, channels)); | ||
| 2248 | + } | ||
| 2249 | + None => {} | ||
| 2250 | + } | ||
| 2251 | + } | ||
| 2138 | for (i, rx) in rxs.iter().enumerate() { | 2252 | for (i, rx) in rxs.iter().enumerate() { |
| 2139 | while live[i] && pending[i].is_empty() { | 2253 | while live[i] && pending[i].is_empty() { |
| 2140 | match rx.recv() { | 2254 | match rx.recv() { |
crates/engine/src/decode.rsmodified+1 -1
| @@ -87,7 +87,7 @@ impl Backend { | |||
| 87 | pub struct BackendCell(Arc<AtomicU8>); | 87 | pub struct BackendCell(Arc<AtomicU8>); |
| 88 | 88 | ||
| 89 | impl BackendCell { | 89 | impl BackendCell { |
| 90 | - fn new(backend: Backend) -> Self { | 90 | + pub(crate) fn new(backend: Backend) -> Self { |
| 91 | Self(Arc::new(AtomicU8::new(backend.code()))) | 91 | Self(Arc::new(AtomicU8::new(backend.code()))) |
| 92 | } | 92 | } |
| 93 | 93 | ||
crates/engine/src/edith.rsmodified+7 -4
| @@ -19,10 +19,13 @@ | |||
| 19 | //! gain audio 1 -3.0 | 19 | //! gain audio 1 -3.0 |
| 20 | //! ``` | 20 | //! ``` |
| 21 | //! | 21 | //! |
| 22 | -//! The `fps` line is the rate the timeline was cut at, printed so it reads back | 22 | +//! The `fps` line is the rate the timeline was cut at -- the scaffolding |
| 23 | -//! bit-exactly. A file without one (every dialect before v9) means "whatever | 23 | +//! source's own unless a rate was picked |
| 24 | -//! the scaffolding source runs at", which is what such a project always was and | 24 | +//! ([`crate::PlaybackSession::set_frame_rate`]), and the *only* thing that says |
| 25 | -//! is an answer only a project holding a video has | 25 | +//! so once one was, since every clip number in the file is counted in it. |
| 26 | +//! Printed so it reads back bit-exactly. A file without one (every dialect | ||
| 27 | +//! before v9) means "whatever the scaffolding source runs at", which is what | ||
| 28 | +//! such a project always was and is an answer only a project holding a video has | ||
| 26 | //! ([`crate::PlaybackSession::open_project`]). | 29 | //! ([`crate::PlaybackSession::open_project`]). |
| 27 | //! | 30 | //! |
| 28 | //! A `subtitle` line is `subtitle <track> <path>`: which track of that file the | 31 | //! A `subtitle` line is `subtitle <track> <path>`: which track of that file the |
crates/engine/src/export.rsmodified+250 -1
| @@ -66,9 +66,10 @@ use oxideav_core::Muxer as _; | |||
| 66 | use crate::audio::{AudioMeta, AudioSession}; | 66 | use crate::audio::{AudioMeta, AudioSession}; |
| 67 | use crate::demux::{Demuxer, VideoMeta}; | 67 | use crate::demux::{Demuxer, VideoMeta}; |
| 68 | use crate::hw::{HwEncoder, HwSession}; | 68 | use crate::hw::{HwEncoder, HwSession}; |
| 69 | -use crate::mux::{AudioParams, Av1Params, HevcParams, MkvMuxer, Mp4Muxer, VideoParams}; | 69 | +use crate::mux::{AudioParams, Av1Params, HevcParams, MkvMuxer, Mp4Muxer, SubParams, VideoParams}; |
| 70 | use crate::project::{LaneKind, Project, Rate}; | 70 | use crate::project::{LaneKind, Project, Rate}; |
| 71 | use crate::scale::Composer; | 71 | use crate::scale::Composer; |
| 72 | +use crate::subtitle::{Cue, SubtitleTrack}; | ||
| 72 | 73 | ||
| 73 | /// Progress is reported in permille: an atomic integer the render loop can read | 74 | /// Progress is reported in permille: an atomic integer the render loop can read |
| 74 | /// without a lock, fine enough for any progress bar. | 75 | /// without a lock, fine enough for any progress bar. |
| @@ -241,6 +242,16 @@ pub struct ExportSettings { | |||
| 241 | /// it used to. Means nothing to WAV and FLAC, which code no rate, and | 242 | /// it used to. Means nothing to WAV and FLAC, which code no rate, and |
| 242 | /// nothing to a *copied* AAC track, which carries its source's. | 243 | /// nothing to a *copied* AAC track, which carries its source's. |
| 243 | pub audio_kbps: Option<u32>, | 244 | pub audio_kbps: Option<u32>, |
| 245 | + /// Which of the project's subtitle tracks travels with the file: an index | ||
| 246 | + /// into [`Project::subtitles`], which is the same list a front-end picks a | ||
| 247 | + /// row of. `None` writes none -- what every caller wrote before there was a | ||
| 248 | + /// choice, so an export of a timeline without subtitles is the file it | ||
| 249 | + /// always was, byte for byte. | ||
| 250 | + /// | ||
| 251 | + /// Only a Matroska container carries it: an mp4's `tx3g` is a different | ||
| 252 | + /// beast and nothing here writes one, so an mp4 export says so | ||
| 253 | + /// ([`planned_subtitles`]) rather than dropping the track in silence. | ||
| 254 | + pub subtitles: Option<usize>, | ||
| 244 | } | 255 | } |
| 245 | 256 | ||
| 246 | struct Shared { | 257 | struct Shared { |
| @@ -546,6 +557,139 @@ pub fn audio_rate_refusal(project: &Project, format: Format) -> Option<&'static | |||
| 546 | } | 557 | } |
| 547 | } | 558 | } |
| 548 | 559 | ||
| 560 | +/// The track a Matroska export carries, or `None`: no pick, a pick nothing | ||
| 561 | +/// answers, a track that could not be read, one with no cue left on the | ||
| 562 | +/// exported timeline -- and every mp4, whose refusal [`planned_subtitles`] says | ||
| 563 | +/// out loud before the button is pressed. | ||
| 564 | +fn export_subtitles( | ||
| 565 | + project: &Project, | ||
| 566 | + meta: &VideoMeta, | ||
| 567 | + settings: &ExportSettings, | ||
| 568 | +) -> Option<SubParams> { | ||
| 569 | + if !matches!(settings.format, Format::Av1 | Format::Hevc) { | ||
| 570 | + return None; | ||
| 571 | + } | ||
| 572 | + let track = project.subtitles().get(settings.subtitles?)?; | ||
| 573 | + if track.refused.is_some() { | ||
| 574 | + return None; | ||
| 575 | + } | ||
| 576 | + let cues = timeline_cues(project, track, meta.frame_rate); | ||
| 577 | + (!cues.is_empty()).then(|| SubParams { | ||
| 578 | + label: track.label.clone(), | ||
| 579 | + cues, | ||
| 580 | + }) | ||
| 581 | +} | ||
| 582 | + | ||
| 583 | +/// The track's cues where the *exported* timeline puts them, which is the only | ||
| 584 | +/// clock the file has: the export writes timeline frame 0 onwards and nothing | ||
| 585 | +/// else, exactly as the sound is mixed from frame 0 and resized to the | ||
| 586 | +/// timeline's own length ([`encode_audio`]). | ||
| 587 | +/// | ||
| 588 | +/// Which clock the cues arrive in is what the track itself says: | ||
| 589 | +/// | ||
| 590 | +/// * a track out of a *file* (`SubtitleTrack::track`) is timed against that | ||
| 591 | +/// file, so each cue is carried through the spans that play it -- a cue over | ||
| 592 | +/// a stretch that was cut out is gone, one straddling a cut keeps the half | ||
| 593 | +/// that is still there, and one after a rippled delete moves back with the | ||
| 594 | +/// picture it belongs to. The *edges* a cut clips to are frames -- that is | ||
| 595 | +/// what a cut is -- but a cue nothing clipped keeps its own microseconds, so | ||
| 596 | +/// an untouched timeline exports the times the source states. | ||
| 597 | +/// * a *standalone* file (`subs.srt`) is timed against nothing else -- there is | ||
| 598 | +/// no clip to hang it on and no offset in the project to shift it by -- so it | ||
| 599 | +/// is the timeline's own clock, which is where it was drawn while editing | ||
| 600 | +/// (`Player::subtitle_overlay`). Clipped to the exported length and no more. | ||
| 601 | +/// | ||
| 602 | +/// This is also what the *preview* draws: the plate over the picture and the | ||
| 603 | +/// timeline strip both ask it through | ||
| 604 | +/// [`PlaybackSession::timeline_cues`](crate::PlaybackSession::timeline_cues), so | ||
| 605 | +/// what a rippled timeline shows and what its export writes are one answer by | ||
| 606 | +/// construction rather than two maps kept in step by hand. | ||
| 607 | +/// | ||
| 608 | +/// Pure and cheap enough to ask per repaint (a walk of the spans and of the | ||
| 609 | +/// cues, no file opened), which is how a front-end asks it. | ||
| 610 | +pub fn timeline_cues(project: &Project, track: &SubtitleTrack, fps: f64) -> Vec<Cue> { | ||
| 611 | + let frames = project.timeline_frames(); | ||
| 612 | + let us = |frame: u32| (f64::from(frame) / fps * 1e6).round() as i64; | ||
| 613 | + let end = us(frames); | ||
| 614 | + // The file the cues are timed against, when there is one on this timeline. | ||
| 615 | + // A track whose media has since been dropped from the project has no span | ||
| 616 | + // to be carried through and falls back to the timeline's clock, which is | ||
| 617 | + // what it was drawn on. | ||
| 618 | + // | ||
| 619 | + // Through the same `canonical` a source is indexed by, or the two spellings | ||
| 620 | + // of one file (an argv `../assets/film.mkv`, a symlinked folder) would read | ||
| 621 | + // as two files and the cues would quietly fall back to the timeline's clock. | ||
| 622 | + let source = track.track.and_then(|_| { | ||
| 623 | + let path = crate::project::canonical(&track.path); | ||
| 624 | + project.sources().iter().position(|s| s.path == path) | ||
| 625 | + }); | ||
| 626 | + let Some(source) = source else { | ||
| 627 | + return track | ||
| 628 | + .cues | ||
| 629 | + .iter() | ||
| 630 | + .filter_map(|cue| { | ||
| 631 | + let (start_us, end_us) = (cue.start_us.max(0), cue.end_us.min(end)); | ||
| 632 | + (end_us > start_us).then(|| Cue { | ||
| 633 | + start_us, | ||
| 634 | + end_us, | ||
| 635 | + text: cue.text.clone(), | ||
| 636 | + }) | ||
| 637 | + }) | ||
| 638 | + .collect(); | ||
| 639 | + }; | ||
| 640 | + let mut out = Vec::new(); | ||
| 641 | + for span in project.composite_spans_from(0) { | ||
| 642 | + let Some((_, in_frame)) = span.from.filter(|&(from, _)| from == source) else { | ||
| 643 | + continue; | ||
| 644 | + }; | ||
| 645 | + // What of the file this span plays, as *time in the file*: a clip counts | ||
| 646 | + // the timeline's frames whatever its file was shot at ([`Rate`]), which | ||
| 647 | + // is what makes those frames the same seconds a cue is timed in. | ||
| 648 | + let (first, last) = (us(in_frame), us(in_frame + span.source_len())); | ||
| 649 | + // Where that lands, and how fast: a cue is carried by the same factor | ||
| 650 | + // the pictures under it are, so a slowed clip stretches its subtitles | ||
| 651 | + // with it instead of leaving them behind. | ||
| 652 | + let start = us(span.start); | ||
| 653 | + let onto = |t: i64| start + ((t - first) as f64 / span.speed.as_f64()).round() as i64; | ||
| 654 | + for cue in &track.cues { | ||
| 655 | + let (a, b) = (cue.start_us.max(first), cue.end_us.min(last)); | ||
| 656 | + if b <= a { | ||
| 657 | + continue; // wholly outside what this span kept | ||
| 658 | + } | ||
| 659 | + out.push(Cue { | ||
| 660 | + start_us: onto(a), | ||
| 661 | + end_us: onto(b).min(end), | ||
| 662 | + text: cue.text.clone(), | ||
| 663 | + }); | ||
| 664 | + } | ||
| 665 | + } | ||
| 666 | + // The spans come in timeline order but a cue's *own* order across them does | ||
| 667 | + // not: a Matroska muxer writes blocks as they come up. | ||
| 668 | + out.sort_by_key(|cue| cue.start_us); | ||
| 669 | + out | ||
| 670 | +} | ||
| 671 | + | ||
| 672 | +/// What [`start`] would do about the subtitles, in the words a card shows. | ||
| 673 | +/// Pure, like [`planned_audio`]: no file is opened, so it may be asked per | ||
| 674 | +/// repaint. | ||
| 675 | +pub fn planned_subtitles(project: &Project, format: Format, pick: Option<usize>) -> String { | ||
| 676 | + let Some(track) = pick.and_then(|i| project.subtitles().get(i)) else { | ||
| 677 | + return "none".into(); | ||
| 678 | + }; | ||
| 679 | + if let Some(why) = &track.refused { | ||
| 680 | + return format!("{} — {why}", track.label); | ||
| 681 | + } | ||
| 682 | + match format { | ||
| 683 | + _ if track.cues.is_empty() => "none".into(), | ||
| 684 | + Format::Av1 | Format::Hevc => format!("{} → embedded", track.label), | ||
| 685 | + // Said before the export rather than after it: an mp4 carries text in | ||
| 686 | + // `tx3g` and nothing here writes one, so the honest answer is the | ||
| 687 | + // container that does. | ||
| 688 | + format if format.has_video() => "mkv only — an mp4 carries none".into(), | ||
| 689 | + _ => "none — this format is the sound alone".into(), | ||
| 690 | + } | ||
| 691 | +} | ||
| 692 | + | ||
| 549 | /// What [`start`] would encode the picture with, probed the way the export | 693 | /// What [`start`] would encode the picture with, probed the way the export |
| 550 | /// probes it -- the very encoder is opened and closed again -- so this is a | 694 | /// probes it -- the very encoder is opened and closed again -- so this is a |
| 551 | /// measurement and not a promise. `None` for a format that carries no picture. | 695 | /// measurement and not a promise. `None` for a format that carries no picture. |
| @@ -791,6 +935,10 @@ fn run( | |||
| 791 | // Taken by the Matroska muxer at creation; the mp4 one writes its track | 935 | // Taken by the Matroska muxer at creation; the mp4 one writes its track |
| 792 | // after the picture, so for that path this is still `Some` at the end. | 936 | // after the picture, so for that path this is still `Some` at the end. |
| 793 | let mut packets = audio.map(|track| track.packets); | 937 | let mut packets = audio.map(|track| track.packets); |
| 938 | + // ...and the cues with them, for the same reason: the subtitle track is | ||
| 939 | + // declared in the header and its blocks are interleaved into the clusters, | ||
| 940 | + // so the muxer needs the lot before the first picture is written. | ||
| 941 | + let mut subs = export_subtitles(project, meta, settings); | ||
| 794 | 942 | ||
| 795 | // One header parse per source, before any of them is decoded: what rate | 943 | // One header parse per source, before any of them is decoded: what rate |
| 796 | // each file was shot at against the timeline's ([`Rate`]), which is how the | 944 | // each file was shot at against the timeline's ([`Rate`]), which is how the |
| @@ -939,6 +1087,7 @@ fn run( | |||
| 939 | settings, | 1087 | settings, |
| 940 | audio_params.as_ref(), | 1088 | audio_params.as_ref(), |
| 941 | &mut packets, | 1089 | &mut packets, |
| 1090 | + &mut subs, | ||
| 942 | au, | 1091 | au, |
| 943 | key, | 1092 | key, |
| 944 | )?; | 1093 | )?; |
| @@ -959,6 +1108,7 @@ fn run( | |||
| 959 | settings, | 1108 | settings, |
| 960 | audio_params.as_ref(), | 1109 | audio_params.as_ref(), |
| 961 | &mut packets, | 1110 | &mut packets, |
| 1111 | + &mut subs, | ||
| 962 | au, | 1112 | au, |
| 963 | key, | 1113 | key, |
| 964 | )?; | 1114 | )?; |
| @@ -1419,6 +1569,7 @@ fn write_video( | |||
| 1419 | settings: &ExportSettings, | 1569 | settings: &ExportSettings, |
| 1420 | audio: Option<&AudioParams>, | 1570 | audio: Option<&AudioParams>, |
| 1421 | packets: &mut Option<Vec<crate::AacPacket>>, | 1571 | packets: &mut Option<Vec<crate::AacPacket>>, |
| 1572 | + subs: &mut Option<SubParams>, | ||
| 1422 | au: &[u8], | 1573 | au: &[u8], |
| 1423 | key: bool, | 1574 | key: bool, |
| 1424 | ) -> crate::Result<()> { | 1575 | ) -> crate::Result<()> { |
| @@ -1446,6 +1597,7 @@ fn write_video( | |||
| 1446 | hvcc: &hvcc, | 1597 | hvcc: &hvcc, |
| 1447 | }, | 1598 | }, |
| 1448 | sound, | 1599 | sound, |
| 1600 | + subs.take(), | ||
| 1449 | )?)) else { | 1601 | )?)) else { |
| 1450 | unreachable!("just inserted a Matroska muxer") | 1602 | unreachable!("just inserted a Matroska muxer") |
| 1451 | }; | 1603 | }; |
| @@ -1502,6 +1654,7 @@ fn write_video( | |||
| 1502 | out, | 1654 | out, |
| 1503 | ¶ms(meta, au)?, | 1655 | ¶ms(meta, au)?, |
| 1504 | sound, | 1656 | sound, |
| 1657 | + subs.take(), | ||
| 1505 | )?)) else { | 1658 | )?)) else { |
| 1506 | unreachable!("just inserted a Matroska muxer") | 1659 | unreachable!("just inserted a Matroska muxer") |
| 1507 | }; | 1660 | }; |
| @@ -2156,6 +2309,102 @@ impl SwDecoder { | |||
| 2156 | mod tests { | 2309 | mod tests { |
| 2157 | use super::*; | 2310 | use super::*; |
| 2158 | 2311 | ||
| 2312 | + /// A track of three cues, in whichever clock `track` says: `Some(n)` is a | ||
| 2313 | + /// track of the media file, `None` a `.srt` beside it. | ||
| 2314 | + fn subtitles(path: &str, track: Option<u64>) -> SubtitleTrack { | ||
| 2315 | + SubtitleTrack { | ||
| 2316 | + path: path.into(), | ||
| 2317 | + track, | ||
| 2318 | + label: "eng".into(), | ||
| 2319 | + cues: vec![ | ||
| 2320 | + Cue { | ||
| 2321 | + start_us: 500_000, | ||
| 2322 | + end_us: 1_500_000, | ||
| 2323 | + text: "first".into(), | ||
| 2324 | + }, | ||
| 2325 | + Cue { | ||
| 2326 | + start_us: 2_000_000, | ||
| 2327 | + end_us: 3_250_000, | ||
| 2328 | + text: "second".into(), | ||
| 2329 | + }, | ||
| 2330 | + Cue { | ||
| 2331 | + start_us: 4_000_000, | ||
| 2332 | + end_us: 4_750_000, | ||
| 2333 | + text: "third".into(), | ||
| 2334 | + }, | ||
| 2335 | + ], | ||
| 2336 | + refused: None, | ||
| 2337 | + } | ||
| 2338 | + } | ||
| 2339 | + | ||
| 2340 | + /// A standalone subtitle file is timed against the timeline itself -- there | ||
| 2341 | + /// is no clip to hang it on -- so a cut moves the pictures and not it. What | ||
| 2342 | + /// it does get is the exported length: a cue past the end of the file would | ||
| 2343 | + /// otherwise be a block after the last picture. | ||
| 2344 | + /// | ||
| 2345 | + /// The pair of this, the embedded clock, is measured against a real exported | ||
| 2346 | + /// file in `tests/export_subs.rs`; both live in one function and this is the | ||
| 2347 | + /// half that needs no encoder. | ||
| 2348 | + #[test] | ||
| 2349 | + fn a_subtitle_file_beside_the_media_keeps_the_timelines_own_clock() { | ||
| 2350 | + // 5 seconds at 30, with `[0.5s, 2.5s)` cut out of it: 3 seconds left. | ||
| 2351 | + let mut project = Project::single("/nonexistent/film.mp4", 150); | ||
| 2352 | + let track = subtitles("/nonexistent/film.srt", None); | ||
| 2353 | + assert!(project.ripple_delete(15, 60)); | ||
| 2354 | + assert_eq!(project.timeline_frames(), 90); | ||
| 2355 | + let cues = timeline_cues(&project, &track, 30.0); | ||
| 2356 | + assert_eq!( | ||
| 2357 | + cues, | ||
| 2358 | + vec![ | ||
| 2359 | + Cue { | ||
| 2360 | + start_us: 500_000, | ||
| 2361 | + end_us: 1_500_000, | ||
| 2362 | + text: "first".into() | ||
| 2363 | + }, | ||
| 2364 | + // Clipped to the three seconds the export writes... | ||
| 2365 | + Cue { | ||
| 2366 | + start_us: 2_000_000, | ||
| 2367 | + end_us: 3_000_000, | ||
| 2368 | + text: "second".into() | ||
| 2369 | + }, | ||
| 2370 | + // ...and the one wholly past the end is not written at all. | ||
| 2371 | + ] | ||
| 2372 | + ); | ||
| 2373 | + // A track *of a file* the project no longer plays has no span to be | ||
| 2374 | + // carried through either, so it falls back to the same clock rather | ||
| 2375 | + // than exporting nothing. | ||
| 2376 | + let orphan = subtitles("/nonexistent/other.mkv", Some(2)); | ||
| 2377 | + assert_eq!(timeline_cues(&project, &orphan, 30.0).len(), 2); | ||
| 2378 | + } | ||
| 2379 | + | ||
| 2380 | + /// The embedded clock, without an encoder in it: the cut moves the cues with | ||
| 2381 | + /// the pictures, and a cue nothing clipped keeps its own microseconds. | ||
| 2382 | + #[test] | ||
| 2383 | + fn a_track_of_the_media_is_carried_through_the_cut() { | ||
| 2384 | + let mut project = Project::single("/nonexistent/film.mkv", 150); | ||
| 2385 | + let track = subtitles("/nonexistent/film.mkv", Some(2)); | ||
| 2386 | + assert!(project.ripple_delete(15, 60), "cut 0.5s..2.5s out"); | ||
| 2387 | + let cues = timeline_cues(&project, &track, 30.0); | ||
| 2388 | + assert_eq!( | ||
| 2389 | + cues, | ||
| 2390 | + vec![ | ||
| 2391 | + // The first cue was wholly inside the cut. The second straddled | ||
| 2392 | + // its far edge and kept the 0.75s that is still there... | ||
| 2393 | + Cue { | ||
| 2394 | + start_us: 500_000, | ||
| 2395 | + end_us: 1_250_000, | ||
| 2396 | + text: "second".into() | ||
| 2397 | + }, | ||
| 2398 | + // ...and the third simply moves back the two seconds that went. | ||
| 2399 | + Cue { | ||
| 2400 | + start_us: 2_000_000, | ||
| 2401 | + end_us: 2_750_000, | ||
| 2402 | + text: "third".into() | ||
| 2403 | + }, | ||
| 2404 | + ] | ||
| 2405 | + ); | ||
| 2406 | + } | ||
| 2407 | + | ||
| 2159 | #[test] | 2408 | #[test] |
| 2160 | fn bitrate_clamps_at_both_ends() { | 2409 | fn bitrate_clamps_at_both_ends() { |
| 2161 | let meta = |width, height, frame_rate| VideoMeta { | 2410 | let meta = |width, height, frame_rate| VideoMeta { |
crates/engine/src/limiter.rsmodified+91 -1
| @@ -106,6 +106,11 @@ pub struct LimiterState { | |||
| 106 | /// delay line, which is how the latency is paid back (module docs). | 106 | /// delay line, which is how the latency is paid back (module docs). |
| 107 | warm: usize, | 107 | warm: usize, |
| 108 | gain: f32, | 108 | gain: f32, |
| 109 | + /// Switched out while the mix runs ([`LimiterState::retune`]): the line | ||
| 110 | + /// still delays and still emits a frame per frame, only nothing is held | ||
| 111 | + /// down. Dropping the state instead would drop the frames still inside the | ||
| 112 | + /// line, and those frames are what the master clock counts. | ||
| 113 | + bypass: bool, | ||
| 109 | ceiling: f32, | 114 | ceiling: f32, |
| 110 | /// Where the knee starts, as an amplitude: under this the fast path runs | 115 | /// Where the knee starts, as an amplitude: under this the fast path runs |
| 111 | /// and no logarithm is taken. | 116 | /// and no logarithm is taken. |
| @@ -125,6 +130,7 @@ impl LimiterState { | |||
| 125 | at: 0, | 130 | at: 0, |
| 126 | warm: frames - 1, | 131 | warm: frames - 1, |
| 127 | gain: 1.0, | 132 | gain: 1.0, |
| 133 | + bypass: !params.on, | ||
| 128 | ceiling: db_to_linear(ceiling_db), | 134 | ceiling: db_to_linear(ceiling_db), |
| 129 | knee_floor: db_to_linear(ceiling_db - KNEE_DB / 2.0), | 135 | knee_floor: db_to_linear(ceiling_db - KNEE_DB / 2.0), |
| 130 | // One time constant per sample: the gain covers 63% of the way back | 136 | // One time constant per sample: the gain covers 63% of the way back |
| @@ -133,6 +139,34 @@ impl LimiterState { | |||
| 133 | } | 139 | } |
| 134 | } | 140 | } |
| 135 | 141 | ||
| 142 | + /// One switched in **while the mix is already running**: the same limiter, | ||
| 143 | + /// except that it swallows nothing to fill its delay line -- what comes out | ||
| 144 | + /// first is the line's own [`LOOKAHEAD_MS`] of silence and the mix behind | ||
| 145 | + /// it, where a fresh state would have eaten that much of the mix instead. | ||
| 146 | + /// | ||
| 147 | + /// Which matters because the count *is* the clock: a mixer that emitted | ||
| 148 | + /// fewer samples than the timeline asked for would slide the picture off | ||
| 149 | + /// the sound by the lookahead, once per switch-on. A hair of silence at the | ||
| 150 | + /// moment somebody engages a limiter is the honest price. | ||
| 151 | + pub fn engaged(params: &Limiter, sample_rate: u32, channels: usize) -> Self { | ||
| 152 | + Self { | ||
| 153 | + warm: 0, | ||
| 154 | + ..Self::new(params, sample_rate, channels) | ||
| 155 | + } | ||
| 156 | + } | ||
| 157 | + | ||
| 158 | + /// Points a running limiter at another setting -- a ceiling dragged, the | ||
| 159 | + /// switch flipped -- without touching the delay line, the peak window or | ||
| 160 | + /// the gain it is holding. That is what makes the ceiling a live control: | ||
| 161 | + /// rebuilding the state would restart the window (a pump) and lose the | ||
| 162 | + /// frames inside the line (a slip against the picture). | ||
| 163 | + pub fn retune(&mut self, params: &Limiter) { | ||
| 164 | + let ceiling_db = params.with_ceiling(params.ceiling_db).ceiling_db; | ||
| 165 | + self.bypass = !params.on; | ||
| 166 | + self.ceiling = db_to_linear(ceiling_db); | ||
| 167 | + self.knee_floor = db_to_linear(ceiling_db - KNEE_DB / 2.0); | ||
| 168 | + } | ||
| 169 | + | ||
| 136 | /// Rewrites `buf` -- interleaved frames -- as the limited mix. Shorter than | 170 | /// Rewrites `buf` -- interleaved frames -- as the limited mix. Shorter than |
| 137 | /// what came in by the delay line's length, once, at the first call. | 171 | /// what came in by the delay line's length, once, at the first call. |
| 138 | pub fn process(&mut self, buf: &mut Vec<f32>) { | 172 | pub fn process(&mut self, buf: &mut Vec<f32>) { |
| @@ -163,8 +197,14 @@ impl LimiterState { | |||
| 163 | self.warm -= 1; | 197 | self.warm -= 1; |
| 164 | continue; | 198 | continue; |
| 165 | } | 199 | } |
| 200 | + // Bypassed, the line is a delay and nothing else: the frames come | ||
| 201 | + // out as they went in, one for one. | ||
| 202 | + let gain = match self.bypass { | ||
| 203 | + true => 1.0, | ||
| 204 | + false => self.gain, | ||
| 205 | + }; | ||
| 166 | for c in 0..channels { | 206 | for c in 0..channels { |
| 167 | - out.push(self.line[self.at * channels + c] * self.gain); | 207 | + out.push(self.line[self.at * channels + c] * gain); |
| 168 | } | 208 | } |
| 169 | } | 209 | } |
| 170 | *buf = out; | 210 | *buf = out; |
| @@ -240,6 +280,56 @@ mod tests { | |||
| 240 | assert_eq!(buf.len(), rate as usize * 2 - (state.peaks.len() - 1) * 2); | 280 | assert_eq!(buf.len(), rate as usize * 2 - (state.peaks.len() - 1) * 2); |
| 241 | } | 281 | } |
| 242 | 282 | ||
| 283 | + /// A ceiling dragged while the mix runs: the new one is honoured from the | ||
| 284 | + /// next block, the delay line keeps running -- so the block is as long as | ||
| 285 | + /// it would have been, which is what the master clock counts -- and | ||
| 286 | + /// switching the limiter out leaves the samples alone rather than dropping | ||
| 287 | + /// the ones still inside the line. | ||
| 288 | + #[test] | ||
| 289 | + fn a_retune_moves_the_ceiling_and_costs_no_samples() { | ||
| 290 | + let rate = 48_000; | ||
| 291 | + let mut state = LimiterState::engaged( | ||
| 292 | + &Limiter { | ||
| 293 | + ceiling_db: -3.0, | ||
| 294 | + on: true, | ||
| 295 | + }, | ||
| 296 | + rate, | ||
| 297 | + 2, | ||
| 298 | + ); | ||
| 299 | + let block: Vec<f32> = (0..2_000).map(|i| 2.0 * ((i % 7) as f32 - 3.0)).collect(); | ||
| 300 | + | ||
| 301 | + // Engaged mid-stream: nothing is swallowed, so the count is the count. | ||
| 302 | + let mut buf = block.clone(); | ||
| 303 | + state.process(&mut buf); | ||
| 304 | + assert_eq!(buf.len(), block.len(), "an engaged limiter ate samples"); | ||
| 305 | + let hot = buf.iter().fold(0.0f32, |m, s| m.max(s.abs())); | ||
| 306 | + assert!(hot <= db_to_linear(-3.0) + 1e-6, "peak {hot} passed -3 dB"); | ||
| 307 | + | ||
| 308 | + // Down to -12: the same length again, and quieter. | ||
| 309 | + state.retune(&Limiter { | ||
| 310 | + ceiling_db: -12.0, | ||
| 311 | + on: true, | ||
| 312 | + }); | ||
| 313 | + let mut buf = block.clone(); | ||
| 314 | + state.process(&mut buf); | ||
| 315 | + assert_eq!(buf.len(), block.len(), "a retune ate samples"); | ||
| 316 | + let quiet = buf.iter().fold(0.0f32, |m, s| m.max(s.abs())); | ||
| 317 | + assert!(quiet <= db_to_linear(-12.0) + 1e-6, "peak {quiet} passed -12 dB"); | ||
| 318 | + assert!(quiet < hot, "the ceiling did not move: {hot} -> {quiet}"); | ||
| 319 | + | ||
| 320 | + // Switched out: the line still delays, so the count still holds, and | ||
| 321 | + // what comes out is the mix as it was written. | ||
| 322 | + state.retune(&Limiter { | ||
| 323 | + ceiling_db: -12.0, | ||
| 324 | + on: false, | ||
| 325 | + }); | ||
| 326 | + let mut buf = block.clone(); | ||
| 327 | + state.process(&mut buf); | ||
| 328 | + assert_eq!(buf.len(), block.len(), "a bypass ate samples"); | ||
| 329 | + let raw = buf.iter().fold(0.0f32, |m, s| m.max(s.abs())); | ||
| 330 | + assert!(raw > 1.0, "bypassed, the mix is untouched: peak {raw}"); | ||
| 331 | + } | ||
| 332 | + | ||
| 243 | /// Flat settings are a passthrough, which is what the export invariant | 333 | /// Flat settings are a passthrough, which is what the export invariant |
| 244 | /// rests on: 0 dB is exactly 1.0, never 0.9999999. | 334 | /// rests on: 0 dB is exactly 1.0, never 0.9999999. |
| 245 | #[test] | 335 | #[test] |
crates/engine/src/mux.rsmodified+142 -1
| @@ -482,6 +482,11 @@ const CODEC_DELAY: u32 = 0x56AA; | |||
| 482 | const CLUSTER: u32 = 0x1F43_B675; | 482 | const CLUSTER: u32 = 0x1F43_B675; |
| 483 | const CLUSTER_TIMESTAMP: u32 = 0xE7; | 483 | const CLUSTER_TIMESTAMP: u32 = 0xE7; |
| 484 | const SIMPLE_BLOCK: u32 = 0xA3; | 484 | const SIMPLE_BLOCK: u32 = 0xA3; |
| 485 | +const TRACK_NAME: u32 = 0x536E; | ||
| 486 | +const TRACK_LANGUAGE: u32 = 0x22B59C; | ||
| 487 | +const BLOCK_GROUP: u32 = 0xA0; | ||
| 488 | +const BLOCK: u32 = 0xA1; | ||
| 489 | +const BLOCK_DURATION: u32 = 0x9B; | ||
| 485 | 490 | ||
| 486 | /// One millisecond, the tick every Matroska muxer writes and this one's block | 491 | /// One millisecond, the tick every Matroska muxer writes and this one's block |
| 487 | /// timestamps are in. The *rate* is not derived from these -- `DefaultDuration` | 492 | /// timestamps are in. The *rate* is not derived from these -- `DefaultDuration` |
| @@ -532,6 +537,34 @@ pub struct HevcParams<'a> { | |||
| 532 | pub hvcc: &'a [u8], | 537 | pub hvcc: &'a [u8], |
| 533 | } | 538 | } |
| 534 | 539 | ||
| 540 | +/// The soft subtitle track a Matroska file carries beside the picture: text, | ||
| 541 | +/// timed, still text in the file -- a player draws it and a user can turn it | ||
| 542 | +/// off, which is what "soft" means and what burning it into the pixels is not. | ||
| 543 | +/// | ||
| 544 | +/// The cues are the *exported timeline's* (`export::timeline_cues` puts them | ||
| 545 | +/// there), because the file's clock is the timeline's; nothing here shifts | ||
| 546 | +/// anything. | ||
| 547 | +pub struct SubParams { | ||
| 548 | + /// What the track is called in the file. A three-letter code goes in as | ||
| 549 | + /// `Language`, which is what a player's subtitle menu reads; anything else | ||
| 550 | + /// is a `Name`, which is what it shows when there is no language to show. | ||
| 551 | + /// | ||
| 552 | + /// ponytail: one string for both because a [`crate::subtitle::SubtitleTrack`] | ||
| 553 | + /// carries one label and not a (language, name) pair. The upgrade path is to | ||
| 554 | + /// keep the two apart from the demuxer down -- `MkvSubtitle` already has | ||
| 555 | + /// them -- and it belongs to whoever needs a per-language export list. | ||
| 556 | + pub label: String, | ||
| 557 | + /// In start order, which is the order they are written in. | ||
| 558 | + pub cues: Vec<crate::subtitle::Cue>, | ||
| 559 | +} | ||
| 560 | + | ||
| 561 | +/// The cues waiting to be interleaved into the clusters, [`MkvAudio`]'s twin. | ||
| 562 | +struct MkvSubs { | ||
| 563 | + cues: Vec<crate::subtitle::Cue>, | ||
| 564 | + /// Cues already written. | ||
| 565 | + next: usize, | ||
| 566 | +} | ||
| 567 | + | ||
| 535 | /// Writes one AV1 video track as Matroska (`.mkv`), and the timeline's AAC | 568 | /// Writes one AV1 video track as Matroska (`.mkv`), and the timeline's AAC |
| 536 | /// beside it where there is any: an `A_AAC` track whose `CodecPrivate` is the | 569 | /// beside it where there is any: an `A_AAC` track whose `CodecPrivate` is the |
| 537 | /// two-byte `AudioSpecificConfig` an mp4's `esds` carries, which is what | 570 | /// two-byte `AudioSpecificConfig` an mp4's `esds` carries, which is what |
| @@ -562,6 +595,9 @@ pub struct MkvMuxer { | |||
| 562 | /// The AAC track, if the timeline has sound, and how far it has been | 595 | /// The AAC track, if the timeline has sound, and how far it has been |
| 563 | /// written. | 596 | /// written. |
| 564 | audio: Option<MkvAudio>, | 597 | audio: Option<MkvAudio>, |
| 598 | + /// The subtitle track, if one travels with the file, and how far it has | ||
| 599 | + /// been written. | ||
| 600 | + subs: Option<MkvSubs>, | ||
| 565 | } | 601 | } |
| 566 | 602 | ||
| 567 | /// The sound waiting to be interleaved into the clusters. | 603 | /// The sound waiting to be interleaved into the clusters. |
| @@ -588,6 +624,7 @@ impl MkvMuxer { | |||
| 588 | path: &Path, | 624 | path: &Path, |
| 589 | video: &Av1Params, | 625 | video: &Av1Params, |
| 590 | audio: Option<(&AudioParams, Vec<crate::AacPacket>)>, | 626 | audio: Option<(&AudioParams, Vec<crate::AacPacket>)>, |
| 627 | + subs: Option<SubParams>, | ||
| 591 | ) -> crate::Result<Self> { | 628 | ) -> crate::Result<Self> { |
| 592 | if video.config.is_empty() { | 629 | if video.config.is_empty() { |
| 593 | return Err("no AV1 sequence header for the track's CodecPrivate".into()); | 630 | return Err("no AV1 sequence header for the track's CodecPrivate".into()); |
| @@ -602,6 +639,7 @@ impl MkvMuxer { | |||
| 602 | b"V_AV1", | 639 | b"V_AV1", |
| 603 | &av1c, | 640 | &av1c, |
| 604 | audio, | 641 | audio, |
| 642 | + subs, | ||
| 605 | ) | 643 | ) |
| 606 | } | 644 | } |
| 607 | 645 | ||
| @@ -616,6 +654,7 @@ impl MkvMuxer { | |||
| 616 | path: &Path, | 654 | path: &Path, |
| 617 | video: &HevcParams, | 655 | video: &HevcParams, |
| 618 | audio: Option<(&AudioParams, Vec<crate::AacPacket>)>, | 656 | audio: Option<(&AudioParams, Vec<crate::AacPacket>)>, |
| 657 | + subs: Option<SubParams>, | ||
| 619 | ) -> crate::Result<Self> { | 658 | ) -> crate::Result<Self> { |
| 620 | if video.hvcc.is_empty() { | 659 | if video.hvcc.is_empty() { |
| 621 | return Err("no hvcC record for the track's CodecPrivate".into()); | 660 | return Err("no hvcC record for the track's CodecPrivate".into()); |
| @@ -628,9 +667,11 @@ impl MkvMuxer { | |||
| 628 | b"V_MPEGH/ISO/HEVC", | 667 | b"V_MPEGH/ISO/HEVC", |
| 629 | video.hvcc, | 668 | video.hvcc, |
| 630 | audio, | 669 | audio, |
| 670 | + subs, | ||
| 631 | ) | 671 | ) |
| 632 | } | 672 | } |
| 633 | 673 | ||
| 674 | + #[allow(clippy::too_many_arguments)] | ||
| 634 | fn open( | 675 | fn open( |
| 635 | path: &Path, | 676 | path: &Path, |
| 636 | width: u32, | 677 | width: u32, |
| @@ -639,6 +680,7 @@ impl MkvMuxer { | |||
| 639 | codec_id: &[u8], | 680 | codec_id: &[u8], |
| 640 | codec_private: &[u8], | 681 | codec_private: &[u8], |
| 641 | audio: Option<(&AudioParams, Vec<crate::AacPacket>)>, | 682 | audio: Option<(&AudioParams, Vec<crate::AacPacket>)>, |
| 683 | + subs: Option<SubParams>, | ||
| 642 | ) -> crate::Result<Self> { | 684 | ) -> crate::Result<Self> { |
| 643 | if !frame_rate.is_finite() || frame_rate <= 0.0 { | 685 | if !frame_rate.is_finite() || frame_rate <= 0.0 { |
| 644 | return Err(format!("bad frame rate {frame_rate}").into()); | 686 | return Err(format!("bad frame rate {frame_rate}").into()); |
| @@ -697,6 +739,12 @@ impl MkvMuxer { | |||
| 697 | if let Some((audio, _)) = &audio { | 739 | if let Some((audio, _)) = &audio { |
| 698 | elem(&mut tracks, TRACK_ENTRY, &aac_track_entry(audio)?); | 740 | elem(&mut tracks, TRACK_ENTRY, &aac_track_entry(audio)?); |
| 699 | } | 741 | } |
| 742 | + // Declared even where the audio track is not: the numbers are fixed | ||
| 743 | + // (1 picture, 2 sound, 3 text) rather than counted, so a file with | ||
| 744 | + // subtitles and no sound still says track 3 in its blocks. | ||
| 745 | + if let Some(subs) = &subs { | ||
| 746 | + elem(&mut tracks, TRACK_ENTRY, &subtitle_track_entry(&subs.label)); | ||
| 747 | + } | ||
| 700 | elem(&mut head, TRACKS, &tracks); | 748 | elem(&mut head, TRACKS, &tracks); |
| 701 | 749 | ||
| 702 | let mut file = File::create(path)?; | 750 | let mut file = File::create(path)?; |
| @@ -715,6 +763,10 @@ impl MkvMuxer { | |||
| 715 | samples: 0, | 763 | samples: 0, |
| 716 | sample_rate: params.sample_rate.max(1), | 764 | sample_rate: params.sample_rate.max(1), |
| 717 | }), | 765 | }), |
| 766 | + subs: subs.map(|subs| MkvSubs { | ||
| 767 | + cues: subs.cues, | ||
| 768 | + next: 0, | ||
| 769 | + }), | ||
| 718 | }) | 770 | }) |
| 719 | } | 771 | } |
| 720 | 772 | ||
| @@ -742,8 +794,10 @@ impl MkvMuxer { | |||
| 742 | uint(&mut self.cluster, CLUSTER_TIMESTAMP, ts as u64); | 794 | uint(&mut self.cluster, CLUSTER_TIMESTAMP, ts as u64); |
| 743 | } | 795 | } |
| 744 | // The sound this picture plays under goes in first, into the cluster the | 796 | // The sound this picture plays under goes in first, into the cluster the |
| 745 | - // picture opened: a player reads the two together. | 797 | + // picture opened: a player reads the two together. The cue over it with |
| 798 | + // them, for the same reason. | ||
| 746 | self.drain_audio(ts)?; | 799 | self.drain_audio(ts)?; |
| 800 | + self.drain_subs(ts)?; | ||
| 747 | self.block(1, ts, key, obus); | 801 | self.block(1, ts, key, obus); |
| 748 | self.frames += 1; | 802 | self.frames += 1; |
| 749 | Ok(()) | 803 | Ok(()) |
| @@ -784,6 +838,41 @@ impl MkvMuxer { | |||
| 784 | } | 838 | } |
| 785 | } | 839 | } |
| 786 | 840 | ||
| 841 | + /// Every cue that has come up by `until`, into the current cluster -- | ||
| 842 | + /// [`drain_audio`](MkvMuxer::drain_audio)'s twin, and `i64::MAX` at | ||
| 843 | + /// [`finish`](MkvMuxer::finish) writes what is left: a cue may still be on | ||
| 844 | + /// screen over the last picture, and one written nowhere is one a player | ||
| 845 | + /// never shows. | ||
| 846 | + fn drain_subs(&mut self, until: i64) -> crate::Result<()> { | ||
| 847 | + loop { | ||
| 848 | + let Some(subs) = &mut self.subs else { | ||
| 849 | + return Ok(()); | ||
| 850 | + }; | ||
| 851 | + let Some(cue) = subs.cues.get_mut(subs.next) else { | ||
| 852 | + return Ok(()); | ||
| 853 | + }; | ||
| 854 | + // Milliseconds, the tick this file is written in: a cue is read for | ||
| 855 | + // a second or more and no eye finds the half a tick it rounds by. | ||
| 856 | + let ts = (cue.start_us + 500) / 1_000; | ||
| 857 | + if ts > until { | ||
| 858 | + return Ok(()); | ||
| 859 | + } | ||
| 860 | + // A cue that says it ends before it starts stays up for one tick | ||
| 861 | + // rather than for a duration a reader would take as unsigned. | ||
| 862 | + let ms = ((cue.end_us - cue.start_us + 500) / 1_000).max(1) as u64; | ||
| 863 | + let text = std::mem::take(&mut cue.text); | ||
| 864 | + subs.next += 1; | ||
| 865 | + // A cluster of its own where the text has run past what a 16-bit | ||
| 866 | + // relative timestamp reaches, exactly as the sound's drain does. | ||
| 867 | + if self.cluster.is_empty() || ts - self.cluster_ts >= CLUSTER_MS { | ||
| 868 | + self.flush()?; | ||
| 869 | + self.cluster_ts = ts; | ||
| 870 | + uint(&mut self.cluster, CLUSTER_TIMESTAMP, ts as u64); | ||
| 871 | + } | ||
| 872 | + self.block_group(SUB_TRACK, ts, ms, text.as_bytes()); | ||
| 873 | + } | ||
| 874 | + } | ||
| 875 | + | ||
| 787 | /// One `SimpleBlock` of `track`, timed against the open cluster. Every AAC | 876 | /// One `SimpleBlock` of `track`, timed against the open cluster. Every AAC |
| 788 | /// packet is a keyframe; a picture is one when the encoder said so. | 877 | /// packet is a keyframe; a picture is one when the encoder said so. |
| 789 | fn block(&mut self, track: u8, ts: i64, key: bool, payload: &[u8]) { | 878 | fn block(&mut self, track: u8, ts: i64, key: bool, payload: &[u8]) { |
| @@ -795,6 +884,24 @@ impl MkvMuxer { | |||
| 795 | elem(&mut self.cluster, SIMPLE_BLOCK, &block); | 884 | elem(&mut self.cluster, SIMPLE_BLOCK, &block); |
| 796 | } | 885 | } |
| 797 | 886 | ||
| 887 | + /// One `BlockGroup`: a `Block` and the `BlockDuration` beside it. That pair | ||
| 888 | + /// is how a cue says when it goes away -- a `SimpleBlock` has nowhere to put | ||
| 889 | + /// a duration, and a subtitle without one stays up until whatever a player | ||
| 890 | + /// decides, which is what a subtitle must never do. | ||
| 891 | + fn block_group(&mut self, track: u8, ts: i64, duration_ms: u64, payload: &[u8]) { | ||
| 892 | + let mut block = Vec::with_capacity(payload.len() + 4); | ||
| 893 | + block.push(0x80 | track); // the track number as a one-byte EBML integer | ||
| 894 | + block.extend_from_slice(&((ts - self.cluster_ts) as i16).to_be_bytes()); | ||
| 895 | + // No flags a text block can carry: not lacing, and "keyframe" is a | ||
| 896 | + // `SimpleBlock` field that a plain `Block` does not have at all. | ||
| 897 | + block.push(0); | ||
| 898 | + block.extend_from_slice(payload); | ||
| 899 | + let mut group = Vec::new(); | ||
| 900 | + elem(&mut group, BLOCK, &block); | ||
| 901 | + uint(&mut group, BLOCK_DURATION, duration_ms); | ||
| 902 | + elem(&mut self.cluster, BLOCK_GROUP, &group); | ||
| 903 | + } | ||
| 904 | + | ||
| 798 | fn flush(&mut self) -> crate::Result<()> { | 905 | fn flush(&mut self) -> crate::Result<()> { |
| 799 | if self.cluster.is_empty() { | 906 | if self.cluster.is_empty() { |
| 800 | return Ok(()); | 907 | return Ok(()); |
| @@ -814,6 +921,7 @@ impl MkvMuxer { | |||
| 814 | // Whatever sound outlasts the last picture, before the last cluster is | 921 | // Whatever sound outlasts the last picture, before the last cluster is |
| 815 | // closed: a track cut short here is a file that goes silent at the end. | 922 | // closed: a track cut short here is a file that goes silent at the end. |
| 816 | self.drain_audio(i64::MAX)?; | 923 | self.drain_audio(i64::MAX)?; |
| 924 | + self.drain_subs(i64::MAX)?; | ||
| 817 | self.flush()?; | 925 | self.flush()?; |
| 818 | if self.frames == 0 { | 926 | if self.frames == 0 { |
| 819 | return Err("no frames were written to the Matroska file".into()); | 927 | return Err("no frames were written to the Matroska file".into()); |
| @@ -878,6 +986,36 @@ fn aac_track_entry(audio: &AudioParams) -> crate::Result<Vec<u8>> { | |||
| 878 | Ok(entry) | 986 | Ok(entry) |
| 879 | } | 987 | } |
| 880 | 988 | ||
| 989 | +/// Which track a subtitle block names. Fixed, like the picture's 1 and the | ||
| 990 | +/// sound's 2: a file with no audio track still writes its text on 3, so nothing | ||
| 991 | +/// has to count tracks to read a block. | ||
| 992 | +const SUB_TRACK: u8 = 3; | ||
| 993 | + | ||
| 994 | +/// The `TrackEntry` of the subtitle track: type 0x11 (subtitles) and | ||
| 995 | +/// `S_TEXT/UTF8`, whose blocks are the cue's own UTF-8 text and whose timing is | ||
| 996 | +/// the block's -- the codec every player draws and the one this project's own | ||
| 997 | +/// reader parses back (`subtitle::cues_of`). | ||
| 998 | +/// | ||
| 999 | +/// The label is a `Language` where it is one (`eng`, `tur`: three letters is | ||
| 1000 | +/// what ISO-639-2 is) and a `Name` otherwise, which is exactly what | ||
| 1001 | +/// [`crate::subtitle::of_matroska`] reads back out, so a track exported and | ||
| 1002 | +/// re-imported keeps the name it had. | ||
| 1003 | +fn subtitle_track_entry(label: &str) -> Vec<u8> { | ||
| 1004 | + let mut entry = Vec::new(); | ||
| 1005 | + uint(&mut entry, TRACK_NUMBER, u64::from(SUB_TRACK)); | ||
| 1006 | + uint(&mut entry, TRACK_UID, u64::from(SUB_TRACK)); | ||
| 1007 | + uint(&mut entry, TRACK_TYPE, 0x11); | ||
| 1008 | + uint(&mut entry, FLAG_LACING, 0); | ||
| 1009 | + elem(&mut entry, CODEC_ID, b"S_TEXT/UTF8"); | ||
| 1010 | + let code = label.len() == 3 && label.bytes().all(|b| b.is_ascii_lowercase()); | ||
| 1011 | + match (code, label.is_empty()) { | ||
| 1012 | + (true, _) => elem(&mut entry, TRACK_LANGUAGE, label.as_bytes()), | ||
| 1013 | + (false, false) => elem(&mut entry, TRACK_NAME, label.as_bytes()), | ||
| 1014 | + (false, true) => {} | ||
| 1015 | + } | ||
| 1016 | + entry | ||
| 1017 | +} | ||
| 1018 | + | ||
| 881 | /// The sequence header OBU of a coded temporal unit, for the track's | 1019 | /// The sequence header OBU of a coded temporal unit, for the track's |
| 882 | /// `CodecPrivate`. `None` when the unit carries none, which the first keyframe | 1020 | /// `CodecPrivate`. `None` when the unit carries none, which the first keyframe |
| 883 | /// of a stream never may -- no decoder can start without it. | 1021 | /// of a stream never may -- no decoder can start without it. |
| @@ -1444,6 +1582,7 @@ mod tests { | |||
| 1444 | }, | 1582 | }, |
| 1445 | packets, | 1583 | packets, |
| 1446 | )), | 1584 | )), |
| 1585 | + None, | ||
| 1447 | ) | 1586 | ) |
| 1448 | .unwrap(); | 1587 | .unwrap(); |
| 1449 | // Half a second of picture under a second of sound: the tail of the | 1588 | // Half a second of picture under a second of sound: the tail of the |
| @@ -1571,6 +1710,7 @@ mod tests { | |||
| 1571 | config, | 1710 | config, |
| 1572 | }, | 1711 | }, |
| 1573 | None, | 1712 | None, |
| 1713 | + None, | ||
| 1574 | ) | 1714 | ) |
| 1575 | .unwrap(); | 1715 | .unwrap(); |
| 1576 | muxer.write_frame(&key, true).unwrap(); | 1716 | muxer.write_frame(&key, true).unwrap(); |
| @@ -1614,6 +1754,7 @@ mod tests { | |||
| 1614 | config: &[], | 1754 | config: &[], |
| 1615 | }, | 1755 | }, |
| 1616 | None, | 1756 | None, |
| 1757 | + None, | ||
| 1617 | ) | 1758 | ) |
| 1618 | .is_err() | 1759 | .is_err() |
| 1619 | ); | 1760 | ); |
crates/engine/src/playback.rsmodified+457 -76
| @@ -12,7 +12,7 @@ | |||
| 12 | //! the renderer decides which frame that means. | 12 | //! the renderer decides which frame that means. |
| 13 | 13 | ||
| 14 | use std::path::Path; | 14 | use std::path::Path; |
| 15 | -use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; | 15 | +use std::sync::atomic::{AtomicBool, AtomicI64, AtomicU64, Ordering}; |
| 16 | use std::sync::mpsc::{Receiver, TryRecvError}; | 16 | use std::sync::mpsc::{Receiver, TryRecvError}; |
| 17 | use std::sync::{Arc, Mutex}; | 17 | use std::sync::{Arc, Mutex}; |
| 18 | use std::thread; | 18 | use std::thread; |
| @@ -32,6 +32,13 @@ use crate::scale::{Composer, FitPolicy}; | |||
| 32 | /// only has to be short next to that; it costs one wakeup per 10 ms of audio. | 32 | /// only has to be short next to that; it costs one wakeup per 10 ms of audio. |
| 33 | const RING_FULL_WAIT: Duration = Duration::from_millis(10); | 33 | const RING_FULL_WAIT: Duration = Duration::from_millis(10); |
| 34 | 34 | ||
| 35 | +/// How long the feeder waits out a ring that took *nothing*: the flush of a | ||
| 36 | +/// restart, which only the device's own callback can clear (`engine-audio` | ||
| 37 | +/// refuses a write queued behind one). Short, because this is the gap at the | ||
| 38 | +/// head of every restart and the ear is in it -- one wakeup per millisecond, | ||
| 39 | +/// for the millisecond or two it lasts. | ||
| 40 | +const FLUSH_WAIT: Duration = Duration::from_millis(1); | ||
| 41 | + | ||
| 35 | /// The timeline a file with no picture scaffolds: 1080p at 30 fps, H.264 -- | 42 | /// The timeline a file with no picture scaffolds: 1080p at 30 fps, H.264 -- |
| 36 | /// nothing was shot on it, so it is the canvas a *later* import meets rather | 43 | /// nothing was shot on it, so it is the canvas a *later* import meets rather |
| 37 | /// than a description of the song. H.264 because it is the one codec that | 44 | /// than a description of the song. H.264 because it is the one codec that |
| @@ -91,6 +98,18 @@ struct Audio { | |||
| 91 | /// Bumped by every seek. A feeder only owns the device while this still | 98 | /// Bumped by every seek. A feeder only owns the device while this still |
| 92 | /// matches the value it started with; see [`feed`]. | 99 | /// matches the value it started with; see [`feed`]. |
| 93 | epoch: Arc<AtomicU64>, | 100 | epoch: Arc<AtomicU64>, |
| 101 | + /// The device position the *current* stream's first real sample was queued | ||
| 102 | + /// at, `-1` until the feeder has queued one. Written by the feeder under the | ||
| 103 | + /// device lock, read by [`tick`](PlaybackSession::tick). | ||
| 104 | + /// | ||
| 105 | + /// This is what keeps a restart out of the timeline. Between a flush and the | ||
| 106 | + /// first sample of the new stream the device plays silence -- a decoder open | ||
| 107 | + /// is tens of milliseconds -- and that silence is elapsed *device* time | ||
| 108 | + /// ([`crate::ao`] counts it, as it must: it really was played). It is not | ||
| 109 | + /// elapsed *timeline* time, and a clock anchored on the first poll after a | ||
| 110 | + /// seek counts it as such, which is a permanent offset between the picture | ||
| 111 | + /// and the sound, re-rolled by every edit made while playing. | ||
| 112 | + content_at: Arc<AtomicI64>, | ||
| 94 | /// The last [`TAP_SAMPLES`] mono samples handed to the device, oldest | 113 | /// The last [`TAP_SAMPLES`] mono samples handed to the device, oldest |
| 95 | /// first: what a meter or an analyser draws. Written by the feeder, which | 114 | /// first: what a meter or an analyser draws. Written by the feeder, which |
| 96 | /// is not the device's own callback -- the plugin's RT thread never sees | 115 | /// is not the device's own callback -- the plugin's RT thread never sees |
| @@ -158,6 +177,11 @@ pub struct PlaybackSession { | |||
| 158 | /// starts here, and a caller offering sizes to pick from needs the media's | 177 | /// starts here, and a caller offering sizes to pick from needs the media's |
| 159 | /// own among them or a project moved off it could never come back. | 178 | /// own among them or a project moved off it could never come back. |
| 160 | native: (u32, u32), | 179 | native: (u32, u32), |
| 180 | + /// ...and the scaffolding source's own frame rate, kept for exactly that | ||
| 181 | + /// reason: the project rate starts here, and the list a caller offers rates | ||
| 182 | + /// from needs the media's own on it or a project moved off it has no way | ||
| 183 | + /// back ([`PlaybackSession::set_frame_rate`] is not an undo step either). | ||
| 184 | + native_fps: f64, | ||
| 161 | frames: Receiver<Frame>, | 185 | frames: Receiver<Frame>, |
| 162 | /// The current decode worker. | 186 | /// The current decode worker. |
| 163 | worker: Worker, | 187 | worker: Worker, |
| @@ -228,6 +252,39 @@ pub struct PlaybackSession { | |||
| 228 | span: Option<Span>, | 252 | span: Option<Span>, |
| 229 | /// The last clip has been played out; see [`PlaybackSession::is_eos`]. | 253 | /// The last clip has been played out; see [`PlaybackSession::is_eos`]. |
| 230 | eos: bool, | 254 | eos: bool, |
| 255 | + /// The mix the running mixer is reading, when there is one: what lets a | ||
| 256 | + /// fader and the master ceiling move without rebuilding the audio pipeline | ||
| 257 | + /// at all ([`crate::audio::MixControls`]). `None` for a timeline that is | ||
| 258 | + /// not mixed -- one audio lane at unity with the limiter off, which is the | ||
| 259 | + /// bit-exact single-stream path -- and the first move off that reopens the | ||
| 260 | + /// stream once, mixed, and lives from there. | ||
| 261 | + mix: Option<Arc<crate::audio::MixControls>>, | ||
| 262 | + /// An audio stream has been started and has not yet played a sample: the | ||
| 263 | + /// window [`tick`](Self::tick) holds the clock still through, so the silence | ||
| 264 | + /// of a restart is never counted as timeline time. See | ||
| 265 | + /// [`Audio::content_at`]. | ||
| 266 | + priming: bool, | ||
| 267 | +} | ||
| 268 | + | ||
| 269 | +/// What an edit dirtied -- which half of the pipeline has to be rebuilt for the | ||
| 270 | +/// change to be seen or heard, and, far more to the point, which half must not | ||
| 271 | +/// be. | ||
| 272 | +/// | ||
| 273 | +/// Rebuilding a half is expensive and *audible*: the video worker costs a | ||
| 274 | +/// decoder open (98 ms of VA-API init, worst case, measured) and the audio one | ||
| 275 | +/// costs a flush, a re-open and a hole in the sound. A grade changes no sample | ||
| 276 | +/// and a fader changes no picture, so neither may pay the other's price -- that | ||
| 277 | +/// is the whole of this type. | ||
| 278 | +#[derive(Clone, Copy, PartialEq, Eq, Debug)] | ||
| 279 | +enum Dirty { | ||
| 280 | + /// The picture only: a grade, a fit policy, the project resolution. The | ||
| 281 | + /// sound keeps playing, untouched, and the clock never moves. | ||
| 282 | + Picture, | ||
| 283 | + /// The sound only: a clip's equalizer. The picture keeps playing. | ||
| 284 | + Sound, | ||
| 285 | + /// The timeline itself -- what is where, how long, how fast. Both halves | ||
| 286 | + /// are rebuilt, because both are decoding the wrong thing. | ||
| 287 | + Both, | ||
| 231 | } | 288 | } |
| 232 | 289 | ||
| 233 | impl PlaybackSession { | 290 | impl PlaybackSession { |
| @@ -277,6 +334,7 @@ impl PlaybackSession { | |||
| 277 | Ok(Self { | 334 | Ok(Self { |
| 278 | meta, | 335 | meta, |
| 279 | native: (meta.width, meta.height), | 336 | native: (meta.width, meta.height), |
| 337 | + native_fps: meta.frame_rate, | ||
| 280 | frames: stream.frames, | 338 | frames: stream.frames, |
| 281 | worker: stream.worker, | 339 | worker: stream.worker, |
| 282 | backend: stream.backend, | 340 | backend: stream.backend, |
| @@ -291,6 +349,8 @@ impl PlaybackSession { | |||
| 291 | span_rate: Rate::REAL_TIME, | 349 | span_rate: Rate::REAL_TIME, |
| 292 | span, | 350 | span, |
| 293 | eos: false, | 351 | eos: false, |
| 352 | + mix: None, | ||
| 353 | + priming: false, | ||
| 294 | }) | 354 | }) |
| 295 | } | 355 | } |
| 296 | 356 | ||
| @@ -375,6 +435,7 @@ impl PlaybackSession { | |||
| 375 | Ok(Self { | 435 | Ok(Self { |
| 376 | meta, | 436 | meta, |
| 377 | native: (width, height), | 437 | native: (width, height), |
| 438 | + native_fps: frame_rate, | ||
| 378 | frames: stream.frames, | 439 | frames: stream.frames, |
| 379 | worker: stream.worker, | 440 | worker: stream.worker, |
| 380 | backend: stream.backend, | 441 | backend: stream.backend, |
| @@ -395,6 +456,8 @@ impl PlaybackSession { | |||
| 395 | span_rate: Rate::REAL_TIME, | 456 | span_rate: Rate::REAL_TIME, |
| 396 | span, | 457 | span, |
| 397 | eos: false, | 458 | eos: false, |
| 459 | + mix: None, | ||
| 460 | + priming: false, | ||
| 398 | }) | 461 | }) |
| 399 | } | 462 | } |
| 400 | 463 | ||
| @@ -451,6 +514,7 @@ impl PlaybackSession { | |||
| 451 | Ok(Self { | 514 | Ok(Self { |
| 452 | meta, | 515 | meta, |
| 453 | native: (meta.width, meta.height), | 516 | native: (meta.width, meta.height), |
| 517 | + native_fps: IMAGE_ONLY_RATE, | ||
| 454 | frames: stream.frames, | 518 | frames: stream.frames, |
| 455 | worker: stream.worker, | 519 | worker: stream.worker, |
| 456 | backend: stream.backend, | 520 | backend: stream.backend, |
| @@ -465,6 +529,8 @@ impl PlaybackSession { | |||
| 465 | span_rate: Rate::REAL_TIME, | 529 | span_rate: Rate::REAL_TIME, |
| 466 | span, | 530 | span, |
| 467 | eos: false, | 531 | eos: false, |
| 532 | + mix: None, | ||
| 533 | + priming: false, | ||
| 468 | }) | 534 | }) |
| 469 | } | 535 | } |
| 470 | 536 | ||
| @@ -585,6 +651,32 @@ impl PlaybackSession { | |||
| 585 | meta.width = width; | 651 | meta.width = width; |
| 586 | meta.height = height; | 652 | meta.height = height; |
| 587 | } | 653 | } |
| 654 | + // ...and the project's own *rate*, which is the scaffold's unless the | ||
| 655 | + // file says otherwise. The two made-up rates above already took the | ||
| 656 | + // saved one (their counts are computed from it); a scaffold with a | ||
| 657 | + // picture keeps its own here, so a project cut at a rate nobody picked | ||
| 658 | + // is the file it always was -- and one where a rate *was* picked | ||
| 659 | + // ([`set_frame_rate`](Self::set_frame_rate)) comes back at it rather | ||
| 660 | + // than at the media's, which would leave every clip number counted in | ||
| 661 | + // frames the timeline no longer has. | ||
| 662 | + let native_fps = match crate::is_audio(&first.path) { | ||
| 663 | + true => AUDIO_ONLY_CANVAS.2, | ||
| 664 | + false if crate::is_image(&first.path) => IMAGE_ONLY_RATE, | ||
| 665 | + false => meta.frame_rate, | ||
| 666 | + }; | ||
| 667 | + if let Some(fps) = saved_fps { | ||
| 668 | + meta.frame_rate = fps; | ||
| 669 | + } | ||
| 670 | + // A song and a still have no rate of their own to be conformed from: | ||
| 671 | + // their length above was counted in the timeline's frames already, | ||
| 672 | + // whatever those are. A file with pictures is read through [`Rate`] like | ||
| 673 | + // any other source when the project is cut at another rate. | ||
| 674 | + let made_up = crate::is_audio(&first.path) || crate::is_image(&first.path); | ||
| 675 | + let scaffold_rate = match made_up || native_fps == meta.frame_rate { | ||
| 676 | + true => Rate::REAL_TIME, | ||
| 677 | + false => Rate::from_fps(native_fps, meta.frame_rate) | ||
| 678 | + .map_err(|e| format!("source {}: {e}", first.path.display()))?, | ||
| 679 | + }; | ||
| 588 | let first_audio = first_audio_of(&doc.sources)?; | 680 | let first_audio = first_audio_of(&doc.sources)?; |
| 589 | 681 | ||
| 590 | // In source order, with the scaffold's own count in its own slot: the | 682 | // In source order, with the scaffold's own count in its own slot: the |
| @@ -599,8 +691,8 @@ impl PlaybackSession { | |||
| 599 | let mut rates = Vec::with_capacity(doc.sources.len()); | 691 | let mut rates = Vec::with_capacity(doc.sources.len()); |
| 600 | for (i, source) in doc.sources.iter().enumerate() { | 692 | for (i, source) in doc.sources.iter().enumerate() { |
| 601 | if i == scaffold { | 693 | if i == scaffold { |
| 602 | - counts.push(meta.frame_count); | 694 | + counts.push(scaffold_rate.timeline_at(meta.frame_count)); |
| 603 | - rates.push(Rate::REAL_TIME); | 695 | + rates.push(scaffold_rate); |
| 604 | continue; | 696 | continue; |
| 605 | } | 697 | } |
| 606 | // A still has neither a rate to match nor a track to match with: | 698 | // A still has neither a rate to match nor a track to match with: |
| @@ -704,6 +796,7 @@ impl PlaybackSession { | |||
| 704 | let mut session = Self { | 796 | let mut session = Self { |
| 705 | meta, | 797 | meta, |
| 706 | native, | 798 | native, |
| 799 | + native_fps, | ||
| 707 | frames: stream.frames, | 800 | frames: stream.frames, |
| 708 | worker: stream.worker, | 801 | worker: stream.worker, |
| 709 | backend: stream.backend, | 802 | backend: stream.backend, |
| @@ -720,6 +813,8 @@ impl PlaybackSession { | |||
| 720 | span_rate: Rate::REAL_TIME, | 813 | span_rate: Rate::REAL_TIME, |
| 721 | span, | 814 | span, |
| 722 | eos: false, | 815 | eos: false, |
| 816 | + mix: None, | ||
| 817 | + priming: false, | ||
| 723 | }; | 818 | }; |
| 724 | // The scaffolding above opened source 0 from its first frame and the | 819 | // The scaffolding above opened source 0 from its first frame and the |
| 725 | // whole of its audio; this puts both onto the clip the playhead is | 820 | // whole of its audio; this puts both onto the clip the playhead is |
| @@ -752,6 +847,33 @@ impl PlaybackSession { | |||
| 752 | crate::export::planned_audio(&self.project, format) | 847 | crate::export::planned_audio(&self.project, format) |
| 753 | } | 848 | } |
| 754 | 849 | ||
| 850 | + /// What an export would do about the subtitle track at `pick` -- | ||
| 851 | + /// [`crate::export::planned_subtitles`], asked of the project a front-end is | ||
| 852 | + /// holding, and pure for the same reason. `pick` is a row of | ||
| 853 | + /// [`subtitles`](Self::subtitles). | ||
| 854 | + pub fn planned_subtitles(&self, format: crate::export::Format, pick: Option<usize>) -> String { | ||
| 855 | + crate::export::planned_subtitles(&self.project, format, pick) | ||
| 856 | + } | ||
| 857 | + | ||
| 858 | + /// Where the cues of the track at `pick` land on *this* timeline -- | ||
| 859 | + /// [`crate::export::timeline_cues`], the very map an export writes the file | ||
| 860 | + /// with, so a front-end that draws these draws what the file will say. On a | ||
| 861 | + /// rippled or cut timeline that is the whole point: an embedded track rides | ||
| 862 | + /// the spans that still play it, and a standalone `.srt` keeps the | ||
| 863 | + /// timeline's own clock, clipped to its length. | ||
| 864 | + /// | ||
| 865 | + /// Empty for a row that is not there and for a track that could not be read. | ||
| 866 | + /// Pure and file-free, so it may be asked per repaint; the cost is a walk of | ||
| 867 | + /// the spans and of the cues. | ||
| 868 | + pub fn timeline_cues(&self, pick: usize) -> Vec<crate::subtitle::Cue> { | ||
| 869 | + self.project | ||
| 870 | + .subtitles() | ||
| 871 | + .get(pick) | ||
| 872 | + .map_or_else(Vec::new, |t| { | ||
| 873 | + crate::export::timeline_cues(&self.project, t, self.meta.frame_rate) | ||
| 874 | + }) | ||
| 875 | + } | ||
| 876 | + | ||
| 755 | /// Why the sound's rate is not a choice for this timeline in this format -- | 877 | /// Why the sound's rate is not a choice for this timeline in this format -- |
| 756 | /// [`crate::export::audio_rate_refusal`], asked of the project a front-end | 878 | /// [`crate::export::audio_rate_refusal`], asked of the project a front-end |
| 757 | /// is holding, and pure for the same reason. | 879 | /// is holding, and pure for the same reason. |
| @@ -899,8 +1021,20 @@ impl PlaybackSession { | |||
| 899 | } | 1021 | } |
| 900 | } | 1022 | } |
| 901 | 1023 | ||
| 902 | - /// Whether the timeline has been played out. Any seek clears it, so an edit | 1024 | + /// Whether the timeline has been played out: the picture worker ran to the |
| 903 | - /// after the end (which reseeks) revives the session. | 1025 | + /// end and there was no next clip. It is exactly that and nothing more, |
| 1026 | + /// which is what decides who clears it -- **starting a picture does** | ||
| 1027 | + /// (`start_picture`), so a seek clears it and so does every edit that | ||
| 1028 | + /// rebuilds the picture (`Dirty::Picture`, `Dirty::Both` -- a paste or a | ||
| 1029 | + /// placement past the end revives the session, and it has a new picture to | ||
| 1030 | + /// show for it). | ||
| 1031 | + /// | ||
| 1032 | + /// A **sound-only** edit does not (`Dirty::Sound`: an equalizer, a fader): | ||
| 1033 | + /// it rebuilds the sound where the playhead stands and starts no picture | ||
| 1034 | + /// worker, so the last frame is still the last frame and this is still the | ||
| 1035 | + /// end. A front-end's `Ended` therefore survives an EQ tweak made after the | ||
| 1036 | + /// timeline ran out -- the parameters are on the project either way, and the | ||
| 1037 | + /// next press restarts from the top with them, which is what `Ended` means. | ||
| 904 | pub fn is_eos(&self) -> bool { | 1038 | pub fn is_eos(&self) -> bool { |
| 905 | self.eos | 1039 | self.eos |
| 906 | } | 1040 | } |
| @@ -1031,15 +1165,29 @@ impl PlaybackSession { | |||
| 1031 | gap.map_or(1, |s| s.len), | 1165 | gap.map_or(1, |s| s.len), |
| 1032 | )), | 1166 | )), |
| 1033 | }; | 1167 | }; |
| 1034 | - if let Ok(stream) = opened { | 1168 | + let Ok(stream) = opened else { |
| 1035 | - // Receiver first, worker second: the drop of the *old* receiver is | 1169 | + // The file would not open. The span still goes in -- the timeline |
| 1036 | - // what wakes the outgoing worker if it is parked in `send`, and only | 1170 | + // moves on, there are simply no more pictures -- but the *frames* |
| 1037 | - // then can it return and be reaped by a later sweep. Nothing here | 1171 | + // must not: the old channel's pictures are numbered in the old |
| 1038 | - // joins, so this ordering costs the seek nothing. | 1172 | + // source's frames, and presenting them under the new mapping would |
| 1039 | - self.frames = stream.frames; | 1173 | + // put the wrong picture at the wrong time (and leave |
| 1040 | - self.backend = stream.backend; | 1174 | + // [`decode_backend`](Self::decode_backend) describing a worker that |
| 1041 | - self.retire(stream.worker); | 1175 | + // is no longer feeding anything). A dead receiver instead, which is |
| 1042 | - } | 1176 | + // what carries the session on to the next span. The old worker stays |
| 1177 | + // parked in `self.worker` where the caller already cancelled it; the | ||
| 1178 | + // next span retires it. | ||
| 1179 | + self.frames = std::sync::mpsc::channel().1; | ||
| 1180 | + self.backend = BackendCell::new(Backend::Gap); | ||
| 1181 | + self.span = span; | ||
| 1182 | + return; | ||
| 1183 | + }; | ||
| 1184 | + // Receiver first, worker second: the drop of the *old* receiver is | ||
| 1185 | + // what wakes the outgoing worker if it is parked in `send`, and only | ||
| 1186 | + // then can it return and be reaped by a later sweep. Nothing here | ||
| 1187 | + // joins, so this ordering costs the seek nothing. | ||
| 1188 | + self.frames = stream.frames; | ||
| 1189 | + self.backend = stream.backend; | ||
| 1190 | + self.retire(stream.worker); | ||
| 1043 | self.span = span; | 1191 | self.span = span; |
| 1044 | } | 1192 | } |
| 1045 | 1193 | ||
| @@ -1158,18 +1306,20 @@ impl PlaybackSession { | |||
| 1158 | } | 1306 | } |
| 1159 | 1307 | ||
| 1160 | /// Gives that clip an equalizer, or takes it off with `None`. One undo step, | 1308 | /// Gives that clip an equalizer, or takes it off with `None`. One undo step, |
| 1161 | - /// like every other edit -- and, like every other edit, it *reseeks*: the | 1309 | + /// like every other edit -- and it rebuilds the **sound** where the playhead |
| 1162 | - /// audio workers are rebuilt from the new curves right where the playhead | ||
| 1163 | /// is, so a band changed during playback is heard from the next chunk on | 1310 | /// is, so a band changed during playback is heard from the next chunk on |
| 1164 | - /// rather than at the next play. `false` for a bad index or a non-finite | 1311 | + /// rather than at the next play. The picture is not touched: the video |
| 1165 | - /// band, and nothing changes. | 1312 | + /// worker keeps decoding through it ([`Dirty`]). `false` for a bad index or |
| 1313 | + /// a non-finite band, and nothing changes. | ||
| 1166 | /// | 1314 | /// |
| 1167 | - /// ponytail: the reseek is what makes it live, so the cost of a change is a | 1315 | + /// ponytail: the audio rebuild is what makes it live, so the cost of a |
| 1168 | - /// decoder restart -- inaudible at a drag's end, but too much to call once | 1316 | + /// change is a decoder restart -- inaudible at a drag's end, but too much to |
| 1169 | - /// per pointer sample (a caller commits one change per gesture). Upgrade | 1317 | + /// call once per pointer sample (a caller commits one change per gesture). |
| 1170 | - /// path is an `Arc` swap the running worker polls per chunk. | 1318 | + /// Upgrade path is the per-segment twin of [`crate::audio::MixControls`], |
| 1319 | + /// which the lane worker would poll per chunk the way the mixer polls the | ||
| 1320 | + /// gains. | ||
| 1171 | pub fn set_eq(&mut self, lane: Lane, idx: usize, params: Option<EqParams>) -> bool { | 1321 | pub fn set_eq(&mut self, lane: Lane, idx: usize, params: Option<EqParams>) -> bool { |
| 1172 | - self.edit(|p| p.set_eq(lane, idx, params)) | 1322 | + self.edit(Dirty::Sound, |p| p.set_eq(lane, idx, params)) |
| 1173 | } | 1323 | } |
| 1174 | 1324 | ||
| 1175 | /// How loud that lane plays, in dB -- everything on it, every frequency of | 1325 | /// How loud that lane plays, in dB -- everything on it, every frequency of |
| @@ -1178,12 +1328,36 @@ impl PlaybackSession { | |||
| 1178 | self.project.lane_gain_db(lane) | 1328 | self.project.lane_gain_db(lane) |
| 1179 | } | 1329 | } |
| 1180 | 1330 | ||
| 1181 | - /// Sets it. One undo step and a reseek, the equalizer's rule for the | 1331 | + /// Sets it. One undo step -- and **nothing is rebuilt**: a lane's volume |
| 1182 | - /// equalizer's reason: the mixer is rebuilt from the new volumes right | 1332 | + /// lives at the sum, so the running mixer is handed the new number and |
| 1183 | - /// where the playhead is, so a track turned down during playback is heard | 1333 | + /// picks it up at its next block ([`crate::audio::MixControls`]). A fader |
| 1184 | - /// turned down from the next chunk on. | 1334 | + /// held down under an arrow key therefore moves the level and nothing else: |
| 1335 | + /// no flush, no decoder restart, no hole in the sound and no blink in the | ||
| 1336 | + /// picture. | ||
| 1337 | + /// | ||
| 1338 | + /// The one exception is the timeline that is not mixed at all -- a single | ||
| 1339 | + /// audio lane at unity with the limiter off, which plays through the | ||
| 1340 | + /// bit-exact single-stream path and has no mixer to talk to. Moving *that* | ||
| 1341 | + /// off unity opens one, once; every move after it is live. | ||
| 1185 | pub fn set_lane_gain_db(&mut self, lane: Lane, db: f32) -> bool { | 1342 | pub fn set_lane_gain_db(&mut self, lane: Lane, db: f32) -> bool { |
| 1186 | - self.edit(|p| p.set_lane_gain_db(lane, db)) | 1343 | + if !self.project.set_lane_gain_db(lane, db) { |
| 1344 | + return false; | ||
| 1345 | + } | ||
| 1346 | + self.push_mix(); | ||
| 1347 | + true | ||
| 1348 | + } | ||
| 1349 | + | ||
| 1350 | + /// Hands the mix the running mixer is reading its new settings -- the whole | ||
| 1351 | + /// of what a fader and a ceiling cost. With no mixer listening (the | ||
| 1352 | + /// single-lane flat path, and a session with no sound at all) the sound is | ||
| 1353 | + /// rebuilt instead, which is what opens one. | ||
| 1354 | + fn push_mix(&mut self) { | ||
| 1355 | + let gains = self.project.audio_gains(); | ||
| 1356 | + let limiter = self.project.limiter(); | ||
| 1357 | + match &self.mix { | ||
| 1358 | + Some(mix) => mix.set(gains, limiter), | ||
| 1359 | + None => self.reseek_audio(), | ||
| 1360 | + } | ||
| 1187 | } | 1361 | } |
| 1188 | 1362 | ||
| 1189 | /// The master limiter the whole mix is summed through. | 1363 | /// The master limiter the whole mix is summed through. |
| @@ -1192,9 +1366,25 @@ impl PlaybackSession { | |||
| 1192 | } | 1366 | } |
| 1193 | 1367 | ||
| 1194 | /// Sets it, live like a lane volume and for the same reason -- the ceiling | 1368 | /// Sets it, live like a lane volume and for the same reason -- the ceiling |
| 1195 | - /// a person is dragging has to be the ceiling they are hearing. | 1369 | + /// a person is dragging has to be the ceiling they are hearing. Nothing is |
| 1370 | + /// rebuilt: the running limiter is *retuned* between two blocks | ||
| 1371 | + /// ([`crate::limiter::LimiterState::retune`]), so its delay line keeps | ||
| 1372 | + /// running and the sample count the master clock is made of does not move. | ||
| 1373 | + /// | ||
| 1374 | + /// ponytail: not an undo step, and deliberately -- [`Project::undo`] | ||
| 1375 | + /// restores the lane list, and the limiter is not in it, so snapshotting | ||
| 1376 | + /// here would push a step whose undo changes nothing a person can see or | ||
| 1377 | + /// hear (the twin [`set_lane_gain_db`](Self::set_lane_gain_db) *is* | ||
| 1378 | + /// undoable only because a lane volume lives in that list). The project | ||
| 1379 | + /// resolution is outside undo for the same reason and says so. Upgrade path | ||
| 1380 | + /// is a history that carries the mix beside the lanes, which every existing | ||
| 1381 | + /// snapshot site would then have to fill in. | ||
| 1196 | pub fn set_limiter(&mut self, limiter: crate::limiter::Limiter) -> bool { | 1382 | pub fn set_limiter(&mut self, limiter: crate::limiter::Limiter) -> bool { |
| 1197 | - self.edit(|p| p.set_limiter(limiter)) | 1383 | + if !self.project.set_limiter(limiter) { |
| 1384 | + return false; | ||
| 1385 | + } | ||
| 1386 | + self.push_mix(); | ||
| 1387 | + true | ||
| 1198 | } | 1388 | } |
| 1199 | 1389 | ||
| 1200 | /// Lifts one lane's clip out, leaving a gap: black frames on the video lane, | 1390 | /// Lifts one lane's clip out, leaving a gap: black frames on the video lane, |
| @@ -1203,7 +1393,7 @@ impl PlaybackSession { | |||
| 1203 | /// the last placement there is empties the timeline, which is a state | 1393 | /// the last placement there is empties the timeline, which is a state |
| 1204 | /// ([`is_empty`](Self::is_empty)) and one undo away. | 1394 | /// ([`is_empty`](Self::is_empty)) and one undo away. |
| 1205 | pub fn lift_clip(&mut self, lane: Lane, idx: usize) -> bool { | 1395 | pub fn lift_clip(&mut self, lane: Lane, idx: usize) -> bool { |
| 1206 | - self.edit(|p| p.lift(lane, idx)) | 1396 | + self.edit(Dirty::Both, |p| p.lift(lane, idx)) |
| 1207 | } | 1397 | } |
| 1208 | 1398 | ||
| 1209 | /// Moves that clip onto lane `to` with its head at timeline frame `start` -- | 1399 | /// Moves that clip onto lane `to` with its head at timeline frame `start` -- |
| @@ -1219,7 +1409,7 @@ impl PlaybackSession { | |||
| 1219 | /// pointer on a frame, and converting it back through seconds would be a | 1409 | /// pointer on a frame, and converting it back through seconds would be a |
| 1220 | /// rounding step between the box let go of and the box committed. | 1410 | /// rounding step between the box let go of and the box committed. |
| 1221 | pub fn move_clip_to(&mut self, from: Lane, idx: usize, to: Lane, start: u32) -> bool { | 1411 | pub fn move_clip_to(&mut self, from: Lane, idx: usize, to: Lane, start: u32) -> bool { |
| 1222 | - self.edit(|p| p.move_clip(from, idx, to, start)) | 1412 | + self.edit(Dirty::Both, |p| p.move_clip(from, idx, to, start)) |
| 1223 | } | 1413 | } |
| 1224 | 1414 | ||
| 1225 | /// Drags one end of that clip to timeline frame `to`, changing how much of | 1415 | /// Drags one end of that clip to timeline frame `to`, changing how much of |
| @@ -1401,7 +1591,7 @@ impl PlaybackSession { | |||
| 1401 | /// without the caller having to nudge the playhead itself. `false` for an | 1591 | /// without the caller having to nudge the playhead itself. `false` for an |
| 1402 | /// index that is not there and for a value that is not finite. | 1592 | /// index that is not there and for a value that is not finite. |
| 1403 | pub fn set_color(&mut self, lane: Lane, idx: usize, params: Option<ColorParams>) -> bool { | 1593 | pub fn set_color(&mut self, lane: Lane, idx: usize, params: Option<ColorParams>) -> bool { |
| 1404 | - self.edit(|p| p.set_color(lane, idx, params)) | 1594 | + self.edit(Dirty::Picture, |p| p.set_color(lane, idx, params)) |
| 1405 | } | 1595 | } |
| 1406 | 1596 | ||
| 1407 | /// The same grade and the same reseek without the undo step | 1597 | /// The same grade and the same reseek without the undo step |
| @@ -1409,7 +1599,7 @@ impl PlaybackSession { | |||
| 1409 | /// through, so the frame regrades under the hand and the whole gesture is | 1599 | /// through, so the frame regrades under the hand and the whole gesture is |
| 1410 | /// still a single `z`. | 1600 | /// still a single `z`. |
| 1411 | pub fn set_color_live(&mut self, lane: Lane, idx: usize, params: Option<ColorParams>) -> bool { | 1601 | pub fn set_color_live(&mut self, lane: Lane, idx: usize, params: Option<ColorParams>) -> bool { |
| 1412 | - self.edit(|p| p.set_color_live(lane, idx, params)) | 1602 | + self.edit(Dirty::Picture, |p| p.set_color_live(lane, idx, params)) |
| 1413 | } | 1603 | } |
| 1414 | 1604 | ||
| 1415 | /// The project's resolution: what every clip is composed onto, what the | 1605 | /// The project's resolution: what every clip is composed onto, what the |
| @@ -1426,10 +1616,13 @@ impl PlaybackSession { | |||
| 1426 | self.native | 1616 | self.native |
| 1427 | } | 1617 | } |
| 1428 | 1618 | ||
| 1429 | - /// Sets it. Reseeks like an edit, so the frame on screen is recomposed at | 1619 | + /// Sets it. Rebuilds the **picture** where the playhead is, so the frame on |
| 1430 | - /// the new size at once, paused or playing. `false` for a size that is not a | 1620 | + /// screen is recomposed at the new size at once, paused or playing -- and |
| 1431 | - /// picture -- zero either way, or past 8K, which is where the per-frame | 1621 | + /// the sound is not touched at all: the size of the canvas is not something |
| 1432 | - /// buffers stop being a sane thing to allocate from a keystroke. | 1622 | + /// a sample can carry, so resizing a 4K film mid-play costs neither a hole |
| 1623 | + /// in the audio nor an offset against it ([`Dirty`]). `false` for a size | ||
| 1624 | + /// that is not a picture -- zero either way, or past 8K, which is where the | ||
| 1625 | + /// per-frame buffers stop being a sane thing to allocate from a keystroke. | ||
| 1433 | /// | 1626 | /// |
| 1434 | /// ponytail: not an undo step. The project resolution is not in the lane | 1627 | /// ponytail: not an undo step. The project resolution is not in the lane |
| 1435 | /// snapshots [`Project::undo`] restores, so cycling it back is one more | 1628 | /// snapshots [`Project::undo`] restores, so cycling it back is one more |
| @@ -1444,6 +1637,61 @@ impl PlaybackSession { | |||
| 1444 | } | 1637 | } |
| 1445 | self.meta.width = width; | 1638 | self.meta.width = width; |
| 1446 | self.meta.height = height; | 1639 | self.meta.height = height; |
| 1640 | + self.invalidate(Dirty::Picture); | ||
| 1641 | + true | ||
| 1642 | + } | ||
| 1643 | + | ||
| 1644 | + /// The scaffolding source's own frame rate -- what the project rate started | ||
| 1645 | + /// as, and the one rate a caller offering a list of them must not leave out | ||
| 1646 | + /// ([`native_resolution`](Self::native_resolution)'s reason). | ||
| 1647 | + pub fn native_frame_rate(&self) -> f64 { | ||
| 1648 | + self.native_fps | ||
| 1649 | + } | ||
| 1650 | + | ||
| 1651 | + /// Cuts this timeline at `fps` from here on: every clip is *conformed* to | ||
| 1652 | + /// the new rate ([`Project::retime`]), every source is read through a | ||
| 1653 | + /// [`Rate`] against it, and an export written from this session comes out at | ||
| 1654 | + /// it. The edit survives as the same seconds of the same footage on a finer | ||
| 1655 | + /// or coarser grid -- a 30 fps take on a timeline moved to 24 keeps its | ||
| 1656 | + /// length and its sync, it is simply counted in 24ths now. | ||
| 1657 | + /// | ||
| 1658 | + /// Reseeks like [`set_resolution`](Self::set_resolution), so the picture and | ||
| 1659 | + /// the sound under the playhead are already the new rate's when this | ||
| 1660 | + /// returns. `false` -- changing nothing -- for a rate that is not a rate, for | ||
| 1661 | + /// the one already in force, and for one no timescale can name | ||
| 1662 | + /// ([`crate::mux::frame_timing`], the same wall a file of an unnameable rate | ||
| 1663 | + /// is refused at). | ||
| 1664 | + /// | ||
| 1665 | + /// ponytail: not an undo step, exactly as the project resolution is not -- | ||
| 1666 | + /// and this one *moves the frame numbers*, so the way back is picking the | ||
| 1667 | + /// old rate (or the media's, [`native_frame_rate`](Self::native_frame_rate)) | ||
| 1668 | + /// rather than a `z`, and it lands within a frame of where it started rather | ||
| 1669 | + /// than on it (see [`Project::retime`]). Upgrade path is the same one: the | ||
| 1670 | + /// project's settings snapshotted beside the lanes. | ||
| 1671 | + pub fn set_frame_rate(&mut self, fps: f64) -> bool { | ||
| 1672 | + if !fps.is_finite() || fps <= 0.0 || fps == self.meta.frame_rate { | ||
| 1673 | + return false; | ||
| 1674 | + } | ||
| 1675 | + // Old timeline frames per new one, exactly -- the one map every frame | ||
| 1676 | + // number on every lane goes through. Built before anything is touched, | ||
| 1677 | + // since a rate no timescale can name is a refusal and not a half-retimed | ||
| 1678 | + // project. | ||
| 1679 | + let Ok(k) = Rate::from_fps(self.meta.frame_rate, fps) else { | ||
| 1680 | + return false; | ||
| 1681 | + }; | ||
| 1682 | + // Lengths first: the retime holds every clip inside its source's *new* | ||
| 1683 | + // length, so a clip that played to the last frame of its file still | ||
| 1684 | + // does rather than naming one past the end. | ||
| 1685 | + for count in &mut self.counts { | ||
| 1686 | + *count = k.timeline_at(*count).max(1); | ||
| 1687 | + } | ||
| 1688 | + self.project.retime(k, &self.counts); | ||
| 1689 | + // A file's own rate has not changed; what it is *against* has. | ||
| 1690 | + for rate in &mut self.rates { | ||
| 1691 | + *rate = rate.then(k); | ||
| 1692 | + } | ||
| 1693 | + self.meta.frame_rate = fps; | ||
| 1694 | + self.meta.frame_count = k.timeline_at(self.meta.frame_count).max(1); | ||
| 1447 | let now = self.now(); | 1695 | let now = self.now(); |
| 1448 | self.seek(now); | 1696 | self.seek(now); |
| 1449 | true | 1697 | true |
| @@ -1458,7 +1706,7 @@ impl PlaybackSession { | |||
| 1458 | /// grade: the picture on screen is recomposed through the new policy without | 1706 | /// grade: the picture on screen is recomposed through the new policy without |
| 1459 | /// the caller nudging the playhead. `false` for an index that is not there. | 1707 | /// the caller nudging the playhead. `false` for an index that is not there. |
| 1460 | pub fn set_fit(&mut self, lane: Lane, idx: usize, fit: FitPolicy) -> bool { | 1708 | pub fn set_fit(&mut self, lane: Lane, idx: usize, fit: FitPolicy) -> bool { |
| 1461 | - self.edit(|p| p.set_fit(lane, idx, fit)) | 1709 | + self.edit(Dirty::Picture, |p| p.set_fit(lane, idx, fit)) |
| 1462 | } | 1710 | } |
| 1463 | 1711 | ||
| 1464 | /// The clip at `idx` -- what a caller copies. It is a pair of source frame | 1712 | /// The clip at `idx` -- what a caller copies. It is a pair of source frame |
| @@ -1473,7 +1721,7 @@ impl PlaybackSession { | |||
| 1473 | /// the end of the timeline the clip is appended. One undo step. | 1721 | /// the end of the timeline the clip is appended. One undo step. |
| 1474 | pub fn paste_at(&mut self, timeline_secs: f64, clip: Clip) -> bool { | 1722 | pub fn paste_at(&mut self, timeline_secs: f64, clip: Clip) -> bool { |
| 1475 | let at = secs_to_frame(timeline_secs, self.meta.frame_rate); | 1723 | let at = secs_to_frame(timeline_secs, self.meta.frame_rate); |
| 1476 | - self.edit(|p| p.paste(at, clip)) | 1724 | + self.edit(Dirty::Both, |p| p.paste(at, clip)) |
| 1477 | } | 1725 | } |
| 1478 | 1726 | ||
| 1479 | /// Places the whole of `path` played on its audio `stream` at | 1727 | /// Places the whole of `path` played on its audio `stream` at |
| @@ -1632,7 +1880,7 @@ impl PlaybackSession { | |||
| 1632 | /// and it reseeks like every other edit. | 1880 | /// and it reseeks like every other edit. |
| 1633 | pub fn place_at(&mut self, lane: Lane, timeline_secs: f64, clip: Clip) -> bool { | 1881 | pub fn place_at(&mut self, lane: Lane, timeline_secs: f64, clip: Clip) -> bool { |
| 1634 | let at = secs_to_frame(timeline_secs, self.meta.frame_rate); | 1882 | let at = secs_to_frame(timeline_secs, self.meta.frame_rate); |
| 1635 | - self.edit(|p| p.place(lane, at, clip)) | 1883 | + self.edit(Dirty::Both, |p| p.place(lane, at, clip)) |
| 1636 | } | 1884 | } |
| 1637 | 1885 | ||
| 1638 | /// Removes `lane`'s clip at `idx` and everything under it, closing the gap | 1886 | /// Removes `lane`'s clip at `idx` and everything under it, closing the gap |
| @@ -1646,12 +1894,12 @@ impl PlaybackSession { | |||
| 1646 | /// not `V1`'s, and a front-end that could only say "the third clip" would | 1894 | /// not `V1`'s, and a front-end that could only say "the third clip" would |
| 1647 | /// delete the wrong one the moment a second lane exists. | 1895 | /// delete the wrong one the moment a second lane exists. |
| 1648 | pub fn delete_clip(&mut self, lane: Lane, idx: usize) -> bool { | 1896 | pub fn delete_clip(&mut self, lane: Lane, idx: usize) -> bool { |
| 1649 | - self.edit(|p| p.delete_in(lane, idx)) | 1897 | + self.edit(Dirty::Both, |p| p.delete_in(lane, idx)) |
| 1650 | } | 1898 | } |
| 1651 | 1899 | ||
| 1652 | /// Undoes the last successful edit, and reseeks like a delete. | 1900 | /// Undoes the last successful edit, and reseeks like a delete. |
| 1653 | pub fn undo(&mut self) -> bool { | 1901 | pub fn undo(&mut self) -> bool { |
| 1654 | - self.edit(Project::undo) | 1902 | + self.edit(Dirty::Both, Project::undo) |
| 1655 | } | 1903 | } |
| 1656 | 1904 | ||
| 1657 | /// Takes `path` into the **library**: it becomes a source of this session, | 1905 | /// Takes `path` into the **library**: it becomes a source of this session, |
| @@ -1743,18 +1991,36 @@ impl PlaybackSession { | |||
| 1743 | Ok(source) | 1991 | Ok(source) |
| 1744 | } | 1992 | } |
| 1745 | 1993 | ||
| 1746 | - /// Applies an edit and, if it took, reseeks onto the new mapping. `seek` | 1994 | + /// Applies an edit and, if it took, rebuilds **what it dirtied** and nothing |
| 1747 | - /// clamps to the new duration and keeps playing playing, so a delete that | 1995 | + /// else ([`Dirty`]). A structural edit reseeks: `seek` clamps to the new |
| 1748 | - /// shortens the timeline past the playhead lands on the last frame. | 1996 | + /// duration and keeps playing playing, so a delete that shortens the |
| 1749 | - fn edit(&mut self, f: impl FnOnce(&mut Project) -> bool) -> bool { | 1997 | + /// timeline past the playhead lands on the last frame. A grade or a fit |
| 1998 | + /// policy rebuilds the picture where it stands, with the sound running | ||
| 1999 | + /// through it untouched -- no flush, no re-open, no hole -- and an | ||
| 2000 | + /// equalizer the other way round. | ||
| 2001 | + fn edit(&mut self, dirty: Dirty, f: impl FnOnce(&mut Project) -> bool) -> bool { | ||
| 1750 | if !f(&mut self.project) { | 2002 | if !f(&mut self.project) { |
| 1751 | return false; | 2003 | return false; |
| 1752 | } | 2004 | } |
| 1753 | - let now = self.now(); | 2005 | + self.invalidate(dirty); |
| 1754 | - self.seek(now); | ||
| 1755 | true | 2006 | true |
| 1756 | } | 2007 | } |
| 1757 | 2008 | ||
| 2009 | + /// Rebuilds the dirtied half (or both) at the playhead. | ||
| 2010 | + fn invalidate(&mut self, dirty: Dirty) { | ||
| 2011 | + match dirty { | ||
| 2012 | + Dirty::Picture => { | ||
| 2013 | + let (_, target) = self.landing(self.now()); | ||
| 2014 | + self.start_picture(target); | ||
| 2015 | + } | ||
| 2016 | + Dirty::Sound => self.reseek_audio(), | ||
| 2017 | + Dirty::Both => { | ||
| 2018 | + let now = self.now(); | ||
| 2019 | + self.seek(now); | ||
| 2020 | + } | ||
| 2021 | + } | ||
| 2022 | + } | ||
| 2023 | + | ||
| 1758 | /// Current timeline position in seconds. | 2024 | /// Current timeline position in seconds. |
| 1759 | pub fn now(&self) -> f64 { | 2025 | pub fn now(&self) -> f64 { |
| 1760 | self.clock.now() | 2026 | self.clock.now() |
| @@ -1856,12 +2122,51 @@ impl PlaybackSession { | |||
| 1856 | /// Playing stays playing and paused stays paused -- but a paused seek still | 2122 | /// Playing stays playing and paused stays paused -- but a paused seek still |
| 1857 | /// decodes, so the caller can show the frame it landed on. | 2123 | /// decodes, so the caller can show the frame it landed on. |
| 1858 | pub fn seek(&mut self, secs: f64) { | 2124 | pub fn seek(&mut self, secs: f64) { |
| 2125 | + let (t, target) = self.landing(secs); | ||
| 2126 | + let was_playing = self.clock.is_playing(); | ||
| 2127 | + self.stop_audio(); | ||
| 2128 | + self.start_picture(target); | ||
| 2129 | + let audio_running = self.start_audio(target); | ||
| 2130 | + // Same invariant as `play`: position the clock before audio restarts. | ||
| 2131 | + if audio_running && self.clock.source() != ClockSource::Audio { | ||
| 2132 | + self.clock.switch_to_audio(); | ||
| 2133 | + } | ||
| 2134 | + self.clock.seek_to(t); | ||
| 2135 | + self.resume(was_playing); | ||
| 2136 | + } | ||
| 2137 | + | ||
| 2138 | + /// Where a seek to `secs` lands: the clamped timeline position and the | ||
| 2139 | + /// timeline frame it means. The one place the clamp lives, so every | ||
| 2140 | + /// invalidation below lands on the same frame a seek would. | ||
| 2141 | + fn landing(&self, secs: f64) -> (f64, u32) { | ||
| 1859 | let fps = self.meta.frame_rate; | 2142 | let fps = self.meta.frame_rate; |
| 1860 | let total = self.project.timeline_frames(); | 2143 | let total = self.project.timeline_frames(); |
| 1861 | let t = secs.clamp(0.0, f64::from(total) / fps); | 2144 | let t = secs.clamp(0.0, f64::from(total) / fps); |
| 1862 | - let target = secs_to_frame(t, fps).min(total.saturating_sub(1)); | 2145 | + (t, secs_to_frame(t, fps).min(total.saturating_sub(1))) |
| 1863 | - let was_playing = self.clock.is_playing(); | 2146 | + } |
| 2147 | + | ||
| 2148 | + /// Rebuilds the **picture** at `target` and touches nothing else: the sound | ||
| 2149 | + /// keeps playing out of the same stream, the clock keeps running, and a | ||
| 2150 | + /// grade dragged during playback is therefore silent. | ||
| 2151 | + fn start_picture(&mut self, target: u32) { | ||
| 2152 | + // Cancel first, drop second: the old worker may be parked in `send` on | ||
| 2153 | + // the bounded channel, where only the disconnect wakes it -- and it | ||
| 2154 | + // then finds the flag already set. It is then parked, not joined; see | ||
| 2155 | + // [`retire`](Self::retire), which is what keeps a scrub off the price | ||
| 2156 | + // of a VA-API init. | ||
| 2157 | + self.worker.cancel(); | ||
| 2158 | + // The span runs from `target` to the end of whatever it landed in -- a | ||
| 2159 | + // clip, or a gap, which starts a black-frame worker instead. `None` is | ||
| 2160 | + // the emptied timeline, black too, and `start_span` says so. | ||
| 2161 | + self.start_span(self.project.composite_span_at(target)); | ||
| 2162 | + self.eos = false; | ||
| 2163 | + } | ||
| 1864 | 2164 | ||
| 2165 | + /// Silences the device and supersedes whatever is feeding it: the first half | ||
| 2166 | + /// of every audio restart, and the only thing that ever discards queued | ||
| 2167 | + /// sound. | ||
| 2168 | + fn stop_audio(&mut self) { | ||
| 2169 | + self.mix = None; | ||
| 1865 | if let Some(audio) = &self.audio { | 2170 | if let Some(audio) = &self.audio { |
| 1866 | let ao = audio.ao.lock().unwrap(); | 2171 | let ao = audio.ao.lock().unwrap(); |
| 1867 | ao.set_active(false); | 2172 | ao.set_active(false); |
| @@ -1869,25 +2174,31 @@ impl PlaybackSession { | |||
| 1869 | // feeder re-checks the epoch inside that same lock: whatever it is | 2174 | // feeder re-checks the epoch inside that same lock: whatever it is |
| 1870 | // carrying can no longer reach the ring after this point. | 2175 | // carrying can no longer reach the ring after this point. |
| 1871 | audio.epoch.fetch_add(1, Ordering::Release); | 2176 | audio.epoch.fetch_add(1, Ordering::Release); |
| 2177 | + // Nothing of the new stream has been played yet, by definition. | ||
| 2178 | + audio.content_at.store(-1, Ordering::Release); | ||
| 1872 | ao.flush(); | 2179 | ao.flush(); |
| 1873 | // The flushed samples are not being played any more, so nothing may | 2180 | // The flushed samples are not being played any more, so nothing may |
| 1874 | // still be drawn from them. | 2181 | // still be drawn from them. |
| 1875 | audio.tap.lock().unwrap().clear(); | 2182 | audio.tap.lock().unwrap().clear(); |
| 1876 | } | 2183 | } |
| 2184 | + } | ||
| 1877 | 2185 | ||
| 1878 | - // Cancel first, drop second: the old worker may be parked in `send` on | 2186 | + /// Puts the device back where it was: playing if it was playing, and with |
| 1879 | - // the bounded channel, where only the disconnect wakes it -- and it | 2187 | + /// the clock held until the new stream is really audible (see |
| 1880 | - // then finds the flag already set. It is then parked, not joined; see | 2188 | + /// [`Audio::content_at`]). |
| 1881 | - // [`retire`](Self::retire), which is what keeps a scrub off the price | 2189 | + fn resume(&mut self, was_playing: bool) { |
| 1882 | - // of a VA-API init. | 2190 | + self.priming = true; |
| 1883 | - self.worker.cancel(); | 2191 | + if was_playing && let Some(audio) = &self.audio { |
| 1884 | - // The span runs from `target` to the end of whatever it landed in -- a | 2192 | + audio.ao.lock().unwrap().set_active(true); |
| 1885 | - // clip, or a gap, which starts a black-frame worker instead. `None` is | 2193 | + } |
| 1886 | - // the emptied timeline, black too, and `start_span` says so. | 2194 | + } |
| 1887 | - self.start_span(self.project.composite_span_at(target)); | ||
| 1888 | - self.eos = false; | ||
| 1889 | 2195 | ||
| 2196 | + /// Rebuilds the **sound** from `target` -- the second half of a restart -- | ||
| 2197 | + /// and says whether anything will be fed. | ||
| 2198 | + fn start_audio(&mut self, target: u32) -> bool { | ||
| 2199 | + let fps = self.meta.frame_rate; | ||
| 1890 | let mut audio_running = false; | 2200 | let mut audio_running = false; |
| 2201 | + let mut live = None; | ||
| 1891 | if let Some(audio) = &self.audio | 2202 | if let Some(audio) = &self.audio |
| 1892 | && !audio.died.load(Ordering::Acquire) | 2203 | && !audio.died.load(Ordering::Acquire) |
| 1893 | { | 2204 | { |
| @@ -1921,32 +2232,58 @@ impl PlaybackSession { | |||
| 1921 | // the library row said, and what an export copies (`export::run`). | 2232 | // the library row said, and what an export copies (`export::run`). |
| 1922 | let sources = self.project.audio_sources(); | 2233 | let sources = self.project.audio_sources(); |
| 1923 | // ...and the mix settings over the lot: each lane's own volume on | 2234 | // ...and the mix settings over the lot: each lane's own volume on |
| 1924 | - // its way into the sum and the master limiter over the sum, both | 2235 | + // its way into the sum and the master limiter over the sum. These |
| 1925 | - // rebuilt here like the curves above, which is what makes a lane | 2236 | + // two are handed over *live* as well as at the open: they sit at |
| 1926 | - // fader and a ceiling audible while the timeline runs. | 2237 | + // the sum, where nothing is decoded, so a fader moved later is a |
| 2238 | + // number the running mixer picks up rather than a stream rebuilt | ||
| 2239 | + // under the ear ([`crate::audio::MixControls`]). | ||
| 1927 | let gains = self.project.audio_gains(); | 2240 | let gains = self.project.audio_gains(); |
| 1928 | let limiter = self.project.limiter(); | 2241 | let limiter = self.project.limiter(); |
| 1929 | - audio_running = match AudioSession::open_mixed_streams_master( | 2242 | + let controls = crate::audio::MixControls::new(gains.clone(), limiter); |
| 1930 | - &sources, &segs, &eqs, &speeds, &gains, limiter, | 2243 | + audio_running = match AudioSession::open_mixed_streams_live( |
| 2244 | + &sources, | ||
| 2245 | + &segs, | ||
| 2246 | + &eqs, | ||
| 2247 | + &speeds, | ||
| 2248 | + &gains, | ||
| 2249 | + limiter, | ||
| 2250 | + Some(&controls), | ||
| 1931 | ) { | 2251 | ) { |
| 1932 | Ok(Some((_, rx))) => audio.spawn_feeder(rx), | 2252 | Ok(Some((_, rx))) => audio.spawn_feeder(rx), |
| 1933 | _ => false, | 2253 | _ => false, |
| 1934 | }; | 2254 | }; |
| 2255 | + // Only a mixed timeline has a mixer to talk to; the single-lane | ||
| 2256 | + // flat path is the bit-exact one and has none. | ||
| 2257 | + live = (audio_running && controls.is_live()).then_some(controls); | ||
| 1935 | if !audio_running { | 2258 | if !audio_running { |
| 1936 | // Nothing will ever be fed again; let `tick` fall to wall time | 2259 | // Nothing will ever be fed again; let `tick` fall to wall time |
| 1937 | // instead of waiting on a device that has no more work coming. | 2260 | // instead of waiting on a device that has no more work coming. |
| 1938 | audio.fed_all.store(true, Ordering::Release); | 2261 | audio.fed_all.store(true, Ordering::Release); |
| 1939 | } | 2262 | } |
| 1940 | } | 2263 | } |
| 2264 | + self.mix = live; | ||
| 2265 | + audio_running | ||
| 2266 | + } | ||
| 1941 | 2267 | ||
| 1942 | - // Same invariant as `play`: position the clock before audio restarts. | 2268 | + /// Rebuilds the sound alone, from where the playhead is: what a change that |
| 2269 | + /// no picture can show goes through. The video worker is left decoding, so | ||
| 2270 | + /// the picture does not blink -- and the clock, held still by | ||
| 2271 | + /// [`resume`](Self::resume) until the new stream is audible, puts the sound | ||
| 2272 | + /// back exactly where the picture already is. | ||
| 2273 | + /// | ||
| 2274 | + /// End of stream is deliberately left alone -- no picture worker is started | ||
| 2275 | + /// here, so a timeline that was played out still is; see | ||
| 2276 | + /// [`is_eos`](Self::is_eos). | ||
| 2277 | + fn reseek_audio(&mut self) { | ||
| 2278 | + let (t, target) = self.landing(self.now()); | ||
| 2279 | + let was_playing = self.clock.is_playing(); | ||
| 2280 | + self.stop_audio(); | ||
| 2281 | + let audio_running = self.start_audio(target); | ||
| 1943 | if audio_running && self.clock.source() != ClockSource::Audio { | 2282 | if audio_running && self.clock.source() != ClockSource::Audio { |
| 1944 | self.clock.switch_to_audio(); | 2283 | self.clock.switch_to_audio(); |
| 1945 | } | 2284 | } |
| 1946 | self.clock.seek_to(t); | 2285 | self.clock.seek_to(t); |
| 1947 | - if was_playing && let Some(audio) = &self.audio { | 2286 | + self.resume(was_playing); |
| 1948 | - audio.ao.lock().unwrap().set_active(true); | ||
| 1949 | - } | ||
| 1950 | } | 2287 | } |
| 1951 | 2288 | ||
| 1952 | /// Renders the edited timeline to `out` on a worker thread. The session is | 2289 | /// Renders the edited timeline to `out` on a worker thread. The session is |
| @@ -2000,10 +2337,35 @@ impl PlaybackSession { | |||
| 2000 | // Audio EOF. Wall time carries the same timeline on from here, with | 2337 | // Audio EOF. Wall time carries the same timeline on from here, with |
| 2001 | // no jump, and this branch cannot be reached again. | 2338 | // no jump, and this branch cannot be reached again. |
| 2002 | self.clock.switch_to_wall(); | 2339 | self.clock.switch_to_wall(); |
| 2003 | - } else { | 2340 | + return; |
| 2341 | + } | ||
| 2342 | + if self.priming { | ||
| 2343 | + // A stream that has been started and has not been heard yet: the | ||
| 2344 | + // device is playing the silence of its own restart, and none of it | ||
| 2345 | + // is timeline time ([`Audio::content_at`]). The clock holds where | ||
| 2346 | + // the seek left it -- so the picture holds too, on the frame it | ||
| 2347 | + // landed on, rather than sliding ahead of a sound that has not | ||
| 2348 | + // started. | ||
| 2349 | + let started = audio.content_at.load(Ordering::Acquire); | ||
| 2350 | + if started < 0 { | ||
| 2351 | + return; | ||
| 2352 | + } | ||
| 2353 | + // ...and then the *first sample of the stream* becomes the | ||
| 2354 | + // reference, not whatever position this poll happened to catch: the | ||
| 2355 | + // clock's own anchor is its first report ([`PlaybackClock`]), and | ||
| 2356 | + // anchoring it here is what makes a mid-play edit cost no offset. | ||
| 2357 | + // | ||
| 2358 | + // ponytail: `started` is the position when the sample was queued, | ||
| 2359 | + // and it is heard at the next callback -- up to one quantum (5-21 | ||
| 2360 | + // ms) later, so that much of the restart is still counted. Upgrade | ||
| 2361 | + // path is the position at the first *pop* of real audio, which only | ||
| 2362 | + // the plugin's RT thread can see. | ||
| 2004 | self.clock | 2363 | self.clock |
| 2005 | - .set_audio_position(position as u64, audio.sample_rate); | 2364 | + .set_audio_position(started as u64, audio.sample_rate); |
| 2365 | + self.priming = false; | ||
| 2006 | } | 2366 | } |
| 2367 | + self.clock | ||
| 2368 | + .set_audio_position(position as u64, audio.sample_rate); | ||
| 2007 | } | 2369 | } |
| 2008 | } | 2370 | } |
| 2009 | 2371 | ||
| @@ -2232,6 +2594,7 @@ fn open_audio(path: &Path, stream: usize) -> (Option<Audio>, Option<String>) { | |||
| 2232 | fed_all: Arc::new(AtomicBool::new(false)), | 2594 | fed_all: Arc::new(AtomicBool::new(false)), |
| 2233 | died: Arc::new(AtomicBool::new(false)), | 2595 | died: Arc::new(AtomicBool::new(false)), |
| 2234 | epoch: Arc::new(AtomicU64::new(0)), | 2596 | epoch: Arc::new(AtomicU64::new(0)), |
| 2597 | + content_at: Arc::new(AtomicI64::new(-1)), | ||
| 2235 | tap: Arc::new(Mutex::new(Vec::with_capacity(TAP_SAMPLES))), | 2598 | tap: Arc::new(Mutex::new(Vec::with_capacity(TAP_SAMPLES))), |
| 2236 | }; | 2599 | }; |
| 2237 | (audio.spawn_feeder(rx).then_some(audio), None) | 2600 | (audio.spawn_feeder(rx).then_some(audio), None) |
| @@ -2257,21 +2620,39 @@ fn feed(rx: Receiver<AudioChunk>, audio: &Audio, epoch: u64) { | |||
| 2257 | if audio.epoch.load(Ordering::Acquire) != epoch { | 2620 | if audio.epoch.load(Ordering::Acquire) != epoch { |
| 2258 | return; | 2621 | return; |
| 2259 | } | 2622 | } |
| 2260 | - match ao.write(&pending) { | 2623 | + let accepted = match ao.write(&pending) { |
| 2261 | Some(n) => n, | 2624 | Some(n) => n, |
| 2262 | None => { | 2625 | None => { |
| 2263 | // Output died; flag it so `tick` moves the clock to wall time. | 2626 | // Output died; flag it so `tick` moves the clock to wall time. |
| 2264 | audio.died.store(true, Ordering::Release); | 2627 | audio.died.store(true, Ordering::Release); |
| 2265 | return; | 2628 | return; |
| 2266 | } | 2629 | } |
| 2630 | + }; | ||
| 2631 | + // The first sample of this stream to reach the ring, stamped with | ||
| 2632 | + // what the device had played by then: everything before it was the | ||
| 2633 | + // silence of the restart, and [`PlaybackSession::tick`] anchors the | ||
| 2634 | + // clock here so that silence is never timeline time. Under the | ||
| 2635 | + // device lock, with the epoch already checked, so the stamp and the | ||
| 2636 | + // sample belong to the same stream. | ||
| 2637 | + if accepted > 0 && audio.content_at.load(Ordering::Acquire) < 0 { | ||
| 2638 | + let at = ao.position().unwrap_or(0).max(0); | ||
| 2639 | + audio.content_at.store(at, Ordering::Release); | ||
| 2267 | } | 2640 | } |
| 2641 | + accepted | ||
| 2268 | }; | 2642 | }; |
| 2269 | audio.fed.fetch_add(accepted as u64, Ordering::Relaxed); | 2643 | audio.fed.fetch_add(accepted as u64, Ordering::Relaxed); |
| 2270 | audio.note_tap(&pending[..accepted]); | 2644 | audio.note_tap(&pending[..accepted]); |
| 2271 | pending.drain(..accepted); | 2645 | pending.drain(..accepted); |
| 2272 | if !pending.is_empty() { | 2646 | if !pending.is_empty() { |
| 2273 | - // Ring full: nothing to do but let the device drain it. | 2647 | + // Ring full: nothing to do but let the device drain it. Except when |
| 2274 | - thread::sleep(RING_FULL_WAIT); | 2648 | + // *nothing* was taken, which after a flush means the ring is still |
| 2649 | + // waiting for the device to consume the flush flag rather than | ||
| 2650 | + // being full: that is the head of a restart, and every millisecond | ||
| 2651 | + // spent parked there is a millisecond of silence. | ||
| 2652 | + match accepted { | ||
| 2653 | + 0 => thread::sleep(FLUSH_WAIT), | ||
| 2654 | + _ => thread::sleep(RING_FULL_WAIT), | ||
| 2655 | + } | ||
| 2275 | } | 2656 | } |
| 2276 | } | 2657 | } |
| 2277 | } | 2658 | } |
crates/engine/src/project.rsmodified+66 -3
| @@ -289,6 +289,11 @@ impl Rate { | |||
| 289 | // fps is scale/ticks, so the ratio is (src_scale/src_ticks) / (tl_scale/tl_ticks). | 289 | // fps is scale/ticks, so the ratio is (src_scale/src_ticks) / (tl_scale/tl_ticks). |
| 290 | let num = u64::from(src_scale) * u64::from(tl_ticks); | 290 | let num = u64::from(src_scale) * u64::from(tl_ticks); |
| 291 | let den = u64::from(src_ticks) * u64::from(tl_scale); | 291 | let den = u64::from(src_ticks) * u64::from(tl_scale); |
| 292 | + Ok(Self::reduced(num, den)) | ||
| 293 | + } | ||
| 294 | + | ||
| 295 | + /// `num` frames of a file per `den` frames of a timeline, in lowest terms. | ||
| 296 | + fn reduced(num: u64, den: u64) -> Self { | ||
| 292 | let g = gcd(num, den); | 297 | let g = gcd(num, den); |
| 293 | let (mut num, mut den) = (num / g, den / g); | 298 | let (mut num, mut den) = (num / g, den / g); |
| 294 | // A ratio no pair of real frame rates produces, but the fields are `u32` | 299 | // A ratio no pair of real frame rates produces, but the fields are `u32` |
| @@ -296,10 +301,22 @@ impl Rate { | |||
| 296 | while num > u64::from(u32::MAX) || den > u64::from(u32::MAX) { | 301 | while num > u64::from(u32::MAX) || den > u64::from(u32::MAX) { |
| 297 | (num, den) = (num.div_ceil(2), den.div_ceil(2)); | 302 | (num, den) = (num.div_ceil(2), den.div_ceil(2)); |
| 298 | } | 303 | } |
| 299 | - Ok(Self { | 304 | + Self { |
| 300 | source: num.max(1) as u32, | 305 | source: num.max(1) as u32, |
| 301 | timeline: den.max(1) as u32, | 306 | timeline: den.max(1) as u32, |
| 302 | - }) | 307 | + } |
| 308 | + } | ||
| 309 | + | ||
| 310 | + /// The same file against a timeline that has itself been retimed: `self` is | ||
| 311 | + /// its frames per frame of the old timeline and `k` is old frames per new | ||
| 312 | + /// one, so this is its frames per frame of the *new* one -- exactly, without | ||
| 313 | + /// going back through an `f64` fps that names neither rate | ||
| 314 | + /// ([`crate::PlaybackSession::set_frame_rate`]). | ||
| 315 | + pub fn then(self, k: Rate) -> Self { | ||
| 316 | + Self::reduced( | ||
| 317 | + u64::from(self.source) * u64::from(k.source), | ||
| 318 | + u64::from(self.timeline) * u64::from(k.timeline), | ||
| 319 | + ) | ||
| 303 | } | 320 | } |
| 304 | 321 | ||
| 305 | pub fn is_real_time(self) -> bool { | 322 | pub fn is_real_time(self) -> bool { |
| @@ -1423,6 +1440,52 @@ impl Project { | |||
| 1423 | true | 1440 | true |
| 1424 | } | 1441 | } |
| 1425 | 1442 | ||
| 1443 | + /// Every frame number on every lane rewritten onto a timeline counted at | ||
| 1444 | + /// another rate: `k` is old timeline frames per new one, `counts` is how | ||
| 1445 | + /// long each source is on the *new* timeline (indexed as | ||
| 1446 | + /// [`Project::sources`] is), and the edit survives as the same seconds of | ||
| 1447 | + /// the same footage. What [`crate::PlaybackSession::set_frame_rate`] does to | ||
| 1448 | + /// the edit list, and the only thing that touches the frame numbers without | ||
| 1449 | + /// being an edit anyone made. | ||
| 1450 | + /// | ||
| 1451 | + /// Every position -- a clip's start and its end alike -- goes through the | ||
| 1452 | + /// one map [`Rate::timeline_at`], so two clips that met still meet, a gap | ||
| 1453 | + /// stays a gap, and a take's picture and its sound land on the same frame on | ||
| 1454 | + /// their two lanes: no lane can drift against another. A clip is then only | ||
| 1455 | + /// ever made to *fit* the room its own start and end mapped to, never to | ||
| 1456 | + /// outgrow it, which is what keeps the lane sorted and disjoint (the cursor | ||
| 1457 | + /// below is the backstop for the one case that could: a slow clip so short | ||
| 1458 | + /// that no source range fits its new room at all). | ||
| 1459 | + /// | ||
| 1460 | + /// ponytail: not exact both ways. Each rate change re-rounds every boundary | ||
| 1461 | + /// onto the new grid, so a rate picked, unpicked and picked again is within | ||
| 1462 | + /// a frame of where it started rather than back at it. Upgrade path is | ||
| 1463 | + /// keeping the edit list at one reference rate and conforming on the way | ||
| 1464 | + /// out, which every frame number in this module would then be measured in. | ||
| 1465 | + pub fn retime(&mut self, k: Rate, counts: &[u32]) { | ||
| 1466 | + for lane in &mut self.lanes { | ||
| 1467 | + let mut cursor = 0; | ||
| 1468 | + for clip in &mut lane.clips { | ||
| 1469 | + let start = k.timeline_at(clip.start).max(cursor); | ||
| 1470 | + // The room its own end mapped to -- never zero, since a clip is | ||
| 1471 | + // never empty even on a grid too coarse to hold it. | ||
| 1472 | + let room = k.timeline_at(clip.end()).saturating_sub(start).max(1); | ||
| 1473 | + let count = counts.get(clip.source).copied().unwrap_or(u32::MAX).max(1); | ||
| 1474 | + // Its footage, held inside the file's new length: a clip whose | ||
| 1475 | + // out-point was the last frame of its source must not come out | ||
| 1476 | + // of this naming a frame past the end -- that is a project that | ||
| 1477 | + // would not open again ([`crate::PlaybackSession::open_project`] | ||
| 1478 | + // refuses one by name). | ||
| 1479 | + let in_frame = k.timeline_at(clip.in_frame).min(count - 1); | ||
| 1480 | + let len = clip.speed.fit(room).unwrap_or(1).clamp(1, count - in_frame); | ||
| 1481 | + clip.start = start; | ||
| 1482 | + clip.in_frame = in_frame; | ||
| 1483 | + clip.out_frame = in_frame + len; | ||
| 1484 | + cursor = clip.end(); | ||
| 1485 | + } | ||
| 1486 | + } | ||
| 1487 | + } | ||
| 1488 | + | ||
| 1426 | /// Length of the timeline in frames: where the *last* lane runs out. A lane | 1489 | /// Length of the timeline in frames: where the *last* lane runs out. A lane |
| 1427 | /// that ends early is a trailing gap in that lane, not a shorter timeline. | 1490 | /// that ends early is a trailing gap in that lane, not a shorter timeline. |
| 1428 | pub fn timeline_frames(&self) -> u32 { | 1491 | pub fn timeline_frames(&self) -> u32 { |
| @@ -3063,7 +3126,7 @@ fn open_room(clips: &mut Vec<Clip>, at: u32, len: u32) { | |||
| 3063 | /// Absolute, symlink-resolved when the file is reachable; the path as given | 3126 | /// Absolute, symlink-resolved when the file is reachable; the path as given |
| 3064 | /// when it is not -- an unreadable path still deserves an index, it simply | 3127 | /// when it is not -- an unreadable path still deserves an index, it simply |
| 3065 | /// dedups by spelling. | 3128 | /// dedups by spelling. |
| 3066 | -fn canonical(path: &Path) -> PathBuf { | 3129 | +pub(crate) fn canonical(path: &Path) -> PathBuf { |
| 3067 | std::fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf()) | 3130 | std::fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf()) |
| 3068 | } | 3131 | } |
| 3069 | 3132 | ||
crates/engine/tests/export_subs.rsadded+295 -0
| @@ -0,0 +1,295 @@ | |||
| 1 | +//! Subtitles leave with the file: a Matroska export carries the picked track as | ||
| 2 | +//! `S_TEXT/UTF8`, timed on the *exported* timeline -- so a cut moves the cues | ||
| 3 | +//! with the pictures they belong to -- and an mp4 says it cannot rather than | ||
| 4 | +//! dropping them in silence. | ||
| 5 | +//! | ||
| 6 | +//! Two witnesses for every cue: this project's own Matroska reader | ||
| 7 | +//! (`demux::matroska_subtitles`, the way an exported file comes back into a | ||
| 8 | +//! project) and, where the box has it, ffmpeg -- which is what "it plays | ||
| 9 | +//! elsewhere" means and the only thing that can say this file is not merely | ||
| 10 | +//! self-consistent. | ||
| 11 | +//! | ||
| 12 | +//! ```text | ||
| 13 | +//! cargo test -p engine --release --test export_subs -- --nocapture | ||
| 14 | +//! ``` | ||
| 15 | + | ||
| 16 | +use std::path::{Path, PathBuf}; | ||
| 17 | +use std::process::Command; | ||
| 18 | +use std::sync::Once; | ||
| 19 | +use std::time::{Duration, Instant}; | ||
| 20 | + | ||
| 21 | +use engine::export::{ExportSettings, Format}; | ||
| 22 | +use engine::project::Lane; | ||
| 23 | +use engine::subtitle::{self, Cue, SubtitleTrack}; | ||
| 24 | +use engine::{ExportHandle, Project}; | ||
| 25 | + | ||
| 26 | +/// The media fixture: five seconds at 30 fps, and a picture this box can decode | ||
| 27 | +/// with nothing installed. | ||
| 28 | +const MEDIA: &str = "test_av.mp4"; | ||
| 29 | +const FRAMES: u32 = 150; | ||
| 30 | +/// What a cue may be out by: the file's own tick, a millisecond. The mapping is | ||
| 31 | +/// exact microseconds -- only the write rounds -- so nothing wider than this is | ||
| 32 | +/// being allowed for. | ||
| 33 | +const SLACK_US: i64 = 1_000; | ||
| 34 | + | ||
| 35 | +fn asset(name: &str) -> PathBuf { | ||
| 36 | + PathBuf::from(env!("CARGO_MANIFEST_DIR")) | ||
| 37 | + .join("../../assets") | ||
| 38 | + .join(name) | ||
| 39 | +} | ||
| 40 | + | ||
| 41 | +fn out_path(name: &str) -> PathBuf { | ||
| 42 | + let path = | ||
| 43 | + std::env::temp_dir().join(format!("ve_subs_export_{name}_{}.mkv", std::process::id())); | ||
| 44 | + let _ = std::fs::remove_file(&path); | ||
| 45 | + path | ||
| 46 | +} | ||
| 47 | + | ||
| 48 | +fn pin_software() { | ||
| 49 | + static PIN: Once = Once::new(); | ||
| 50 | + PIN.call_once(|| unsafe { | ||
| 51 | + std::env::set_var("VE_SW", "1"); | ||
| 52 | + std::env::set_var("VE_SW_ENC", "1"); | ||
| 53 | + }); | ||
| 54 | +} | ||
| 55 | + | ||
| 56 | +fn wait(handle: &ExportHandle, limit: Duration) -> engine::Result<()> { | ||
| 57 | + let started = Instant::now(); | ||
| 58 | + while !handle.is_finished() { | ||
| 59 | + assert!( | ||
| 60 | + started.elapsed() < limit, | ||
| 61 | + "export did not finish in {limit:?}" | ||
| 62 | + ); | ||
| 63 | + std::thread::sleep(Duration::from_millis(20)); | ||
| 64 | + } | ||
| 65 | + handle.result().expect("a finished export has an outcome") | ||
| 66 | +} | ||
| 67 | + | ||
| 68 | +/// The three cues the subtitle fixtures hold (`tests/subtitles.rs` pins them | ||
| 69 | +/// against the real `.srt`, `.ass` and `.mkv`), on a timeline of the media they | ||
| 70 | +/// are timed against. | ||
| 71 | +/// | ||
| 72 | +/// The track says it came out of *this* media file, which is what an embedded | ||
| 73 | +/// track is and what makes its cues the file's own clock rather than the | ||
| 74 | +/// timeline's. Written out here rather than read out of `test_subs.mkv` because | ||
| 75 | +/// that fixture's picture is AV1 and there is no software AV1 decoder to export | ||
| 76 | +/// it through; the cues are the same three either way. | ||
| 77 | +fn track() -> SubtitleTrack { | ||
| 78 | + SubtitleTrack { | ||
| 79 | + path: asset(MEDIA), | ||
| 80 | + track: Some(2), | ||
| 81 | + label: "eng".into(), | ||
| 82 | + cues: vec![ | ||
| 83 | + Cue { | ||
| 84 | + start_us: 500_000, | ||
| 85 | + end_us: 1_500_000, | ||
| 86 | + text: "first line".into(), | ||
| 87 | + }, | ||
| 88 | + Cue { | ||
| 89 | + start_us: 2_000_000, | ||
| 90 | + end_us: 3_250_000, | ||
| 91 | + text: "second line\nwith a break".into(), | ||
| 92 | + }, | ||
| 93 | + Cue { | ||
| 94 | + start_us: 4_000_000, | ||
| 95 | + end_us: 4_750_000, | ||
| 96 | + text: "third line".into(), | ||
| 97 | + }, | ||
| 98 | + ], | ||
| 99 | + refused: None, | ||
| 100 | + } | ||
| 101 | +} | ||
| 102 | + | ||
| 103 | +fn project() -> Project { | ||
| 104 | + Project::single(asset(MEDIA), FRAMES).with_subtitles(vec![track()]) | ||
| 105 | +} | ||
| 106 | + | ||
| 107 | +/// Exports `project` as an HEVC Matroska carrying subtitle track `pick`, and | ||
| 108 | +/// hands back what our own reader finds in the file. | ||
| 109 | +fn exported(name: &str, project: Project, pick: Option<usize>) -> (PathBuf, Vec<Cue>) { | ||
| 110 | + pin_software(); | ||
| 111 | + let out = out_path(name); | ||
| 112 | + let (meta, _) = engine::demux::Demuxer::open(&asset(MEDIA)).expect("probe the media"); | ||
| 113 | + let handle = engine::export::start( | ||
| 114 | + project, | ||
| 115 | + meta, | ||
| 116 | + &out, | ||
| 117 | + &ExportSettings { | ||
| 118 | + format: Format::Hevc, | ||
| 119 | + subtitles: pick, | ||
| 120 | + ..Default::default() | ||
| 121 | + }, | ||
| 122 | + ); | ||
| 123 | + wait(&handle, Duration::from_secs(300)).expect("the export finishes"); | ||
| 124 | + let tracks = subtitle::of_matroska(&out).expect("read the export back"); | ||
| 125 | + match pick { | ||
| 126 | + None => { | ||
| 127 | + assert!(tracks.is_empty(), "no pick, no track: {tracks:?}"); | ||
| 128 | + (out, Vec::new()) | ||
| 129 | + } | ||
| 130 | + Some(_) => { | ||
| 131 | + assert_eq!(tracks.len(), 1, "exactly the picked track: {tracks:?}"); | ||
| 132 | + assert_eq!(tracks[0].refused, None, "the track reads back as text"); | ||
| 133 | + (out, tracks[0].cues.clone()) | ||
| 134 | + } | ||
| 135 | + } | ||
| 136 | +} | ||
| 137 | + | ||
| 138 | +/// What ffmpeg makes of the same file's subtitle track, as an SRT on stdout: | ||
| 139 | +/// a second implementation reading the bytes, which is the whole point of it. | ||
| 140 | +/// `None` where there is no ffmpeg on the box -- the test is not about this | ||
| 141 | +/// machine's packages. | ||
| 142 | +fn ffmpeg_srt(path: &Path) -> Option<String> { | ||
| 143 | + let out = Command::new("ffmpeg") | ||
| 144 | + .args(["-v", "error", "-i"]) | ||
| 145 | + .arg(path) | ||
| 146 | + .args(["-map", "0:s:0", "-f", "srt", "-"]) | ||
| 147 | + .output() | ||
| 148 | + .ok()?; | ||
| 149 | + assert!( | ||
| 150 | + out.status.success(), | ||
| 151 | + "ffmpeg refused the exported subtitles: {}", | ||
| 152 | + String::from_utf8_lossy(&out.stderr) | ||
| 153 | + ); | ||
| 154 | + Some(String::from_utf8_lossy(&out.stdout).into_owned()) | ||
| 155 | +} | ||
| 156 | + | ||
| 157 | +fn near(got: i64, want: i64, what: &str) { | ||
| 158 | + assert!( | ||
| 159 | + (got - want).abs() <= SLACK_US, | ||
| 160 | + "{what}: {got} us is not within a frame of {want} us" | ||
| 161 | + ); | ||
| 162 | +} | ||
| 163 | + | ||
| 164 | +/// The whole timeline, untouched: the file comes back with the very cues the | ||
| 165 | +/// source's track holds, at the times it holds them -- and ffmpeg reads the | ||
| 166 | +/// same three lines out of it. | ||
| 167 | +#[test] | ||
| 168 | +fn an_mkv_export_carries_the_picked_subtitle_track() { | ||
| 169 | + let (out, cues) = exported("plain", project(), Some(0)); | ||
| 170 | + assert_eq!(cues.len(), 3, "three cues: {cues:?}"); | ||
| 171 | + let want = [ | ||
| 172 | + (500_000, 1_500_000, "first line"), | ||
| 173 | + (2_000_000, 3_250_000, "second line\nwith a break"), | ||
| 174 | + (4_000_000, 4_750_000, "third line"), | ||
| 175 | + ]; | ||
| 176 | + for (cue, (start, end, text)) in cues.iter().zip(want) { | ||
| 177 | + near(cue.start_us, start, "cue start"); | ||
| 178 | + near(cue.end_us, end, "cue end"); | ||
| 179 | + assert_eq!(cue.text, text, "the text travels, line breaks and all"); | ||
| 180 | + } | ||
| 181 | + // ...and the track is named the way it was named in the source, so the | ||
| 182 | + // subtitle menu of whatever plays this says `eng` too. | ||
| 183 | + let tracks = subtitle::of_matroska(&out).expect("read back"); | ||
| 184 | + assert_eq!(tracks[0].label, "eng"); | ||
| 185 | + let raw = engine::demux::matroska_subtitles(&out).expect("walk the tracks element"); | ||
| 186 | + assert_eq!(raw[0].codec, "S_TEXT/UTF8"); | ||
| 187 | + assert_eq!(raw[0].language, "eng", "the label went in as a language"); | ||
| 188 | + | ||
| 189 | + match ffmpeg_srt(&out) { | ||
| 190 | + Some(srt) => { | ||
| 191 | + println!("ffmpeg reads the exported track back as:\n{srt}"); | ||
| 192 | + assert!(srt.contains("first line"), "{srt}"); | ||
| 193 | + assert!(srt.contains("with a break"), "{srt}"); | ||
| 194 | + assert!(srt.contains("00:00:00,500 --> 00:00:01,500"), "{srt}"); | ||
| 195 | + assert!(srt.contains("00:00:04,000 --> 00:00:04,750"), "{srt}"); | ||
| 196 | + } | ||
| 197 | + None => println!("no ffmpeg on this box: our own reader is the only witness"), | ||
| 198 | + } | ||
| 199 | + std::fs::remove_file(&out).unwrap(); | ||
| 200 | +} | ||
| 201 | + | ||
| 202 | +/// A cut timeline: `[0.5s, 2.5s)` rippled out of it, which is one cue gone | ||
| 203 | +/// entirely, one that straddles the far edge and keeps the half still there, | ||
| 204 | +/// and one that simply moves back with the picture. | ||
| 205 | +#[test] | ||
| 206 | +fn a_cut_moves_the_cues_with_the_pictures() { | ||
| 207 | + let mut project = project(); | ||
| 208 | + assert!(project.ripple_delete(15, 60), "cut 0.5s..2.5s out"); | ||
| 209 | + assert_eq!(project.timeline_frames(), 90, "three seconds are left"); | ||
| 210 | + assert_eq!( | ||
| 211 | + project.lane(Lane::V1).len(), | ||
| 212 | + 2, | ||
| 213 | + "the hole closed, over two placements of the one source" | ||
| 214 | + ); | ||
| 215 | + | ||
| 216 | + let (out, cues) = exported("cut", project, Some(0)); | ||
| 217 | + assert_eq!( | ||
| 218 | + cues.len(), | ||
| 219 | + 2, | ||
| 220 | + "the cue inside the cut is gone, the other two are not: {cues:?}" | ||
| 221 | + ); | ||
| 222 | + // 2.0s..3.25s of the source, of which 2.5s on survived, landing where the | ||
| 223 | + // cut left it: 0.5s..1.25s. | ||
| 224 | + near( | ||
| 225 | + cues[0].start_us, | ||
| 226 | + 500_000, | ||
| 227 | + "the straddling cue starts at the cut", | ||
| 228 | + ); | ||
| 229 | + near( | ||
| 230 | + cues[0].end_us, | ||
| 231 | + 1_250_000, | ||
| 232 | + "...and keeps the rest of its length", | ||
| 233 | + ); | ||
| 234 | + assert_eq!(cues[0].text, "second line\nwith a break"); | ||
| 235 | + // 4.0s..4.75s of the source, two seconds back. | ||
| 236 | + near( | ||
| 237 | + cues[1].start_us, | ||
| 238 | + 2_000_000, | ||
| 239 | + "the last cue moves back by the cut", | ||
| 240 | + ); | ||
| 241 | + near(cues[1].end_us, 2_750_000, "...end with it"); | ||
| 242 | + assert_eq!(cues[1].text, "third line"); | ||
| 243 | + | ||
| 244 | + if let Some(srt) = ffmpeg_srt(&out) { | ||
| 245 | + println!("ffmpeg reads the cut export back as:\n{srt}"); | ||
| 246 | + assert!( | ||
| 247 | + !srt.contains("first line"), | ||
| 248 | + "the cut cue is not there: {srt}" | ||
| 249 | + ); | ||
| 250 | + assert!(srt.contains("00:00:00,500 --> 00:00:01,250"), "{srt}"); | ||
| 251 | + assert!(srt.contains("00:00:02,000 --> 00:00:02,750"), "{srt}"); | ||
| 252 | + assert!(srt.contains("third line"), "{srt}"); | ||
| 253 | + } | ||
| 254 | + std::fs::remove_file(&out).unwrap(); | ||
| 255 | +} | ||
| 256 | + | ||
| 257 | +/// Nothing picked is nothing written -- the file every export of a timeline | ||
| 258 | +/// without subtitles has always been. | ||
| 259 | +#[test] | ||
| 260 | +fn an_export_with_no_pick_carries_no_subtitle_track() { | ||
| 261 | + // `exported` asserts the file has no subtitle track at all; this is the | ||
| 262 | + // pick being absent rather than the timeline having nothing to pick. | ||
| 263 | + let (out, cues) = exported("none", project(), None); | ||
| 264 | + assert_eq!(cues, Vec::new()); | ||
| 265 | + std::fs::remove_file(&out).unwrap(); | ||
| 266 | +} | ||
| 267 | + | ||
| 268 | +/// What the card says before the button is pressed, which is where an mp4's | ||
| 269 | +/// refusal has to land: the file is not the place to find out. | ||
| 270 | +#[test] | ||
| 271 | +fn the_plan_says_what_each_container_does_with_them() { | ||
| 272 | + let project = project(); | ||
| 273 | + let plan = |format| engine::export::planned_subtitles(&project, format, Some(0)); | ||
| 274 | + assert_eq!(plan(Format::Hevc), "eng → embedded"); | ||
| 275 | + assert_eq!(plan(Format::Av1), "eng → embedded"); | ||
| 276 | + assert_eq!(plan(Format::Mp4), "mkv only — an mp4 carries none"); | ||
| 277 | + assert_eq!(plan(Format::HevcMp4), "mkv only — an mp4 carries none"); | ||
| 278 | + assert_eq!(plan(Format::Wav), "none — this format is the sound alone"); | ||
| 279 | + // No pick, and a pick nothing answers, are both "none" rather than a panic | ||
| 280 | + // or a lie. | ||
| 281 | + assert_eq!( | ||
| 282 | + engine::export::planned_subtitles(&project, Format::Hevc, None), | ||
| 283 | + "none" | ||
| 284 | + ); | ||
| 285 | + assert_eq!( | ||
| 286 | + engine::export::planned_subtitles(&project, Format::Hevc, Some(9)), | ||
| 287 | + "none" | ||
| 288 | + ); | ||
| 289 | + // A timeline that never had subtitles says the same thing. | ||
| 290 | + let bare = Project::single(asset(MEDIA), FRAMES); | ||
| 291 | + assert_eq!( | ||
| 292 | + engine::export::planned_subtitles(&bare, Format::Hevc, Some(0)), | ||
| 293 | + "none" | ||
| 294 | + ); | ||
| 295 | +} | ||
crates/engine/tests/invalidation.rsadded+308 -0
| @@ -0,0 +1,308 @@ | |||
| 1 | +//! What an edit is allowed to tear down, and what it is not. | ||
| 2 | +//! | ||
| 3 | +//! Every setting a person can move while a timeline plays dirties *one* half of | ||
| 4 | +//! the pipeline at most: a grade, a fit policy and the project resolution are | ||
| 5 | +//! pictures, an equalizer is sound, and a fader is not even that -- it is a | ||
| 6 | +//! number the running mixer picks up between two blocks. The tests here are the | ||
| 7 | +//! measurement of that claim, and the thing they measure is the **audio tap**: | ||
| 8 | +//! it is the sound the device was handed last, and a restart clears it (the | ||
| 9 | +//! ring is flushed and nothing is fed again until a decoder has reopened, tens | ||
| 10 | +//! of milliseconds later). An empty tap right after an edit therefore *is* the | ||
| 11 | +//! hole in the sound the user reported hearing when they dragged a colour | ||
| 12 | +//! slider. | ||
| 13 | +//! | ||
| 14 | +//! Every test runs anywhere: with no PipeWire daemon there is no device, no tap | ||
| 15 | +//! and nothing to protect, so the audio assertions are made only when there is | ||
| 16 | +//! sound to make them about -- the clock assertions run either way. | ||
| 17 | +//! | ||
| 18 | +//! ```text | ||
| 19 | +//! cargo test -p engine --test invalidation -- --nocapture | ||
| 20 | +//! ``` | ||
| 21 | + | ||
| 22 | +use std::path::{Path, PathBuf}; | ||
| 23 | +use std::thread::sleep; | ||
| 24 | +use std::time::Duration; | ||
| 25 | + | ||
| 26 | +use engine::PlaybackSession; | ||
| 27 | +use engine::color::ColorParams; | ||
| 28 | +use engine::limiter::Limiter; | ||
| 29 | +use engine::project::Lane; | ||
| 30 | + | ||
| 31 | +fn asset(name: &str) -> PathBuf { | ||
| 32 | + PathBuf::from(env!("CARGO_MANIFEST_DIR")) | ||
| 33 | + .join("../../assets") | ||
| 34 | + .join(name) | ||
| 35 | +} | ||
| 36 | + | ||
| 37 | +/// Silent, like every other suite that plays a real file: these tests are about | ||
| 38 | +/// whether the sound is *interrupted*, not about what it sounds like, and the | ||
| 39 | +/// gain is the last multiply before the device -- everything measured here is | ||
| 40 | +/// decoded, fed and counted exactly as it is when it is audible. | ||
| 41 | +fn open(path: &Path) -> PlaybackSession { | ||
| 42 | + let session = PlaybackSession::open(path).expect("open"); | ||
| 43 | + session.set_gain(0.0); | ||
| 44 | + session | ||
| 45 | +} | ||
| 46 | + | ||
| 47 | +/// How many samples the device has been handed lately. `None` with no audio | ||
| 48 | +/// device at all -- the machine's business, and nothing to assert about. | ||
| 49 | +fn heard(session: &PlaybackSession) -> Option<usize> { | ||
| 50 | + session.audio_tap().map(|(tap, _)| tap.len()) | ||
| 51 | +} | ||
| 52 | + | ||
| 53 | +/// Plays until the device has really been handed something, so a later empty | ||
| 54 | +/// tap means "this edit emptied it" rather than "it was never filled". | ||
| 55 | +fn play_until_heard(session: &mut PlaybackSession) -> Option<usize> { | ||
| 56 | + session.play(); | ||
| 57 | + for _ in 0..200 { | ||
| 58 | + session.tick(); | ||
| 59 | + while session.try_frame().is_some() {} | ||
| 60 | + if heard(session).is_none_or(|n| n > 0) { | ||
| 61 | + break; | ||
| 62 | + } | ||
| 63 | + sleep(Duration::from_millis(10)); | ||
| 64 | + } | ||
| 65 | + let filled = heard(session); | ||
| 66 | + if filled == Some(0) { | ||
| 67 | + panic!("the device was never fed: nothing to measure"); | ||
| 68 | + } | ||
| 69 | + filled | ||
| 70 | +} | ||
| 71 | + | ||
| 72 | +/// A grade dragged while the timeline plays. The slider commits per pointer | ||
| 73 | +/// sample (`set_color_live`), which used to reseek the whole session per | ||
| 74 | +/// sample: an audio flush, an audio re-open and a video decoder rebuild, ~40 | ||
| 75 | +/// times across one drag of the bar. The sound must not notice. | ||
| 76 | +#[test] | ||
| 77 | +fn a_grade_during_playback_never_touches_the_sound() { | ||
| 78 | + let mut session = open(&asset("test_av.mp4")); | ||
| 79 | + let filled = play_until_heard(&mut session); | ||
| 80 | + let before = session.now(); | ||
| 81 | + | ||
| 82 | + for step in 0..20 { | ||
| 83 | + let grade = ColorParams { | ||
| 84 | + saturation: 1.0 - step as f32 / 40.0, | ||
| 85 | + ..Default::default() | ||
| 86 | + }; | ||
| 87 | + assert!( | ||
| 88 | + session.set_color_live(Lane::V1, 0, Some(grade)), | ||
| 89 | + "the grade takes at step {step}" | ||
| 90 | + ); | ||
| 91 | + // Right now, with no wait: a flush shows up here before anything can | ||
| 92 | + // refill it. | ||
| 93 | + if let Some(n) = heard(&session) { | ||
| 94 | + assert!( | ||
| 95 | + n > 0, | ||
| 96 | + "step {step} of the drag emptied the device queue -- the sound was torn down by a colour change" | ||
| 97 | + ); | ||
| 98 | + } | ||
| 99 | + session.tick(); | ||
| 100 | + while session.try_frame().is_some() {} | ||
| 101 | + } | ||
| 102 | + | ||
| 103 | + assert_eq!( | ||
| 104 | + heard(&session).is_some(), | ||
| 105 | + filled.is_some(), | ||
| 106 | + "the audio path disappeared across the drag" | ||
| 107 | + ); | ||
| 108 | + let after = session.now(); | ||
| 109 | + assert!( | ||
| 110 | + after >= before, | ||
| 111 | + "the clock went backwards across the drag: {before:.3}s -> {after:.3}s" | ||
| 112 | + ); | ||
| 113 | + assert!( | ||
| 114 | + after - before < 0.5, | ||
| 115 | + "20 grade steps cost {:.3}s of timeline", | ||
| 116 | + after - before | ||
| 117 | + ); | ||
| 118 | + eprintln!("20 live grades: clock {before:.3}s -> {after:.3}s, tap {filled:?} samples"); | ||
| 119 | +} | ||
| 120 | + | ||
| 121 | +/// The project resolution, changed while the timeline plays -- the 4K film the | ||
| 122 | +/// report came from. Every clip is recomposed onto the new canvas, which is a | ||
| 123 | +/// video decoder rebuild and nothing else: no sample changes, so no sample may | ||
| 124 | +/// be discarded and the clock may not be re-anchored (that re-anchor, onto an | ||
| 125 | +/// empty ring, is what put the picture permanently ahead of the sound). | ||
| 126 | +#[test] | ||
| 127 | +fn a_resolution_change_during_playback_never_touches_the_sound() { | ||
| 128 | + let mut session = open(&asset("test_av.mp4")); | ||
| 129 | + let filled = play_until_heard(&mut session); | ||
| 130 | + let native = session.native_resolution(); | ||
| 131 | + let before = session.now(); | ||
| 132 | + | ||
| 133 | + for (w, h) in [(1920, 1080), (640, 360), (3840, 2160)] { | ||
| 134 | + assert!(session.set_resolution(w, h), "resize to {w}x{h}"); | ||
| 135 | + if let Some(n) = heard(&session) { | ||
| 136 | + assert!( | ||
| 137 | + n > 0, | ||
| 138 | + "resizing to {w}x{h} emptied the device queue -- the sound was torn down by a picture setting" | ||
| 139 | + ); | ||
| 140 | + } | ||
| 141 | + let at = session.now(); | ||
| 142 | + assert!( | ||
| 143 | + at >= before && at - before < 0.5, | ||
| 144 | + "the clock jumped across the resize: {before:.3}s -> {at:.3}s" | ||
| 145 | + ); | ||
| 146 | + assert_eq!(session.resolution(), (w, h)); | ||
| 147 | + session.tick(); | ||
| 148 | + while session.try_frame().is_some() {} | ||
| 149 | + } | ||
| 150 | + assert_eq!( | ||
| 151 | + session.native_resolution(), | ||
| 152 | + native, | ||
| 153 | + "the media's own size is not the project's" | ||
| 154 | + ); | ||
| 155 | + assert_eq!( | ||
| 156 | + heard(&session).is_some(), | ||
| 157 | + filled.is_some(), | ||
| 158 | + "the audio path disappeared across the resizes" | ||
| 159 | + ); | ||
| 160 | + | ||
| 161 | + // ...and it is still running afterwards, at real speed. | ||
| 162 | + let mark = session.now(); | ||
| 163 | + for _ in 0..30 { | ||
| 164 | + session.tick(); | ||
| 165 | + while session.try_frame().is_some() {} | ||
| 166 | + sleep(Duration::from_millis(10)); | ||
| 167 | + } | ||
| 168 | + let ran = session.now() - mark; | ||
| 169 | + eprintln!("after three resizes the clock ran {ran:.3}s in 0.3s of real time"); | ||
| 170 | + assert!(ran > 0.05, "the clock stalled after the resize: {ran:.3}s"); | ||
| 171 | +} | ||
| 172 | + | ||
| 173 | +/// A fader and the master ceiling, moved while the timeline plays. Both live at | ||
| 174 | +/// the mix and nowhere else, so a running mixer picks them up between blocks -- | ||
| 175 | +/// nothing is flushed, nothing is reopened, and the picture does not blink. | ||
| 176 | +/// | ||
| 177 | +/// The *first* move is allowed one restart: a single audio lane at unity with | ||
| 178 | +/// the limiter off is not mixed at all (the bit-exact path), so moving off it | ||
| 179 | +/// is what opens a mixer. Every move after that is live, which is what an arrow | ||
| 180 | +/// key held down on the mix card actually does. | ||
| 181 | +#[test] | ||
| 182 | +fn a_fader_during_playback_stops_restarting_the_sound() { | ||
| 183 | + let mut session = open(&asset("test_av.mp4")); | ||
| 184 | + let filled = play_until_heard(&mut session); | ||
| 185 | + if filled.is_none() { | ||
| 186 | + eprintln!("no audio device: nothing to mix"); | ||
| 187 | + return; | ||
| 188 | + } | ||
| 189 | + | ||
| 190 | + // The move that opens the mixer, and the refill after it. | ||
| 191 | + assert!(session.set_lane_gain_db(Lane::A1, -3.0), "turn A1 down"); | ||
| 192 | + play_until_heard(&mut session); | ||
| 193 | + | ||
| 194 | + for step in 1..=20 { | ||
| 195 | + let db = -3.0 - step as f32 * 0.5; | ||
| 196 | + assert!(session.set_lane_gain_db(Lane::A1, db), "fader to {db} dB"); | ||
| 197 | + assert_eq!( | ||
| 198 | + heard(&session), | ||
| 199 | + filled, | ||
| 200 | + "nudge {step} emptied the device queue -- a fader restarted the stream" | ||
| 201 | + ); | ||
| 202 | + } | ||
| 203 | + // ...and the ceiling beside it, which is retuned rather than rebuilt. | ||
| 204 | + for step in 0..8 { | ||
| 205 | + let limiter = Limiter { | ||
| 206 | + on: step % 2 == 0, | ||
| 207 | + ..Limiter::default() | ||
| 208 | + } | ||
| 209 | + .with_ceiling(-1.0 - step as f32); | ||
| 210 | + assert!(session.set_limiter(limiter), "ceiling {step}"); | ||
| 211 | + assert_eq!( | ||
| 212 | + heard(&session), | ||
| 213 | + filled, | ||
| 214 | + "limiter step {step} emptied the device queue" | ||
| 215 | + ); | ||
| 216 | + } | ||
| 217 | + assert_eq!(session.lane_gain_db(Lane::A1), -13.0); | ||
| 218 | + eprintln!("20 fader nudges and 8 limiter moves: not one restart"); | ||
| 219 | +} | ||
| 220 | + | ||
| 221 | +/// The other half of the rule, and the one that makes it a *classification* | ||
| 222 | +/// rather than a blanket "never rebuild": an equalizer really is a change to | ||
| 223 | +/// the samples, so it does restart the audio -- and must leave the picture | ||
| 224 | +/// alone while it does. | ||
| 225 | +#[test] | ||
| 226 | +fn an_equalizer_rebuilds_the_sound_and_only_the_sound() { | ||
| 227 | + let mut session = open(&asset("test_av.mp4")); | ||
| 228 | + play_until_heard(&mut session); | ||
| 229 | + let before = session.now(); | ||
| 230 | + | ||
| 231 | + let params = engine::eq::EqParams::default_layout(); | ||
| 232 | + let mut curve = params.clone(); | ||
| 233 | + curve.bands[0].gain_db = 6.0; | ||
| 234 | + assert!(session.set_eq(Lane::A1, 0, Some(curve)), "equalize A1's clip"); | ||
| 235 | + | ||
| 236 | + let after = session.now(); | ||
| 237 | + assert!( | ||
| 238 | + after >= before && after - before < 0.5, | ||
| 239 | + "the equalizer moved the playhead: {before:.3}s -> {after:.3}s" | ||
| 240 | + ); | ||
| 241 | + // The picture keeps coming: the video worker was never cancelled. | ||
| 242 | + let mut frames = 0; | ||
| 243 | + for _ in 0..60 { | ||
| 244 | + session.tick(); | ||
| 245 | + while session.try_frame().is_some() { | ||
| 246 | + frames += 1; | ||
| 247 | + } | ||
| 248 | + sleep(Duration::from_millis(10)); | ||
| 249 | + } | ||
| 250 | + eprintln!("{frames} frames across an equalizer change, clock at {:.3}s", session.now()); | ||
| 251 | + assert!(frames > 0, "the picture stopped when the sound was rebuilt"); | ||
| 252 | +} | ||
| 253 | + | ||
| 254 | +/// The same classification asked at the one place it decides something a person | ||
| 255 | +/// can see: **after the timeline has played out**. A sound edit rebuilds the | ||
| 256 | +/// sound and starts no picture worker, so end of stream stands -- the last frame | ||
| 257 | +/// is still the last frame, the transport is still `Ended`, and the next press | ||
| 258 | +/// restarts from the top with the new curve on it. A revival here would spend | ||
| 259 | +/// that state on an edit with nothing new to show, leaving a play press to run | ||
| 260 | +/// the clock off the end instead of starting the film again. | ||
| 261 | +#[test] | ||
| 262 | +fn a_sound_edit_after_the_end_leaves_the_end_where_it_is() { | ||
| 263 | + let mut session = open(&asset("test_av.mp4")); | ||
| 264 | + // A breath short of the end: the tail is what this is about. | ||
| 265 | + session.seek(4.8); | ||
| 266 | + session.play(); | ||
| 267 | + let deadline = std::time::Instant::now() + Duration::from_secs(20); | ||
| 268 | + while !session.is_eos() { | ||
| 269 | + assert!( | ||
| 270 | + std::time::Instant::now() < deadline, | ||
| 271 | + "never reached the end of a 5 s file" | ||
| 272 | + ); | ||
| 273 | + session.tick(); | ||
| 274 | + while session.try_frame().is_some() {} | ||
| 275 | + } | ||
| 276 | + // What the front-end does on the crossing (`Player::pump`): stopped, on the | ||
| 277 | + // out point, and still ended. | ||
| 278 | + session.halt_at_end(); | ||
| 279 | + let ended_at = session.now(); | ||
| 280 | + assert_eq!(ended_at, session.timeline_duration()); | ||
| 281 | + | ||
| 282 | + let mut curve = engine::eq::EqParams::default_layout(); | ||
| 283 | + curve.bands[0].gain_db = 6.0; | ||
| 284 | + assert!(session.set_eq(Lane::A1, 0, Some(curve)), "equalize at the end"); | ||
| 285 | + assert!( | ||
| 286 | + session.is_eos(), | ||
| 287 | + "an equalizer past the end revived the session: nothing new to show" | ||
| 288 | + ); | ||
| 289 | + assert!(!session.is_playing(), "...and it started the transport again"); | ||
| 290 | + assert!( | ||
| 291 | + (session.now() - ended_at).abs() < 1e-9, | ||
| 292 | + "the playhead left the out point: {:.6}s", | ||
| 293 | + session.now() | ||
| 294 | + ); | ||
| 295 | + // The parameters landed all the same -- that is what "the edit took" means. | ||
| 296 | + assert!(session.eq_of(Lane::A1, 0).is_some(), "the curve did not apply"); | ||
| 297 | + | ||
| 298 | + // The fader's first move at the end goes down the same road (no mix is | ||
| 299 | + // running to push it into, so it reseeks the audio too). | ||
| 300 | + assert!(session.set_lane_gain_db(Lane::A1, -6.0), "fader at the end"); | ||
| 301 | + assert!(session.is_eos(), "a fader past the end revived the session"); | ||
| 302 | + assert_eq!(session.lane_gain_db(Lane::A1), -6.0); | ||
| 303 | + | ||
| 304 | + // And the restart off that end is still there, which is what the state was | ||
| 305 | + // being kept for. | ||
| 306 | + session.seek(0.0); | ||
| 307 | + assert!(!session.is_eos(), "a seek revives a played-out session"); | ||
| 308 | +} | ||
crates/engine/tests/mixed_fps.rsmodified+109 -0
| @@ -323,6 +323,115 @@ fn a_mixed_rate_project_reloads_unchanged() { | |||
| 323 | std::fs::remove_file(&path).ok(); | 323 | std::fs::remove_file(&path).ok(); |
| 324 | } | 324 | } |
| 325 | 325 | ||
| 326 | +/// The project's rate is the user's to pick, exactly as its resolution is. The | ||
| 327 | +/// timeline is *conformed* to it -- the same seconds of the same footage, | ||
| 328 | +/// counted on a new grid -- every source is read through a [`Rate`] against it, | ||
| 329 | +/// the media's own rate stays reachable, and a save comes back at the rate it | ||
| 330 | +/// was cut at rather than at the media's. | ||
| 331 | +#[test] | ||
| 332 | +fn the_project_rate_is_picked_and_the_timeline_is_conformed_to_it() { | ||
| 333 | + let pal = asset("test_25fps.mp4"); | ||
| 334 | + let mut session = open(asset("test_av.mp4")); | ||
| 335 | + import_and_place(&mut session, &pal); | ||
| 336 | + let duration = session.timeline_duration(); | ||
| 337 | + assert_eq!(session.native_frame_rate(), FPS, "the media's own rate"); | ||
| 338 | + assert!(!session.set_frame_rate(FPS), "the rate already in force"); | ||
| 339 | + assert!(!session.set_frame_rate(0.0), "not a rate at all"); | ||
| 340 | + | ||
| 341 | + assert!( | ||
| 342 | + session.set_frame_rate(24.0), | ||
| 343 | + "24 is a rate a timescale can name" | ||
| 344 | + ); | ||
| 345 | + assert_eq!(session.meta().frame_rate, 24.0); | ||
| 346 | + assert!( | ||
| 347 | + (session.timeline_duration() - duration).abs() < 1.0 / 24.0, | ||
| 348 | + "the timeline is {} s where it was {duration} s", | ||
| 349 | + session.timeline_duration() | ||
| 350 | + ); | ||
| 351 | + // Both files are read through a rate against the new grid now: 5 s and 2 s, | ||
| 352 | + // in 24ths. | ||
| 353 | + assert_eq!(session.file_frames(&asset("test_av.mp4")), 120, "5 s at 24"); | ||
| 354 | + assert_eq!(session.file_frames(&pal), 48, "2 s at 24"); | ||
| 355 | + // ...and each take is still one take on both lanes: every frame number goes | ||
| 356 | + // through one map, so a picture cannot drift off its sound. | ||
| 357 | + let (video, audio) = (session.lane_clips(Lane::V1), session.lane_clips(Lane::A1)); | ||
| 358 | + assert_eq!(video.len(), 2, "the 30 fps take and the 25 fps one"); | ||
| 359 | + for (v, a) in video.iter().zip(audio) { | ||
| 360 | + assert_eq!((v.start, v.len()), (a.start, a.len()), "{v:?} vs {a:?}"); | ||
| 361 | + } | ||
| 362 | + | ||
| 363 | + let path = std::env::temp_dir().join(format!("edith-rate-{}.edith", std::process::id())); | ||
| 364 | + session.save_project(&path).expect("save"); | ||
| 365 | + let reloaded = PlaybackSession::open_project(&path).expect("a retimed project reopens"); | ||
| 366 | + assert_eq!(reloaded.meta().frame_rate, 24.0, "the rate it was cut at"); | ||
| 367 | + assert_eq!( | ||
| 368 | + reloaded.clip_spans(), | ||
| 369 | + session.clip_spans(), | ||
| 370 | + "the same clips" | ||
| 371 | + ); | ||
| 372 | + assert_eq!(reloaded.file_frames(&pal), 48, "recomputed against 24"); | ||
| 373 | + assert_eq!( | ||
| 374 | + reloaded.native_frame_rate(), | ||
| 375 | + FPS, | ||
| 376 | + "the way back is still there" | ||
| 377 | + ); | ||
| 378 | + std::fs::remove_file(&path).ok(); | ||
| 379 | + | ||
| 380 | + // ...and that way back is a pick like any other: the media's own rate. | ||
| 381 | + let native = session.native_frame_rate(); | ||
| 382 | + assert!(session.set_frame_rate(native), "back to the media's own"); | ||
| 383 | + assert_eq!(session.file_frames(&pal), 60, "2 s at 30 again"); | ||
| 384 | + assert!( | ||
| 385 | + (session.timeline_duration() - duration).abs() < 1.0 / 24.0, | ||
| 386 | + "{} s after the round trip, {duration} s before", | ||
| 387 | + session.timeline_duration() | ||
| 388 | + ); | ||
| 389 | +} | ||
| 390 | + | ||
| 391 | +/// ...and an export of it comes out at that rate: the file is written at 24 fps, | ||
| 392 | +/// as many frames as the conformed timeline has, with its sound as long as its | ||
| 393 | +/// picture. | ||
| 394 | +#[test] | ||
| 395 | +fn an_export_runs_at_the_rate_the_project_was_cut_at() { | ||
| 396 | + let mut session = open(asset("test_av.mp4")); | ||
| 397 | + assert!( | ||
| 398 | + session.trim_clip(Lane::V1, 0, Edge::End, 30), | ||
| 399 | + "one second of the 30 fps take" | ||
| 400 | + ); | ||
| 401 | + assert!(session.set_frame_rate(24.0), "cut it at 24 instead"); | ||
| 402 | + let total = (session.timeline_duration() * 24.0).round() as u32; | ||
| 403 | + assert_eq!(total, 24, "one second, in 24ths"); | ||
| 404 | + | ||
| 405 | + let out = std::env::temp_dir().join(format!("edith-rate-{}.mp4", std::process::id())); | ||
| 406 | + wait(&session.export_to_with( | ||
| 407 | + &out, | ||
| 408 | + &ExportSettings { | ||
| 409 | + format: Format::Mp4, | ||
| 410 | + ..ExportSettings::default() | ||
| 411 | + }, | ||
| 412 | + )) | ||
| 413 | + .expect("the export"); | ||
| 414 | + | ||
| 415 | + let (meta, _rx, _cancel) = DecodeSession::open_range(&out, 0, u32::MAX).expect("reopen"); | ||
| 416 | + assert!( | ||
| 417 | + (meta.frame_rate - 24.0).abs() < 0.01, | ||
| 418 | + "the export runs at the picked rate: {}", | ||
| 419 | + meta.frame_rate | ||
| 420 | + ); | ||
| 421 | + assert_eq!( | ||
| 422 | + meta.frame_count, total, | ||
| 423 | + "the export is the timeline's length" | ||
| 424 | + ); | ||
| 425 | + let secs = engine::AudioSession::duration_secs(&out) | ||
| 426 | + .expect("probe the export") | ||
| 427 | + .expect("the export has sound"); | ||
| 428 | + assert!( | ||
| 429 | + (secs - f64::from(total) / 24.0).abs() < 0.05, | ||
| 430 | + "sound is {secs} s under a second of picture" | ||
| 431 | + ); | ||
| 432 | + std::fs::remove_file(&out).ok(); | ||
| 433 | +} | ||
| 434 | + | ||
| 326 | /// The export is what was watched: as many frames as the timeline has, and the | 435 | /// The export is what was watched: as many frames as the timeline has, and the |
| 327 | /// 25 fps clip walked through its file at 25 fps -- 25 pictures over 30 frames, | 436 | /// 25 fps clip walked through its file at 25 fps -- 25 pictures over 30 frames, |
| 328 | /// not 30 of them and not 25 held to the end. | 437 | /// not 30 of them and not 25 held to the end. |
crates/engine/tests/playback.rsmodified+15 -3
| @@ -284,15 +284,27 @@ fn seek_keeps_the_audio_clock() { | |||
| 284 | "clock at {}", | 284 | "clock at {}", |
| 285 | session.now() | 285 | session.now() |
| 286 | ); | 286 | ); |
| 287 | + // From here on the *sound* is what the clock counts, and the sound restarts | ||
| 288 | + // at once -- the video decoder's reopen (up to a VA-API init) happens | ||
| 289 | + // underneath a stream that is already playing, so the window `next_index` | ||
| 290 | + // spends waiting for the first picture is time the timeline really moved | ||
| 291 | + // through. Measured against the wall rather than assumed free: counting it | ||
| 292 | + // is the fix for the offset an edit-while-playing used to leave behind | ||
| 293 | + // (`invalidation.rs`), where the clock re-anchored onto an empty ring and | ||
| 294 | + // the picture stayed that far behind the sound for good. | ||
| 295 | + let from = Instant::now(); | ||
| 287 | let first = next_index(&mut session, "seek(3.0)"); | 296 | let first = next_index(&mut session, "seek(3.0)"); |
| 288 | assert_eq!(first, (3.0 * meta.frame_rate) as u32); | 297 | assert_eq!(first, (3.0 * meta.frame_rate) as u32); |
| 289 | let mut after_seek = None; | 298 | let mut after_seek = None; |
| 290 | run_for(&mut session, &mut after_seek, Duration::from_millis(600)); | 299 | run_for(&mut session, &mut after_seek, Duration::from_millis(600)); |
| 291 | let advanced = session.now(); | 300 | let advanced = session.now(); |
| 292 | - eprintln!("seek(3.0) -> {advanced:.3}s, frames {first}..={after_seek:?}"); | 301 | + let real = from.elapsed().as_secs_f64(); |
| 302 | + eprintln!( | ||
| 303 | + "seek(3.0) -> {advanced:.3}s after {real:.3}s of real time, frames {first}..={after_seek:?}" | ||
| 304 | + ); | ||
| 293 | assert!( | 305 | assert!( |
| 294 | - (3.3..3.9).contains(&advanced), | 306 | + (3.0 + real - 0.35..3.0 + real + 0.35).contains(&advanced), |
| 295 | - "clock did not run at real speed after the seek: {advanced:.3}s" | 307 | + "clock did not run at real speed after the seek: {advanced:.3}s after {real:.3}s" |
| 296 | ); | 308 | ); |
| 297 | 309 | ||
| 298 | // Everything from the target on, and nothing before it: ~2 s of frames. | 310 | // Everything from the target on, and nothing before it: ~2 s of frames. |