From c52b66705915ced5dfe00ea624f84956cb43e7ba Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Wed, 12 Aug 2026 06:16:20 +0300 Subject: [PATCH] =?UTF-8?q?=F0=9F=90=9B=20fix(decode):=20a=20film's=20grai?= =?UTF-8?q?n=20is=20synthesized=20into=20a=20surface=20of=20its=20own?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit An AV1 frame with `apply_grain` set is *displayed* from a second surface: the driver writes the reconstructed picture into the render target, which later frames reference, and the grain-synthesized one into a target the decoder has to hand it. The vendored backend handed it none -- it passed `VA_INVALID_SURFACE` as `current_display_picture` while still asking, in the very same buffer, for the grain -- and radeonsi refuses that picture outright: `vaEndPicture` answers VA_STATUS_ERROR_INVALID_SURFACE. That is what killed the only AV1 film in the library at frame 49, its first picture with grain; 1337 of the first 1504 have it, so AV1 playback on real media had never worked. Every fixture that said otherwise was grainless, which is why `test_av1_grain.mkv` is now beside them and why its test decodes all ninety frames and then asks whether the grain actually reached the picture -- turning `apply_grain` off would make the decode succeed too, and would silently strip the film of its texture. A grainy picture costs two pool frames rather than one, so a sequence whose header admits grain gets a pool of twice the size; one that does not is left exactly as it was, as are H.264, HEVC and VP9, which have no such surface and read back the reconstructed one as always. --- crates/engine-hw/src/lib.rs | 6 +- crates/engine/tests/av1.rs | 59 +++++++++++++++++++ scripts/gen_fixtures.sh | 17 ++++++ .../cros-codecs/src/backend/vaapi/decoder.rs | 58 +++++++++++++++++- .../src/decoder/stateless/av1/vaapi.rs | 47 +++++++++++---- 5 files changed, 173 insertions(+), 14 deletions(-) diff --git a/crates/engine-hw/src/lib.rs b/crates/engine-hw/src/lib.rs index 0ded8cf..4c01862 100644 --- a/crates/engine-hw/src/lib.rs +++ b/crates/engine-hw/src/lib.rs @@ -379,7 +379,11 @@ impl Session { let _ = DecodedHandle::sync(&handle); let borrowed = handle.borrow(); let size = (w as u32, h as u32); - let image = Image::create_from(borrowed.surface(), self.nv12_format, size, size) + // The *display* surface, which is the reconstructed picture for every + // codec here but the second, grain-synthesized one for an AV1 frame that + // asks for film grain -- reading the reconstructed surface of such a + // frame would show the film with its grain stripped off. + let image = Image::create_from(borrowed.display_surface(), self.nv12_format, size, size) .expect("vaGetImage failed"); let va = *image.image(); let data: &[u8] = image.as_ref(); diff --git a/crates/engine/tests/av1.rs b/crates/engine/tests/av1.rs index d1b875b..7dfda7f 100644 --- a/crates/engine/tests/av1.rs +++ b/crates/engine/tests/av1.rs @@ -26,6 +26,9 @@ use engine::{AudioSession, DecodeSession, PlaybackSession, Project}; /// 1280x720@30, 2 s, keyframes 30 apart -- see `scripts/gen_fixtures.sh`. const FRAMES: u32 = 60; const KEYFRAME: u32 = 30; +/// The film grain twin is 3 s of the same shape, for the reason its own test +/// gives. +const GRAIN_FRAMES: u32 = 90; fn asset(name: &str) -> PathBuf { PathBuf::from(env!("CARGO_MANIFEST_DIR")) @@ -209,6 +212,62 @@ fn the_plugin_decodes_every_av1_frame() { ); } +/// The picture's flattest 8x8 block, as a standard deviation of its green +/// channel: 0 where the decoder handed back a smooth picture, well above it +/// where every pixel carries synthesized grain. +fn flattest_block(bgra: &[u8], width: u32, height: u32) -> f64 { + let (w, h) = (width as usize, height as usize); + let mut flattest = f64::MAX; + for y in (0..h - 8).step_by(8) { + for x in (0..w - 8).step_by(8) { + let block = (0..8).flat_map(|dy| { + (0..8).map(move |dx| f64::from(bgra[((y + dy) * w + x + dx) * 4 + 1])) + }); + let values: Vec = block.collect(); + let mean = values.iter().sum::() / values.len() as f64; + let var = + values.iter().map(|v| (v - mean) * (v - mean)).sum::() / values.len() as f64; + flattest = flattest.min(var.sqrt()); + } + } + flattest +} + +/// The defect none of the fixtures above could see: an AV1 frame that asks for +/// film grain is *displayed* from a second surface, which the driver +/// synthesizes the grain into and which the decoder has to give it. Handing it +/// none gets the picture refused outright -- radeonsi answers `vaEndPicture` +/// with VA_STATUS_ERROR_INVALID_SURFACE -- and that killed a real 1080p AV1 +/// film at frame 49, the first of its pictures with `apply_grain` set. Every +/// fixture beside this one is grainless, and every one of them passed. +/// +/// Ninety frames, all of them: a grainy picture costs two pool buffers rather +/// than one, so this turns the pool over several times and cycles the eight +/// reference slots -- decoding "the first handful" is exactly what let the +/// defect live. +#[test] +#[ignore = "needs libengine_hw.so and a VA-API driver with AV1 decode"] +fn a_film_grain_av1_file_decodes_whole_and_keeps_its_grain() { + let (meta, frames) = + DecodeSession::open(asset("test_av1_grain.mkv")).expect("open test_av1_grain.mkv"); + assert_eq!(meta.codec, Codec::Av1); + let frames: Vec<_> = frames.into_iter().collect(); + assert_eq!(frames.len() as u32, GRAIN_FRAMES, "every frame decoded"); + + // ...and the grain is *in* the picture, which is the half "it did not fail" + // cannot say: telling the driver `apply_grain = 0` also makes every frame + // decode, and silently strips the film of the texture it was graded with. + // Grain is noise on every pixel, so no block of a grainy picture is flat; + // this source has plenty of flat ones without it (measured on the fixture: + // 0.00 with the grain off, 1.58 with it on). + let frame = &frames[GRAIN_FRAMES as usize - 30]; + let flattest = flattest_block(&frame.bgra, frame.width, frame.height); + assert!( + flattest > 0.5, + "the grain never reached the picture: flattest 8x8 block deviation {flattest:.3}" + ); +} + /// ...and the 10-bit file through the very call the window's open door makes: a /// user opens it and the timeline shows a picture, read back off the P010 pool /// to the same 8-bit BGRA every other frame arrives in. The whole point of the diff --git a/scripts/gen_fixtures.sh b/scripts/gen_fixtures.sh index d45bb58..fc1fcfc 100755 --- a/scripts/gen_fixtures.sh +++ b/scripts/gen_fixtures.sh @@ -148,6 +148,23 @@ ffmpeg -y -f lavfi -i testsrc2=size=1280x720:rate=30:duration=2 \ -filter_complex "[1:a][2:a]join=inputs=2:channel_layout=stereo,volume='0.5+0.5*sin(2*PI*t)':eval=frame[a]" \ -map 0:v -map "[a]" -c:v libsvtav1 -preset 8 -g 30 -pix_fmt yuv420p \ -c:a aac -b:a 128k assets/test_av1.mkv +# ...and an AV1 file that asks for film grain, which no other fixture here does. +# A frame with `apply_grain` set is *displayed* from a second surface the driver +# synthesizes the grain into, and a decoder that hands it none is refused the +# picture outright (radeonsi: VA_STATUS_ERROR_INVALID_SURFACE out of +# `vaEndPicture`) -- which is how AV1 decode died at frame 49 of a real film +# while every fixture above sailed through. Three seconds rather than two so the +# surface pool wraps several times, `noise` on the source because SVT-AV1 reads +# the grain parameters it signals *off the source* (a clean testsrc2 yields grain +# with no amplitude at all, measured), and `film-grain-denoise=1` so the coded +# picture is the smooth one and the grain is really the decoder's own work. +ffmpeg -y -f lavfi -i "testsrc2=size=1280x720:rate=30:duration=3,noise=alls=24:allf=t+u" \ + -f lavfi -i "sine=frequency=440:duration=3" \ + -f lavfi -i "sine=frequency=880:duration=3" \ + -filter_complex "[1:a][2:a]join=inputs=2:channel_layout=stereo,volume='0.5+0.5*sin(2*PI*t)':eval=frame[a]" \ + -map 0:v -map "[a]" -c:v libsvtav1 -preset 8 -g 30 -pix_fmt yuv420p \ + -svtav1-params film-grain=40:film-grain-denoise=1 \ + -c:a aac -b:a 128k assets/test_av1_grain.mkv # ...and the same file 10-bit, which is what an `av1C` with `high_bitdepth` set # reads as and what the P010 surface pool is picked by -- the AV1 seat of the # pair test_hevc.mkv/test_hevc10.mkv already make for HEVC. libaom rather than diff --git a/vendor/cros-codecs/src/backend/vaapi/decoder.rs b/vendor/cros-codecs/src/backend/vaapi/decoder.rs index 744c3f4..7a11e13 100644 --- a/vendor/cros-codecs/src/backend/vaapi/decoder.rs +++ b/vendor/cros-codecs/src/backend/vaapi/decoder.rs @@ -152,22 +152,39 @@ pub struct VaapiDecodedHandle { state: PictureState<::MemDescriptor>, /// Actual resolution of the visible rectangle in the decoded buffer. display_resolution: Resolution, + /// LOCAL PATCH (see /Cargo.toml [patch.crates-io]): the second surface an + /// AV1 picture with `apply_grain` set is *displayed* from -- the driver + /// synthesizes the grain into it and leaves the reconstructed picture, which + /// is what later frames reference, untouched in `state`'s own surface. + /// `None` for every picture that asks for no grain, which is every picture + /// of every other codec. + display: Option<(Arc, Surface<::MemDescriptor>)>, } impl VaapiDecodedHandle { /// Creates a new pending handle on `surface_id`. fn new(picture: VaapiPicture, display_resolution: Resolution) -> anyhow::Result { let backing_frame = picture.backing_frame; + let display = picture.display; let picture = picture.picture.begin()?.render()?.end()?; Ok(Self { backing_frame: backing_frame, state: PictureState::Pending(picture), display_resolution: display_resolution, + display: display, }) } fn sync(&mut self) -> Result<(), VaError> { - self.state.sync() + self.state.sync()?; + // LOCAL PATCH (see /Cargo.toml [patch.crates-io]): the grain is + // synthesized into a surface of its own, and it is that one the pixels + // are read back off, so waiting only on the reconstructed picture would + // hand out a half-written frame. + if let Some((_, surface)) = &self.display { + surface.sync()?; + } + Ok(()) } /// Creates a new picture from the surface backing the current one. Useful for interlaced @@ -176,6 +193,8 @@ impl VaapiDecodedHandle { VaapiPicture { picture: self.state.new_from_same_surface(timestamp), backing_frame: self.backing_frame.clone(), + // Interlaced H.264 only, which no codec here asks film grain of. + display: None, } } @@ -187,6 +206,17 @@ impl VaapiDecodedHandle { self.state.surface() } + /// LOCAL PATCH (see /Cargo.toml [patch.crates-io]): the surface a *viewer* + /// wants, which is the grain-synthesized one where there is one and the + /// reconstructed picture everywhere else. [`Self::surface`] stays the + /// reconstructed one on purpose: that is what the reference lists point at. + pub fn display_surface(&self) -> &Surface<::MemDescriptor> { + match &self.display { + Some((_, surface)) => surface, + None => self.state.surface(), + } + } + /// Returns the timestamp of this handle. fn timestamp(&self) -> u64 { self.state.timestamp() @@ -305,6 +335,7 @@ impl VaapiBackend { pub struct VaapiPicture { picture: Picture>, backing_frame: Arc, + display: Option<(Arc, Surface)>, } impl VaapiPicture { @@ -317,6 +348,31 @@ impl VaapiPicture { Self { backing_frame: Arc::new(backing_frame), picture: Picture::new(timestamp, context, surface), + display: None, + } + } + + /// LOCAL PATCH (see /Cargo.toml [patch.crates-io]): gives this picture the + /// second surface an AV1 frame with `apply_grain` set is displayed from. The + /// driver writes the reconstructed picture into the render target as always + /// and the grain-synthesized one into this; a driver told to apply grain with + /// no such target refuses the picture outright (radeonsi answers + /// `vaEndPicture` with VA_STATUS_ERROR_INVALID_SURFACE). + pub fn set_display_frame(&mut self, display: &Rc, frame: V) { + let surface = frame + .to_native_handle(display) + .expect("Failed to export film grain target to vaapi picture!") + .into(); + self.display = Some((Arc::new(frame), surface)); + } + + /// The id [`Self::set_display_frame`] handed over, or `VA_INVALID_SURFACE` + /// when this picture wants no grain -- which is what the picture parameter + /// buffer's `current_display_picture` takes either way. + pub fn display_surface_id(&self) -> libva::VASurfaceID { + match &self.display { + Some((_, surface)) => surface.id(), + None => libva::VA_INVALID_SURFACE, } } diff --git a/vendor/cros-codecs/src/decoder/stateless/av1/vaapi.rs b/vendor/cros-codecs/src/decoder/stateless/av1/vaapi.rs index cc06ca2..3712330 100644 --- a/vendor/cros-codecs/src/decoder/stateless/av1/vaapi.rs +++ b/vendor/cros-codecs/src/decoder/stateless/av1/vaapi.rs @@ -87,7 +87,16 @@ impl VaStreamInfo for &StreamInfo { } fn min_num_surfaces(&self) -> usize { - NUM_SURFACES + // LOCAL PATCH (see /Cargo.toml [patch.crates-io]): a sequence that may + // synthesize film grain displays every grainy picture from a second + // surface (`VaapiPicture::set_display_frame`), so every one of the frames + // in flight -- the eight of the reference map, the one being decoded, the + // ones handed out but not yet read back -- can cost two. A sequence whose + // header says grain never happens is left at the count it always had. + match self.seq_header.film_grain_params_present { + true => 2 * NUM_SURFACES, + false => NUM_SURFACES, + } } fn coded_size(&self) -> Resolution { @@ -106,10 +115,6 @@ impl From<&FrameHeaderObu> for libva::AV1FilmGrain { fn from(hdr: &FrameHeaderObu) -> Self { let fg = &hdr.film_grain_params; - if fg.apply_grain { - log::warn!("Film grain is not officially supported yet.") - } - let film_grain_fields = libva::AV1FilmGrainFields::new( u32::from(fg.apply_grain), u32::from(fg.chroma_scaling_from_luma), @@ -238,6 +243,7 @@ fn build_pic_param( hdr: &FrameHeaderObu, stream_info: &StreamInfo, current_frame: libva::VASurfaceID, + current_display_picture: libva::VASurfaceID, reference_frames: &[Option>; NUM_REF_FRAMES], ) -> anyhow::Result { let seq = stream_info.seq_header.clone(); @@ -414,8 +420,8 @@ fn build_pic_param( .context("Invalid matrix_coefficients")?, &seq_info_fields, current_frame, - libva::VA_INVALID_SURFACE, /* film grain is unsupported for now */ - vec![], /* anchor_frames_list */ + current_display_picture, + vec![], /* anchor_frames_list */ u16::try_from(hdr.upscaled_width - 1).context("Invalid frame width")?, u16::try_from(hdr.frame_height - 1).context("Invalid frame height")?, 0, /* output_frame_width_in_tiles_minus_1 */ @@ -498,15 +504,26 @@ impl StatelessAV1DecoderBackend for VaapiBackend { fn new_picture( &mut self, - _hdr: &FrameHeaderObu, + hdr: &FrameHeaderObu, timestamp: u64, alloc_cb: &mut dyn FnMut() -> Option, ) -> NewPictureResult { - Ok(VaapiPicture::new( + let mut picture = VaapiPicture::new( timestamp, Rc::clone(&self.context), alloc_cb().ok_or(NewPictureError::OutOfOutputBuffers)?, - )) + ); + // LOCAL PATCH (see /Cargo.toml [patch.crates-io]): a frame that asks for + // film grain is displayed from a second surface, so it costs two frames + // of the pool rather than one -- which is why `min_num_surfaces` above + // counts double for a sequence that may use grain. Failing the second + // allocation drops the first back into the pool with the picture, and the + // caller resubmits exactly as it does for the first. + if hdr.film_grain_params.apply_grain { + let frame = alloc_cb().ok_or(NewPictureError::OutOfOutputBuffers)?; + picture.set_display_frame(self.context.display(), frame); + } + Ok(picture) } fn begin_picture( @@ -516,8 +533,14 @@ impl StatelessAV1DecoderBackend for VaapiBackend { hdr: &FrameHeaderObu, reference_frames: &[Option; NUM_REF_FRAMES], ) -> StatelessBackendResult<()> { - let pic_param = build_pic_param(hdr, stream_info, picture.surface().id(), reference_frames) - .context("Failed to build picture parameter")?; + let pic_param = build_pic_param( + hdr, + stream_info, + picture.surface().id(), + picture.display_surface_id(), + reference_frames, + ) + .context("Failed to build picture parameter")?; let pic_param = self .context .create_buffer(pic_param)