FilmCraft: An open-source, nonlinear video editor written by scratch in pure Rust
media: import animated WebP as a clip (#3038)
thiscallnetcb6dee282dd5
diff --git a/README.md b/README.mdindex 102e4a2a3..95fb0a8c2 100644--- a/README.md+++ b/README.md@@ -192,7 +192,7 @@ No FFmpeg inside. The video codecs, AAC, Opus and the containers are our own Rus| **MP4 / MOV** | ✓ | ✓ | Fragmented MP4, edit lists, timecode tracks || **Matroska / WebM** | ✓ | | Lacing, Cues, header stripping, HDR colour metadata || **AVI** | ✓ | | AVI 1.0 and OpenDML (files past 1 GB); Motion JPEG, H.264, HEVC and uncompressed RGB / YUV with PCM, MP3, MP2 or AC-3. DivX / Xvid and DV not yet |-| **Stills** | ✓ | ✓ | Import PNG, JPEG, GIF, WebP, TIFF and BMP (animated GIF and APNG as clips, with transparency); export PNG sequences and animated GIF |+| **Stills** | ✓ | ✓ | Import PNG, JPEG, GIF, WebP, TIFF and BMP (animated GIF, APNG and WebP as clips, with transparency); export PNG sequences and animated GIF |Also imported: MPEG-2 / MPEG-1 video, AC-3, MP2, MXF (OP1a / OP-Atom), MPEG transport and program streams (AVCHD, broadcast, DVD), Ogg and image sequences. Not yet: AV1 export, camera RAW, E-AC-3. Hardware decoding works on macOS (VideoToolbox), Windows (Media Foundation) and, for H.264 and HEVC, Linux (VA-API); H.264 export can use NVIDIA's encoder on Windows and Linux (opt-in), and H.265 (HEVC Main, 8-bit) export works through it (NVENC on Windows, VideoToolbox on macOS) ([#30](https://github.com/storytold/filmcraft/issues/30)).diff --git a/crates/media/src/animated.rs b/crates/media/src/animated.rsindex e20188a14..b327b89ed 100644--- a/crates/media/src/animated.rs+++ b/crates/media/src/animated.rs@@ -1,11 +1,11 @@-//! Animated images (APNG and animated GIF) as movie clips (#402).+//! Animated images (APNG, animated GIF, and animated WebP) as movie clips (#402).//!//! The still decoders read only the first picture of these files. [`open`] decodes every frame//! instead, composited onto the full canvas by the `image` crate (APNG blend and dispose operations,-//! GIF disposal methods), and keeps them with their timing:+//! GIF and WebP disposal methods), and keeps them with their timing://!-//! - each frame lasts its own delay; GIF delays of 10 ms or less play as 100 ms and APNG delays-//! under 10 ms as 10 ms, as browsers do, so a zero delay never makes a zero-length frame;+//! - each frame lasts its own delay; GIF delays of 10 ms or less play as 100 ms and APNG and WebP+//! delays under 10 ms as 10 ms, as browsers do, so a zero delay never makes a zero-length frame;//! - consecutive identical frames are merged (one picture, the sum of their delays);//! - the clip is one pass through the animation (the file's loop count is not applied);//! - transparency is kept: the source reports alpha when any frame has a pixel that is not fully@@ -31,29 +31,37 @@ use crate::{FrameRequest, MediaError, MediaInfo, MediaKind, MediaSource, Result,pub const MAX_FRAMES: usize = 10_000;/// Most bytes of decoded RGBA pictures kept from one file (after merging identical frames).pub const MAX_DECODED_BYTES: usize = 1 << 30;+/// Most RGBA bytes in one animation canvas while its decoder produces a frame.+const MAX_DECODED_FRAME_BYTES: usize = 512 << 20;/// Animated image formats.#[derive(Clone, Copy, Debug, PartialEq, Eq)]pub enum Format {Apng,Gif,+ WebP,}impl Format {+ /// Identify an animated image format from its container signature.fn sniff(b: &[u8]) -> Option<Format> {if b.starts_with(b"\x89PNG\r\n\x1a\n") {Some(Format::Apng)} else if b.starts_with(b"GIF87a") || b.starts_with(b"GIF89a") {Some(Format::Gif)+ } else if b.get(0..4) == Some(&b"RIFF"[..]) && b.get(8..12) == Some(&b"WEBP"[..]) {+ Some(Format::WebP)} else {None}}+ /// Return the codec label shown in media metadata.fn codec(self) -> &'static str {match self {Format::Apng => "APNG",Format::Gif => "GIF",+ Format::WebP => "WebP",}}@@ -66,6 +74,7 @@ impl Format {let (numer, denom) = match self {Format::Gif if ms <= 10 => (100, 1),Format::Apng if ms < 10 => (10, 1),+ Format::WebP if ms < 10 => (10, 1),_ => (numer, denom),};let ticks = numer.saturating_mul(TICKS_PER_SECOND as u128) / denom.saturating_mul(1000);@@ -81,8 +90,8 @@ pub struct AnimatedSource {starts: Vec<Tick>,}-/// Decode `bytes` as an animated image. `None` when it is not an APNG or GIF with at least two-/// frames that decode (the caller then opens it as a still).+/// Decode `bytes` as an animated image. `None` when it is not an APNG, GIF, or animated WebP with+/// at least two frames that decode (the caller then opens it as a still).pub fn open(name: &str, bytes: &[u8]) -> Option<Result<AnimatedSource>> {let format = Format::sniff(bytes)?;let frames = match format {@@ -99,19 +108,34 @@ pub fn open(name: &str, bytes: &[u8]) -> Option<Result<AnimatedSource>> {d.set_limits(Limits::default()).ok()?;d.into_frames()}+ Format::WebP => {+ let mut d = image::codecs::webp::WebPDecoder::new(Cursor::new(bytes)).ok()?;+ if !d.has_animation() {+ return None;+ }+ let (width, height) = d.dimensions();+ if rgba_bytes(width, height).is_none_or(|bytes| bytes > MAX_DECODED_FRAME_BYTES) {+ return Some(Err(MediaError::Unsupported(format!("{name}: animated WebP canvas exceeds the {MAX_DECODED_FRAME_BYTES}-byte frame limit"))));+ }+ d.set_limits(Limits::default()).ok()?;+ d.into_frames()+ }};AnimatedSource::from_frames(name, format, frames, bytes.len() as u64).map(Ok)}impl AnimatedSource {+ /// Build a clip from decoded full-canvas frames, merging consecutive identical pictures.fn from_frames(name: &str, format: Format, frames: Frames<'_>, file_size: u64) -> Option<Self> {let mut pictures: Vec<(u32, u32, Vec<u8>)> = Vec::new();let mut durations: Vec<Tick> = Vec::new();+ let mut decoded_frames = 0usize;let mut decoded = 0usize;let mut has_alpha = false;for frame in frames.take(MAX_FRAMES) {// a damaged frame ends the animation at the frames before itlet Ok(frame) = frame else { break };+ decoded_frames = decoded_frames.saturating_add(1);let ticks = format.frame_ticks(frame.delay());let buffer = frame.into_buffer();let (w, h) = buffer.dimensions();@@ -131,7 +155,7 @@ impl AnimatedSource {pictures.push((w, h, rgba));durations.push(ticks);}- if pictures.len() < 2 {+ if pictures.len() < 2 && !(format == Format::WebP && decoded_frames >= 2) {return None;}let (width, height) = pictures.first().map(|p| (p.0, p.1))?;@@ -182,6 +206,11 @@ impl AnimatedSource {}}+/// Checked byte size of an RGBA8 image.+fn rgba_bytes(width: u32, height: u32) -> Option<usize> {+ usize::try_from(width).ok()?.checked_mul(usize::try_from(height).ok()?)?.checked_mul(4)+}+/// The clip's frame rate: the rate of its most common frame duration, when that is a sensible video/// rate (1 to 120 frames per second), else 30 fps. Frames are shown for their own durations/// whatever this says; it sets the clip's timebase (e.g. a sequence made from the clip).@@ -207,14 +236,17 @@ fn rate_of(durations: &[Tick]) -> FrameRate {}impl MediaSource for AnimatedSource {+ /// Return the clip's media metadata.fn info(&self) -> &MediaInfo {&self.info}+ /// Return the picture displayed at the requested media time.fn video_frame(&self, req: FrameRequest) -> Result<Arc<VideoFrame>> {self.frames.get(self.index_at(req.time)).cloned().ok_or(MediaError::NoStream("video"))}+ /// Animated image files do not provide audio.fn audio(&self, _start: i64, _frames: usize, _sample_rate: u32) -> Result<AudioBuffer> {Err(MediaError::NoStream("audio"))}diff --git a/crates/media/src/animated_tests.rs b/crates/media/src/animated_tests.rsindex be77ca879..d3db3b7de 100644--- a/crates/media/src/animated_tests.rs+++ b/crates/media/src/animated_tests.rs@@ -1,5 +1,5 @@use super::*;-use crate::{FrameRequest, MediaKind, open_bytes};+use crate::{FrameRequest, MediaError, MediaKind, open_bytes};const W: u32 = 4;const H: u32 = 2;@@ -51,10 +51,71 @@ fn gif(frames: &[(Vec<u8>, u32)]) -> Vec<u8> {out}+/// A small animated WebP built from lossless WebP frame bitstreams.+fn webp(frames: &[(Vec<u8>, u32)]) -> Vec<u8> {+ fn chunk(out: &mut Vec<u8>, kind: &[u8; 4], data: &[u8]) {+ out.extend_from_slice(kind);+ out.extend_from_slice(&u32::try_from(data.len()).unwrap().to_le_bytes());+ out.extend_from_slice(data);+ if !data.len().is_multiple_of(2) {+ out.push(0);+ }+ }++ fn u24(out: &mut [u8], value: u32) {+ out[0] = value as u8;+ out[1] = (value >> 8) as u8;+ out[2] = (value >> 16) as u8;+ }++ fn frame_chunk(pixels: &[u8], duration_ms: u32) -> Vec<u8> {+ let mut encoded = Vec::new();+ image::codecs::webp::WebPEncoder::new_lossless(&mut encoded).encode(pixels, W, H, image::ExtendedColorType::Rgba8).unwrap();++ let mut pos = 12;+ let bitstream = loop {+ let header = encoded.get(pos..pos + 8).unwrap();+ let size = u32::from_le_bytes(header[4..8].try_into().unwrap()) as usize;+ let end = pos + 8 + size + size % 2;+ if &header[..4] == b"VP8L" {+ break encoded.get(pos..end).unwrap().to_vec();+ }+ pos = end;+ };++ let mut data = vec![0; 16];+ u24(&mut data[6..9], W - 1);+ u24(&mut data[9..12], H - 1);+ u24(&mut data[12..15], duration_ms);+ data[15] = 0x02; // replace the previous canvas instead of blending+ data.extend_from_slice(&bitstream);+ data+ }++ let mut chunks = Vec::new();+ let mut extended = [0; 10];+ extended[0] = 0x12; // alpha and animation flags+ u24(&mut extended[4..7], W - 1);+ u24(&mut extended[7..10], H - 1);+ chunk(&mut chunks, b"VP8X", &extended);+ chunk(&mut chunks, b"ANIM", &[0, 0, 0, 0, 0, 0]);+ for (pixels, duration_ms) in frames {+ chunk(&mut chunks, b"ANMF", &frame_chunk(pixels, *duration_ms));+ }++ let mut out = b"RIFF".to_vec();+ out.extend_from_slice(&u32::try_from(chunks.len() + 4).unwrap().to_le_bytes());+ out.extend_from_slice(b"WEBP");+ out.extend_from_slice(&chunks);+ out+}++/// Convert a whole number of milliseconds to media ticks.fn ms(n: i64) -> Tick {Tick(n * TICKS_PER_SECOND / 1000)}+/// Read the decoded RGBA pixels shown at a media time.fn pixels(s: &dyn MediaSource, t: Tick) -> Vec<u8> {match &s.video_frame(FrameRequest::full(t)).unwrap().data {filmcraft_frame::PixelData::Rgba8(p) => p.to_vec(),@@ -111,13 +172,62 @@ fn animated_gif_plays_every_frame_with_transparency() {assert_eq!(&pixels(&*s, ms(40))[0..4], &[0, 255, 0, 255]);}+#[test]+fn animated_webp_plays_every_frame_with_timing_and_transparency() {+ let (red, green) = (picture([255, 0, 0], 128), picture([0, 255, 0], 0));+ let bytes = webp(&[(red.clone(), 40), (green.clone(), 60)]);+ let s = open_bytes("wave.webp", bytes.into(), &[]).unwrap();+ let info = s.info();+ assert_eq!(info.kind, MediaKind::Movie);+ assert_eq!(info.video.as_ref().unwrap().codec, "WebP");+ assert_eq!(info.duration, ms(100));+ assert!(info.video.as_ref().unwrap().has_alpha);+ assert_eq!(pixels(&*s, Tick::ZERO), red);+ assert_eq!(pixels(&*s, ms(39)), red);+ assert_eq!(pixels(&*s, ms(40)), green);+}++#[test]+fn identical_webp_frames_remain_a_clip_when_merged() {+ let frame = picture([20, 40, 60], 255);+ let bytes = webp(&[(frame.clone(), 40), (frame, 60)]);+ let decoded = open("hold.webp", &bytes).expect("animated WebP").expect("decodes");+ assert_eq!(decoded.frame_count(), 1, "equal pictures still merge");+ assert_eq!(decoded.info().kind, MediaKind::Movie);+ assert_eq!(decoded.info().duration, ms(100), "merged frames keep their encoded duration");++ let imported = open_bytes("hold.webp", bytes.into(), &[]).unwrap();+ assert_eq!(imported.info().kind, MediaKind::Movie, "the still-image fallback must not discard the duration");+ assert_eq!(imported.info().duration, ms(100));+}++#[test]+fn animated_webp_rejects_an_oversized_canvas_before_decoding_frames() {+ let frame = picture([1, 2, 3], 255);+ let mut bytes = webp(&[(frame.clone(), 40), (frame, 60)]);+ // VP8X canvas width and height are stored as 24-bit values minus one.+ for (offset, dimension) in [(24, 25_000u32), (27, 25_000u32)] {+ let value = (dimension - 1).to_le_bytes();+ bytes[offset..offset + 3].copy_from_slice(&value[..3]);+ }+ assert!(matches!(+ open("large.webp", &bytes),+ Some(Err(MediaError::Unsupported(message))) if message.contains("frame limit")+ ));+}+#[test]fn single_frame_files_stay_stills() {let one_frame_apng = apng(&[(picture([1, 2, 3], 255), (1, 10))]);let one_frame_gif = gif(&[(picture([1, 2, 3], 255), 100)]);+ let one_frame_webp = webp(&[(picture([1, 2, 3], 255), 100)]);let mut plain = std::io::Cursor::new(Vec::new());image::RgbaImage::from_raw(W, H, picture([1, 2, 3], 0)).unwrap().write_to(&mut plain, image::ImageFormat::Png).unwrap();- for (name, bytes) in [("one.png", one_frame_apng), ("one.gif", one_frame_gif), ("plain.png", plain.into_inner())] {+ let mut plain_webp = Vec::new();+ image::codecs::webp::WebPEncoder::new_lossless(&mut plain_webp).encode(&picture([1, 2, 3], 0), W, H, image::ExtendedColorType::Rgba8).unwrap();+ for (name, bytes) in+ [("one.png", one_frame_apng), ("one.gif", one_frame_gif), ("one.webp", one_frame_webp), ("plain.png", plain.into_inner()), ("plain.webp", plain_webp)]+ {assert!(open(name, &bytes).is_none(), "{name}");let s = open_bytes(name, bytes.into(), &[]).unwrap();assert_eq!(s.info().kind, MediaKind::Still, "{name}");@@ -129,7 +239,8 @@ fn damaged_files_never_panic() {let frames: Vec<_> = (0..6u8).map(|i| (picture([i * 40, 0, 255 - i * 40], i * 40), (1, 10))).collect();let png_bytes = apng(&frames);let gif_bytes = gif(&frames.iter().map(|(p, _)| (p.clone(), 100)).collect::<Vec<_>>());- for whole in [png_bytes, gif_bytes] {+ let webp_bytes = webp(&frames.iter().map(|(p, _)| (p.clone(), 100)).collect::<Vec<_>>());+ for whole in [png_bytes, gif_bytes, webp_bytes] {for cut in (0..whole.len()).step_by(7) {// truncated: opens as fewer frames, a still or an error, never a paniclet _ = open_bytes("cut", whole[..cut].to_vec().into(), &[]);@@ -166,6 +277,8 @@ fn frame_delays_have_browser_minimums_and_never_overflow() {assert_eq!(Format::Apng.frame_ticks(d(40, 1)), ms(40));assert_eq!(Format::Apng.frame_ticks(d(1000, 3)), Tick(TICKS_PER_SECOND / 3));assert!(Format::Apng.frame_ticks(d(u32::MAX, 1)).0 > 0);+ assert_eq!(Format::WebP.frame_ticks(d(0, 1)), ms(10));+ assert_eq!(Format::WebP.frame_ticks(d(40, 1)), ms(40));}#[test]diff --git a/crates/media/src/lib.rs b/crates/media/src/lib.rsindex f875705ed..069c550a8 100644--- a/crates/media/src/lib.rs+++ b/crates/media/src/lib.rs@@ -203,7 +203,7 @@ pub fn open_bytes(name: &str, bytes: Arc<[u8]>, extra: &[Opener]) -> Result<Sharif wav::sniff(&bytes) {return Ok(Arc::new(wav::WavSource::parse(name, bytes)?));}- // APNG and animated GIF play as movies (#402); single-frame files fall through to the stills+ // APNG, animated GIF, and animated WebP play as movies (#402); single-frame files fall through to the stillsif let Some(r) = animated::open(name, &bytes) {return Ok(Arc::new(r?));}