🔀 merge(T3): mixed-fps timelines — clips count timeline frames, exact rational conform
Browse files at this commit9 changed files +867 -76
- crates/app/src/main.rs +7 -1
- crates/engine/src/export.rs +68 -7
- crates/engine/src/lib.rs +1 -1
- crates/engine/src/playback.rs +152 -49
- crates/engine/src/project.rs +192 -0
- crates/engine/tests/audio_files.rs +9 -8
- crates/engine/tests/mixed_fps.rs +419 -0
- crates/engine/tests/playback.rs +8 -7
- scripts/gen_fixtures.sh +11 -3
crates/app/src/main.rsmodified+7 -1
| @@ -3580,12 +3580,18 @@ impl Player { | |||
| 3580 | None => String::new(), | 3580 | None => String::new(), |
| 3581 | } | 3581 | } |
| 3582 | ), | 3582 | ), |
| 3583 | + // The file's *own* frame rate, not the timeline's: a clip shot | ||
| 3584 | + // at another rate plays at the speed it was shot at, and the | ||
| 3585 | + // row that says where it came from has to say which rate that | ||
| 3586 | + // was. | ||
| 3583 | (None, Some(meta)) => format!( | 3587 | (None, Some(meta)) => format!( |
| 3584 | "{} — {}x{} @ {:.2} fps · drag onto a lane, or Add at playhead", | 3588 | "{} — {}x{} @ {:.2} fps · drag onto a lane, or Add at playhead", |
| 3585 | row.path.display(), | 3589 | row.path.display(), |
| 3586 | meta.width, | 3590 | meta.width, |
| 3587 | meta.height, | 3591 | meta.height, |
| 3588 | - meta.frame_rate | 3592 | + self.session |
| 3593 | + .as_ref() | ||
| 3594 | + .map_or(meta.frame_rate, |session| session.file_fps(&row.path)) | ||
| 3589 | ), | 3595 | ), |
| 3590 | (None, None) => row.path.display().to_string(), | 3596 | (None, None) => row.path.display().to_string(), |
| 3591 | }; | 3597 | }; |
crates/engine/src/export.rsmodified+68 -7
| @@ -15,7 +15,9 @@ | |||
| 15 | //! picture is re-encoded, so the frame walk honours a rate: it takes the source | 15 | //! picture is re-encoded, so the frame walk honours a rate: it takes the source |
| 16 | //! frame each timeline frame shows ([`crate::project::Speed::source_at`], the | 16 | //! frame each timeline frame shows ([`crate::project::Speed::source_at`], the |
| 17 | //! very frame preview holds there) and encodes a held one again rather than | 17 | //! very frame preview holds there) and encodes a held one again rather than |
| 18 | -//! decoding it twice. The sound is *copied* unless a filter forces a decode, and | 18 | +//! decoding it twice. A clip whose *file* was shot at another rate than the |
| 19 | +//! timeline goes through the same walk with one more conversion on the end | ||
| 20 | +//! ([`crate::project::Rate`]), so it is encoded at the speed it was shot at. The sound is *copied* unless a filter forces a decode, and | ||
| 19 | //! a packet carries no rate -- so a speeded clip on the one audio lane an mp4 | 21 | //! a packet carries no rate -- so a speeded clip on the one audio lane an mp4 |
| 20 | //! copies is refused by name ([`copy_audio`]) rather than written out at 1.00x | 22 | //! copies is refused by name ([`copy_audio`]) rather than written out at 1.00x |
| 21 | //! under a re-timed picture. | 23 | //! under a re-timed picture. |
| @@ -44,7 +46,7 @@ use crate::audio::{AudioMeta, AudioSession}; | |||
| 44 | use crate::demux::{Demuxer, VideoMeta}; | 46 | use crate::demux::{Demuxer, VideoMeta}; |
| 45 | use crate::hw::{HwEncoder, HwSession}; | 47 | use crate::hw::{HwEncoder, HwSession}; |
| 46 | use crate::mux::{AudioParams, Av1Params, MkvMuxer, Mp4Muxer, VideoParams}; | 48 | use crate::mux::{AudioParams, Av1Params, MkvMuxer, Mp4Muxer, VideoParams}; |
| 47 | -use crate::project::{LaneKind, Project}; | 49 | +use crate::project::{LaneKind, Project, Rate}; |
| 48 | use crate::scale::Composer; | 50 | use crate::scale::Composer; |
| 49 | 51 | ||
| 50 | /// Progress is reported in permille: an atomic integer the render loop can read | 52 | /// Progress is reported in permille: an atomic integer the render loop can read |
| @@ -345,6 +347,19 @@ fn copy_audio( | |||
| 345 | ) | 347 | ) |
| 346 | .into()); | 348 | .into()); |
| 347 | } | 349 | } |
| 350 | + // A frame *rate* of its own is not one of those, and that is deliberate: | ||
| 351 | + // do not "fix" this into a re-encode. A clip counts the **timeline's** | ||
| 352 | + // frames whatever its file was shot at ([`Rate`]), so the window this copy | ||
| 353 | + // trims a source's sound to is `start..end` in whole timeline frames -- | ||
| 354 | + // exactly the seconds the picture covers -- and the file is read at the | ||
| 355 | + // pitch it was recorded at, which is what playing at the rate it was shot at | ||
| 356 | + // means. There is no per-clip stretch to express, so the packets are already | ||
| 357 | + // the right sound in the right place; re-encoding a conformed lane would buy | ||
| 358 | + // nothing and cost a generation of loss on every mixed-rate export | ||
| 359 | + // (`tests/mixed_fps.rs`, `an_export_of_two_rates_runs_at_the_speed_it_was_shot` | ||
| 360 | + // measures the copied sound against the picture). A *speed* is different | ||
| 361 | + // because it resamples, which is why it is refused above. | ||
| 362 | + // | ||
| 348 | // ...and last, whether any clip on it carries an equalizer. An EQ is sample | 363 | // ...and last, whether any clip on it carries an equalizer. An EQ is sample |
| 349 | // math and a copy never decodes, so copying such a lane would write the clip | 364 | // math and a copy never decodes, so copying such a lane would write the clip |
| 350 | // *flat*, silently -- the failure a missing audio track is. This lane is | 365 | // *flat*, silently -- the failure a missing audio track is. This lane is |
| @@ -469,6 +484,16 @@ fn run( | |||
| 469 | chan_conf: track.chan_conf, | 484 | chan_conf: track.chan_conf, |
| 470 | }); | 485 | }); |
| 471 | 486 | ||
| 487 | + // One header parse per source, before any of them is decoded: what rate | ||
| 488 | + // each file was shot at against the timeline's ([`Rate`]), which is how the | ||
| 489 | + // clip's timeline frames below become frames of the file. Real time for a | ||
| 490 | + // still, a song and a single-rate project, where every conversion below is | ||
| 491 | + // the identity. | ||
| 492 | + let rates: Vec<Rate> = sources | ||
| 493 | + .iter() | ||
| 494 | + .map(|source| source_rate(&source.path, meta.frame_rate)) | ||
| 495 | + .collect(); | ||
| 496 | + | ||
| 472 | let mut encoder = Enc::open(meta, settings)?; | 497 | let mut encoder = Enc::open(meta, settings)?; |
| 473 | let mut muxer = None; | 498 | let mut muxer = None; |
| 474 | let mut done = 0u32; | 499 | let mut done = 0u32; |
| @@ -483,14 +508,18 @@ fn run( | |||
| 483 | // encoder is *not* reopened, so the export is one continuous stream | 508 | // encoder is *not* reopened, so the export is one continuous stream |
| 484 | // whose GOP boundaries need not line up with the cuts -- nor with the | 509 | // whose GOP boundaries need not line up with the cuts -- nor with the |
| 485 | // file boundaries, which are just cuts that change the path. | 510 | // file boundaries, which are just cuts that change the path. |
| 486 | - let mut pictures = match span.from { | 511 | + let (mut pictures, rate, in_frame) = match span.from { |
| 487 | Some((source, in_frame)) => { | 512 | Some((source, in_frame)) => { |
| 488 | let entry = sources | 513 | let entry = sources |
| 489 | .get(source) | 514 | .get(source) |
| 490 | .ok_or_else(|| format!("clip names source {source} of {}", sources.len()))?; | 515 | .ok_or_else(|| format!("clip names source {source} of {}", sources.len()))?; |
| 491 | - Some(ClipDecoder::open(&entry.path, in_frame)?) | 516 | + let rate = rates[source]; |
| 517 | + // Opened at the file's own frame, which is the only place the | ||
| 518 | + // file's numbering is used -- the span's are the timeline's. | ||
| 519 | + let pictures = ClipDecoder::open(&entry.path, rate.source_at(in_frame))?; | ||
| 520 | + (Some(pictures), rate, in_frame) | ||
| 492 | } | 521 | } |
| 493 | - None => None, | 522 | + None => (None, Rate::REAL_TIME, 0), |
| 494 | }; | 523 | }; |
| 495 | // What this span is graded by -- the same answer playback's decoder | 524 | // What this span is graded by -- the same answer playback's decoder |
| 496 | // carries, so the export is the picture that was watched. `None` for a | 525 | // carries, so the export is the picture that was watched. `None` for a |
| @@ -521,10 +550,24 @@ fn run( | |||
| 521 | let mut done_here = 0u32; | 550 | let mut done_here = 0u32; |
| 522 | // Source frames already taken out of this span's decoder. | 551 | // Source frames already taken out of this span's decoder. |
| 523 | let mut taken = 0u32; | 552 | let mut taken = 0u32; |
| 553 | + // The whole of the mapping, in the order it composes: the speed says | ||
| 554 | + // which of the clip's (timeline-rate) frames a timeline frame shows, | ||
| 555 | + // and the rate says which frame of the *file* that is -- counted from | ||
| 556 | + // the one the decoder was opened at. At real time and at the timeline's | ||
| 557 | + // own rate this is `Speed::source_at` and nothing else, which is the | ||
| 558 | + // walk a single-rate project has always taken. | ||
| 559 | + let opened_at = rate.source_at(in_frame); | ||
| 560 | + let source_at = | ||
| 561 | + |offset: u32| rate.source_at(in_frame + span.speed.source_at(offset)) - opened_at; | ||
| 524 | while done_here < span.len { | 562 | while done_here < span.len { |
| 525 | cancelled(shared)?; | 563 | cancelled(shared)?; |
| 526 | - let want = span.speed.source_at(done_here); | 564 | + let want = source_at(done_here); |
| 527 | - let repeats = span.speed.repeats(done_here, span.len); | 565 | + // How many timeline frames from here show that same picture: one at |
| 566 | + // real time, more when the clip is slowed or its file is slower | ||
| 567 | + // than the timeline. Encoded again rather than decoded twice. | ||
| 568 | + let repeats = (done_here..span.len) | ||
| 569 | + .take_while(|&offset| source_at(offset) == want) | ||
| 570 | + .count() as u32; | ||
| 528 | let picture = match &mut pictures { | 571 | let picture = match &mut pictures { |
| 529 | Some(pictures) => { | 572 | Some(pictures) => { |
| 530 | let mut ran_out = false; | 573 | let mut ran_out = false; |
| @@ -622,6 +665,24 @@ fn run( | |||
| 622 | Ok(()) | 665 | Ok(()) |
| 623 | } | 666 | } |
| 624 | 667 | ||
| 668 | +/// What rate `path` was shot at against a timeline at `timeline_fps` | ||
| 669 | +/// ([`Rate`]). [`Rate::REAL_TIME`] for the files that have no rate of their own | ||
| 670 | +/// -- a still, a song -- and for one that will not open here: the decoder is | ||
| 671 | +/// opened a few lines later and fails the export by name, which is a better | ||
| 672 | +/// error than this one could raise. | ||
| 673 | +fn source_rate(path: &Path, timeline_fps: f64) -> Rate { | ||
| 674 | + if crate::is_image(path) || crate::is_audio(path) { | ||
| 675 | + return Rate::REAL_TIME; | ||
| 676 | + } | ||
| 677 | + match Demuxer::open(path) { | ||
| 678 | + // ...and one whose rate cannot be named against the timeline's, which | ||
| 679 | + // `matches_timeline` refuses at import, so nothing on a timeline is on | ||
| 680 | + // this arm either. | ||
| 681 | + Ok((meta, _)) => Rate::from_fps(meta.frame_rate, timeline_fps).unwrap_or(Rate::REAL_TIME), | ||
| 682 | + Err(_) => Rate::REAL_TIME, | ||
| 683 | + } | ||
| 684 | +} | ||
| 685 | + | ||
| 625 | /// Where a clip sits on the timeline as a person reads it: `mm:ss`, short | 686 | /// Where a clip sits on the timeline as a person reads it: `mm:ss`, short |
| 626 | /// enough to sit inside a refusal and exact enough to go and find the clip. | 687 | /// enough to sit inside a refusal and exact enough to go and find the clip. |
| 627 | /// Not the app's frame-accurate timecode -- an engine refusal is prose, and a | 688 | /// Not the app's frame-accurate timecode -- an engine refusal is prose, and a |
crates/engine/src/lib.rsmodified+1 -1
| @@ -27,7 +27,7 @@ pub use demux::{Codec, VideoMeta}; | |||
| 27 | pub use export::ExportHandle; | 27 | pub use export::ExportHandle; |
| 28 | pub use mux::{AudioParams, Mp4Muxer, VideoParams}; | 28 | pub use mux::{AudioParams, Mp4Muxer, VideoParams}; |
| 29 | pub use playback::PlaybackSession; | 29 | pub use playback::PlaybackSession; |
| 30 | -pub use project::{Clip, Project, Speed}; | 30 | +pub use project::{Clip, Project, Rate, Speed}; |
| 31 | 31 | ||
| 32 | /// Whether a path names a standalone audio file -- a source with no picture, | 32 | /// Whether a path names a standalone audio file -- a source with no picture, |
| 33 | /// which belongs on the audio lane and nowhere else. Extension only, lowercased: | 33 | /// which belongs on the audio lane and nowhere else. Extension only, lowercased: |
crates/engine/src/playback.rsmodified+152 -49
| @@ -25,7 +25,7 @@ use crate::color::ColorParams; | |||
| 25 | use crate::decode::{DecodeSession, Frame, Worker}; | 25 | use crate::decode::{DecodeSession, Frame, Worker}; |
| 26 | use crate::demux::{Codec, Demuxer, VideoMeta}; | 26 | use crate::demux::{Codec, Demuxer, VideoMeta}; |
| 27 | use crate::eq::EqParams; | 27 | use crate::eq::EqParams; |
| 28 | -use crate::project::{Clip, Edge, Lane, LaneKind, Project, Source, Span, Speed}; | 28 | +use crate::project::{Clip, Edge, Lane, LaneKind, Project, Rate, Source, Span, Speed}; |
| 29 | use crate::scale::{Composer, FitPolicy}; | 29 | use crate::scale::{Composer, FitPolicy}; |
| 30 | 30 | ||
| 31 | /// How long the feeder waits out a full ring. The ring holds a second, so this | 31 | /// How long the feeder waits out a full ring. The ring holds a second, so this |
| @@ -40,10 +40,11 @@ const RING_FULL_WAIT: Duration = Duration::from_millis(10); | |||
| 40 | /// honest; both are what a video imported onto such a timeline is held to | 40 | /// honest; both are what a video imported onto such a timeline is held to |
| 41 | /// ([`matches_timeline`]). | 41 | /// ([`matches_timeline`]). |
| 42 | /// | 42 | /// |
| 43 | -/// ponytail: a 25 fps video refused by an audio-only timeline it could have | 43 | +/// ponytail: a 25 fps video imported onto an audio-only timeline it could have |
| 44 | -/// defined is the ceiling here. Upgrade path is adopting the first *picture's* | 44 | +/// defined plays at 25 fps, correctly, but on a 30 fps timeline -- it is read |
| 45 | -/// rate and codec on import, which means retiming every audio clip already | 45 | +/// through [`Rate`] like any other file shot at another rate rather than |
| 46 | -/// placed in frames. | 46 | +/// defining one. Upgrade path is adopting the first *picture's* rate and codec |
| 47 | +/// on import, which means retiming every audio clip already placed in frames. | ||
| 47 | const AUDIO_ONLY_CANVAS: (u32, u32, f64) = (1920, 1080, 30.0); | 48 | const AUDIO_ONLY_CANVAS: (u32, u32, f64) = (1920, 1080, 30.0); |
| 48 | 49 | ||
| 49 | /// The frame rate a timeline scaffolded from a still image runs at, for | 50 | /// The frame rate a timeline scaffolded from a still image runs at, for |
| @@ -193,6 +194,20 @@ pub struct PlaybackSession { | |||
| 193 | /// not -- with the single exception `sources` itself has, | 194 | /// not -- with the single exception `sources` itself has, |
| 194 | /// [`Self::remove_source`], which takes the same entry out of both. | 195 | /// [`Self::remove_source`], which takes the same entry out of both. |
| 195 | counts: Vec<u32>, | 196 | counts: Vec<u32>, |
| 197 | + /// What each source's own frame rate is against this timeline's, indexed | ||
| 198 | + /// and grown exactly as [`Self::counts`] is (and shortened with it by | ||
| 199 | + /// [`Self::remove_source`]). [`Rate::REAL_TIME`] for a file shot at the | ||
| 200 | + /// timeline's rate -- and for a still and a song, which have no rate of | ||
| 201 | + /// their own -- so a single-rate project converts nothing anywhere. | ||
| 202 | + /// | ||
| 203 | + /// A clip counts *timeline* frames ([`Rate`]); this is the one thing that | ||
| 204 | + /// knows which frames of the file those are, and only | ||
| 205 | + /// [`start_span`](Self::start_span) and [`try_frame`](Self::try_frame) ask. | ||
| 206 | + rates: Vec<Rate>, | ||
| 207 | + /// The rate of the source the current worker is decoding, kept beside | ||
| 208 | + /// [`Self::span`] because the frames coming back are numbered in *its* | ||
| 209 | + /// file's frames and nothing else can put them back on the timeline. | ||
| 210 | + span_rate: Rate, | ||
| 196 | /// What the current video worker was opened for: where it sits on the | 211 | /// What the current video worker was opened for: where it sits on the |
| 197 | /// timeline, how long it runs, and which source frame it started at -- | 212 | /// timeline, how long it runs, and which source frame it started at -- |
| 198 | /// together they rewrite a source frame index into a timeline one. Not a | 213 | /// together they rewrite a source frame index into a timeline one. Not a |
| @@ -265,6 +280,9 @@ impl PlaybackSession { | |||
| 265 | audio_disabled, | 280 | audio_disabled, |
| 266 | project, | 281 | project, |
| 267 | counts: vec![meta.frame_count], | 282 | counts: vec![meta.frame_count], |
| 283 | + // Source 0 *is* the timeline's rate: it defined it. | ||
| 284 | + rates: vec![Rate::REAL_TIME], | ||
| 285 | + span_rate: Rate::REAL_TIME, | ||
| 268 | span, | 286 | span, |
| 269 | eos: false, | 287 | eos: false, |
| 270 | }) | 288 | }) |
| @@ -365,6 +383,9 @@ impl PlaybackSession { | |||
| 365 | audio_disabled, | 383 | audio_disabled, |
| 366 | project, | 384 | project, |
| 367 | counts: vec![meta.frame_count], | 385 | counts: vec![meta.frame_count], |
| 386 | + // Source 0 *is* the timeline's rate: it defined it. | ||
| 387 | + rates: vec![Rate::REAL_TIME], | ||
| 388 | + span_rate: Rate::REAL_TIME, | ||
| 368 | span, | 389 | span, |
| 369 | eos: false, | 390 | eos: false, |
| 370 | }) | 391 | }) |
| @@ -431,6 +452,9 @@ impl PlaybackSession { | |||
| 431 | audio_disabled: None, | 452 | audio_disabled: None, |
| 432 | project, | 453 | project, |
| 433 | counts: vec![meta.frame_count], | 454 | counts: vec![meta.frame_count], |
| 455 | + // Source 0 *is* the timeline's rate: it defined it. | ||
| 456 | + rates: vec![Rate::REAL_TIME], | ||
| 457 | + span_rate: Rate::REAL_TIME, | ||
| 434 | span, | 458 | span, |
| 435 | eos: false, | 459 | eos: false, |
| 436 | }) | 460 | }) |
| @@ -554,9 +578,16 @@ impl PlaybackSession { | |||
| 554 | // clip check below indexes this list by source, so it must line up with | 578 | // clip check below indexes this list by source, so it must line up with |
| 555 | // `doc.sources` whichever entry the scaffolding came from. | 579 | // `doc.sources` whichever entry the scaffolding came from. |
| 556 | let mut counts = Vec::with_capacity(doc.sources.len()); | 580 | let mut counts = Vec::with_capacity(doc.sources.len()); |
| 581 | + // Beside it, one entry per source, grown at every `push` below: the | ||
| 582 | + // scaffold defines the rate, so it is read frame for frame; every other | ||
| 583 | + // one is however long it is *in this timeline's frames*, which is the | ||
| 584 | + // length `import` noted for it and the wall the clip check below holds | ||
| 585 | + // it to. | ||
| 586 | + let mut rates = Vec::with_capacity(doc.sources.len()); | ||
| 557 | for (i, source) in doc.sources.iter().enumerate() { | 587 | for (i, source) in doc.sources.iter().enumerate() { |
| 558 | if i == scaffold { | 588 | if i == scaffold { |
| 559 | counts.push(meta.frame_count); | 589 | counts.push(meta.frame_count); |
| 590 | + rates.push(Rate::REAL_TIME); | ||
| 560 | continue; | 591 | continue; |
| 561 | } | 592 | } |
| 562 | // A still has neither a rate to match nor a track to match with: | 593 | // A still has neither a rate to match nor a track to match with: |
| @@ -567,6 +598,7 @@ impl PlaybackSession { | |||
| 567 | crate::decode::image_size(&source.path) | 598 | crate::decode::image_size(&source.path) |
| 568 | .map_err(|e| format!("source {}: {e}", source.path.display()))?; | 599 | .map_err(|e| format!("source {}: {e}", source.path.display()))?; |
| 569 | counts.push(image_frames(meta.frame_rate)); | 600 | counts.push(image_frames(meta.frame_rate)); |
| 601 | + rates.push(Rate::REAL_TIME); | ||
| 570 | continue; | 602 | continue; |
| 571 | } | 603 | } |
| 572 | // A source with no picture is checked on what it does have, and | 604 | // A source with no picture is checked on what it does have, and |
| @@ -576,13 +608,15 @@ impl PlaybackSession { | |||
| 576 | audio_matches(source, &first_audio) | 608 | audio_matches(source, &first_audio) |
| 577 | .map_err(|e| format!("source {}: {e}", source.path.display()))?; | 609 | .map_err(|e| format!("source {}: {e}", source.path.display()))?; |
| 578 | counts.push(audio_frames(&source.path, meta.frame_rate)?); | 610 | counts.push(audio_frames(&source.path, meta.frame_rate)?); |
| 611 | + rates.push(Rate::REAL_TIME); | ||
| 579 | continue; | 612 | continue; |
| 580 | } | 613 | } |
| 581 | let (other, _) = Demuxer::open(&source.path) | 614 | let (other, _) = Demuxer::open(&source.path) |
| 582 | .map_err(|e| format!("source {}: {e}", source.path.display()))?; | 615 | .map_err(|e| format!("source {}: {e}", source.path.display()))?; |
| 583 | - matches_timeline(source, &other, &meta, &first_audio) | 616 | + let rate = matches_timeline(source, &other, &meta, &first_audio) |
| 584 | .map_err(|e| format!("source {}: {e}", source.path.display()))?; | 617 | .map_err(|e| format!("source {}: {e}", source.path.display()))?; |
| 585 | - counts.push(other.frame_count); | 618 | + counts.push(rate.timeline_at(other.frame_count)); |
| 619 | + rates.push(rate); | ||
| 586 | } | 620 | } |
| 587 | // The video lane can only play files that have pictures. Hand-written | 621 | // The video lane can only play files that have pictures. Hand-written |
| 588 | // (or hand-edited) project files are the one door this can come in | 622 | // (or hand-edited) project files are the one door this can come in |
| @@ -656,6 +690,8 @@ impl PlaybackSession { | |||
| 656 | audio_disabled, | 690 | audio_disabled, |
| 657 | project, | 691 | project, |
| 658 | counts, | 692 | counts, |
| 693 | + rates, | ||
| 694 | + span_rate: Rate::REAL_TIME, | ||
| 659 | span, | 695 | span, |
| 660 | eos: false, | 696 | eos: false, |
| 661 | }; | 697 | }; |
| @@ -733,9 +769,15 @@ impl PlaybackSession { | |||
| 733 | // (`speed_maps_both_ways`). An empty timeline has no span, | 769 | // (`speed_maps_both_ways`). An empty timeline has no span, |
| 734 | // and its one black frame is frame 0. Real time is the | 770 | // and its one black frame is frame 0. Real time is the |
| 735 | // arithmetic this always did, frame for frame. | 771 | // arithmetic this always did, frame for frame. |
| 736 | - frame.index = self | 772 | + // ...through the file's own rate first, which is the ceil |
| 737 | - .span | 773 | + // half of *that* pair: the picture at source frame `i` is |
| 738 | - .map_or(frame.index, |s| s.timeline_at(frame.index)); | 774 | + // due at the first timeline-rate frame that shows it, and a |
| 775 | + // slower file's picture is therefore held for the frames in | ||
| 776 | + // between. Real time for a gap and for a single-rate | ||
| 777 | + // project, where this is the identity. | ||
| 778 | + frame.index = self.span.map_or(frame.index, |s| { | ||
| 779 | + s.timeline_at(self.span_rate.timeline_at(frame.index)) | ||
| 780 | + }); | ||
| 739 | return Some(frame); | 781 | return Some(frame); |
| 740 | } | 782 | } |
| 741 | Err(TryRecvError::Empty) => return None, | 783 | Err(TryRecvError::Empty) => return None, |
| @@ -805,6 +847,14 @@ impl PlaybackSession { | |||
| 805 | /// timeline still moves, there are simply no more pictures, and the | 847 | /// timeline still moves, there are simply no more pictures, and the |
| 806 | /// disconnected receiver carries the session on to the next span. | 848 | /// disconnected receiver carries the session on to the next span. |
| 807 | fn start_span(&mut self, span: Option<Span>) { | 849 | fn start_span(&mut self, span: Option<Span>) { |
| 850 | + // Which file's frames the worker about to be opened will number its | ||
| 851 | + // pictures in: the span's own source, and real time for a gap, whose | ||
| 852 | + // black worker counts timeline frames already. Set before the open, | ||
| 853 | + // because the open is the first thing that converts with it. | ||
| 854 | + self.span_rate = match span.and_then(|s| s.from) { | ||
| 855 | + Some((source, _)) => self.rates.get(source).copied().unwrap_or(Rate::REAL_TIME), | ||
| 856 | + None => Rate::REAL_TIME, | ||
| 857 | + }; | ||
| 808 | let opened = match span { | 858 | let opened = match span { |
| 809 | // The grade is the composite's at this frame -- the same clip the | 859 | // The grade is the composite's at this frame -- the same clip the |
| 810 | // span itself came from -- and it is constant across the span, so | 860 | // span itself came from -- and it is constant across the span, so |
| @@ -841,10 +891,17 @@ impl PlaybackSession { | |||
| 841 | .. | 891 | .. |
| 842 | }) => DecodeSession::open_worker( | 892 | }) => DecodeSession::open_worker( |
| 843 | &self.project.sources()[source].path, | 893 | &self.project.sources()[source].path, |
| 844 | - in_frame, | 894 | + // The file's own frames, which is the only place they exist: |
| 895 | + // a clip counts the timeline's ([`Rate`]). | ||
| 896 | + self.span_rate.source_at(in_frame), | ||
| 845 | // Source frames, which a speed makes more (or fewer) than the | 897 | // Source frames, which a speed makes more (or fewer) than the |
| 846 | - // timeline frames the span covers. | 898 | + // timeline frames the span covers -- and which a file shot at |
| 847 | - in_frame + span.expect("matched above").source_len(), | 899 | + // another rate makes fewer (or more) again. One past the last |
| 900 | + // frame this span shows, not one past its length: at another | ||
| 901 | + // rate those are two different frames. | ||
| 902 | + self.span_rate.source_at( | ||
| 903 | + in_frame + span.expect("matched above").source_len().saturating_sub(1), | ||
| 904 | + ) + 1, | ||
| 848 | self.project | 905 | self.project |
| 849 | .composite_color_at(start) | 906 | .composite_color_at(start) |
| 850 | .copied() | 907 | .copied() |
| @@ -1120,13 +1177,36 @@ impl PlaybackSession { | |||
| 1120 | self.project.trim_room(lane, idx, edge, &self.counts) | 1177 | self.project.trim_room(lane, idx, edge, &self.counts) |
| 1121 | } | 1178 | } |
| 1122 | 1179 | ||
| 1123 | - /// Records how long a source is, for a source index that may be one | 1180 | + /// Records how long a source is and what rate it was shot at, for a source |
| 1124 | - /// `Project::import` just made or one it handed back. See [`Self::counts`]. | 1181 | + /// index that may be one `Project::import` just made or one it handed back. |
| 1125 | - fn note_frames(&mut self, source: usize, frames: u32) { | 1182 | + /// See [`Self::counts`] and [`Self::rates`], which are one table in two |
| 1183 | + /// vectors and grow together. | ||
| 1184 | + fn note_frames(&mut self, source: usize, frames: u32, rate: Rate) { | ||
| 1126 | if source == self.counts.len() { | 1185 | if source == self.counts.len() { |
| 1127 | self.counts.push(frames); | 1186 | self.counts.push(frames); |
| 1187 | + self.rates.push(rate); | ||
| 1128 | } | 1188 | } |
| 1129 | debug_assert_eq!(self.counts.len(), self.project.sources().len()); | 1189 | debug_assert_eq!(self.counts.len(), self.project.sources().len()); |
| 1190 | + debug_assert_eq!(self.rates.len(), self.counts.len()); | ||
| 1191 | + } | ||
| 1192 | + | ||
| 1193 | + /// The rate noted for whichever source plays `path`, by | ||
| 1194 | + /// [`file_frames`](Self::file_frames)'s rule: one file is one rate however | ||
| 1195 | + /// many audio tracks it carries. [`Rate::REAL_TIME`] for a file this session | ||
| 1196 | + /// has never taken in. | ||
| 1197 | + fn file_rate(&self, path: &Path) -> Rate { | ||
| 1198 | + self.source_of(path) | ||
| 1199 | + .map_or(Rate::REAL_TIME, |i| self.rates[i]) | ||
| 1200 | + } | ||
| 1201 | + | ||
| 1202 | + /// Which source `path` is, canonicalising only if it has to: a source's own | ||
| 1203 | + /// path is canonical ([`Source::new`]), so a caller handing one back from | ||
| 1204 | + /// [`sources`](Self::sources) -- which is every library row -- hits on the | ||
| 1205 | + /// first walk and never pays for the `canonicalize` syscall the second one | ||
| 1206 | + /// makes. One rule, so a path that names a length names a rate too. | ||
| 1207 | + fn source_of(&self, path: &Path) -> Option<usize> { | ||
| 1208 | + let at = |wanted: &Path| self.project.sources().iter().position(|s| s.path == wanted); | ||
| 1209 | + at(path).or_else(|| at(&Source::new(path, 0).path)) | ||
| 1130 | } | 1210 | } |
| 1131 | 1211 | ||
| 1132 | /// How long the whole of `path` is, in timeline frames: the length noted | 1212 | /// How long the whole of `path` is, in timeline frames: the length noted |
| @@ -1138,14 +1218,20 @@ impl PlaybackSession { | |||
| 1138 | /// audio tracks it carries -- the picture's frame count for an mp4, the | 1218 | /// audio tracks it carries -- the picture's frame count for an mp4, the |
| 1139 | /// playing time for a song. | 1219 | /// playing time for a song. |
| 1140 | pub fn file_frames(&self, path: &Path) -> u32 { | 1220 | pub fn file_frames(&self, path: &Path) -> u32 { |
| 1141 | - let at = |wanted: &Path| self.project.sources().iter().position(|s| s.path == wanted); | 1221 | + self.source_of(path).map_or(0, |i| self.counts[i]) |
| 1142 | - // A source's own path is canonical ([`Source::new`]), so a caller | 1222 | + } |
| 1143 | - // handing one back from [`sources`](Self::sources) -- which is every | 1223 | + |
| 1144 | - // library row -- hits on the first walk and never pays for the | 1224 | + /// What rate the file at `path` was *shot* at, in frames per second -- which |
| 1145 | - // `canonicalize` syscall the second one makes. | 1225 | + /// is the timeline's own rate for every source that shares it, and is not |
| 1146 | - at(path) | 1226 | + /// for one placed at another ([`Rate`]). By path like |
| 1147 | - .or_else(|| at(&Source::new(path, 0).path)) | 1227 | + /// [`file_frames`](Self::file_frames), and the timeline's rate for a file |
| 1148 | - .map_or(0, |i| self.counts[i]) | 1228 | + /// this session has never taken in (and for a still and a song, which were |
| 1229 | + /// shot at no rate at all). | ||
| 1230 | + /// | ||
| 1231 | + /// What a library row names the file with: the timeline's rate there would | ||
| 1232 | + /// be a lie about a 23.976 fps file the moment one can join. | ||
| 1233 | + pub fn file_fps(&self, path: &Path) -> f64 { | ||
| 1234 | + self.file_rate(path).as_f64() * self.meta.frame_rate | ||
| 1149 | } | 1235 | } |
| 1150 | 1236 | ||
| 1151 | /// The clip the picture is coming from at `timeline_secs`: the lane it sits | 1237 | /// The clip the picture is coming from at `timeline_secs`: the lane it sits |
| @@ -1304,8 +1390,9 @@ impl PlaybackSession { | |||
| 1304 | let first = self.first_audio()?; | 1390 | let first = self.first_audio()?; |
| 1305 | audio_matches(&wanted, &first)?; | 1391 | audio_matches(&wanted, &first)?; |
| 1306 | } | 1392 | } |
| 1393 | + let rate = self.file_rate(&wanted.path); | ||
| 1307 | let source = self.project.import(path, stream); | 1394 | let source = self.project.import(path, stream); |
| 1308 | - self.note_frames(source, frames); | 1395 | + self.note_frames(source, frames, rate); |
| 1309 | let clip = Clip { | 1396 | let clip = Clip { |
| 1310 | start: 0, | 1397 | start: 0, |
| 1311 | in_frame: 0, | 1398 | in_frame: 0, |
| @@ -1387,6 +1474,7 @@ impl PlaybackSession { | |||
| 1387 | // count one index late. | 1474 | // count one index late. |
| 1388 | if idx < self.counts.len() { | 1475 | if idx < self.counts.len() { |
| 1389 | self.counts.remove(idx); | 1476 | self.counts.remove(idx); |
| 1477 | + self.rates.remove(idx); | ||
| 1390 | } | 1478 | } |
| 1391 | let now = self.now(); | 1479 | let now = self.now(); |
| 1392 | self.seek(now); | 1480 | self.seek(now); |
| @@ -1441,11 +1529,14 @@ impl PlaybackSession { | |||
| 1441 | /// nothing playable, so there is nothing for [`undo`](Self::undo) to take | 1529 | /// nothing playable, so there is nothing for [`undo`](Self::undo) to take |
| 1442 | /// back, and nothing reseeks. | 1530 | /// back, and nothing reseeks. |
| 1443 | /// | 1531 | /// |
| 1444 | - /// Refused unless it can join the timeline -- same codec, same frame rate, | 1532 | + /// Refused unless it can join the timeline -- same codec, same audio |
| 1445 | - /// same audio parameters or both silent; the `Err` names the property that | 1533 | + /// parameters or both silent; the `Err` names the property that disagrees, |
| 1446 | - /// disagrees, for a caller to show. Nothing is changed by a refusal. A | 1534 | + /// for a caller to show. Nothing is changed by a refusal. A *resolution* of |
| 1447 | - /// *resolution* of its own is not a refusal: the clip is placed on the | 1535 | + /// its own is not a refusal: the clip is placed on the project canvas by its |
| 1448 | - /// project canvas by its fit policy ([`PlaybackSession::set_fit`]). | 1536 | + /// fit policy ([`PlaybackSession::set_fit`]) -- and neither is a *frame |
| 1537 | + /// rate* of its own: the file is placed for the seconds it lasts and read at | ||
| 1538 | + /// [`Rate`] against the timeline's rate, so it plays at the speed it was | ||
| 1539 | + /// shot at. | ||
| 1449 | pub fn import(&mut self, path: &Path) -> crate::Result<usize> { | 1540 | pub fn import(&mut self, path: &Path) -> crate::Result<usize> { |
| 1450 | if crate::is_audio(path) { | 1541 | if crate::is_audio(path) { |
| 1451 | return self.import_audio(path); | 1542 | return self.import_audio(path); |
| @@ -1458,9 +1549,15 @@ impl PlaybackSession { | |||
| 1458 | // Stream 0: an import brings a file in on its first audio track, and | 1549 | // Stream 0: an import brings a file in on its first audio track, and |
| 1459 | // [`place_stream_at`](Self::place_stream_at) is how any other one of | 1550 | // [`place_stream_at`](Self::place_stream_at) is how any other one of |
| 1460 | // its streams reaches the timeline afterwards. | 1551 | // its streams reaches the timeline afterwards. |
| 1461 | - matches_timeline(&Source::new(path, 0), &meta, &self.meta, &first)?; | 1552 | + // ...and the rate it will be read at comes back from the check that |
| 1553 | + // accepted it, so the number the refusal was decided on is the number | ||
| 1554 | + // the file is played by. | ||
| 1555 | + let rate = matches_timeline(&Source::new(path, 0), &meta, &self.meta, &first)?; | ||
| 1462 | let source = self.project.import(path, 0); | 1556 | let source = self.project.import(path, 0); |
| 1463 | - self.note_frames(source, meta.frame_count); | 1557 | + // Its length *on this timeline*: a file shot slower than the timeline |
| 1558 | + // runs covers more frames than it holds, which is the whole of what | ||
| 1559 | + // placing it at another rate means ([`Rate`]). | ||
| 1560 | + self.note_frames(source, rate.timeline_at(meta.frame_count), rate); | ||
| 1464 | Ok(source) | 1561 | Ok(source) |
| 1465 | } | 1562 | } |
| 1466 | 1563 | ||
| @@ -1480,7 +1577,7 @@ impl PlaybackSession { | |||
| 1480 | audio_matches(&Source::new(path, 0), &first)?; | 1577 | audio_matches(&Source::new(path, 0), &first)?; |
| 1481 | let frames = audio_frames(path, self.meta.frame_rate)?; | 1578 | let frames = audio_frames(path, self.meta.frame_rate)?; |
| 1482 | let source = self.project.import(path, 0); | 1579 | let source = self.project.import(path, 0); |
| 1483 | - self.note_frames(source, frames); | 1580 | + self.note_frames(source, frames, Rate::REAL_TIME); |
| 1484 | Ok(source) | 1581 | Ok(source) |
| 1485 | } | 1582 | } |
| 1486 | 1583 | ||
| @@ -1504,7 +1601,7 @@ impl PlaybackSession { | |||
| 1504 | .into()); | 1601 | .into()); |
| 1505 | } | 1602 | } |
| 1506 | let source = self.project.import(path, 0); | 1603 | let source = self.project.import(path, 0); |
| 1507 | - self.note_frames(source, image_frames(self.meta.frame_rate)); | 1604 | + self.note_frames(source, image_frames(self.meta.frame_rate), Rate::REAL_TIME); |
| 1508 | Ok(source) | 1605 | Ok(source) |
| 1509 | } | 1606 | } |
| 1510 | 1607 | ||
| @@ -1766,15 +1863,16 @@ impl Drop for PlaybackSession { | |||
| 1766 | 1863 | ||
| 1767 | /// Whether `path`, already demuxed to `meta`, may join a timeline whose | 1864 | /// Whether `path`, already demuxed to `meta`, may join a timeline whose |
| 1768 | /// parameters are `timeline` and whose audio probes as `first`: same codec, | 1865 | /// parameters are `timeline` and whose audio probes as `first`: same codec, |
| 1769 | -/// same frame rate, same audio parameters or both silent. | 1866 | +/// same audio parameters or both silent, and a frame rate that can be named |
| 1867 | +/// against the timeline's. The [`Rate`] it will be read at comes back with the | ||
| 1868 | +/// answer, so the number the check was decided on is the number it plays by. | ||
| 1770 | /// | 1869 | /// |
| 1771 | /// *Not* the same size any more. A project has its own resolution | 1870 | /// *Not* the same size any more. A project has its own resolution |
| 1772 | /// ([`PlaybackSession::set_resolution`]) and every clip is placed on it by its | 1871 | /// ([`PlaybackSession::set_resolution`]) and every clip is placed on it by its |
| 1773 | /// own fit policy, so a 640x360 file joining a 1920x1080 timeline is a | 1872 | /// own fit policy, so a 640x360 file joining a 1920x1080 timeline is a |
| 1774 | -/// letterboxed clip rather than a refusal. The frame rate stays refused on | 1873 | +/// letterboxed clip rather than a refusal, and so is a frame rate of its own: |
| 1775 | -/// purpose: mixing rates means resampling the *timeline*, which is a different | 1874 | +/// the timeline keeps its own rate and the file is read at [`Rate`] against it |
| 1776 | -/// problem from resampling a picture, and a refusal is the honest answer until | 1875 | +/// ([`PlaybackSession::import`] notes how long it is *here*). |
| 1777 | -/// it is solved. | ||
| 1778 | /// | 1876 | /// |
| 1779 | /// The `Err` names the property that disagrees, and those strings are what a | 1877 | /// The `Err` names the property that disagrees, and those strings are what a |
| 1780 | /// front-end shows verbatim; [`PlaybackSession::import`] and | 1878 | /// front-end shows verbatim; [`PlaybackSession::import`] and |
| @@ -1785,7 +1883,7 @@ fn matches_timeline( | |||
| 1785 | meta: &VideoMeta, | 1883 | meta: &VideoMeta, |
| 1786 | timeline: &VideoMeta, | 1884 | timeline: &VideoMeta, |
| 1787 | first: &Option<crate::AudioProbe>, | 1885 | first: &Option<crate::AudioProbe>, |
| 1788 | -) -> crate::Result<()> { | 1886 | +) -> crate::Result<Rate> { |
| 1789 | // Codec first: one timeline is one kind of source. Mixing them would decode | 1887 | // Codec first: one timeline is one kind of source. Mixing them would decode |
| 1790 | // (every clip opens its own decoder) but on a machine without the VA-API | 1888 | // (every clip opens its own decoder) but on a machine without the VA-API |
| 1791 | // plugin the VP9 half would be black frames with the refusal only on | 1889 | // plugin the VP9 half would be black frames with the refusal only on |
| @@ -1798,15 +1896,20 @@ fn matches_timeline( | |||
| 1798 | ) | 1896 | ) |
| 1799 | .into()); | 1897 | .into()); |
| 1800 | } | 1898 | } |
| 1801 | - // Container frame rates are computed from timescales, so never `==`. | 1899 | + // The frame rate is *not* a refusal any more: a file shot at another rate is |
| 1802 | - if (meta.frame_rate - timeline.frame_rate).abs() > 0.01 { | 1900 | + // placed for the seconds it lasts and read through [`Rate`] at the |
| 1803 | - return Err(format!( | 1901 | + // decoder's door, so it plays at the speed it was shot at on a timeline |
| 1804 | - "{:.3} fps does not match the timeline's {:.3} fps", | 1902 | + // that counts frames faster or slower. |
| 1805 | - meta.frame_rate, timeline.frame_rate | 1903 | + // |
| 1806 | - ) | 1904 | + // A rate that cannot be *named* still is, and this is the one place it is |
| 1807 | - .into()); | 1905 | + // caught: `Rate::from_fps` builds itself out of the muxer's own timescales, |
| 1808 | - } | 1906 | + // and a file whose rate has none of those (a container that says nothing and |
| 1809 | - audio_matches(source, first) | 1907 | + // holds one block, so the demuxer measures 0 fps) would otherwise be read |
| 1908 | + // 1:1 in silence -- the old rate gate refused those too, by arithmetic | ||
| 1909 | + // accident. The `Err` is `mux::frame_timing`'s own words. | ||
| 1910 | + let rate = Rate::from_fps(meta.frame_rate, timeline.frame_rate)?; | ||
| 1911 | + audio_matches(source, first)?; | ||
| 1912 | + Ok(rate) | ||
| 1810 | } | 1913 | } |
| 1811 | 1914 | ||
| 1812 | /// Whether a candidate's audio may join a timeline whose first source probes as | 1915 | /// Whether a candidate's audio may join a timeline whose first source probes as |
crates/engine/src/project.rsmodified+192 -0
| @@ -221,9 +221,120 @@ impl std::fmt::Display for Speed { | |||
| 221 | } | 221 | } |
| 222 | } | 222 | } |
| 223 | 223 | ||
| 224 | +/// What a file's own frame rate is against the timeline's, as an exact | ||
| 225 | +/// rational: how many frames of the *file* one frame of the timeline is worth. | ||
| 226 | +/// | ||
| 227 | +/// Every frame number in this module counts **timeline** frames -- a clip's | ||
| 228 | +/// `in_frame` and `out_frame` included -- so a 23.976 fps file placed on a 30 fps | ||
| 229 | +/// timeline is as many frames long as the seconds it lasts, and every edit | ||
| 230 | +/// (trim, split, speed, paste) is the same arithmetic it always was. This is the | ||
| 231 | +/// one conversion, and it happens at the decoder's door: [`PlaybackSession`] | ||
| 232 | +/// opens a worker with it and [`crate::export`] pulls pictures through it. The | ||
| 233 | +/// file's own numbering exists nowhere else. | ||
| 234 | +/// | ||
| 235 | +/// The same floor/ceil pair as [`Speed`], for the same reason: the frame an | ||
| 236 | +/// export encodes at a timeline frame has to be the frame playback is holding | ||
| 237 | +/// there. Composed *after* a speed rather than folded into it, so a 2x 24 fps | ||
| 238 | +/// clip on a 30 fps timeline is exactly both (`rate_composes_with_speed`). | ||
| 239 | +/// | ||
| 240 | +/// Rational and not an `f64`, exactly: 24000/1001 over 30 is `800/1001` and | ||
| 241 | +/// stays `800/1001` however far the timeline runs, where a rate rounded to | ||
| 242 | +/// (say) milli-fps would leave a fraction of a frame per clip to pile up into a | ||
| 243 | +/// visible drift over an hour (`a_23_976_rate_is_exact_and_never_drifts`). | ||
| 244 | +/// | ||
| 245 | +/// [`PlaybackSession`]: crate::PlaybackSession | ||
| 246 | +#[derive(Clone, Copy, PartialEq, Eq, Debug)] | ||
| 247 | +pub struct Rate { | ||
| 248 | + /// Frames of the file... | ||
| 249 | + source: u32, | ||
| 250 | + /// ...per this many frames of the timeline it plays on. Never zero. | ||
| 251 | + timeline: u32, | ||
| 252 | +} | ||
| 253 | + | ||
| 254 | +impl Rate { | ||
| 255 | + /// A file shot at the timeline's own rate: every conversion below is the | ||
| 256 | + /// identity, which is the path a single-rate project is on. | ||
| 257 | + pub const REAL_TIME: Self = Self { | ||
| 258 | + source: 1, | ||
| 259 | + timeline: 1, | ||
| 260 | + }; | ||
| 261 | + | ||
| 262 | + /// The rate of a file at `source_fps` on a timeline at `timeline_fps`, | ||
| 263 | + /// exactly. | ||
| 264 | + /// | ||
| 265 | + /// Both rates come out of a container as a division, so neither is ever the | ||
| 266 | + /// number it means (`23.976023976...`); [`crate::mux::frame_timing`] is what | ||
| 267 | + /// already knows how to name one exactly -- it is the same pair the muxer | ||
| 268 | + /// counts an export's frames in -- and this is that pair divided by that | ||
| 269 | + /// pair, reduced. A rate no timescale can name is an `Err` in that | ||
| 270 | + /// function's own words rather than a silent 1:1 -- `matches_timeline` is | ||
| 271 | + /// where a file carrying one is refused by name, beside the codec. | ||
| 272 | + /// | ||
| 273 | + /// Exactly [`REAL_TIME`](Self::REAL_TIME) when the two agree, which is every | ||
| 274 | + /// timeline that had ever opened in this editor before mixed rates. | ||
| 275 | + pub fn from_fps(source_fps: f64, timeline_fps: f64) -> crate::Result<Self> { | ||
| 276 | + let (src_scale, src_ticks) = crate::mux::frame_timing(source_fps)?; | ||
| 277 | + let (tl_scale, tl_ticks) = crate::mux::frame_timing(timeline_fps)?; | ||
| 278 | + // fps is scale/ticks, so the ratio is (src_scale/src_ticks) / (tl_scale/tl_ticks). | ||
| 279 | + let num = u64::from(src_scale) * u64::from(tl_ticks); | ||
| 280 | + let den = u64::from(src_ticks) * u64::from(tl_scale); | ||
| 281 | + let g = gcd(num, den); | ||
| 282 | + let (mut num, mut den) = (num / g, den / g); | ||
| 283 | + // A ratio no pair of real frame rates produces, but the fields are `u32` | ||
| 284 | + // so that every multiplication below fits a `u64` at any frame count. | ||
| 285 | + while num > u64::from(u32::MAX) || den > u64::from(u32::MAX) { | ||
| 286 | + (num, den) = (num.div_ceil(2), den.div_ceil(2)); | ||
| 287 | + } | ||
| 288 | + Ok(Self { | ||
| 289 | + source: num.max(1) as u32, | ||
| 290 | + timeline: den.max(1) as u32, | ||
| 291 | + }) | ||
| 292 | + } | ||
| 293 | + | ||
| 294 | + pub fn is_real_time(self) -> bool { | ||
| 295 | + self.source == self.timeline | ||
| 296 | + } | ||
| 297 | + | ||
| 298 | + /// As a multiplier of the timeline's rate: what a *file's* own frame rate | ||
| 299 | + /// is, given the timeline's, for a library row that names it. | ||
| 300 | + pub fn as_f64(self) -> f64 { | ||
| 301 | + f64::from(self.source) / f64::from(self.timeline) | ||
| 302 | + } | ||
| 303 | + | ||
| 304 | + /// Which frame of the file the `frame`th timeline-rate frame of it is: | ||
| 305 | + /// floored, [`Speed::source_at`]'s half of the pair. | ||
| 306 | + pub fn source_at(self, frame: u32) -> u32 { | ||
| 307 | + (u64::from(frame) * u64::from(self.source) / u64::from(self.timeline)) | ||
| 308 | + .min(u64::from(u32::MAX)) as u32 | ||
| 309 | + } | ||
| 310 | + | ||
| 311 | + /// Its inverse, ceiled ([`Speed::timeline_at`]'s half): the first | ||
| 312 | + /// timeline-rate frame that shows source frame `source_frame` -- which is | ||
| 313 | + /// the stamp playback puts on a decoded picture, and, applied to a file's | ||
| 314 | + /// frame *count*, how long that file is in timeline frames. | ||
| 315 | + pub fn timeline_at(self, source_frame: u32) -> u32 { | ||
| 316 | + (u64::from(source_frame) * u64::from(self.timeline)) | ||
| 317 | + .div_ceil(u64::from(self.source)) | ||
| 318 | + .min(u64::from(u32::MAX)) as u32 | ||
| 319 | + } | ||
| 320 | +} | ||
| 321 | + | ||
| 322 | +/// Greatest common divisor, for reducing a [`Rate`] to the numbers that fit its | ||
| 323 | +/// fields. `a` for `gcd(a, 0)`, and never zero: something divides by it. | ||
| 324 | +fn gcd(a: u64, b: u64) -> u64 { | ||
| 325 | + match b { | ||
| 326 | + 0 => a.max(1), | ||
| 327 | + b => gcd(b, a % b), | ||
| 328 | + } | ||
| 329 | +} | ||
| 330 | + | ||
| 224 | /// A half-open `[in_frame, out_frame)` range of frames of source | 331 | /// A half-open `[in_frame, out_frame)` range of frames of source |
| 225 | /// [`source`](Clip::source), placed at timeline frame [`start`](Clip::start). | 332 | /// [`source`](Clip::source), placed at timeline frame [`start`](Clip::start). |
| 226 | /// Never empty. | 333 | /// Never empty. |
| 334 | +/// | ||
| 335 | +/// Counted at the **timeline's** frame rate, not the file's: a source shot at | ||
| 336 | +/// another rate is converted at the decoder's door ([`Rate`]), so every edit | ||
| 337 | +/// here is frames of one clock. | ||
| 227 | #[derive(Clone, Copy, PartialEq, Eq, Debug)] | 338 | #[derive(Clone, Copy, PartialEq, Eq, Debug)] |
| 228 | pub struct Clip { | 339 | pub struct Clip { |
| 229 | /// Timeline frame the clip's first frame is shown at. Meaningless on a | 340 | /// Timeline frame the clip's first frame is shown at. Meaningless on a |
| @@ -4557,6 +4668,87 @@ mod tests { | |||
| 4557 | assert_eq!(Speed::from_permille(2500).to_string(), "2.50x"); | 4668 | assert_eq!(Speed::from_permille(2500).to_string(), "2.50x"); |
| 4558 | } | 4669 | } |
| 4559 | 4670 | ||
| 4671 | + /// [`Rate`] is [`Speed`]'s pair again, over the *file's* rate: the frame an | ||
| 4672 | + /// export encodes at a timeline frame is the one playback is holding there, | ||
| 4673 | + /// a file is as long in timeline frames as the seconds it lasts, and the two | ||
| 4674 | + /// compose so a speeded clip at another rate is exactly both. | ||
| 4675 | + #[test] | ||
| 4676 | + fn rate_composes_with_speed() { | ||
| 4677 | + // 23.976 into 30 (the ratio that does not terminate), 30 into 23.976, | ||
| 4678 | + // 60 into 30, 25 into 30 -- and the timeline's own rate, which must be | ||
| 4679 | + // the identity map or a single-rate project would move. | ||
| 4680 | + for (source_fps, timeline_fps) in [ | ||
| 4681 | + (24000. / 1001., 30.), | ||
| 4682 | + (30., 24000. / 1001.), | ||
| 4683 | + (60., 30.), | ||
| 4684 | + (25., 30.), | ||
| 4685 | + (30., 30.), | ||
| 4686 | + ] { | ||
| 4687 | + let rate = Rate::from_fps(source_fps, timeline_fps).expect("a nameable rate"); | ||
| 4688 | + for n in 0..2000u32 { | ||
| 4689 | + let source = rate.source_at(n); | ||
| 4690 | + // The stamp is the *first* timeline-rate frame that shows it, so | ||
| 4691 | + // the picture on screen at `n` is the picture encoded at `n`. | ||
| 4692 | + let held = (0..=source + 4) | ||
| 4693 | + .filter(|&s| rate.timeline_at(s) <= n) | ||
| 4694 | + .next_back(); | ||
| 4695 | + assert_eq!(held, Some(source), "{source_fps} on {timeline_fps} at {n}"); | ||
| 4696 | + } | ||
| 4697 | + // A file of `count` frames is `timeline_at(count)` frames long here, | ||
| 4698 | + // and its last one still reads a frame the file has. | ||
| 4699 | + for count in 1..500u32 { | ||
| 4700 | + let frames = rate.timeline_at(count); | ||
| 4701 | + assert!(frames >= 1, "a file is never zero frames long"); | ||
| 4702 | + assert!( | ||
| 4703 | + rate.source_at(frames - 1) < count, | ||
| 4704 | + "{source_fps} on {timeline_fps}: {count} frames reads past the file" | ||
| 4705 | + ); | ||
| 4706 | + } | ||
| 4707 | + // No drift: the mapping is one exact division of the *rate itself*, | ||
| 4708 | + // not an accumulation and not a rounded rate, so an hour in is as | ||
| 4709 | + // true as the first second. (Held to the real ratio of the two rates | ||
| 4710 | + // the caller asked for -- `as_f64` would be true of a wrong rate.) | ||
| 4711 | + for n in [1u32, 100, 10_000, 500_000, 3_000_000] { | ||
| 4712 | + let want = f64::from(n) * source_fps / timeline_fps; | ||
| 4713 | + assert!( | ||
| 4714 | + (f64::from(rate.source_at(n)) - want).abs() < 1., | ||
| 4715 | + "{source_fps} on {timeline_fps}: frame {n} drifted" | ||
| 4716 | + ); | ||
| 4717 | + } | ||
| 4718 | + } | ||
| 4719 | + // The timeline's own rate is the identity, whichever way it is written. | ||
| 4720 | + assert!(Rate::from_fps(30., 30.).expect("30 over 30").is_real_time()); | ||
| 4721 | + assert!( | ||
| 4722 | + Rate::from_fps(30.0004, 30.) | ||
| 4723 | + .expect("30.0004 over 30") | ||
| 4724 | + .is_real_time(), | ||
| 4725 | + "a rate is named by the muxer's timescales, and 30.0004 is 30030/1001" | ||
| 4726 | + ); | ||
| 4727 | + // ...and a rate no timescale can name is an `Err`, not a silent 1:1: the | ||
| 4728 | + // one thing `matches_timeline` refuses a file for now that the rate gate | ||
| 4729 | + // is gone. | ||
| 4730 | + assert!(Rate::from_fps(0., 30.).is_err(), "not a rate at all"); | ||
| 4731 | + assert!(Rate::from_fps(30., f64::NAN).is_err()); | ||
| 4732 | + for n in 0..1000 { | ||
| 4733 | + assert_eq!(Rate::REAL_TIME.source_at(n), n); | ||
| 4734 | + assert_eq!(Rate::REAL_TIME.timeline_at(n), n); | ||
| 4735 | + } | ||
| 4736 | + // ...and the composition, in the order the decoder's door applies it: | ||
| 4737 | + // the speed picks the clip's (timeline-rate) frame, the rate picks the | ||
| 4738 | + // file's. A 2x clip of a 23.976 fps file on a 30 fps timeline reads two | ||
| 4739 | + // timeline frames per frame shown, each of them exactly 800/1001 of a | ||
| 4740 | + // file frame. | ||
| 4741 | + let rate = Rate::from_fps(24000. / 1001., 30.).expect("23.976 over 30"); | ||
| 4742 | + let speed = Speed::from_permille(2000); | ||
| 4743 | + for d in 0..100u32 { | ||
| 4744 | + assert_eq!( | ||
| 4745 | + rate.source_at(speed.source_at(d)), | ||
| 4746 | + (u64::from(d) * 2 * 800 / 1001) as u32, | ||
| 4747 | + "2x of a 23.976 fps file at timeline frame {d}" | ||
| 4748 | + ); | ||
| 4749 | + } | ||
| 4750 | + } | ||
| 4751 | + | ||
| 4560 | /// The mapping a speed changes, and the one it does not: a 2x clip reads two | 4752 | /// The mapping a speed changes, and the one it does not: a 2x clip reads two |
| 4561 | /// source frames per timeline frame and still starts at its own in-point, | 4753 | /// source frames per timeline frame and still starts at its own in-point, |
| 4562 | /// and a half-speed one shows every source frame twice. | 4754 | /// and a half-speed one shows every source frame twice. |
crates/engine/tests/audio_files.rsmodified+9 -8
| @@ -386,20 +386,21 @@ fn a_video_joins_a_timeline_a_song_started() { | |||
| 386 | import_and_place(&mut session, &asset("test_av.mp4")); | 386 | import_and_place(&mut session, &asset("test_av.mp4")); |
| 387 | assert_eq!(session.lane_clips(Lane::V1).len(), 1, "a picture at last"); | 387 | assert_eq!(session.lane_clips(Lane::V1).len(), 1, "a picture at last"); |
| 388 | assert_eq!(session.lane_clips(Lane::A1).len(), 2); | 388 | assert_eq!(session.lane_clips(Lane::A1).len(), 2); |
| 389 | - // And a file at another rate is refused in the timeline's own words rather | 389 | + // A sample rate the device cannot have two of is still refused in the |
| 390 | - // than silently retiming the song already on the lane -- the sample rate at | 390 | + // timeline's own words... |
| 391 | - // one door, the *frame* rate at the other: the canvas a song scaffolds has | ||
| 392 | - // a frame rate of its own (30 fps), and a 25 fps picture cannot join it. | ||
| 393 | let e = refusal(session.import(&asset("test_tone_48k.wav"))); | 391 | let e = refusal(session.import(&asset("test_tone_48k.wav"))); |
| 394 | assert_eq!( | 392 | assert_eq!( |
| 395 | e, | 393 | e, |
| 396 | "audio 48000 Hz 2 ch does not match the timeline's 44100 Hz 2 ch" | 394 | "audio 48000 Hz 2 ch does not match the timeline's 44100 Hz 2 ch" |
| 397 | ); | 395 | ); |
| 398 | - assert_eq!( | ||
| 399 | - refusal(session.import(&asset("test_25fps.mp4"))), | ||
| 400 | - "25.000 fps does not match the timeline's 30.000 fps" | ||
| 401 | - ); | ||
| 402 | assert_eq!(session.sources().len(), 2, "a refusal left a library row"); | 396 | assert_eq!(session.sources().len(), 2, "a refusal left a library row"); |
| 397 | + // ...but a *frame* rate of its own is not a refusal: the canvas a song | ||
| 398 | + // scaffolds runs at 30 fps and a 25 fps picture joins it at the length it | ||
| 399 | + // lasts in seconds (50 frames of file, 60 of timeline). | ||
| 400 | + session | ||
| 401 | + .import(&asset("test_25fps.mp4")) | ||
| 402 | + .expect("25 fps joins the 30 fps canvas a song scaffolded"); | ||
| 403 | + assert_eq!(session.file_frames(&asset("test_25fps.mp4")), 60); | ||
| 403 | } | 404 | } |
| 404 | 405 | ||
| 405 | /// Blocks until the export settles, whichever way it settled. | 406 | /// Blocks until the export settles, whichever way it settled. |
crates/engine/tests/mixed_fps.rsadded+419 -0
| @@ -0,0 +1,419 @@ | |||
| 1 | +//! Clips shot at other frame rates on one timeline: what a 25 fps and a 23.976 | ||
| 2 | +//! fps file do on the 30 fps timeline `test_av.mp4` scaffolds. | ||
| 3 | +//! | ||
| 4 | +//! Everything goes through the front door -- `import`, `place_stream_at`, | ||
| 5 | +//! `seek`, `export_to_with`, `open_project` -- because the whole claim is that a | ||
| 6 | +//! *user* can put two rates on one timeline and watch both at the speed they | ||
| 7 | +//! were shot at. `project.rs`'s own `rate_composes_with_speed` owns the | ||
| 8 | +//! arithmetic; what is measured here is that the pictures and the file agree | ||
| 9 | +//! with it. | ||
| 10 | +//! | ||
| 11 | +//! ```text | ||
| 12 | +//! cargo test -p engine --test mixed_fps | ||
| 13 | +//! ``` | ||
| 14 | + | ||
| 15 | +use std::path::{Path, PathBuf}; | ||
| 16 | +use std::thread::sleep; | ||
| 17 | +use std::time::{Duration, Instant}; | ||
| 18 | + | ||
| 19 | +use engine::export::{ExportSettings, Format}; | ||
| 20 | +use engine::project::{Edge, Lane, Rate, Speed}; | ||
| 21 | +use engine::{DecodeSession, Frame, PlaybackSession}; | ||
| 22 | + | ||
| 23 | +/// The timeline's rate, which `test_av.mp4` (30 fps, 5 s) defines. | ||
| 24 | +const FPS: f64 = 30.0; | ||
| 25 | + | ||
| 26 | +fn asset(name: &str) -> PathBuf { | ||
| 27 | + PathBuf::from(env!("CARGO_MANIFEST_DIR")) | ||
| 28 | + .join("../../assets") | ||
| 29 | + .join(name) | ||
| 30 | +} | ||
| 31 | + | ||
| 32 | +/// Silent, for `tests/playback.rs`'s reason: the suite plays real files. | ||
| 33 | +fn open(path: impl AsRef<Path>) -> PlaybackSession { | ||
| 34 | + let session = PlaybackSession::open(path).expect("open"); | ||
| 35 | + session.set_gain(0.0); | ||
| 36 | + session | ||
| 37 | +} | ||
| 38 | + | ||
| 39 | +fn next_frame(session: &mut PlaybackSession, what: &str) -> Frame { | ||
| 40 | + let deadline = Instant::now() + Duration::from_secs(10); | ||
| 41 | + loop { | ||
| 42 | + if let Some(frame) = session.try_frame() { | ||
| 43 | + return frame; | ||
| 44 | + } | ||
| 45 | + assert!(Instant::now() < deadline, "no frame after {what}"); | ||
| 46 | + sleep(Duration::from_millis(4)); | ||
| 47 | + } | ||
| 48 | +} | ||
| 49 | + | ||
| 50 | +/// One frame of a file, decoded straight from it: the picture a mapping is | ||
| 51 | +/// checked against, in the file's *own* numbering. | ||
| 52 | +fn source_frame(path: &Path, index: u32) -> Vec<u8> { | ||
| 53 | + let (_, rx, _cancel) = DecodeSession::open_range(path, index, index + 1).expect("open_range"); | ||
| 54 | + let frame = rx | ||
| 55 | + .recv_timeout(Duration::from_secs(10)) | ||
| 56 | + .expect("reference frame"); | ||
| 57 | + assert_eq!(frame.index, index, "open_range starts where it is told"); | ||
| 58 | + frame.bgra | ||
| 59 | +} | ||
| 60 | + | ||
| 61 | +/// Imports `path` and drags it onto the end of the timeline, the way a library | ||
| 62 | +/// row reaches a lane. | ||
| 63 | +fn import_and_place(session: &mut PlaybackSession, path: &Path) { | ||
| 64 | + session.import(path).expect("the file joins this timeline"); | ||
| 65 | + let end = session.timeline_duration(); | ||
| 66 | + assert!( | ||
| 67 | + session | ||
| 68 | + .place_stream_at(end, path, 0, None) | ||
| 69 | + .expect("a file just imported is on this timeline"), | ||
| 70 | + "the drag onto the end of the timeline" | ||
| 71 | + ); | ||
| 72 | +} | ||
| 73 | + | ||
| 74 | +fn wait(handle: &engine::ExportHandle) -> engine::Result<()> { | ||
| 75 | + let deadline = Instant::now() + Duration::from_secs(180); | ||
| 76 | + while !handle.is_finished() { | ||
| 77 | + assert!(Instant::now() < deadline, "export did not finish"); | ||
| 78 | + sleep(Duration::from_millis(20)); | ||
| 79 | + } | ||
| 80 | + handle.result().expect("a finished export has an outcome") | ||
| 81 | +} | ||
| 82 | + | ||
| 83 | +/// How different two pictures are, sampled: a re-encode moves every pixel a | ||
| 84 | +/// little and a *different* picture of `testsrc2` moves them a lot, so the two | ||
| 85 | +/// are never close to the threshold below. | ||
| 86 | +fn difference(a: &[u8], b: &[u8]) -> f64 { | ||
| 87 | + assert_eq!(a.len(), b.len(), "two pictures of one size"); | ||
| 88 | + let (mut sum, mut n) = (0f64, 0u32); | ||
| 89 | + for i in (0..a.len()).step_by(997) { | ||
| 90 | + sum += f64::from(a[i].abs_diff(b[i])); | ||
| 91 | + n += 1; | ||
| 92 | + } | ||
| 93 | + sum / f64::from(n.max(1)) | ||
| 94 | +} | ||
| 95 | + | ||
| 96 | +/// A file's length is the seconds it lasts, in the timeline's frames -- not the | ||
| 97 | +/// frames it holds. That is the whole of what placing another rate means: 50 | ||
| 98 | +/// frames of 25 fps and 48 of 23.976 fps are both two seconds, and two seconds | ||
| 99 | +/// of a 30 fps timeline is 60 frames. | ||
| 100 | +#[test] | ||
| 101 | +fn a_file_at_another_rate_is_placed_for_the_seconds_it_lasts() { | ||
| 102 | + let mut session = open(asset("test_av.mp4")); | ||
| 103 | + assert_eq!(session.file_frames(&asset("test_av.mp4")), 150, "5 s at 30"); | ||
| 104 | + | ||
| 105 | + let pal = asset("test_25fps.mp4"); | ||
| 106 | + session | ||
| 107 | + .import(&pal) | ||
| 108 | + .expect("25 fps joins a 30 fps timeline"); | ||
| 109 | + assert_eq!(session.file_frames(&pal), 60, "50 frames at 25 fps is 2 s"); | ||
| 110 | + | ||
| 111 | + // 24000/1001: 48 frames is 2.002 s, which is 60.06 frames of 30 fps -- | ||
| 112 | + // rounded *up*, so the last picture is still reachable by a trim. | ||
| 113 | + let ntsc = asset("test_23976fps.mp4"); | ||
| 114 | + session.import(&ntsc).expect("23.976 joins it too"); | ||
| 115 | + assert_eq!(session.file_frames(&ntsc), 61); | ||
| 116 | + | ||
| 117 | + // ...and placed, both are as long on the timeline as they are in the ear. | ||
| 118 | + let end = session.timeline_duration(); | ||
| 119 | + session | ||
| 120 | + .place_stream_at(end, &pal, 0, None) | ||
| 121 | + .expect("the drag"); | ||
| 122 | + assert!( | ||
| 123 | + (session.timeline_duration() - (5.0 + 2.0)).abs() < 1e-9, | ||
| 124 | + "a 2 s clip made the timeline {} s", | ||
| 125 | + session.timeline_duration() | ||
| 126 | + ); | ||
| 127 | + let end = session.timeline_duration(); | ||
| 128 | + session | ||
| 129 | + .place_stream_at(end, &ntsc, 0, None) | ||
| 130 | + .expect("the drag"); | ||
| 131 | + assert!( | ||
| 132 | + (session.timeline_duration() - (5.0 + 2.0 + 61. / FPS)).abs() < 1e-9, | ||
| 133 | + "{} s", | ||
| 134 | + session.timeline_duration() | ||
| 135 | + ); | ||
| 136 | + // ...and the sound that came down with each take is the same length as its | ||
| 137 | + // picture: a placed take is one linked group, so a rate that stretched only | ||
| 138 | + // the picture would slide the two apart on the very first drag. | ||
| 139 | + let (video, audio) = (session.lane_clips(Lane::V1), session.lane_clips(Lane::A1)); | ||
| 140 | + assert_eq!(video.len(), 3, "the 30 fps take and the two others"); | ||
| 141 | + assert_eq!(audio.len(), video.len(), "one audio clip per take"); | ||
| 142 | + for (v, a) in video.iter().zip(audio) { | ||
| 143 | + assert_eq!((v.start, v.len()), (a.start, a.len()), "{v:?} vs {a:?}"); | ||
| 144 | + } | ||
| 145 | +} | ||
| 146 | + | ||
| 147 | +/// The NTSC ratio, which the 23.976 fps fixture is shot at: 24000/1001 over 30 | ||
| 148 | +/// is exactly 800/1001, and it stays exact however far the timeline runs. A rate | ||
| 149 | +/// rounded to a float -- or to milli-fps -- would leave a fraction of a frame | ||
| 150 | +/// per clip to pile up into a visible drift over an hour, which is why the | ||
| 151 | +/// mapping is built out of the muxer's own timescales and not a division. | ||
| 152 | +#[test] | ||
| 153 | +fn a_23_976_rate_is_exact_and_never_drifts() { | ||
| 154 | + let ntsc = Rate::from_fps(24_000.0 / 1001.0, FPS).expect("23.976 over 30"); | ||
| 155 | + assert!( | ||
| 156 | + (ntsc.as_f64() - 800.0 / 1001.0).abs() < 1e-15, | ||
| 157 | + "{}", | ||
| 158 | + ntsc.as_f64() | ||
| 159 | + ); | ||
| 160 | + // Independent integer arithmetic, out to an hour of source and past it: 800 | ||
| 161 | + // source frames per 1001 timeline ones, and a file's length is that ceiled | ||
| 162 | + // (the last picture must still be reachable by a trim). | ||
| 163 | + for source in [1u64, 2, 24, 1000, 86_486, 500_000, 1_000_000] { | ||
| 164 | + assert_eq!( | ||
| 165 | + u64::from(ntsc.timeline_at(source as u32)), | ||
| 166 | + (source * 1001).div_ceil(800), | ||
| 167 | + "{source} source frames" | ||
| 168 | + ); | ||
| 169 | + } | ||
| 170 | + // ...and the two directions stay each other's inverse at every one of them: | ||
| 171 | + // the frame an export writes at timeline frame `d` is the frame playback is | ||
| 172 | + // holding there, which is what `timeline_at`'s ceil buys. | ||
| 173 | + for d in [0u32, 1, 2, 3, 1000, 100_000, 1_000_000] { | ||
| 174 | + let source = ntsc.source_at(d); | ||
| 175 | + assert!(ntsc.timeline_at(source) <= d, "frame {d} is not yet due"); | ||
| 176 | + assert!( | ||
| 177 | + ntsc.timeline_at(source + 1) > d, | ||
| 178 | + "the next frame is due too early at {d}" | ||
| 179 | + ); | ||
| 180 | + } | ||
| 181 | + // A timeline's own rate conforms by nothing at all, exactly -- whichever of | ||
| 182 | + // the two rates it is written at. | ||
| 183 | + assert!(Rate::from_fps(FPS, FPS).expect("30 over 30").is_real_time()); | ||
| 184 | + assert!( | ||
| 185 | + Rate::from_fps(24_000.0 / 1001.0, 24_000.0 / 1001.0) | ||
| 186 | + .expect("ntsc over ntsc") | ||
| 187 | + .is_real_time() | ||
| 188 | + ); | ||
| 189 | + // A rate no timescale can name is refused rather than read 1:1 in silence: | ||
| 190 | + // the one thing `matches_timeline` still turns a file away for. | ||
| 191 | + assert!(Rate::from_fps(0.0, FPS).is_err(), "not a rate at all"); | ||
| 192 | +} | ||
| 193 | + | ||
| 194 | +/// The picture on screen at a timeline frame is the picture the *file* holds | ||
| 195 | +/// there: frame `floor(offset * 25/30)` of a 25 fps clip, which is what playing | ||
| 196 | +/// at the speed it was shot at means, frame for frame. | ||
| 197 | +#[test] | ||
| 198 | +fn playback_shows_the_frame_the_file_holds_there() { | ||
| 199 | + let pal = asset("test_25fps.mp4"); | ||
| 200 | + let mut session = open(asset("test_av.mp4")); | ||
| 201 | + import_and_place(&mut session, &pal); | ||
| 202 | + session.pause(); | ||
| 203 | + // The clip starts at timeline frame 150 (5 s) and runs 60 frames. | ||
| 204 | + let start = 150u32; | ||
| 205 | + for offset in [0u32, 1, 5, 6, 29, 30, 47, 59] { | ||
| 206 | + let at = start + offset; | ||
| 207 | + session.seek(f64::from(at) / FPS); | ||
| 208 | + let landed = next_frame(&mut session, "a seek into the 25 fps clip"); | ||
| 209 | + assert_eq!(landed.index, at, "a seek lands on the frame it asked for"); | ||
| 210 | + let want = (u64::from(offset) * 25_000 / 30_000) as u32; | ||
| 211 | + assert!( | ||
| 212 | + landed.bgra == source_frame(&pal, want), | ||
| 213 | + "timeline frame {at} (offset {offset}) is not source frame {want}" | ||
| 214 | + ); | ||
| 215 | + } | ||
| 216 | + // Past the last picture the file holds, the clip is still on the timeline: | ||
| 217 | + // its last frame is shown, not black and not a panic. | ||
| 218 | + session.seek(f64::from(start + 59) / FPS); | ||
| 219 | + let last = next_frame(&mut session, "the last frame of the clip"); | ||
| 220 | + assert!(last.bgra == source_frame(&pal, 49), "source frame 49 last"); | ||
| 221 | + // ...and the frame in front of it is the 30 fps take, frame for frame: a | ||
| 222 | + // rate belongs to the source that has one, so the clip beside it is read | ||
| 223 | + // exactly as it was before any of this existed. | ||
| 224 | + let av = asset("test_av.mp4"); | ||
| 225 | + session.seek(f64::from(start - 1) / FPS); | ||
| 226 | + let before = next_frame(&mut session, "the last frame of the 30 fps take"); | ||
| 227 | + assert_eq!(before.index, start - 1); | ||
| 228 | + assert!( | ||
| 229 | + before.bgra == source_frame(&av, start - 1), | ||
| 230 | + "the 30 fps clip is still frame for frame" | ||
| 231 | + ); | ||
| 232 | +} | ||
| 233 | + | ||
| 234 | +/// A trim of a clip at another rate is dragged in *timeline* frames and commits | ||
| 235 | +/// the source range those frames are worth -- so the box is exactly the room it | ||
| 236 | +/// was dragged to, and the picture at its new edge is the file's own frame | ||
| 237 | +/// there. | ||
| 238 | +#[test] | ||
| 239 | +fn a_clip_at_another_rate_trims_to_the_room_it_was_dragged_to() { | ||
| 240 | + let pal = asset("test_25fps.mp4"); | ||
| 241 | + let mut session = open(asset("test_av.mp4")); | ||
| 242 | + import_and_place(&mut session, &pal); | ||
| 243 | + session.pause(); | ||
| 244 | + let start = 150u32; | ||
| 245 | + // Drag its tail back to 30 timeline frames of room: one second, which at 25 | ||
| 246 | + // fps is the file's first 25 pictures. | ||
| 247 | + assert!( | ||
| 248 | + session.trim_clip(Lane::V1, 1, Edge::End, start + 30), | ||
| 249 | + "trim the tail of the 25 fps clip" | ||
| 250 | + ); | ||
| 251 | + let clip = session.lane_clips(Lane::V1)[1]; | ||
| 252 | + assert_eq!((clip.start, clip.len()), (start, 30), "{clip:?}"); | ||
| 253 | + session.seek(f64::from(start + 29) / FPS); | ||
| 254 | + let last = next_frame(&mut session, "the trimmed tail"); | ||
| 255 | + assert!( | ||
| 256 | + last.bgra == source_frame(&pal, 24), | ||
| 257 | + "one second of a 25 fps file ends on its frame 24" | ||
| 258 | + ); | ||
| 259 | + // ...and its head, dragged forward into source it keeps: 6 timeline frames | ||
| 260 | + // in is 5 source frames in, and the tail did not move. | ||
| 261 | + assert!(session.trim_clip(Lane::V1, 1, Edge::Start, start + 6)); | ||
| 262 | + let clip = session.lane_clips(Lane::V1)[1]; | ||
| 263 | + assert_eq!((clip.start, clip.len()), (start + 6, 24), "{clip:?}"); | ||
| 264 | + session.seek(f64::from(start + 6) / FPS); | ||
| 265 | + let head = next_frame(&mut session, "the trimmed head"); | ||
| 266 | + assert!( | ||
| 267 | + head.bgra == source_frame(&pal, 5), | ||
| 268 | + "6 frames of a 30 fps timeline is 5 frames of a 25 fps file" | ||
| 269 | + ); | ||
| 270 | +} | ||
| 271 | + | ||
| 272 | +/// A speed and a frame rate compose: a 2x 25 fps clip on a 30 fps timeline is | ||
| 273 | +/// half as many timeline frames and reads twice as far into the file for each | ||
| 274 | +/// of them. | ||
| 275 | +#[test] | ||
| 276 | +fn a_speeded_clip_at_another_rate_is_exactly_both() { | ||
| 277 | + let pal = asset("test_25fps.mp4"); | ||
| 278 | + let mut session = open(asset("test_av.mp4")); | ||
| 279 | + import_and_place(&mut session, &pal); | ||
| 280 | + session | ||
| 281 | + .set_speed(Lane::V1, 1, Speed::from_permille(2000)) | ||
| 282 | + .expect("nothing is in the way of a clip that got shorter"); | ||
| 283 | + session.pause(); | ||
| 284 | + let start = 150u32; | ||
| 285 | + assert!( | ||
| 286 | + (session.timeline_duration() - (5.0 + 1.0)).abs() < 1e-9, | ||
| 287 | + "2 s at 2x is 1 s: {}", | ||
| 288 | + session.timeline_duration() | ||
| 289 | + ); | ||
| 290 | + for offset in [0u32, 3, 14, 29] { | ||
| 291 | + let at = start + offset; | ||
| 292 | + session.seek(f64::from(at) / FPS); | ||
| 293 | + let landed = next_frame(&mut session, "a seek into the speeded clip"); | ||
| 294 | + assert_eq!(landed.index, at); | ||
| 295 | + // The speed picks the clip's (timeline-rate) frame, the rate picks the | ||
| 296 | + // file's -- in that order, which is the order the decoder's door | ||
| 297 | + // applies them. | ||
| 298 | + let want = (u64::from(offset) * 2 * 25_000 / 30_000) as u32; | ||
| 299 | + assert!( | ||
| 300 | + landed.bgra == source_frame(&pal, want), | ||
| 301 | + "2x at offset {offset} is not source frame {want}" | ||
| 302 | + ); | ||
| 303 | + } | ||
| 304 | +} | ||
| 305 | + | ||
| 306 | +/// A saved project reloads at the same lengths: `open_project` recomputes every | ||
| 307 | +/// source's rate from the file, so a mixed-rate timeline is not one that only | ||
| 308 | +/// the session that built it could hold. | ||
| 309 | +#[test] | ||
| 310 | +fn a_mixed_rate_project_reloads_unchanged() { | ||
| 311 | + let pal = asset("test_25fps.mp4"); | ||
| 312 | + let mut session = open(asset("test_av.mp4")); | ||
| 313 | + import_and_place(&mut session, &pal); | ||
| 314 | + let duration = session.timeline_duration(); | ||
| 315 | + let spans = session.clip_spans(); | ||
| 316 | + let path = std::env::temp_dir().join(format!("edith-mixed-{}.edith", std::process::id())); | ||
| 317 | + session.save_project(&path).expect("save"); | ||
| 318 | + | ||
| 319 | + let reloaded = PlaybackSession::open_project(&path).expect("a mixed-rate project reopens"); | ||
| 320 | + assert_eq!(reloaded.clip_spans(), spans, "the same clips, in seconds"); | ||
| 321 | + assert!((reloaded.timeline_duration() - duration).abs() < 1e-9); | ||
| 322 | + assert_eq!(reloaded.file_frames(&pal), 60, "the length was recomputed"); | ||
| 323 | + std::fs::remove_file(&path).ok(); | ||
| 324 | +} | ||
| 325 | + | ||
| 326 | +/// 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, | ||
| 328 | +/// not 30 of them and not 25 held to the end. | ||
| 329 | +#[test] | ||
| 330 | +fn an_export_of_two_rates_runs_at_the_speed_it_was_shot() { | ||
| 331 | + let pal = asset("test_25fps.mp4"); | ||
| 332 | + let mut session = open(asset("test_av.mp4")); | ||
| 333 | + // A short head of the 30 fps take, then the whole of the 25 fps one -- | ||
| 334 | + // enough of each to be a mixed timeline, short enough to encode in a test. | ||
| 335 | + // The sound comes with it: a placed take is one linked group. | ||
| 336 | + assert!( | ||
| 337 | + session.trim_clip(Lane::V1, 0, Edge::End, 15), | ||
| 338 | + "trim the 30 fps take to half a second" | ||
| 339 | + ); | ||
| 340 | + import_and_place(&mut session, &pal); | ||
| 341 | + assert!( | ||
| 342 | + session.trim_clip(Lane::V1, 1, Edge::End, 45), | ||
| 343 | + "one second of the 25 fps clip" | ||
| 344 | + ); | ||
| 345 | + let total = (session.timeline_duration() * FPS).round() as u32; | ||
| 346 | + assert_eq!(total, 45, "15 frames of 30 fps and 30 of the 25 fps clip"); | ||
| 347 | + | ||
| 348 | + let out = std::env::temp_dir().join(format!("edith-mixed-{}.mp4", std::process::id())); | ||
| 349 | + wait(&session.export_to_with( | ||
| 350 | + &out, | ||
| 351 | + &ExportSettings { | ||
| 352 | + format: Format::Mp4, | ||
| 353 | + ..ExportSettings::default() | ||
| 354 | + }, | ||
| 355 | + )) | ||
| 356 | + .expect("the export"); | ||
| 357 | + | ||
| 358 | + // Duration first: the file is as long as the timeline, so the mixed rates | ||
| 359 | + // did not stretch or shorten it. | ||
| 360 | + let (meta, rx, _cancel) = DecodeSession::open_range(&out, 0, u32::MAX).expect("reopen"); | ||
| 361 | + assert!( | ||
| 362 | + (meta.frame_rate - FPS).abs() < 0.01, | ||
| 363 | + "the export runs at the timeline's rate: {}", | ||
| 364 | + meta.frame_rate | ||
| 365 | + ); | ||
| 366 | + assert_eq!( | ||
| 367 | + meta.frame_count, total, | ||
| 368 | + "the export is the timeline's length" | ||
| 369 | + ); | ||
| 370 | + let written: Vec<Vec<u8>> = rx.into_iter().map(|frame| frame.bgra).collect(); | ||
| 371 | + assert_eq!(written.len() as u32, total, "every frame came back"); | ||
| 372 | + | ||
| 373 | + // ...and motion: inside the 25 fps clip, 30 exported frames show 25 | ||
| 374 | + // pictures, so 5 of them are a picture held from the frame before. A clip | ||
| 375 | + // played at the wrong rate would hold none (too fast, and it would run out | ||
| 376 | + // of file) or hold half of them (too slow). | ||
| 377 | + let held = (16..total as usize) | ||
| 378 | + .filter(|&i| difference(&written[i - 1], &written[i]) < 2.0) | ||
| 379 | + .count(); | ||
| 380 | + assert_eq!( | ||
| 381 | + held, 5, | ||
| 382 | + "30 timeline frames of a 25 fps clip hold 5 pictures over" | ||
| 383 | + ); | ||
| 384 | + | ||
| 385 | + // ...and *which* picture each of those frames is: the very one playback | ||
| 386 | + // holds there, which is the whole reason the two conversions are one | ||
| 387 | + // floor/ceil pair. Nearer its own source frame than either neighbour rather | ||
| 388 | + // than equal to it -- the export is re-encoded, so no pixel survives whole. | ||
| 389 | + for offset in [0u32, 1, 6, 12, 24, 29] { | ||
| 390 | + let want = (u64::from(offset) * 25_000 / 30_000) as u32; | ||
| 391 | + let mine = difference(&written[(15 + offset) as usize], &source_frame(&pal, want)); | ||
| 392 | + for other in [want.saturating_sub(1), want + 1] { | ||
| 393 | + if other == want { | ||
| 394 | + continue; | ||
| 395 | + } | ||
| 396 | + assert!( | ||
| 397 | + mine < difference(&written[(15 + offset) as usize], &source_frame(&pal, other)), | ||
| 398 | + "exported frame {offset} of the 25 fps clip is nearer source \ | ||
| 399 | + frame {other} than its own {want}" | ||
| 400 | + ); | ||
| 401 | + } | ||
| 402 | + } | ||
| 403 | + | ||
| 404 | + // The sound came out as long as the picture, from a *packet copy*: a clip | ||
| 405 | + // counts timeline frames whatever its file was shot at, so the window this | ||
| 406 | + // export trimmed the 25 fps file's AAC to is whole timeline frames and the | ||
| 407 | + // copy is in sync. This is the assertion behind the note in | ||
| 408 | + // `export::copy_audio` that says not to turn a conformed lane into a | ||
| 409 | + // re-encode. | ||
| 410 | + let secs = engine::AudioSession::duration_secs(&out) | ||
| 411 | + .expect("probe the export") | ||
| 412 | + .expect("the export has sound"); | ||
| 413 | + let want = f64::from(total) / FPS; | ||
| 414 | + assert!( | ||
| 415 | + (secs - want).abs() < 0.05, | ||
| 416 | + "sound is {secs} s under {want} s of picture" | ||
| 417 | + ); | ||
| 418 | + std::fs::remove_file(&out).ok(); | ||
| 419 | +} | ||
crates/engine/tests/playback.rsmodified+8 -7
| @@ -813,14 +813,15 @@ fn import_refuses_what_does_not_match() { | |||
| 813 | "a resolution of its own is not a refusal any more: {err}" | 813 | "a resolution of its own is not a refusal any more: {err}" |
| 814 | ); | 814 | ); |
| 815 | 815 | ||
| 816 | - // Same codec, same audio, 25 fps: the one property left, named with both | 816 | + // A frame rate of its own is no longer a refusal either: 25 fps joins a |
| 817 | - // rates. Mixing rates would mean retiming the timeline itself, and there is | 817 | + // 30 fps timeline and is read at `Rate` against it -- see |
| 818 | - // no resampler for that, so the refusal is the honest answer. | 818 | + // `tests/mixed_fps.rs` for what it then plays like. |
| 819 | - let err = session | 819 | + session |
| 820 | .import(&asset("test_25fps.mp4")) | 820 | .import(&asset("test_25fps.mp4")) |
| 821 | - .expect_err("25 fps must not join a 30 fps timeline") | 821 | + .expect("25 fps may join a 30 fps timeline"); |
| 822 | - .to_string(); | 822 | + session |
| 823 | - assert_eq!(err, "25.000 fps does not match the timeline's 30.000 fps"); | 823 | + .remove_source(&asset("test_25fps.mp4"), 0) |
| 824 | + .expect("...and the row it made comes back off"); | ||
| 824 | 825 | ||
| 825 | // Same size and rate, no audio track: the timeline has one. | 826 | // Same size and rate, no audio track: the timeline has one. |
| 826 | let err = session | 827 | let err = session |
scripts/gen_fixtures.shmodified+11 -3
| @@ -161,15 +161,23 @@ enable='between(t,1,1.1)'[v];\ | |||
| 161 | ffmpeg -y -f lavfi -i testsrc2=size=640x360:rate=30:duration=2 \ | 161 | ffmpeg -y -f lavfi -i testsrc2=size=640x360:rate=30:duration=2 \ |
| 162 | -an -c:v libx264 -profile:v baseline -pix_fmt yuv420p assets/test_mismatch.mp4 | 162 | -an -c:v libx264 -profile:v baseline -pix_fmt yuv420p assets/test_mismatch.mp4 |
| 163 | # Frame-rate fixture: test_av.mp4 in every respect a timeline is held to -- same | 163 | # Frame-rate fixture: test_av.mp4 in every respect a timeline is held to -- same |
| 164 | -# codec, same profile, same 44.1k stereo AAC -- except that it runs at 25 fps. | 164 | +# codec, same profile, same 44.1k stereo AAC -- except that it runs at 25 fps, |
| 165 | -# The only thing left for an import to refuse is the rate, which is what makes | 165 | +# so a timeline of 30 fps clips has one at another rate to read through `Rate`. |
| 166 | -# the refusal's wording testable. | ||
| 167 | ffmpeg -y -f lavfi -i testsrc2=size=1280x720:rate=25:duration=2 \ | 166 | ffmpeg -y -f lavfi -i testsrc2=size=1280x720:rate=25:duration=2 \ |
| 168 | -f lavfi -i "sine=frequency=440:duration=2" \ | 167 | -f lavfi -i "sine=frequency=440:duration=2" \ |
| 169 | -f lavfi -i "sine=frequency=880:duration=2" \ | 168 | -f lavfi -i "sine=frequency=880:duration=2" \ |
| 170 | -filter_complex "[1:a][2:a]join=inputs=2:channel_layout=stereo,volume='0.5+0.5*sin(2*PI*t)':eval=frame[a]" \ | 169 | -filter_complex "[1:a][2:a]join=inputs=2:channel_layout=stereo,volume='0.5+0.5*sin(2*PI*t)':eval=frame[a]" \ |
| 171 | -map 0:v -map "[a]" -c:v libx264 -profile:v baseline -pix_fmt yuv420p \ | 170 | -map 0:v -map "[a]" -c:v libx264 -profile:v baseline -pix_fmt yuv420p \ |
| 172 | -c:a aac -b:a 128k assets/test_25fps.mp4 | 171 | -c:a aac -b:a 128k assets/test_25fps.mp4 |
| 172 | +# ...and the same again at 23.976 fps (24000/1001), the rate whose ratio to a | ||
| 173 | +# 30 fps timeline does not terminate: what the frame mapping's rounding is | ||
| 174 | +# actually tested against. | ||
| 175 | +ffmpeg -y -f lavfi -i testsrc2=size=1280x720:rate=24000/1001:duration=2 \ | ||
| 176 | + -f lavfi -i "sine=frequency=440:duration=2" \ | ||
| 177 | + -f lavfi -i "sine=frequency=880:duration=2" \ | ||
| 178 | + -filter_complex "[1:a][2:a]join=inputs=2:channel_layout=stereo,volume='0.5+0.5*sin(2*PI*t)':eval=frame[a]" \ | ||
| 179 | + -map 0:v -map "[a]" -c:v libx264 -profile:v baseline -pix_fmt yuv420p \ | ||
| 180 | + -c:a aac -b:a 128k assets/test_23976fps.mp4 | ||
| 173 | # Standalone audio fixtures: the same 440/880 Hz tone with the 1 Hz pulse the | 181 | # Standalone audio fixtures: the same 440/880 Hz tone with the 1 Hz pulse the |
| 174 | # A/V fixture carries, at test_av.mp4's own 44.1k stereo -- so an imported song | 182 | # A/V fixture carries, at test_av.mp4's own 44.1k stereo -- so an imported song |
| 175 | # can share a timeline with the video clips and the peaks tests can reuse the | 183 | # can share a timeline with the video clips and the peaks tests can reuse the |