forge
Explore
Log in

Don't you dare go Hollow

A dissolve renders in export, blended frame by frame

Browse files at this commit

1c45bb65be735a394356b0975b91274d6a90e820Ahmet Kaan GümüşParent: 86ef2d5fc86f32
  • feat
    • a dissolve renders in export, blended frame by frame
Show full message
✨ feat(engine): a dissolve renders in export, blended frame by frame
crates/engine/src/export.rsmodified+204 -9
@@ -79,7 +79,7 @@ use crate::mux::{
7979 AudioParams, Av1Params, CopyParams, HevcParams, MkvMuxer, Mp4Muxer, SubParams, VideoParams,
8080 };
8181 use crate::project::{Lane, LaneKind, Project, Rate};
82-use crate::scale::Composer;
82+use crate::scale::{blend_i420, Composer};
8383 use crate::subtitle::{Cue, SubtitleTrack};
8484 use crate::tonemap::{self, ToneMapper};
8585
@@ -1021,6 +1021,72 @@ fn export_spans(project: &Project, range: Option<(u32, u32)>) -> Vec<crate::proj
10211021 spans
10221022 }
10231023
1024+/// The cross-dissolve this span's tail owes its successor, or `None` for a
1025+/// hard cut. `(b_source, b_in_frame, window, b_start)`: which source and
1026+/// source frame the dissolve's B side starts reading, how many *output*
1027+/// frames the blend ramps across, and where B sits on the timeline (which is
1028+/// what its own grade and fit are keyed on, [`Project::composite_color_at`]
1029+/// and [`Project::composite_fit_at`]).
1030+///
1031+/// [`Clip::transition_out`] is trusted only after adjacency is checked again
1032+/// here: a trim or a split since it was set leaves the stored number in
1033+/// place but not its meaning, so a stale one plays as the hard cut it now
1034+/// is rather than as a dissolve into a clip that no longer follows.
1035+fn dissolve_window(project: &Project, span: &crate::project::Span) -> Option<(usize, u32, u32, u32)> {
1036+ let (source, _) = span.from?;
1037+ let (lane, idx) = project.composite_clip_at(span.start)?;
1038+ let clips = project.lane(lane);
1039+ let a = clips.get(idx)?;
1040+ if a.source != source || a.transition_out == 0 {
1041+ return None;
1042+ }
1043+ let b = clips.get(idx + 1)?;
1044+ if a.end() != b.start {
1045+ return None; // trimmed or split apart since the dissolve was set
1046+ }
1047+ // The span must run uninterrupted all the way to A's own end: a higher
1048+ // video lane taking over before that means there is no tail of A left
1049+ // here to blend into anything.
1050+ if span.start + span.len != a.end() {
1051+ return None;
1052+ }
1053+ let window = a
1054+ .transition_out
1055+ .min(a.frames())
1056+ .min(b.frames())
1057+ .min(span.len);
1058+ (window > 0).then_some((b.source, b.in_frame, window, b.start))
1059+}
1060+
1061+/// `B`'s weight in [`blend_i420`] at output frame `idx_in_window` of `window`
1062+/// (`idx_in_window < window`): a ramp from just above 0 to just below 1 that
1063+/// never actually reaches either end, so the first blended frame still shows
1064+/// a trace of A and the last still a trace of B -- the cut a hard transition
1065+/// would have made lands one frame *after* the window, at full B, rather than
1066+/// inside it.
1067+fn dissolve_weight(idx_in_window: u32, window: u32) -> f32 {
1068+ (idx_in_window + 1) as f32 / (window + 1) as f32
1069+}
1070+
1071+/// A dissolve's B side, open beside A's own decoder for this span's tail:
1072+/// its own decoder, and everything [`place_picture`] needs to put its frames
1073+/// on the same canvas, in the same space, graded the way B is graded rather
1074+/// than the way A is -- [`Project::composite_color_at`]/`composite_fit_at`
1075+/// asked at B's own start, not at the timeline position the blend writes to,
1076+/// which is still inside A's span.
1077+struct Dissolve<'a> {
1078+ /// How many output frames the blend ramps across.
1079+ window: u32,
1080+ /// The first output frame of this span's tail that is inside the window.
1081+ tail_start: u32,
1082+ decoder: ClipDecoder,
1083+ mapper: Option<&'a ToneMapper>,
1084+ remap: Option<(Matrix, Matrix)>,
1085+ grade: Option<crate::color::ColorParams>,
1086+ canvas: Composer,
1087+ graded: (Vec<u8>, Vec<u8>, Vec<u8>),
1088+}
1089+
10241090 /// The track's cues where the *exported* timeline puts them, which is the only
10251091 /// clock the file has: the export writes timeline frame 0 onwards and nothing
10261092 /// else, exactly as the sound is mixed from frame 0 and resized to the
@@ -1555,6 +1621,20 @@ impl CopyPlan {
15551621 if !span.speed.is_normal() {
15561622 return None;
15571623 }
1624+ // A copied packet is the source's own picture, never a blend: a
1625+ // live dissolve on this span's tail forces the whole video track
1626+ // through the encoder, exactly as a grade or a speed does below.
1627+ //
1628+ // corner-cut: the whole file falls back rather than only the
1629+ // clips either side of the dissolve -- [`CopyPlan`] is already
1630+ // all-or-nothing per export ([`CopyPlan`]'s own doc comment
1631+ // states why), so one dissolve on a two-hour film re-encodes all
1632+ // of it. Upgrade path: splice a re-encoded region between two
1633+ // copied ones, which needs the sample-table writer that doc
1634+ // comment already names as the cost of a finer copy.
1635+ if dissolve_window(project, &span).is_some() {
1636+ return None;
1637+ }
15581638 // The grade playback shows, which a copied packet never went
15591639 // through. `None` and the identity are the same untouched picture.
15601640 if project
@@ -2432,6 +2512,12 @@ fn run(
24322512 // encoder is *not* reopened, so the export is one continuous stream
24332513 // whose GOP boundaries need not line up with the cuts -- nor with the
24342514 // file boundaries, which are just cuts that change the path.
2515+ // Whether this span's tail dissolves into its successor -- decided
2516+ // before A's own decoder is opened, because it is what decides
2517+ // whether A may take the DMA fast path at all: the blend below needs
2518+ // A's pixels on the CPU, so a dissolving span never asks for a GPU
2519+ // buffer, not even outside its own window.
2520+ let dissolve = dissolve_window(project, &span);
24352521 let (mut pictures, rate, in_frame, color, mapper) = match span.from {
24362522 Some((source, in_frame)) => {
24372523 let entry = sources
@@ -2450,7 +2536,8 @@ fn run(
24502536 && remap_into(Some(color), false, out_color.matrix).is_none()
24512537 && project
24522538 .composite_color_at(span.start)
2453- .is_none_or(|params| params.is_identity());
2539+ .is_none_or(|params| params.is_identity())
2540+ && dissolve.is_none();
24542541 let want = untouched.then(|| encoder.dma_want(meta)).flatten();
24552542 // Opened at the file's own frame, which is the only place the
24562543 // file's numbering is used -- the span's are the timeline's.
@@ -2490,6 +2577,33 @@ fn run(
24902577 meta.height,
24912578 project.composite_fit_at(span.start),
24922579 );
2580+ // B's own decoder, opened beside A's: the two streams come off their
2581+ // files together for exactly the frames the tail below blends, and
2582+ // nothing else in this span ever touches it.
2583+ let mut b = dissolve
2584+ .map(|(b_source, b_in_frame, window, b_start)| -> crate::Result<_> {
2585+ let entry = sources.get(b_source).ok_or_else(|| {
2586+ format!("clip names source {b_source} of {}", sources.len())
2587+ })?;
2588+ let (b_rate, b_color, _peak) = rates[b_source];
2589+ let b_mapper = tone[b_source].as_ref();
2590+ let b_remap = remap_into(Some(b_color), b_mapper.is_some(), out_color.matrix);
2591+ Ok(Dissolve {
2592+ window,
2593+ tail_start: span.len - window,
2594+ decoder: ClipDecoder::open(&entry.path, b_rate.source_at(b_in_frame), None)?,
2595+ mapper: b_mapper,
2596+ remap: b_remap,
2597+ grade: project.composite_color_at(b_start).copied(),
2598+ canvas: Composer::new(
2599+ meta.width,
2600+ meta.height,
2601+ project.composite_fit_at(b_start),
2602+ ),
2603+ graded: (Vec::new(), Vec::new(), Vec::new()),
2604+ })
2605+ })
2606+ .transpose()?;
24932607 // Timeline frames, taken a *source* frame at a time: at a rate other
24942608 // than real time the two are not the same count, and the span says which
24952609 // source frame each timeline frame shows ([`Speed::source_at`]) -- the
@@ -2583,14 +2697,45 @@ fn run(
25832697 // Once per timeline frame this source frame covers: one at real time
25842698 // and faster, more when the clip is slowed -- the picture is already
25852699 // graded and placed, so a held frame costs an encode and no decode.
2586- for _ in 0..repeats {
2587- let coded = match &frame {
2588- Frame::Dma(dma) => encoder.encode_dma(dma, settings.intra_only)?,
2589- Frame::Pixels(..) => {
2590- let (y, u, v, width, height) =
2591- placed.expect("a picture with pixels was placed");
2592- encoder.encode(y, u, v, width, height, settings.intra_only)?
2700+ for r in 0..repeats {
2701+ // Inside the window every *output* frame gets its own B
2702+ // picture -- decoded fresh here rather than once for the
2703+ // whole held A frame -- which is what makes a slowed A's
2704+ // tail still ramp one weight per frame shown rather than one
2705+ // per source frame.
2706+ let in_window = b.as_ref().is_some_and(|d| done_here + r >= d.tail_start);
2707+ let coded = match (&mut b, in_window) {
2708+ (Some(d), true) => {
2709+ let (ay, au, av, aw, ah) =
2710+ placed.expect("a dissolving span always decodes to pixels");
2711+ match d.decoder.next()? {
2712+ // B's file ran out inside the window: A's own
2713+ // picture carries the frame rather than the
2714+ // export losing it.
2715+ None => encoder.encode(ay, au, av, aw, ah, settings.intra_only)?,
2716+ Some(Frame::Dma(_)) => {
2717+ unreachable!("b's decoder was opened with no DMA want")
2718+ }
2719+ Some(Frame::Pixels(by, bu, bv, bw, bh)) => {
2720+ let (by, bu, bv, _, _) = place_picture(
2721+ by, bu, bv, bw, bh, d.grade, d.remap, d.mapper,
2722+ &mut d.graded, &mut d.canvas,
2723+ );
2724+ let idx_in_window = done_here + r - d.tail_start;
2725+ let t = dissolve_weight(idx_in_window, d.window);
2726+ let (y, u, v) = blend_i420((ay, au, av), (by, bu, bv), t);
2727+ encoder.encode(&y, &u, &v, aw, ah, settings.intra_only)?
2728+ }
2729+ }
25932730 }
2731+ _ => match &frame {
2732+ Frame::Dma(dma) => encoder.encode_dma(dma, settings.intra_only)?,
2733+ Frame::Pixels(..) => {
2734+ let (y, u, v, width, height) =
2735+ placed.expect("a picture with pixels was placed");
2736+ encoder.encode(y, u, v, width, height, settings.intra_only)?
2737+ }
2738+ },
25942739 };
25952740 if let Some((au, key)) = coded {
25962741 write_video(
@@ -4848,4 +4993,54 @@ mod tests {
48484993 // ...and the even one it neighbours opens.
48494994 assert!(Enc::open(&meta(1920, 1080), &settings).is_ok());
48504995 }
4996+
4997+ /// Weights ramp from just above 0 to just below 1 and never touch either
4998+ /// end -- the frame *after* the window is where a viewer would see plain
4999+ /// B, and the window itself never quite repeats a hard cut's own instant.
5000+ #[test]
5001+ fn dissolve_weight_ramps_strictly_between_zero_and_one() {
5002+ assert_eq!(dissolve_weight(0, 1), 0.5, "a one-frame window is the midpoint");
5003+ assert_eq!(dissolve_weight(0, 4), 0.2);
5004+ assert_eq!(dissolve_weight(1, 4), 0.4);
5005+ assert_eq!(dissolve_weight(2, 4), 0.6);
5006+ assert_eq!(dissolve_weight(3, 4), 0.8);
5007+ }
5008+
5009+ /// [`dissolve_window`] reads [`crate::project::Clip::transition_out`] back
5010+ /// only once adjacency is re-checked at render time: two clips a split
5011+ /// just made, still touching, still name B by its own source and its own
5012+ /// timeline start.
5013+ #[test]
5014+ fn dissolve_window_names_bs_source_in_frame_window_and_start() {
5015+ use crate::project::{Lane, Project};
5016+ let mut p = Project::single("/nonexistent/film.mkv", 20);
5017+ assert!(p.split(15));
5018+ assert!(p.set_transition_out(Lane::V1, 0, 5));
5019+ let spans = export_spans(&p, None);
5020+ let a_span = spans.iter().find(|s| s.start == 0).expect("clip A's span");
5021+ assert_eq!(
5022+ dissolve_window(&p, a_span),
5023+ Some((0, 15, 5, 15)),
5024+ "b's source, b's in_frame, the window, b's timeline start"
5025+ );
5026+ }
5027+
5028+ /// A `transition_out` set while two clips touched, then made stale by a
5029+ /// trim that opens a gap between them: the number is still in storage,
5030+ /// [`dissolve_window`] reads `None` from it, and the span renders as the
5031+ /// hard cut two clips that no longer touch actually are.
5032+ #[test]
5033+ fn a_stale_transition_out_after_a_trim_renders_as_a_hard_cut() {
5034+ use crate::project::{Edge, Lane, Project};
5035+ let mut p = Project::single("/nonexistent/film.mkv", 20);
5036+ assert!(p.split(15));
5037+ assert!(p.set_transition_out(Lane::V1, 0, 5));
5038+ assert!(p.trim(Lane::V1, 1, Edge::Start, 18, &[100]), "opens a gap");
5039+ let spans = export_spans(&p, None);
5040+ let a_span = spans.iter().find(|s| s.start == 0).expect("clip A's span");
5041+ assert!(
5042+ dissolve_window(&p, a_span).is_none(),
5043+ "b no longer abuts a; hard cut"
5044+ );
5045+ }
48515046 }