forge
Explore
Log in

Don't you dare go Hollow

A film's grain is synthesized into a surface of its own

Browse files at this commit

c52b66705915ced5dfe00ea624f84956cb43e7baAhmet Kaan GümüşParent: 8e2a297
  • fix
    • a film's grain is synthesized into a surface of its own
Show full message
🐛 fix(decode): a film's grain is synthesized into a surface of its own

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.rsmodified+5 -1
@@ -379,7 +379,11 @@ impl Session {
379 let _ = DecodedHandle::sync(&handle);379 let _ = DecodedHandle::sync(&handle);
380 let borrowed = handle.borrow();380 let borrowed = handle.borrow();
381 let size = (w as u32, h as u32);381 let size = (w as u32, h as u32);
382- let image = Image::create_from(borrowed.surface(), self.nv12_format, size, size)382+ // The *display* surface, which is the reconstructed picture for every
383+ // codec here but the second, grain-synthesized one for an AV1 frame that
384+ // asks for film grain -- reading the reconstructed surface of such a
385+ // frame would show the film with its grain stripped off.
386+ let image = Image::create_from(borrowed.display_surface(), self.nv12_format, size, size)
383 .expect("vaGetImage failed");387 .expect("vaGetImage failed");
384 let va = *image.image();388 let va = *image.image();
385 let data: &[u8] = image.as_ref();389 let data: &[u8] = image.as_ref();
crates/engine/tests/av1.rsmodified+59 -0
@@ -26,6 +26,9 @@ use engine::{AudioSession, DecodeSession, PlaybackSession, Project};
26 /// 1280x720@30, 2 s, keyframes 30 apart -- see `scripts/gen_fixtures.sh`.26 /// 1280x720@30, 2 s, keyframes 30 apart -- see `scripts/gen_fixtures.sh`.
27 const FRAMES: u32 = 60;27 const FRAMES: u32 = 60;
28 const KEYFRAME: u32 = 30;28 const KEYFRAME: u32 = 30;
29+/// The film grain twin is 3 s of the same shape, for the reason its own test
30+/// gives.
31+const GRAIN_FRAMES: u32 = 90;
29 32
30 fn asset(name: &str) -> PathBuf {33 fn asset(name: &str) -> PathBuf {
31 PathBuf::from(env!("CARGO_MANIFEST_DIR"))34 PathBuf::from(env!("CARGO_MANIFEST_DIR"))
@@ -209,6 +212,62 @@ fn the_plugin_decodes_every_av1_frame() {
209 );212 );
210 }213 }
211 214
215+/// The picture's flattest 8x8 block, as a standard deviation of its green
216+/// channel: 0 where the decoder handed back a smooth picture, well above it
217+/// where every pixel carries synthesized grain.
218+fn flattest_block(bgra: &[u8], width: u32, height: u32) -> f64 {
219+ let (w, h) = (width as usize, height as usize);
220+ let mut flattest = f64::MAX;
221+ for y in (0..h - 8).step_by(8) {
222+ for x in (0..w - 8).step_by(8) {
223+ let block = (0..8).flat_map(|dy| {
224+ (0..8).map(move |dx| f64::from(bgra[((y + dy) * w + x + dx) * 4 + 1]))
225+ });
226+ let values: Vec<f64> = block.collect();
227+ let mean = values.iter().sum::<f64>() / values.len() as f64;
228+ let var =
229+ values.iter().map(|v| (v - mean) * (v - mean)).sum::<f64>() / values.len() as f64;
230+ flattest = flattest.min(var.sqrt());
231+ }
232+ }
233+ flattest
234+}
235+
236+/// The defect none of the fixtures above could see: an AV1 frame that asks for
237+/// film grain is *displayed* from a second surface, which the driver
238+/// synthesizes the grain into and which the decoder has to give it. Handing it
239+/// none gets the picture refused outright -- radeonsi answers `vaEndPicture`
240+/// with VA_STATUS_ERROR_INVALID_SURFACE -- and that killed a real 1080p AV1
241+/// film at frame 49, the first of its pictures with `apply_grain` set. Every
242+/// fixture beside this one is grainless, and every one of them passed.
243+///
244+/// Ninety frames, all of them: a grainy picture costs two pool buffers rather
245+/// than one, so this turns the pool over several times and cycles the eight
246+/// reference slots -- decoding "the first handful" is exactly what let the
247+/// defect live.
248+#[test]
249+#[ignore = "needs libengine_hw.so and a VA-API driver with AV1 decode"]
250+fn a_film_grain_av1_file_decodes_whole_and_keeps_its_grain() {
251+ let (meta, frames) =
252+ DecodeSession::open(asset("test_av1_grain.mkv")).expect("open test_av1_grain.mkv");
253+ assert_eq!(meta.codec, Codec::Av1);
254+ let frames: Vec<_> = frames.into_iter().collect();
255+ assert_eq!(frames.len() as u32, GRAIN_FRAMES, "every frame decoded");
256+
257+ // ...and the grain is *in* the picture, which is the half "it did not fail"
258+ // cannot say: telling the driver `apply_grain = 0` also makes every frame
259+ // decode, and silently strips the film of the texture it was graded with.
260+ // Grain is noise on every pixel, so no block of a grainy picture is flat;
261+ // this source has plenty of flat ones without it (measured on the fixture:
262+ // 0.00 with the grain off, 1.58 with it on).
263+ let frame = &frames[GRAIN_FRAMES as usize - 30];
264+ let flattest = flattest_block(&frame.bgra, frame.width, frame.height);
265+ assert!(
266+ flattest > 0.5,
267+ "the grain never reached the picture: flattest 8x8 block deviation {flattest:.3}"
268+ );
269+}
270+
212 /// ...and the 10-bit file through the very call the window's open door makes: a271 /// ...and the 10-bit file through the very call the window's open door makes: a
213 /// user opens it and the timeline shows a picture, read back off the P010 pool272 /// user opens it and the timeline shows a picture, read back off the P010 pool
214 /// to the same 8-bit BGRA every other frame arrives in. The whole point of the273 /// to the same 8-bit BGRA every other frame arrives in. The whole point of the
scripts/gen_fixtures.shmodified+17 -0
@@ -148,6 +148,23 @@ ffmpeg -y -f lavfi -i testsrc2=size=1280x720:rate=30:duration=2 \
148 -filter_complex "[1:a][2:a]join=inputs=2:channel_layout=stereo,volume='0.5+0.5*sin(2*PI*t)':eval=frame[a]" \148 -filter_complex "[1:a][2:a]join=inputs=2:channel_layout=stereo,volume='0.5+0.5*sin(2*PI*t)':eval=frame[a]" \
149 -map 0:v -map "[a]" -c:v libsvtav1 -preset 8 -g 30 -pix_fmt yuv420p \149 -map 0:v -map "[a]" -c:v libsvtav1 -preset 8 -g 30 -pix_fmt yuv420p \
150 -c:a aac -b:a 128k assets/test_av1.mkv150 -c:a aac -b:a 128k assets/test_av1.mkv
151+# ...and an AV1 file that asks for film grain, which no other fixture here does.
152+# A frame with `apply_grain` set is *displayed* from a second surface the driver
153+# synthesizes the grain into, and a decoder that hands it none is refused the
154+# picture outright (radeonsi: VA_STATUS_ERROR_INVALID_SURFACE out of
155+# `vaEndPicture`) -- which is how AV1 decode died at frame 49 of a real film
156+# while every fixture above sailed through. Three seconds rather than two so the
157+# surface pool wraps several times, `noise` on the source because SVT-AV1 reads
158+# the grain parameters it signals *off the source* (a clean testsrc2 yields grain
159+# with no amplitude at all, measured), and `film-grain-denoise=1` so the coded
160+# picture is the smooth one and the grain is really the decoder's own work.
161+ffmpeg -y -f lavfi -i "testsrc2=size=1280x720:rate=30:duration=3,noise=alls=24:allf=t+u" \
162+ -f lavfi -i "sine=frequency=440:duration=3" \
163+ -f lavfi -i "sine=frequency=880:duration=3" \
164+ -filter_complex "[1:a][2:a]join=inputs=2:channel_layout=stereo,volume='0.5+0.5*sin(2*PI*t)':eval=frame[a]" \
165+ -map 0:v -map "[a]" -c:v libsvtav1 -preset 8 -g 30 -pix_fmt yuv420p \
166+ -svtav1-params film-grain=40:film-grain-denoise=1 \
167+ -c:a aac -b:a 128k assets/test_av1_grain.mkv
151 # ...and the same file 10-bit, which is what an `av1C` with `high_bitdepth` set168 # ...and the same file 10-bit, which is what an `av1C` with `high_bitdepth` set
152 # reads as and what the P010 surface pool is picked by -- the AV1 seat of the169 # reads as and what the P010 surface pool is picked by -- the AV1 seat of the
153 # pair test_hevc.mkv/test_hevc10.mkv already make for HEVC. libaom rather than170 # pair test_hevc.mkv/test_hevc10.mkv already make for HEVC. libaom rather than
vendor/cros-codecs/src/backend/vaapi/decoder.rsmodified+57 -1
@@ -152,22 +152,39 @@ pub struct VaapiDecodedHandle<V: VideoFrame> {
152 state: PictureState<<V as VideoFrame>::MemDescriptor>,152 state: PictureState<<V as VideoFrame>::MemDescriptor>,
153 /// Actual resolution of the visible rectangle in the decoded buffer.153 /// Actual resolution of the visible rectangle in the decoded buffer.
154 display_resolution: Resolution,154 display_resolution: Resolution,
155+ /// LOCAL PATCH (see /Cargo.toml [patch.crates-io]): the second surface an
156+ /// AV1 picture with `apply_grain` set is *displayed* from -- the driver
157+ /// synthesizes the grain into it and leaves the reconstructed picture, which
158+ /// is what later frames reference, untouched in `state`'s own surface.
159+ /// `None` for every picture that asks for no grain, which is every picture
160+ /// of every other codec.
161+ display: Option<(Arc<V>, Surface<<V as VideoFrame>::MemDescriptor>)>,
155 }162 }
156 163
157 impl<V: VideoFrame> VaapiDecodedHandle<V> {164 impl<V: VideoFrame> VaapiDecodedHandle<V> {
158 /// Creates a new pending handle on `surface_id`.165 /// Creates a new pending handle on `surface_id`.
159 fn new(picture: VaapiPicture<V>, display_resolution: Resolution) -> anyhow::Result<Self> {166 fn new(picture: VaapiPicture<V>, display_resolution: Resolution) -> anyhow::Result<Self> {
160 let backing_frame = picture.backing_frame;167 let backing_frame = picture.backing_frame;
168+ let display = picture.display;
161 let picture = picture.picture.begin()?.render()?.end()?;169 let picture = picture.picture.begin()?.render()?.end()?;
162 Ok(Self {170 Ok(Self {
163 backing_frame: backing_frame,171 backing_frame: backing_frame,
164 state: PictureState::Pending(picture),172 state: PictureState::Pending(picture),
165 display_resolution: display_resolution,173 display_resolution: display_resolution,
174+ display: display,
166 })175 })
167 }176 }
168 177
169 fn sync(&mut self) -> Result<(), VaError> {178 fn sync(&mut self) -> Result<(), VaError> {
170- self.state.sync()179+ self.state.sync()?;
180+ // LOCAL PATCH (see /Cargo.toml [patch.crates-io]): the grain is
181+ // synthesized into a surface of its own, and it is that one the pixels
182+ // are read back off, so waiting only on the reconstructed picture would
183+ // hand out a half-written frame.
184+ if let Some((_, surface)) = &self.display {
185+ surface.sync()?;
186+ }
187+ Ok(())
171 }188 }
172 189
173 /// Creates a new picture from the surface backing the current one. Useful for interlaced190 /// Creates a new picture from the surface backing the current one. Useful for interlaced
@@ -176,6 +193,8 @@ impl<V: VideoFrame> VaapiDecodedHandle<V> {
176 VaapiPicture {193 VaapiPicture {
177 picture: self.state.new_from_same_surface(timestamp),194 picture: self.state.new_from_same_surface(timestamp),
178 backing_frame: self.backing_frame.clone(),195 backing_frame: self.backing_frame.clone(),
196+ // Interlaced H.264 only, which no codec here asks film grain of.
197+ display: None,
179 }198 }
180 }199 }
181 200
@@ -187,6 +206,17 @@ impl<V: VideoFrame> VaapiDecodedHandle<V> {
187 self.state.surface()206 self.state.surface()
188 }207 }
189 208
209+ /// LOCAL PATCH (see /Cargo.toml [patch.crates-io]): the surface a *viewer*
210+ /// wants, which is the grain-synthesized one where there is one and the
211+ /// reconstructed picture everywhere else. [`Self::surface`] stays the
212+ /// reconstructed one on purpose: that is what the reference lists point at.
213+ pub fn display_surface(&self) -> &Surface<<V as VideoFrame>::MemDescriptor> {
214+ match &self.display {
215+ Some((_, surface)) => surface,
216+ None => self.state.surface(),
217+ }
218+ }
219+
190 /// Returns the timestamp of this handle.220 /// Returns the timestamp of this handle.
191 fn timestamp(&self) -> u64 {221 fn timestamp(&self) -> u64 {
192 self.state.timestamp()222 self.state.timestamp()
@@ -305,6 +335,7 @@ impl<V: VideoFrame> VaapiBackend<V> {
305 pub struct VaapiPicture<V: VideoFrame> {335 pub struct VaapiPicture<V: VideoFrame> {
306 picture: Picture<PictureNew, Surface<V::MemDescriptor>>,336 picture: Picture<PictureNew, Surface<V::MemDescriptor>>,
307 backing_frame: Arc<V>,337 backing_frame: Arc<V>,
338+ display: Option<(Arc<V>, Surface<V::MemDescriptor>)>,
308 }339 }
309 340
310 impl<V: VideoFrame> VaapiPicture<V> {341 impl<V: VideoFrame> VaapiPicture<V> {
@@ -317,6 +348,31 @@ impl<V: VideoFrame> VaapiPicture<V> {
317 Self {348 Self {
318 backing_frame: Arc::new(backing_frame),349 backing_frame: Arc::new(backing_frame),
319 picture: Picture::new(timestamp, context, surface),350 picture: Picture::new(timestamp, context, surface),
351+ display: None,
352+ }
353+ }
354+
355+ /// LOCAL PATCH (see /Cargo.toml [patch.crates-io]): gives this picture the
356+ /// second surface an AV1 frame with `apply_grain` set is displayed from. The
357+ /// driver writes the reconstructed picture into the render target as always
358+ /// and the grain-synthesized one into this; a driver told to apply grain with
359+ /// no such target refuses the picture outright (radeonsi answers
360+ /// `vaEndPicture` with VA_STATUS_ERROR_INVALID_SURFACE).
361+ pub fn set_display_frame(&mut self, display: &Rc<Display>, frame: V) {
362+ let surface = frame
363+ .to_native_handle(display)
364+ .expect("Failed to export film grain target to vaapi picture!")
365+ .into();
366+ self.display = Some((Arc::new(frame), surface));
367+ }
368+
369+ /// The id [`Self::set_display_frame`] handed over, or `VA_INVALID_SURFACE`
370+ /// when this picture wants no grain -- which is what the picture parameter
371+ /// buffer's `current_display_picture` takes either way.
372+ pub fn display_surface_id(&self) -> libva::VASurfaceID {
373+ match &self.display {
374+ Some((_, surface)) => surface.id(),
375+ None => libva::VA_INVALID_SURFACE,
320 }376 }
321 }377 }
322 378
vendor/cros-codecs/src/decoder/stateless/av1/vaapi.rsmodified+35 -12
@@ -87,7 +87,16 @@ impl VaStreamInfo for &StreamInfo {
87 }87 }
88 88
89 fn min_num_surfaces(&self) -> usize {89 fn min_num_surfaces(&self) -> usize {
90- NUM_SURFACES90+ // LOCAL PATCH (see /Cargo.toml [patch.crates-io]): a sequence that may
91+ // synthesize film grain displays every grainy picture from a second
92+ // surface (`VaapiPicture::set_display_frame`), so every one of the frames
93+ // in flight -- the eight of the reference map, the one being decoded, the
94+ // ones handed out but not yet read back -- can cost two. A sequence whose
95+ // header says grain never happens is left at the count it always had.
96+ match self.seq_header.film_grain_params_present {
97+ true => 2 * NUM_SURFACES,
98+ false => NUM_SURFACES,
99+ }
91 }100 }
92 101
93 fn coded_size(&self) -> Resolution {102 fn coded_size(&self) -> Resolution {
@@ -106,10 +115,6 @@ impl From<&FrameHeaderObu> for libva::AV1FilmGrain {
106 fn from(hdr: &FrameHeaderObu) -> Self {115 fn from(hdr: &FrameHeaderObu) -> Self {
107 let fg = &hdr.film_grain_params;116 let fg = &hdr.film_grain_params;
108 117
109- if fg.apply_grain {
110- log::warn!("Film grain is not officially supported yet.")
111- }
112-
113 let film_grain_fields = libva::AV1FilmGrainFields::new(118 let film_grain_fields = libva::AV1FilmGrainFields::new(
114 u32::from(fg.apply_grain),119 u32::from(fg.apply_grain),
115 u32::from(fg.chroma_scaling_from_luma),120 u32::from(fg.chroma_scaling_from_luma),
@@ -238,6 +243,7 @@ fn build_pic_param<V: VideoFrame>(
238 hdr: &FrameHeaderObu,243 hdr: &FrameHeaderObu,
239 stream_info: &StreamInfo,244 stream_info: &StreamInfo,
240 current_frame: libva::VASurfaceID,245 current_frame: libva::VASurfaceID,
246+ current_display_picture: libva::VASurfaceID,
241 reference_frames: &[Option<VADecodedHandle<V>>; NUM_REF_FRAMES],247 reference_frames: &[Option<VADecodedHandle<V>>; NUM_REF_FRAMES],
242 ) -> anyhow::Result<libva::BufferType> {248 ) -> anyhow::Result<libva::BufferType> {
243 let seq = stream_info.seq_header.clone();249 let seq = stream_info.seq_header.clone();
@@ -414,8 +420,8 @@ fn build_pic_param<V: VideoFrame>(
414 .context("Invalid matrix_coefficients")?,420 .context("Invalid matrix_coefficients")?,
415 &seq_info_fields,421 &seq_info_fields,
416 current_frame,422 current_frame,
417- libva::VA_INVALID_SURFACE, /* film grain is unsupported for now */423+ current_display_picture,
418- vec![], /* anchor_frames_list */424+ vec![], /* anchor_frames_list */
419 u16::try_from(hdr.upscaled_width - 1).context("Invalid frame width")?,425 u16::try_from(hdr.upscaled_width - 1).context("Invalid frame width")?,
420 u16::try_from(hdr.frame_height - 1).context("Invalid frame height")?,426 u16::try_from(hdr.frame_height - 1).context("Invalid frame height")?,
421 0, /* output_frame_width_in_tiles_minus_1 */427 0, /* output_frame_width_in_tiles_minus_1 */
@@ -498,15 +504,26 @@ impl<V: VideoFrame> StatelessAV1DecoderBackend for VaapiBackend<V> {
498 504
499 fn new_picture(505 fn new_picture(
500 &mut self,506 &mut self,
501- _hdr: &FrameHeaderObu,507+ hdr: &FrameHeaderObu,
502 timestamp: u64,508 timestamp: u64,
503 alloc_cb: &mut dyn FnMut() -> Option<V>,509 alloc_cb: &mut dyn FnMut() -> Option<V>,
504 ) -> NewPictureResult<Self::Picture> {510 ) -> NewPictureResult<Self::Picture> {
505- Ok(VaapiPicture::new(511+ let mut picture = VaapiPicture::new(
506 timestamp,512 timestamp,
507 Rc::clone(&self.context),513 Rc::clone(&self.context),
508 alloc_cb().ok_or(NewPictureError::OutOfOutputBuffers)?,514 alloc_cb().ok_or(NewPictureError::OutOfOutputBuffers)?,
509- ))515+ );
516+ // LOCAL PATCH (see /Cargo.toml [patch.crates-io]): a frame that asks for
517+ // film grain is displayed from a second surface, so it costs two frames
518+ // of the pool rather than one -- which is why `min_num_surfaces` above
519+ // counts double for a sequence that may use grain. Failing the second
520+ // allocation drops the first back into the pool with the picture, and the
521+ // caller resubmits exactly as it does for the first.
522+ if hdr.film_grain_params.apply_grain {
523+ let frame = alloc_cb().ok_or(NewPictureError::OutOfOutputBuffers)?;
524+ picture.set_display_frame(self.context.display(), frame);
525+ }
526+ Ok(picture)
510 }527 }
511 528
512 fn begin_picture(529 fn begin_picture(
@@ -516,8 +533,14 @@ impl<V: VideoFrame> StatelessAV1DecoderBackend for VaapiBackend<V> {
516 hdr: &FrameHeaderObu,533 hdr: &FrameHeaderObu,
517 reference_frames: &[Option<Self::Handle>; NUM_REF_FRAMES],534 reference_frames: &[Option<Self::Handle>; NUM_REF_FRAMES],
518 ) -> StatelessBackendResult<()> {535 ) -> StatelessBackendResult<()> {
519- let pic_param = build_pic_param(hdr, stream_info, picture.surface().id(), reference_frames)536+ let pic_param = build_pic_param(
520- .context("Failed to build picture parameter")?;537+ hdr,
538+ stream_info,
539+ picture.surface().id(),
540+ picture.display_surface_id(),
541+ reference_frames,
542+ )
543+ .context("Failed to build picture parameter")?;
521 let pic_param = self544 let pic_param = self
522 .context545 .context
523 .create_buffer(pic_param)546 .create_buffer(pic_param)