forge
Explore
Log in

Don't you dare go Hollow

MVP decode pipeline — mp4 → H.264 → gpui preview

Browse files at this commit

0acbf8d9d315c21ef5f0dfc15d601dae4ea818d2Ahmet Kaan GümüşRoot commit (no parents)
  • feat
    • MVP decode pipeline — mp4 → H.264 → gpui preview
Show full message
🎉 feat: MVP decode pipeline — mp4 → H.264 → gpui preview

- engine: mp4 demux → Annex-B, rusty_h264 software decode, BT.601
  I420→BGRA; decode on worker thread behind a bounded channel
- engine-hw: optional VA-API decode plugin (cros-codecs) behind a
  C ABI, dlopen'd at runtime with silent software fallback; the app
  binary keeps zero libva/gbm/drm linkage so it runs on any distro
- app: gpui window, per-frame RenderImage swap + drop_image
- vendor/: cros-libva + cros-codecs with 3 LOCAL PATCH fixes (libva
  1.23 struct init, radeonsi 64x64 min context, pub surface()) —
  upstream is dormant, so vendor/ is adopted code, not a temp fork
- fixtures are gitignored; scripts/gen_fixtures.sh regenerates them

171 changed files +65247 -0

.gitignoreadded+2 -0
@@ -0,0 +1,2 @@
1+/target
2+/assets
Cargo.lockadded+7399 -0

Diff too large; view file

@@ -0,0 +1,7399 @@
1+# This file is automatically @generated by Cargo.
2+# It is not intended for manual editing.
3+version = 4
4+
5+[[package]]
6+name = "adler2"
7+version = "2.0.1"
8+source = "registry+https://github.com/rust-lang/crates.io-index"
9+checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa"
10+
11+[[package]]
12+name = "aes"
13+version = "0.8.4"
14+source = "registry+https://github.com/rust-lang/crates.io-index"
15+checksum = "b169f7a6d4742236a0a00c541b845991d0ac43e546831af1249753ab4c3aa3a0"
16+dependencies = [
17+ "cfg-if",
18+ "cipher",
19+ "cpufeatures 0.2.17",
20+ "zeroize",
21+]
22+
23+[[package]]
24+name = "ahash"
25+version = "0.8.12"
26+source = "registry+https://github.com/rust-lang/crates.io-index"
27+checksum = "5a15f179cd60c4584b8a8c596927aadc462e27f2ca70c04e0071964a73ba7a75"
28+dependencies = [
29+ "cfg-if",
30+ "const-random",
31+ "once_cell",
32+ "version_check",
33+ "zerocopy",
34+]
35+
36+[[package]]
37+name = "aho-corasick"
38+version = "1.1.5"
39+source = "registry+https://github.com/rust-lang/crates.io-index"
40+checksum = "c982642fa9e8606056828ee9a8505737230110bb1099153c79efe865c59d12ba"
41+dependencies = [
42+ "memchr",
43+]
44+
45+[[package]]
46+name = "aligned"
47+version = "0.4.3"
48+source = "registry+https://github.com/rust-lang/crates.io-index"
49+checksum = "ee4508988c62edf04abd8d92897fca0c2995d907ce1dfeaf369dac3716a40685"
50+dependencies = [
51+ "as-slice",
52+]
53+
54+[[package]]
55+name = "aligned-vec"
56+version = "0.6.4"
57+source = "registry+https://github.com/rust-lang/crates.io-index"
58+checksum = "dc890384c8602f339876ded803c97ad529f3842aba97f6392b3dba0dd171769b"
59+dependencies = [
60+ "equator",
61+]
62+
63+[[package]]
64+name = "anyhow"
65+version = "1.0.104"
66+source = "registry+https://github.com/rust-lang/crates.io-index"
67+checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470"
68+
69+[[package]]
70+name = "app"
71+version = "0.1.0"
72+dependencies = [
73+ "engine",
74+ "gpui",
75+ "image",
76+]
77+
78+[[package]]
79+name = "ar_archive_writer"
80+version = "0.5.3"
81+source = "registry+https://github.com/rust-lang/crates.io-index"
82+checksum = "73cd58deff2140a0a8eae87e417bd01db68a33e148aa93d1e8cd837e55e312b6"
83+dependencies = [
84+ "object",
85+]
86+
87+[[package]]
88+name = "arbitrary"
89+version = "1.4.2"
90+source = "registry+https://github.com/rust-lang/crates.io-index"
91+checksum = "c3d036a3c4ab069c7b410a2ce876bd74808d2d0888a82667669f8e783a898bf1"
92+
93+[[package]]
94+name = "arg_enum_proc_macro"
95+version = "0.3.4"
96+source = "registry+https://github.com/rust-lang/crates.io-index"
97+checksum = "0ae92a5119aa49cdbcf6b9f893fe4e1d98b04ccbf82ee0584ad948a44a734dea"
98+dependencies = [
99+ "proc-macro2",
100+ "quote",
101+ "syn 2.0.119",
102+]
103+
104+[[package]]
105+name = "arrayref"
106+version = "0.3.9"
107+source = "registry+https://github.com/rust-lang/crates.io-index"
108+checksum = "76a2e8124351fda1ef8aaaa3bbd7ebbcb486bbcd4225aca0aa0d84bb2db8fecb"
109+
110+[[package]]
111+name = "arrayvec"
112+version = "0.7.8"
113+source = "registry+https://github.com/rust-lang/crates.io-index"
114+checksum = "d3fb67a6e08acf24fdeccbac2cb6ac4305825bd1f117462e0e6f2f193345ad56"
115+
116+[[package]]
117+name = "as-raw-xcb-connection"
118+version = "1.0.1"
119+source = "registry+https://github.com/rust-lang/crates.io-index"
120+checksum = "175571dd1d178ced59193a6fc02dde1b972eb0bc56c892cde9beeceac5bf0f6b"
121+
122+[[package]]
123+name = "as-slice"
124+version = "0.2.1"
125+source = "registry+https://github.com/rust-lang/crates.io-index"
126+checksum = "516b6b4f0e40d50dcda9365d53964ec74560ad4284da2e7fc97122cd83174516"
127+dependencies = [
128+ "stable_deref_trait",
129+]
130+
131+[[package]]
132+name = "ash"
133+version = "0.38.0+1.3.281"
134+source = "registry+https://github.com/rust-lang/crates.io-index"
135+checksum = "0bb44936d800fea8f016d7f2311c6a4f97aebd5dc86f09906139ec848cf3a46f"
136+dependencies = [
137+ "libloading",
138+]
139+
140+[[package]]
141+name = "ash-window"
142+version = "0.13.0"
143+source = "registry+https://github.com/rust-lang/crates.io-index"
144+checksum = "52bca67b61cb81e5553babde81b8211f713cb6db79766f80168f3e5f40ea6c82"
145+dependencies = [
146+ "ash",
147+ "raw-window-handle",
148+ "raw-window-metal",
149+]
150+
151+[[package]]
152+name = "ashpd"
153+version = "0.11.1"
154+source = "registry+https://github.com/rust-lang/crates.io-index"
155+checksum = "d2f3f79755c74fd155000314eb349864caa787c6592eace6c6882dad873d9c39"
156+dependencies = [
157+ "async-fs",
158+ "async-net",
159+ "enumflags2",
160+ "futures-channel",
161+ "futures-util",
162+ "rand 0.9.5",
163+ "serde",
164+ "serde_repr",
165+ "url",
166+ "wayland-backend",
167+ "wayland-client",
168+ "wayland-protocols 0.32.13",
169+ "zbus",
170+]
171+
172+[[package]]
173+name = "ashpd"
174+version = "0.12.3"
175+source = "registry+https://github.com/rust-lang/crates.io-index"
176+checksum = "33a3c86f3fd70c0ffa500ed189abfa90b5a52398a45d5dc372fcc38ebeb7a645"
177+dependencies = [
178+ "async-fs",
179+ "async-net",
180+ "enumflags2",
181+ "futures-channel",
182+ "futures-util",
183+ "rand 0.9.5",
184+ "serde",
185+ "serde_repr",
186+ "url",
187+ "zbus",
188+]
189+
190+[[package]]
191+name = "async-broadcast"
192+version = "0.7.2"
193+source = "registry+https://github.com/rust-lang/crates.io-index"
194+checksum = "435a87a52755b8f27fcf321ac4f04b2802e337c8c4872923137471ec39c37532"
195+dependencies = [
196+ "event-listener 5.4.2",
197+ "event-listener-strategy",
198+ "futures-core",
199+ "pin-project-lite",
200+]
201+
202+[[package]]
203+name = "async-channel"
204+version = "1.9.0"
205+source = "registry+https://github.com/rust-lang/crates.io-index"
206+checksum = "81953c529336010edd6d8e358f886d9581267795c61b19475b71314bffa46d35"
207+dependencies = [
208+ "concurrent-queue",
209+ "event-listener 2.5.3",
210+ "futures-core",
211+]
212+
213+[[package]]
214+name = "async-channel"
215+version = "2.5.0"
216+source = "registry+https://github.com/rust-lang/crates.io-index"
217+checksum = "924ed96dd52d1b75e9c1a3e6275715fd320f5f9439fb5a4a11fa51f4221158d2"
218+dependencies = [
219+ "concurrent-queue",
220+ "event-listener-strategy",
221+ "futures-core",
222+ "pin-project-lite",
223+]
224+
225+[[package]]
226+name = "async-compression"
227+version = "0.4.43"
228+source = "registry+https://github.com/rust-lang/crates.io-index"
229+checksum = "3976abdc8fe7d1133d43d304afd42abdf5bc3e1319d263d223bde07b5efc4be8"
230+dependencies = [
231+ "compression-codecs",
232+ "compression-core",
233+ "futures-io",
234+ "pin-project-lite",
235+]
236+
237+[[package]]
238+name = "async-executor"
239+version = "1.14.0"
240+source = "registry+https://github.com/rust-lang/crates.io-index"
241+checksum = "c96bf972d85afc50bf5ab8fe2d54d1586b4e0b46c97c50a0c9e71e2f7bcd812a"
242+dependencies = [
243+ "async-task",
244+ "concurrent-queue",
245+ "fastrand 2.5.0",
246+ "futures-lite 2.6.1",
247+ "pin-project-lite",
248+ "slab",
249+]
250+
251+[[package]]
252+name = "async-fs"
253+version = "2.2.0"
254+source = "registry+https://github.com/rust-lang/crates.io-index"
255+checksum = "8034a681df4aed8b8edbd7fbe472401ecf009251c8b40556b304567052e294c5"
256+dependencies = [
257+ "async-lock",
258+ "blocking",
259+ "futures-lite 2.6.1",
260+]
261+
262+[[package]]
263+name = "async-global-executor"
264+version = "2.4.1"
265+source = "registry+https://github.com/rust-lang/crates.io-index"
266+checksum = "05b1b633a2115cd122d73b955eadd9916c18c8f510ec9cd1686404c60ad1c29c"
267+dependencies = [
268+ "async-channel 2.5.0",
269+ "async-executor",
270+ "async-io",
271+ "async-lock",
272+ "blocking",
273+ "futures-lite 2.6.1",
274+ "once_cell",
275+]
276+
277+[[package]]
278+name = "async-io"
279+version = "2.6.0"
280+source = "registry+https://github.com/rust-lang/crates.io-index"
281+checksum = "456b8a8feb6f42d237746d4b3e9a178494627745c3c56c6ea55d92ba50d026fc"
282+dependencies = [
283+ "autocfg",
284+ "cfg-if",
285+ "concurrent-queue",
286+ "futures-io",
287+ "futures-lite 2.6.1",
288+ "parking",
289+ "polling",
290+ "rustix 1.1.4",
291+ "slab",
292+ "windows-sys 0.61.2",
293+]
294+
295+[[package]]
296+name = "async-lock"
297+version = "3.4.2"
298+source = "registry+https://github.com/rust-lang/crates.io-index"
299+checksum = "290f7f2596bd5b78a9fec8088ccd89180d7f9f55b94b0576823bbbdc72ee8311"
300+dependencies = [
301+ "event-listener 5.4.2",
302+ "event-listener-strategy",
303+ "pin-project-lite",
304+]
305+
306+[[package]]
307+name = "async-net"
308+version = "2.0.0"
309+source = "registry+https://github.com/rust-lang/crates.io-index"
310+checksum = "b948000fad4873c1c9339d60f2623323a0cfd3816e5181033c6a5cb68b2accf7"
311+dependencies = [
312+ "async-io",
313+ "blocking",
314+ "futures-lite 2.6.1",
315+]
316+
317+[[package]]
318+name = "async-process"
319+version = "2.5.0"
320+source = "registry+https://github.com/rust-lang/crates.io-index"
321+checksum = "fc50921ec0055cdd8a16de48773bfeec5c972598674347252c0399676be7da75"
322+dependencies = [
323+ "async-channel 2.5.0",
324+ "async-io",
325+ "async-lock",
326+ "async-signal",
327+ "async-task",
328+ "blocking",
329+ "cfg-if",
330+ "event-listener 5.4.2",
331+ "futures-lite 2.6.1",
332+ "rustix 1.1.4",
333+]
334+
335+[[package]]
336+name = "async-recursion"
337+version = "1.1.1"
338+source = "registry+https://github.com/rust-lang/crates.io-index"
339+checksum = "3b43422f69d8ff38f95f1b2bb76517c91589a924d1559a0e935d7c8ce0274c11"
340+dependencies = [
341+ "proc-macro2",
342+ "quote",
343+ "syn 2.0.119",
344+]
345+
346+[[package]]
347+name = "async-signal"
348+version = "0.2.14"
349+source = "registry+https://github.com/rust-lang/crates.io-index"
350+checksum = "52b5aaafa020cf5053a01f2a60e8ff5dccf550f0f77ec54a4e47285ac2bab485"
351+dependencies = [
352+ "async-io",
353+ "async-lock",
354+ "atomic-waker",
355+ "cfg-if",
356+ "futures-core",
357+ "futures-io",
358+ "rustix 1.1.4",
359+ "signal-hook-registry",
360+ "slab",
361+ "windows-sys 0.61.2",
362+]
363+
364+[[package]]
365+name = "async-std"
366+version = "1.13.2"
367+source = "registry+https://github.com/rust-lang/crates.io-index"
368+checksum = "2c8e079a4ab67ae52b7403632e4618815d6db36d2a010cfe41b02c1b1578f93b"
369+dependencies = [
370+ "async-channel 1.9.0",
371+ "async-global-executor",
372+ "async-io",
373+ "async-lock",
374+ "async-process",
375+ "crossbeam-utils",
376+ "futures-channel",
377+ "futures-core",
378+ "futures-io",
379+ "futures-lite 2.6.1",
380+ "gloo-timers",
381+ "kv-log-macro",
382+ "log",
383+ "memchr",
384+ "once_cell",
385+ "pin-project-lite",
386+ "pin-utils",
387+ "slab",
388+ "wasm-bindgen-futures",
389+]
390+
391+[[package]]
392+name = "async-task"
393+version = "4.7.1"
394+source = "registry+https://github.com/rust-lang/crates.io-index"
395+checksum = "8b75356056920673b02621b35afd0f7dda9306d03c79a30f5c56c44cf256e3de"
396+
397+[[package]]
398+name = "async-trait"
399+version = "0.1.92"
400+source = "registry+https://github.com/rust-lang/crates.io-index"
401+checksum = "82f6aeea286b8eb4dd3431a1be1b59d290ace00f5bfd8e2a159bc2a05e2c1667"
402+dependencies = [
403+ "proc-macro2",
404+ "quote",
405+ "syn 3.0.3",
406+]
407+
408+[[package]]
409+name = "async_zip"
410+version = "0.0.17"
411+source = "registry+https://github.com/rust-lang/crates.io-index"
412+checksum = "00b9f7252833d5ed4b00aa9604b563529dd5e11de9c23615de2dcdf91eb87b52"
413+dependencies = [
414+ "async-compression",
415+ "crc32fast",
416+ "futures-lite 2.6.1",
417+ "pin-project",
418+ "thiserror 1.0.69",
419+]
420+
421+[[package]]
422+name = "atomic"
423+version = "0.5.3"
424+source = "registry+https://github.com/rust-lang/crates.io-index"
425+checksum = "c59bdb34bc650a32731b31bd8f0829cc15d24a708ee31559e0bb34f2bc320cba"
426+
427+[[package]]
428+name = "atomic-waker"
429+version = "1.1.2"
430+source = "registry+https://github.com/rust-lang/crates.io-index"
431+checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0"
432+
433+[[package]]
434+name = "autocfg"
435+version = "1.5.1"
436+source = "registry+https://github.com/rust-lang/crates.io-index"
437+checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53"
438+
439+[[package]]
440+name = "av-scenechange"
441+version = "0.14.1"
442+source = "registry+https://github.com/rust-lang/crates.io-index"
443+checksum = "0f321d77c20e19b92c39e7471cf986812cbb46659d2af674adc4331ef3f18394"
444+dependencies = [
445+ "aligned",
446+ "anyhow",
447+ "arg_enum_proc_macro",
448+ "arrayvec",
449+ "log",
450+ "num-rational",
451+ "num-traits",
452+ "pastey",
453+ "rayon",
454+ "thiserror 2.0.20",
455+ "v_frame",
456+ "y4m",
457+]
458+
459+[[package]]
460+name = "av1-grain"
461+version = "0.2.5"
462+source = "registry+https://github.com/rust-lang/crates.io-index"
463+checksum = "8cfddb07216410377231960af4fcab838eaa12e013417781b78bd95ee22077f8"
464+dependencies = [
465+ "anyhow",
466+ "arrayvec",
467+ "log",
468+ "nom 8.0.0",
469+ "num-rational",
470+ "v_frame",
471+]
472+
473+[[package]]
474+name = "avif-serialize"
475+version = "0.8.9"
476+source = "registry+https://github.com/rust-lang/crates.io-index"
477+checksum = "e7178fe5f7d460b13895ebb9dcb28a3a6216d2df2574a0806cb51b555d297f38"
478+dependencies = [
479+ "arrayvec",
480+]
481+
482+[[package]]
483+name = "base64"
484+version = "0.22.1"
485+source = "registry+https://github.com/rust-lang/crates.io-index"
486+checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6"
487+
488+[[package]]
489+name = "bindgen"
490+version = "0.70.1"
491+source = "registry+https://github.com/rust-lang/crates.io-index"
492+checksum = "f49d8fed880d473ea71efb9bf597651e77201bdd4893efe54c9e5d65ae04ce6f"
493+dependencies = [
494+ "bitflags 2.13.1",
495+ "cexpr",
496+ "clang-sys",
497+ "itertools 0.13.0",
498+ "log",
499+ "prettyplease",
500+ "proc-macro2",
501+ "quote",
502+ "regex",
503+ "rustc-hash 1.1.0",
504+ "shlex 1.3.0",
505+ "syn 2.0.119",
506+]
507+
508+[[package]]
509+name = "bindgen"
510+version = "0.71.1"
511+source = "registry+https://github.com/rust-lang/crates.io-index"
512+checksum = "5f58bf3d7db68cfbac37cfc485a8d711e87e064c3d0fe0435b92f7a407f9d6b3"
513+dependencies = [
514+ "bitflags 2.13.1",
515+ "cexpr",
516+ "clang-sys",
517+ "itertools 0.13.0",
518+ "log",
519+ "prettyplease",
520+ "proc-macro2",
521+ "quote",
522+ "regex",
523+ "rustc-hash 2.1.3",
524+ "shlex 1.3.0",
525+ "syn 2.0.119",
526+]
527+
528+[[package]]
529+name = "bit-set"
530+version = "0.8.0"
531+source = "registry+https://github.com/rust-lang/crates.io-index"
532+checksum = "08807e080ed7f9d5433fa9b275196cfc35414f66a0c79d864dc51a0d825231a3"
533+dependencies = [
534+ "bit-vec",
535+]
536+
537+[[package]]
538+name = "bit-vec"
539+version = "0.8.0"
540+source = "registry+https://github.com/rust-lang/crates.io-index"
541+checksum = "5e764a1d40d510daf35e07be9eb06e75770908c27d411ee6c92109c9840eaaf7"
542+
543+[[package]]
544+name = "bit_field"
545+version = "0.10.3"
546+source = "registry+https://github.com/rust-lang/crates.io-index"
547+checksum = "1e4b40c7323adcfc0a41c4b88143ed58346ff65a288fc144329c5c45e05d70c6"
548+
549+[[package]]
550+name = "bitflags"
551+version = "1.3.2"
552+source = "registry+https://github.com/rust-lang/crates.io-index"
553+checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a"
554+
555+[[package]]
556+name = "bitflags"
557+version = "2.13.1"
558+source = "registry+https://github.com/rust-lang/crates.io-index"
559+checksum = "b588b76d00fde79687d7646a9b5bdf3cc0f655e0bbd080335a95d7e96f3587da"
560+
561+[[package]]
562+name = "bitstream-io"
563+version = "4.10.0"
564+source = "registry+https://github.com/rust-lang/crates.io-index"
565+checksum = "7eff00be299a18769011411c9def0d827e8f2d7bf0c3dbf53633147a8867fd1f"
566+dependencies = [
567+ "no_std_io2",
568+]
569+
570+[[package]]
571+name = "blade-graphics"
572+version = "0.7.1"
573+source = "registry+https://github.com/rust-lang/crates.io-index"
574+checksum = "e71cfb73b98eb9f58ee84048aa1bdf4e7497fd20c141b57523499fa066b48fed"
575+dependencies = [
576+ "ash",
577+ "ash-window",
578+ "bitflags 2.13.1",
579+ "bytemuck",
580+ "codespan-reporting",
581+ "glow",
582+ "gpu-alloc",
583+ "gpu-alloc-ash",
584+ "hidden-trait",
585+ "js-sys",
586+ "khronos-egl",
587+ "libloading",
588+ "log",
589+ "mint",
590+ "naga",
591+ "objc2",
592+ "objc2-app-kit",
593+ "objc2-core-foundation",
594+ "objc2-foundation",
595+ "objc2-metal",
596+ "objc2-quartz-core",
597+ "objc2-ui-kit",
598+ "once_cell",
599+ "raw-window-handle",
600+ "slab",
601+ "wasm-bindgen",
602+ "web-sys",
603+]
604+
605+[[package]]
606+name = "blade-macros"
607+version = "0.3.0"
608+source = "registry+https://github.com/rust-lang/crates.io-index"
609+checksum = "27142319e2f4c264581067eaccb9f80acccdde60d8b4bf57cc50cd3152f109ca"
610+dependencies = [
611+ "proc-macro2",
612+ "quote",
613+ "syn 2.0.119",
614+]
615+
616+[[package]]
617+name = "blade-util"
618+version = "0.3.0"
619+source = "registry+https://github.com/rust-lang/crates.io-index"
620+checksum = "3a6be3a82c001ba7a17b6f8e413ede5d1004e6047213f8efaf0ffc15b5c4904c"
621+dependencies = [
622+ "blade-graphics",
623+ "bytemuck",
624+ "log",
625+ "profiling",
626+]
627+
628+[[package]]
629+name = "block"
630+version = "0.1.6"
631+source = "registry+https://github.com/rust-lang/crates.io-index"
632+checksum = "0d8c1fef690941d3e7788d328517591fecc684c084084702d6ff1641e993699a"
633+
634+[[package]]
635+name = "block-buffer"
636+version = "0.10.4"
637+source = "registry+https://github.com/rust-lang/crates.io-index"
638+checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71"
639+dependencies = [
640+ "generic-array",
641+]
642+
643+[[package]]
644+name = "block-buffer"
645+version = "0.12.1"
646+source = "registry+https://github.com/rust-lang/crates.io-index"
647+checksum = "d2f6c7dbe95a6ed67ad9f18e57daf93a2f034c524b99fd2b76d18fdfeb6660aa"
648+dependencies = [
649+ "hybrid-array",
650+]
651+
652+[[package]]
653+name = "block-padding"
654+version = "0.3.3"
655+source = "registry+https://github.com/rust-lang/crates.io-index"
656+checksum = "a8894febbff9f758034a5b8e12d87918f56dfc64a8e1fe757d65e29041538d93"
657+dependencies = [
658+ "generic-array",
659+]
660+
661+[[package]]
662+name = "block2"
663+version = "0.6.2"
664+source = "registry+https://github.com/rust-lang/crates.io-index"
665+checksum = "cdeb9d870516001442e364c5220d3574d2da8dc765554b4a617230d33fa58ef5"
666+dependencies = [
667+ "objc2",
668+]
669+
670+[[package]]
671+name = "blocking"
672+version = "1.6.2"
673+source = "registry+https://github.com/rust-lang/crates.io-index"
674+checksum = "e83f8d02be6967315521be875afa792a316e28d57b5a2d401897e2a7921b7f21"
675+dependencies = [
676+ "async-channel 2.5.0",
677+ "async-task",
678+ "futures-io",
679+ "futures-lite 2.6.1",
680+ "piper",
681+]
682+
683+[[package]]
684+name = "bstr"
685+version = "1.13.0"
686+source = "registry+https://github.com/rust-lang/crates.io-index"
687+checksum = "1f7dc094d718f2e1c1559ad110e27eeaae14a5465d3d56dd6dbd793079fbd530"
688+dependencies = [
689+ "memchr",
690+ "serde_core",
691+]
692+
693+[[package]]
694+name = "built"
695+version = "0.8.1"
696+source = "registry+https://github.com/rust-lang/crates.io-index"
697+checksum = "5c0e531d93d39c34eef561e929e8a7f86d77a5af08aac4f6d6e39976c51858e9"
698+
699+[[package]]
700+name = "bumpalo"
701+version = "3.20.3"
702+source = "registry+https://github.com/rust-lang/crates.io-index"
703+checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649"
704+
705+[[package]]
706+name = "bytemuck"
707+version = "1.25.2"
708+source = "registry+https://github.com/rust-lang/crates.io-index"
709+checksum = "95832e849adfb21180ccb6826a99da14e5d266ae5c2e668e1602cf234f153797"
710+dependencies = [
711+ "bytemuck_derive",
712+]
713+
714+[[package]]
715+name = "bytemuck_derive"
716+version = "1.12.0"
717+source = "registry+https://github.com/rust-lang/crates.io-index"
718+checksum = "fc0e56a716f1e132ff6bf4bdac1c944a3fcdc1cae65f70a4a2a1ac3b401d2d1f"
719+dependencies = [
720+ "proc-macro2",
721+ "quote",
722+ "syn 3.0.3",
723+]
724+
725+[[package]]
726+name = "byteorder"
727+version = "1.5.0"
728+source = "registry+https://github.com/rust-lang/crates.io-index"
729+checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b"
730+
731+[[package]]
732+name = "byteorder-lite"
733+version = "0.1.0"
734+source = "registry+https://github.com/rust-lang/crates.io-index"
735+checksum = "8f1fe948ff07f4bd06c30984e69f5b4899c516a3ef74f34df92a2df2ab535495"
736+
737+[[package]]
738+name = "bytes"
739+version = "1.12.1"
740+source = "registry+https://github.com/rust-lang/crates.io-index"
741+checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04"
742+
743+[[package]]
744+name = "calloop"
745+version = "0.13.0"
746+source = "registry+https://github.com/rust-lang/crates.io-index"
747+checksum = "b99da2f8558ca23c71f4fd15dc57c906239752dd27ff3c00a1d56b685b7cbfec"
748+dependencies = [
749+ "bitflags 2.13.1",
750+ "log",
751+ "polling",
752+ "rustix 0.38.44",
753+ "slab",
754+ "thiserror 1.0.69",
755+]
756+
757+[[package]]
758+name = "calloop-wayland-source"
759+version = "0.3.0"
760+source = "registry+https://github.com/rust-lang/crates.io-index"
761+checksum = "95a66a987056935f7efce4ab5668920b5d0dac4a7c99991a67395f13702ddd20"
762+dependencies = [
763+ "calloop",
764+ "rustix 0.38.44",
765+ "wayland-backend",
766+ "wayland-client",
767+]
768+
769+[[package]]
770+name = "cbc"
771+version = "0.1.2"
772+source = "registry+https://github.com/rust-lang/crates.io-index"
773+checksum = "26b52a9543ae338f279b96b0b9fed9c8093744685043739079ce85cd58f289a6"
774+dependencies = [
775+ "cipher",
776+]
777+
778+[[package]]
779+name = "cbindgen"
780+version = "0.28.0"
781+source = "registry+https://github.com/rust-lang/crates.io-index"
782+checksum = "eadd868a2ce9ca38de7eeafdcec9c7065ef89b42b32f0839278d55f35c54d1ff"
783+dependencies = [
784+ "heck 0.4.1",
785+ "indexmap",
786+ "log",
787+ "proc-macro2",
788+ "quote",
789+ "serde",
790+ "serde_json",
791+ "syn 2.0.119",
792+ "tempfile",
793+ "toml 0.8.23",
794+]
795+
796+[[package]]
797+name = "cc"
798+version = "1.4.2"
799+source = "registry+https://github.com/rust-lang/crates.io-index"
800+checksum = "5d262e149917187838d5b42777c8253bcb64500067342904e7d429499a6f277e"
801+dependencies = [
802+ "find-msvc-tools",
803+ "jobserver",
804+ "libc",
805+ "shlex 2.0.1",
806+]
807+
808+[[package]]
809+name = "cexpr"
810+version = "0.6.0"
811+source = "registry+https://github.com/rust-lang/crates.io-index"
812+checksum = "6fac387a98bb7c37292057cffc56d62ecb629900026402633ae9160df93a8766"
813+dependencies = [
814+ "nom 7.1.3",
815+]
816+
817+[[package]]
818+name = "cfg-if"
819+version = "1.0.4"
820+source = "registry+https://github.com/rust-lang/crates.io-index"
821+checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801"
822+
823+[[package]]
824+name = "cfg_aliases"
825+version = "0.1.1"
826+source = "registry+https://github.com/rust-lang/crates.io-index"
827+checksum = "fd16c4719339c4530435d38e511904438d07cce7950afa3718a84ac36c10e89e"
828+
829+[[package]]
830+name = "cfg_aliases"
831+version = "0.2.2"
832+source = "registry+https://github.com/rust-lang/crates.io-index"
833+checksum = "f079e83a288787bcd14a6aea84cee5c87a67c5a3e660c30f557a3d24761b3527"
834+
835+[[package]]
836+name = "cgl"
837+version = "0.3.2"
838+source = "registry+https://github.com/rust-lang/crates.io-index"
839+checksum = "0ced0551234e87afee12411d535648dd89d2e7f34c78b753395567aff3d447ff"
840+dependencies = [
841+ "libc",
842+]
843+
844+[[package]]
845+name = "chacha20"
846+version = "0.10.1"
847+source = "registry+https://github.com/rust-lang/crates.io-index"
848+checksum = "d524456ba66e72eb8b115ff89e01e497f8e6d11d78b70b1aa13c0fbd97540a81"
849+dependencies = [
850+ "cfg-if",
851+ "cpufeatures 0.3.0",
852+ "rand_core 0.10.1",
853+]
854+
855+[[package]]
856+name = "cipher"
857+version = "0.4.4"
858+source = "registry+https://github.com/rust-lang/crates.io-index"
859+checksum = "773f3b9af64447d2ce9850330c473515014aa235e6a783b02db81ff39e4a3dad"
860+dependencies = [
861+ "crypto-common 0.1.7",
862+ "inout",
863+ "zeroize",
864+]
865+
866+[[package]]
867+name = "clang-sys"
868+version = "1.9.1"
869+source = "registry+https://github.com/rust-lang/crates.io-index"
870+checksum = "157a8ba7b480713b56f4c09fd13fc3e0a22a5dfab8097ba61cbc5feef950788a"
871+dependencies = [
872+ "glob",
873+ "libc",
874+ "libloading",
875+]
876+
877+[[package]]
878+name = "cocoa"
879+version = "0.25.0"
880+source = "registry+https://github.com/rust-lang/crates.io-index"
881+checksum = "f6140449f97a6e97f9511815c5632d84c8aacf8ac271ad77c559218161a1373c"
882+dependencies = [
883+ "bitflags 1.3.2",
884+ "block",
885+ "cocoa-foundation 0.1.2",
886+ "core-foundation 0.9.4",
887+ "core-graphics 0.23.2",
888+ "foreign-types",
889+ "libc",
890+ "objc",
891+]
892+
893+[[package]]
894+name = "cocoa"
895+version = "0.26.0"
896+source = "registry+https://github.com/rust-lang/crates.io-index"
897+checksum = "f79398230a6e2c08f5c9760610eb6924b52aa9e7950a619602baba59dcbbdbb2"
898+dependencies = [
899+ "bitflags 2.13.1",
900+ "block",
901+ "cocoa-foundation 0.2.0",
902+ "core-foundation 0.10.0",
903+ "core-graphics 0.24.0",
904+ "foreign-types",
905+ "libc",
906+ "objc",
907+]
908+
909+[[package]]
910+name = "cocoa-foundation"
911+version = "0.1.2"
912+source = "registry+https://github.com/rust-lang/crates.io-index"
913+checksum = "8c6234cbb2e4c785b456c0644748b1ac416dd045799740356f8363dfe00c93f7"
914+dependencies = [
915+ "bitflags 1.3.2",
916+ "block",
917+ "core-foundation 0.9.4",
918+ "core-graphics-types 0.1.3",
919+ "libc",
920+ "objc",
921+]
922+
923+[[package]]
924+name = "cocoa-foundation"
925+version = "0.2.0"
926+source = "registry+https://github.com/rust-lang/crates.io-index"
927+checksum = "e14045fb83be07b5acf1c0884b2180461635b433455fa35d1cd6f17f1450679d"
928+dependencies = [
929+ "bitflags 2.13.1",
930+ "block",
931+ "core-foundation 0.10.0",
932+ "core-graphics-types 0.2.0",
933+ "libc",
934+ "objc",
935+]
936+
937+[[package]]
938+name = "codespan-reporting"
939+version = "0.12.0"
940+source = "registry+https://github.com/rust-lang/crates.io-index"
941+checksum = "fe6d2e5af09e8c8ad56c969f2157a3d4238cebc7c55f0a517728c38f7b200f81"
942+dependencies = [
943+ "serde",
944+ "termcolor",
945+ "unicode-width",
946+]
947+
948+[[package]]
949+name = "color_quant"
950+version = "1.1.0"
951+source = "registry+https://github.com/rust-lang/crates.io-index"
952+checksum = "3d7b894f5411737b7867f4827955924d7c254fc9f4d91a6aad6b097804b1018b"
953+
954+[[package]]
955+name = "command-fds"
956+version = "0.3.3"
957+source = "registry+https://github.com/rust-lang/crates.io-index"
958+checksum = "1b60b5124979fccd9addd89d8b97a1d6eebb4950694520c75ddd722535ea443f"
959+dependencies = [
960+ "nix 0.31.3",
961+ "thiserror 2.0.20",
962+]
963+
964+[[package]]
965+name = "compression-codecs"
966+version = "0.4.38"
967+source = "registry+https://github.com/rust-lang/crates.io-index"
968+checksum = "ce2548391e9c1929c21bf6aa2680af86fe4c1b33e6cea9ac1cfeec0bd11218cf"
969+dependencies = [
970+ "compression-core",
971+ "deflate64",
972+ "flate2",
973+ "memchr",
974+]
975+
976+[[package]]
977+name = "compression-core"
978+version = "0.4.32"
979+source = "registry+https://github.com/rust-lang/crates.io-index"
980+checksum = "cc14f565cf027a105f7a44ccf9e5b424348421a1d8952a8fc9d499d313107789"
981+
982+[[package]]
983+name = "concurrent-queue"
984+version = "2.5.0"
985+source = "registry+https://github.com/rust-lang/crates.io-index"
986+checksum = "4ca0197aee26d1ae37445ee532fefce43251d24cc7c166799f4d46817f1d3973"
987+dependencies = [
988+ "crossbeam-utils",
989+]
990+
991+[[package]]
992+name = "const-oid"
993+version = "0.10.2"
994+source = "registry+https://github.com/rust-lang/crates.io-index"
995+checksum = "a6ef517f0926dd24a1582492c791b6a4818a4d94e789a334894aa15b0d12f55c"
996+
997+[[package]]
998+name = "const-random"
999+version = "0.1.18"
1000+source = "registry+https://github.com/rust-lang/crates.io-index"
1001+checksum = "87e00182fe74b066627d63b85fd550ac2998d4b0bd86bfed477a0ae4c7c71359"
1002+dependencies = [
1003+ "const-random-macro",
1004+]
1005+
1006+[[package]]
1007+name = "const-random-macro"
1008+version = "0.1.16"
1009+source = "registry+https://github.com/rust-lang/crates.io-index"
1010+checksum = "f9d839f2a20b0aee515dc581a6172f2321f96cab76c1a38a4c584a194955390e"
1011+dependencies = [
1012+ "getrandom 0.2.17",
1013+ "once_cell",
1014+ "tiny-keccak",
1015+]
1016+
1017+[[package]]
1018+name = "convert_case"
1019+version = "0.4.0"
1020+source = "registry+https://github.com/rust-lang/crates.io-index"
1021+checksum = "6245d59a3e82a7fc217c5828a6692dbc6dfb63a0c8c90495621f7b9d79704a0e"
1022+
1023+[[package]]
1024+name = "core-foundation"
1025+version = "0.9.4"
1026+source = "registry+https://github.com/rust-lang/crates.io-index"
1027+checksum = "91e195e091a93c46f7102ec7818a2aa394e1e1771c3ab4825963fa03e45afb8f"
1028+dependencies = [
1029+ "core-foundation-sys",
1030+ "libc",
1031+]
1032+
1033+[[package]]
1034+name = "core-foundation"
1035+version = "0.10.0"
1036+source = "registry+https://github.com/rust-lang/crates.io-index"
1037+checksum = "b55271e5c8c478ad3f38ad24ef34923091e0548492a266d19b3c0b4d82574c63"
1038+dependencies = [
1039+ "core-foundation-sys",
1040+ "libc",
1041+]
1042+
1043+[[package]]
1044+name = "core-foundation-sys"
1045+version = "0.8.7"
1046+source = "registry+https://github.com/rust-lang/crates.io-index"
1047+checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b"
1048+
1049+[[package]]
1050+name = "core-graphics"
1051+version = "0.23.2"
1052+source = "registry+https://github.com/rust-lang/crates.io-index"
1053+checksum = "c07782be35f9e1140080c6b96f0d44b739e2278479f64e02fdab4e32dfd8b081"
1054+dependencies = [
1055+ "bitflags 1.3.2",
1056+ "core-foundation 0.9.4",
1057+ "core-graphics-types 0.1.3",
1058+ "foreign-types",
1059+ "libc",
1060+]
1061+
1062+[[package]]
1063+name = "core-graphics"
1064+version = "0.24.0"
1065+source = "registry+https://github.com/rust-lang/crates.io-index"
1066+checksum = "fa95a34622365fa5bbf40b20b75dba8dfa8c94c734aea8ac9a5ca38af14316f1"
1067+dependencies = [
1068+ "bitflags 2.13.1",
1069+ "core-foundation 0.10.0",
1070+ "core-graphics-types 0.2.0",
1071+ "foreign-types",
1072+ "libc",
1073+]
1074+
1075+[[package]]
1076+name = "core-graphics-helmer-fork"
1077+version = "0.24.0"
1078+source = "registry+https://github.com/rust-lang/crates.io-index"
1079+checksum = "32eb7c354ae9f6d437a6039099ce7ecd049337a8109b23d73e48e8ffba8e9cd5"
1080+dependencies = [
1081+ "bitflags 2.13.1",
1082+ "core-foundation 0.9.4",
1083+ "core-graphics-types 0.1.3",
1084+ "foreign-types",
1085+ "libc",
1086+]
1087+
1088+[[package]]
1089+name = "core-graphics-types"
1090+version = "0.1.3"
1091+source = "registry+https://github.com/rust-lang/crates.io-index"
1092+checksum = "45390e6114f68f718cc7a830514a96f903cccd70d02a8f6d9f643ac4ba45afaf"
1093+dependencies = [
1094+ "bitflags 1.3.2",
1095+ "core-foundation 0.9.4",
1096+ "libc",
1097+]
1098+
1099+[[package]]
1100+name = "core-graphics-types"
1101+version = "0.2.0"
1102+source = "registry+https://github.com/rust-lang/crates.io-index"
1103+checksum = "3d44a101f213f6c4cdc1853d4b78aef6db6bdfa3468798cc1d9912f4735013eb"
1104+dependencies = [
1105+ "bitflags 2.13.1",
1106+ "core-foundation 0.10.0",
1107+ "libc",
1108+]
1109+
1110+[[package]]
1111+name = "core-graphics2"
1112+version = "0.4.1"
1113+source = "registry+https://github.com/rust-lang/crates.io-index"
1114+checksum = "7e4583956b9806b69f73fcb23aee05eb3620efc282972f08f6a6db7504f8334d"
1115+dependencies = [
1116+ "bitflags 2.13.1",
1117+ "block",
1118+ "cfg-if",
1119+ "core-foundation 0.10.0",
1120+ "libc",
1121+]
1122+
1123+[[package]]
1124+name = "core-text"
1125+version = "21.0.0"
1126+source = "registry+https://github.com/rust-lang/crates.io-index"
1127+checksum = "a593227b66cbd4007b2a050dfdd9e1d1318311409c8d600dc82ba1b15ca9c130"
1128+dependencies = [
1129+ "core-foundation 0.10.0",
1130+ "core-graphics 0.24.0",
1131+ "foreign-types",
1132+ "libc",
1133+]
1134+
1135+[[package]]
1136+name = "core-video"
1137+version = "0.4.3"
1138+source = "registry+https://github.com/rust-lang/crates.io-index"
1139+checksum = "d45e71d5be22206bed53c3c3cb99315fc4c3d31b8963808c6bc4538168c4f8ef"
1140+dependencies = [
1141+ "block",
1142+ "core-foundation 0.10.0",
1143+ "core-graphics2",
1144+ "io-surface",
1145+ "libc",
1146+ "metal",
1147+]
1148+
1149+[[package]]
1150+name = "core_maths"
1151+version = "0.1.1"
1152+source = "registry+https://github.com/rust-lang/crates.io-index"
1153+checksum = "77745e017f5edba1a9c1d854f6f3a52dac8a12dd5af5d2f54aecf61e43d80d30"
1154+dependencies = [
1155+ "libm",
1156+]
1157+
1158+[[package]]
1159+name = "cosmic-text"
1160+version = "0.14.2"
1161+source = "registry+https://github.com/rust-lang/crates.io-index"
1162+checksum = "da46a9d5a8905cc538a4a5bceb6a4510de7a51049c5588c0114efce102bcbbe8"
1163+dependencies = [
1164+ "bitflags 2.13.1",
1165+ "fontdb 0.16.2",
1166+ "log",
1167+ "rangemap",
1168+ "rustc-hash 1.1.0",
1169+ "rustybuzz 0.14.1",
1170+ "self_cell",
1171+ "smol_str",
1172+ "swash",
1173+ "sys-locale",
1174+ "ttf-parser 0.21.1",
1175+ "unicode-bidi",
1176+ "unicode-linebreak",
1177+ "unicode-script",
1178+ "unicode-segmentation",
1179+]
1180+
1181+[[package]]
1182+name = "cpufeatures"
1183+version = "0.2.17"
1184+source = "registry+https://github.com/rust-lang/crates.io-index"
1185+checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280"
1186+dependencies = [
1187+ "libc",
1188+]
1189+
1190+[[package]]
1191+name = "cpufeatures"
1192+version = "0.3.0"
1193+source = "registry+https://github.com/rust-lang/crates.io-index"
1194+checksum = "8b2a41393f66f16b0823bb79094d54ac5fbd34ab292ddafb9a0456ac9f87d201"
1195+dependencies = [
1196+ "libc",
1197+]
1198+
1199+[[package]]
1200+name = "crc32fast"
1201+version = "1.5.0"
1202+source = "registry+https://github.com/rust-lang/crates.io-index"
1203+checksum = "9481c1c90cbf2ac953f07c8d4a58aa3945c425b7185c9154d67a65e4230da511"
1204+dependencies = [
1205+ "cfg-if",
1206+]
1207+
1208+[[package]]
1209+name = "cros-codecs"
1210+version = "0.0.6"
1211+dependencies = [
1212+ "anyhow",
1213+ "byteorder",
1214+ "crc32fast",
1215+ "cros-libva",
1216+ "drm",
1217+ "drm-fourcc",
1218+ "gbm",
1219+ "gbm-sys",
1220+ "log",
1221+ "nix 0.28.0",
1222+ "thiserror 1.0.69",
1223+ "zerocopy",
1224+]
1225+
1226+[[package]]
1227+name = "cros-libva"
1228+version = "0.0.12"
1229+dependencies = [
1230+ "bindgen 0.70.1",
1231+ "bitflags 2.13.1",
1232+ "log",
1233+ "pkg-config",
1234+ "regex",
1235+ "thiserror 1.0.69",
1236+]
1237+
1238+[[package]]
1239+name = "crossbeam-deque"
1240+version = "0.8.7"
1241+source = "registry+https://github.com/rust-lang/crates.io-index"
1242+checksum = "5181e0de7b61eb03a81e347d6dd8797bae9da5146707b51077e2d71a54ec0ceb"
1243+dependencies = [
1244+ "crossbeam-epoch",
1245+ "crossbeam-utils",
1246+]
1247+
1248+[[package]]
1249+name = "crossbeam-epoch"
1250+version = "0.9.20"
1251+source = "registry+https://github.com/rust-lang/crates.io-index"
1252+checksum = "2d6914041f254d6e9176c01941b21115dcfb7089e55135a35411081bd106ef3f"
1253+dependencies = [
1254+ "crossbeam-utils",
1255+]
1256+
1257+[[package]]
1258+name = "crossbeam-queue"
1259+version = "0.3.13"
1260+source = "registry+https://github.com/rust-lang/crates.io-index"
1261+checksum = "803d13fb3b09d88be9f4dbc29062c66b19bf7170867ceb746d2a8689bf6c7a26"
1262+dependencies = [
1263+ "crossbeam-utils",
1264+]
1265+
1266+[[package]]
1267+name = "crossbeam-utils"
1268+version = "0.8.22"
1269+source = "registry+https://github.com/rust-lang/crates.io-index"
1270+checksum = "61803da095bee82a81bb1a452ecc25d3b2f1416d1897eb86430c6159ef717c17"
1271+
1272+[[package]]
1273+name = "crunchy"
1274+version = "0.2.4"
1275+source = "registry+https://github.com/rust-lang/crates.io-index"
1276+checksum = "460fbee9c2c2f33933d720630a6a0bac33ba7053db5344fac858d4b8952d77d5"
1277+
1278+[[package]]
1279+name = "crypto-common"
1280+version = "0.1.7"
1281+source = "registry+https://github.com/rust-lang/crates.io-index"
1282+checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a"
1283+dependencies = [
1284+ "generic-array",
1285+ "rand_core 0.6.4",
1286+ "typenum",
1287+]
1288+
1289+[[package]]
1290+name = "crypto-common"
1291+version = "0.2.2"
1292+source = "registry+https://github.com/rust-lang/crates.io-index"
1293+checksum = "ce6e4c961d6cd6c9a86db418387425e8bdeaf05b3c8bc1411e6dca4c252f1453"
1294+dependencies = [
1295+ "hybrid-array",
1296+]
1297+
1298+[[package]]
1299+name = "ctor"
1300+version = "0.4.3"
1301+source = "registry+https://github.com/rust-lang/crates.io-index"
1302+checksum = "ec09e802f5081de6157da9a75701d6c713d8dc3ba52571fd4bd25f412644e8a6"
1303+dependencies = [
1304+ "ctor-proc-macro",
1305+ "dtor",
1306+]
1307+
1308+[[package]]
1309+name = "ctor-proc-macro"
1310+version = "0.0.6"
1311+source = "registry+https://github.com/rust-lang/crates.io-index"
1312+checksum = "e2931af7e13dc045d8e9d26afccc6fa115d64e115c9c84b1166288b46f6782c2"
1313+
1314+[[package]]
1315+name = "data-url"
1316+version = "0.3.2"
1317+source = "registry+https://github.com/rust-lang/crates.io-index"
1318+checksum = "be1e0bca6c3637f992fc1cc7cbc52a78c1ef6db076dbf1059c4323d6a2048376"
1319+
1320+[[package]]
1321+name = "deflate64"
1322+version = "0.1.12"
1323+source = "registry+https://github.com/rust-lang/crates.io-index"
1324+checksum = "ac6b926516df9c60bfa16e107b21086399f8285a44ca9711344b9e553c5146e2"
1325+
1326+[[package]]
1327+name = "derive_more"
1328+version = "0.99.20"
1329+source = "registry+https://github.com/rust-lang/crates.io-index"
1330+checksum = "6edb4b64a43d977b8e99788fe3a04d483834fba1215a7e02caa415b626497f7f"
1331+dependencies = [
1332+ "convert_case",
1333+ "proc-macro2",
1334+ "quote",
1335+ "rustc_version",
1336+ "syn 2.0.119",
1337+]
1338+
1339+[[package]]
1340+name = "digest"
1341+version = "0.10.7"
1342+source = "registry+https://github.com/rust-lang/crates.io-index"
1343+checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292"
1344+dependencies = [
1345+ "block-buffer 0.10.4",
1346+ "crypto-common 0.1.7",
1347+ "subtle",
1348+]
1349+
1350+[[package]]
1351+name = "digest"
1352+version = "0.11.3"
1353+source = "registry+https://github.com/rust-lang/crates.io-index"
1354+checksum = "f1dd6dbb5841937940781866fa1281a1ff7bd3bf827091440879f9994983d5c2"
1355+dependencies = [
1356+ "block-buffer 0.12.1",
1357+ "const-oid",
1358+ "crypto-common 0.2.2",
1359+]
1360+
1361+[[package]]
1362+name = "dirs"
1363+version = "4.0.0"
1364+source = "registry+https://github.com/rust-lang/crates.io-index"
1365+checksum = "ca3aa72a6f96ea37bbc5aa912f6788242832f75369bdfdadcb0e38423f100059"
1366+dependencies = [
1367+ "dirs-sys 0.3.7",
1368+]
1369+
1370+[[package]]
1371+name = "dirs"
1372+version = "5.0.1"
1373+source = "registry+https://github.com/rust-lang/crates.io-index"
1374+checksum = "44c45a9d03d6676652bcb5e724c7e988de1acad23a711b5217ab9cbecbec2225"
1375+dependencies = [
1376+ "dirs-sys 0.4.1",
1377+]
1378+
1379+[[package]]
1380+name = "dirs-sys"
1381+version = "0.3.7"
1382+source = "registry+https://github.com/rust-lang/crates.io-index"
1383+checksum = "1b1d1d91c932ef41c0f2663aa8b0ca0342d444d842c06914aa0a7e352d0bada6"
1384+dependencies = [
1385+ "libc",
1386+ "redox_users",
1387+ "winapi",
1388+]
1389+
1390+[[package]]
1391+name = "dirs-sys"
1392+version = "0.4.1"
1393+source = "registry+https://github.com/rust-lang/crates.io-index"
1394+checksum = "520f05a5cbd335fae5a99ff7a6ab8627577660ee5cfd6a94a6a929b52ff0321c"
1395+dependencies = [
1396+ "libc",
1397+ "option-ext",
1398+ "redox_users",
1399+ "windows-sys 0.48.0",
1400+]
1401+
1402+[[package]]
1403+name = "dispatch"
1404+version = "0.2.0"
1405+source = "registry+https://github.com/rust-lang/crates.io-index"
1406+checksum = "bd0c93bb4b0c6d9b77f4435b0ae98c24d17f1c45b2ff844c6151a07256ca923b"
1407+
1408+[[package]]
1409+name = "dispatch2"
1410+version = "0.3.1"
1411+source = "registry+https://github.com/rust-lang/crates.io-index"
1412+checksum = "1e0e367e4e7da84520dedcac1901e4da967309406d1e51017ae1abfb97adbd38"
1413+dependencies = [
1414+ "bitflags 2.13.1",
1415+ "objc2",
1416+]
1417+
1418+[[package]]
1419+name = "displaydoc"
1420+version = "0.2.7"
1421+source = "registry+https://github.com/rust-lang/crates.io-index"
1422+checksum = "c6232dd377dcc64799954cbd3a9bb882e9cdc1308ccd87b1c098f1fb2eaf82a8"
1423+dependencies = [
1424+ "proc-macro2",
1425+ "quote",
1426+ "syn 3.0.3",
1427+]
1428+
1429+[[package]]
1430+name = "dlib"
1431+version = "0.5.3"
1432+source = "registry+https://github.com/rust-lang/crates.io-index"
1433+checksum = "ab8ecd87370524b461f8557c119c405552c396ed91fc0a8eec68679eab26f94a"
1434+dependencies = [
1435+ "libloading",
1436+]
1437+
1438+[[package]]
1439+name = "downcast-rs"
1440+version = "1.2.1"
1441+source = "registry+https://github.com/rust-lang/crates.io-index"
1442+checksum = "75b325c5dbd37f80359721ad39aca5a29fb04c89279657cffdda8736d0c0b9d2"
1443+
1444+[[package]]
1445+name = "drm"
1446+version = "0.12.0"
1447+source = "registry+https://github.com/rust-lang/crates.io-index"
1448+checksum = "98888c4bbd601524c11a7ed63f814b8825f420514f78e96f752c437ae9cbb5d1"
1449+dependencies = [
1450+ "bitflags 2.13.1",
1451+ "bytemuck",
1452+ "drm-ffi",
1453+ "drm-fourcc",
1454+ "rustix 0.38.44",
1455+]
1456+
1457+[[package]]
1458+name = "drm-ffi"
1459+version = "0.8.0"
1460+source = "registry+https://github.com/rust-lang/crates.io-index"
1461+checksum = "97c98727e48b7ccb4f4aea8cfe881e5b07f702d17b7875991881b41af7278d53"
1462+dependencies = [
1463+ "drm-sys",
1464+ "rustix 0.38.44",
1465+]
1466+
1467+[[package]]
1468+name = "drm-fourcc"
1469+version = "2.2.0"
1470+source = "registry+https://github.com/rust-lang/crates.io-index"
1471+checksum = "0aafbcdb8afc29c1a7ee5fbe53b5d62f4565b35a042a662ca9fecd0b54dae6f4"
1472+
1473+[[package]]
1474+name = "drm-sys"
1475+version = "0.7.0"
1476+source = "registry+https://github.com/rust-lang/crates.io-index"
1477+checksum = "fd39dde40b6e196c2e8763f23d119ddb1a8714534bf7d77fa97a65b0feda3986"
1478+dependencies = [
1479+ "libc",
1480+ "linux-raw-sys 0.6.5",
1481+]
1482+
1483+[[package]]
1484+name = "dtor"
1485+version = "0.0.6"
1486+source = "registry+https://github.com/rust-lang/crates.io-index"
1487+checksum = "97cbdf2ad6846025e8e25df05171abfb30e3ababa12ee0a0e44b9bbe570633a8"
1488+dependencies = [
1489+ "dtor-proc-macro",
1490+]
1491+
1492+[[package]]
1493+name = "dtor-proc-macro"
1494+version = "0.0.5"
1495+source = "registry+https://github.com/rust-lang/crates.io-index"
1496+checksum = "7454e41ff9012c00d53cf7f475c5e3afa3b91b7c90568495495e8d9bf47a1055"
1497+
1498+[[package]]
1499+name = "dunce"
1500+version = "1.0.5"
1501+source = "registry+https://github.com/rust-lang/crates.io-index"
1502+checksum = "92773504d58c093f6de2459af4af33faa518c13451eb8f2b5698ed3d36e7c813"
1503+
1504+[[package]]
1505+name = "dwrote"
1506+version = "0.11.5"
1507+source = "registry+https://github.com/rust-lang/crates.io-index"
1508+checksum = "9e1b35532432acc8b19ceed096e35dfa088d3ea037fe4f3c085f1f97f33b4d02"
1509+dependencies = [
1510+ "lazy_static",
1511+ "libc",
1512+ "winapi",
1513+ "wio",
1514+]
1515+
1516+[[package]]
1517+name = "dyn-clone"
1518+version = "1.0.20"
1519+source = "registry+https://github.com/rust-lang/crates.io-index"
1520+checksum = "d0881ea181b1df73ff77ffaaf9c7544ecc11e82fba9b5f27b262a3c73a332555"
1521+
1522+[[package]]
1523+name = "either"
1524+version = "1.17.0"
1525+source = "registry+https://github.com/rust-lang/crates.io-index"
1526+checksum = "9e5e8f6c15a24b9a3ee5efec809ccd006d3b30e8b3bb63c39af737c7f87daa1d"
1527+
1528+[[package]]
1529+name = "embed-resource"
1530+version = "3.0.11"
1531+source = "registry+https://github.com/rust-lang/crates.io-index"
1532+checksum = "fbfdaacccebec3b28e4866b8973543c7647797db5ada1bdab552e48fe665fbbd"
1533+dependencies = [
1534+ "cc",
1535+ "memchr",
1536+ "rustc_version",
1537+ "toml 1.1.4+spec-1.1.0",
1538+ "vswhom",
1539+ "winreg",
1540+]
1541+
1542+[[package]]
1543+name = "encoding_rs"
1544+version = "0.8.35"
1545+source = "registry+https://github.com/rust-lang/crates.io-index"
1546+checksum = "75030f3c4f45dafd7586dd6780965a8c7e8e285a5ecb86713e63a79c5b2766f3"
1547+dependencies = [
1548+ "cfg-if",
1549+]
1550+
1551+[[package]]
1552+name = "endi"
1553+version = "1.1.1"
1554+source = "registry+https://github.com/rust-lang/crates.io-index"
1555+checksum = "66b7e2430c6dff6a955451e2cfc438f09cea1965a9d6f87f7e3b90decc014099"
1556+
1557+[[package]]
1558+name = "engine"
1559+version = "0.1.0"
1560+dependencies = [
1561+ "libloading",
1562+ "mp4",
1563+ "rusty_h264",
1564+]
1565+
1566+[[package]]
1567+name = "engine-hw"
1568+version = "0.1.0"
1569+dependencies = [
1570+ "cros-codecs",
1571+ "engine",
1572+ "gbm",
1573+]
1574+
1575+[[package]]
1576+name = "enumflags2"
1577+version = "0.7.12"
1578+source = "registry+https://github.com/rust-lang/crates.io-index"
1579+checksum = "1027f7680c853e056ebcec683615fb6fbbc07dbaa13b4d5d9442b146ded4ecef"
1580+dependencies = [
1581+ "enumflags2_derive",
1582+ "serde",
1583+]
1584+
1585+[[package]]
1586+name = "enumflags2_derive"
1587+version = "0.7.12"
1588+source = "registry+https://github.com/rust-lang/crates.io-index"
1589+checksum = "67c78a4d8fdf9953a5c9d458f9efe940fd97a0cab0941c075a813ac594733827"
1590+dependencies = [
1591+ "proc-macro2",
1592+ "quote",
1593+ "syn 2.0.119",
1594+]
1595+
1596+[[package]]
1597+name = "equator"
1598+version = "0.4.2"
1599+source = "registry+https://github.com/rust-lang/crates.io-index"
1600+checksum = "4711b213838dfee0117e3be6ac926007d7f433d7bbe33595975d4190cb07e6fc"
1601+dependencies = [
1602+ "equator-macro",
1603+]
1604+
1605+[[package]]
1606+name = "equator-macro"
1607+version = "0.4.2"
1608+source = "registry+https://github.com/rust-lang/crates.io-index"
1609+checksum = "44f23cf4b44bfce11a86ace86f8a73ffdec849c9fd00a386a53d278bd9e81fb3"
1610+dependencies = [
1611+ "proc-macro2",
1612+ "quote",
1613+ "syn 2.0.119",
1614+]
1615+
1616+[[package]]
1617+name = "equivalent"
1618+version = "1.0.2"
1619+source = "registry+https://github.com/rust-lang/crates.io-index"
1620+checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f"
1621+
1622+[[package]]
1623+name = "erased-serde"
1624+version = "0.4.10"
1625+source = "registry+https://github.com/rust-lang/crates.io-index"
1626+checksum = "d2add8a07dd6a8d93ff627029c51de145e12686fbc36ecb298ac22e74cf02dec"
1627+dependencies = [
1628+ "serde",
1629+ "serde_core",
1630+ "typeid",
1631+]
1632+
1633+[[package]]
1634+name = "errno"
1635+version = "0.3.14"
1636+source = "registry+https://github.com/rust-lang/crates.io-index"
1637+checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb"
1638+dependencies = [
1639+ "libc",
1640+ "windows-sys 0.61.2",
1641+]
1642+
1643+[[package]]
1644+name = "etagere"
1645+version = "0.2.15"
1646+source = "registry+https://github.com/rust-lang/crates.io-index"
1647+checksum = "fc89bf99e5dc15954a60f707c1e09d7540e5cd9af85fa75caa0b510bc08c5342"
1648+dependencies = [
1649+ "euclid",
1650+ "svg_fmt",
1651+]
1652+
1653+[[package]]
1654+name = "euclid"
1655+version = "0.22.14"
1656+source = "registry+https://github.com/rust-lang/crates.io-index"
1657+checksum = "f1a05365e3b1c6d1650318537c7460c6923f1abdd272ad6842baa2b509957a06"
1658+dependencies = [
1659+ "num-traits",
1660+]
1661+
1662+[[package]]
1663+name = "event-listener"
1664+version = "2.5.3"
1665+source = "registry+https://github.com/rust-lang/crates.io-index"
1666+checksum = "0206175f82b8d6bf6652ff7d71a1e27fd2e4efde587fd368662814d6ec1d9ce0"
1667+
1668+[[package]]
1669+name = "event-listener"
1670+version = "5.4.2"
1671+source = "registry+https://github.com/rust-lang/crates.io-index"
1672+checksum = "5a23add41df1562121a9393cb065eab5146a1242410f23a644851e90cfd669d2"
1673+dependencies = [
1674+ "parking",
1675+ "pin-project-lite",
1676+]
1677+
1678+[[package]]
1679+name = "event-listener-strategy"
1680+version = "0.5.4"
1681+source = "registry+https://github.com/rust-lang/crates.io-index"
1682+checksum = "8be9f3dfaaffdae2972880079a491a1a8bb7cbed0b8dd7a347f668b4150a3b93"
1683+dependencies = [
1684+ "event-listener 5.4.2",
1685+ "pin-project-lite",
1686+]
1687+
1688+[[package]]
1689+name = "exr"
1690+version = "1.74.2"
1691+source = "registry+https://github.com/rust-lang/crates.io-index"
1692+checksum = "711fe42c9964295e01ee3fba3f9fe0e1d24b98886950d68efe81b1c76e21adf3"
1693+dependencies = [
1694+ "bit_field",
1695+ "half",
1696+ "lebe",
1697+ "miniz_oxide",
1698+ "num-complex",
1699+ "pulp",
1700+ "rayon-core",
1701+ "smallvec",
1702+ "zune-inflate",
1703+]
1704+
1705+[[package]]
1706+name = "fastrand"
1707+version = "1.9.0"
1708+source = "registry+https://github.com/rust-lang/crates.io-index"
1709+checksum = "e51093e27b0797c359783294ca4f0a911c270184cb10f85783b118614a1501be"
1710+dependencies = [
1711+ "instant",
1712+]
1713+
1714+[[package]]
1715+name = "fastrand"
1716+version = "2.5.0"
1717+source = "registry+https://github.com/rust-lang/crates.io-index"
1718+checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223"
1719+
1720+[[package]]
1721+name = "fax"
1722+version = "0.2.7"
1723+source = "registry+https://github.com/rust-lang/crates.io-index"
1724+checksum = "caf1079563223d5d59d83c85886a56e586cfd5c1a26292e971a0fa266531ac5a"
1725+
1726+[[package]]
1727+name = "fdeflate"
1728+version = "0.3.7"
1729+source = "registry+https://github.com/rust-lang/crates.io-index"
1730+checksum = "1e6853b52649d4ac5c0bd02320cddc5ba956bdb407c4b75a2c6b75bf51500f8c"
1731+dependencies = [
1732+ "simd-adler32",
1733+]
1734+
1735+[[package]]
1736+name = "filedescriptor"
1737+version = "0.8.3"
1738+source = "registry+https://github.com/rust-lang/crates.io-index"
1739+checksum = "e40758ed24c9b2eeb76c35fb0aebc66c626084edd827e07e1552279814c6682d"
1740+dependencies = [
1741+ "libc",
1742+ "thiserror 1.0.69",
1743+ "winapi",
1744+]
1745+
1746+[[package]]
1747+name = "filetime"
1748+version = "0.2.29"
1749+source = "registry+https://github.com/rust-lang/crates.io-index"
1750+checksum = "5c287a33c7f0a620c38e641e7f60827713987b3c0f26e8ddc9462cc69cf75759"
1751+dependencies = [
1752+ "cfg-if",
1753+ "libc",
1754+]
1755+
1756+[[package]]
1757+name = "find-msvc-tools"
1758+version = "0.1.10"
1759+source = "registry+https://github.com/rust-lang/crates.io-index"
1760+checksum = "26b73573e6edcd2af0cdf47bd6cb58f0b3839491263c314eaad1ccf24430e1de"
1761+
1762+[[package]]
1763+name = "flate2"
1764+version = "1.1.9"
1765+source = "registry+https://github.com/rust-lang/crates.io-index"
1766+checksum = "843fba2746e448b37e26a819579957415c8cef339bf08564fe8b7ddbd959573c"
1767+dependencies = [
1768+ "crc32fast",
1769+ "miniz_oxide",
1770+]
1771+
1772+[[package]]
1773+name = "float-cmp"
1774+version = "0.9.0"
1775+source = "registry+https://github.com/rust-lang/crates.io-index"
1776+checksum = "98de4bbd547a563b716d8dfa9aad1cb19bfab00f4fa09a6a4ed21dbcf44ce9c4"
1777+
1778+[[package]]
1779+name = "float-ord"
1780+version = "0.3.2"
1781+source = "registry+https://github.com/rust-lang/crates.io-index"
1782+checksum = "8ce81f49ae8a0482e4c55ea62ebbd7e5a686af544c00b9d090bba3ff9be97b3d"
1783+
1784+[[package]]
1785+name = "float_next_after"
1786+version = "1.0.0"
1787+source = "registry+https://github.com/rust-lang/crates.io-index"
1788+checksum = "8bf7cc16383c4b8d58b9905a8509f02926ce3058053c056376248d958c9df1e8"
1789+
1790+[[package]]
1791+name = "flume"
1792+version = "0.11.1"
1793+source = "registry+https://github.com/rust-lang/crates.io-index"
1794+checksum = "da0e4dd2a88388a1f4ccc7c9ce104604dab68d9f408dc34cd45823d5a9069095"
1795+dependencies = [
1796+ "futures-core",
1797+ "futures-sink",
1798+ "nanorand",
1799+ "spin",
1800+]
1801+
1802+[[package]]
1803+name = "fnv"
1804+version = "1.0.7"
1805+source = "registry+https://github.com/rust-lang/crates.io-index"
1806+checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1"
1807+
1808+[[package]]
1809+name = "foldhash"
1810+version = "0.1.5"
1811+source = "registry+https://github.com/rust-lang/crates.io-index"
1812+checksum = "d9c4f5dac5e15c24eb999c26181a6ca40b39fe946cbe4c263c7209467bc83af2"
1813+
1814+[[package]]
1815+name = "font-types"
1816+version = "0.12.2"
1817+source = "registry+https://github.com/rust-lang/crates.io-index"
1818+checksum = "0a7299a780854a6d391be2ae1c8521c9368471b559dbfd6a8dbd9f407eaff100"
1819+dependencies = [
1820+ "bytemuck",
1821+]
1822+
1823+[[package]]
1824+name = "fontconfig-parser"
1825+version = "0.5.8"
1826+source = "registry+https://github.com/rust-lang/crates.io-index"
1827+checksum = "bbc773e24e02d4ddd8395fd30dc147524273a83e54e0f312d986ea30de5f5646"
1828+dependencies = [
1829+ "roxmltree",
1830+]
1831+
1832+[[package]]
1833+name = "fontdb"
1834+version = "0.16.2"
1835+source = "registry+https://github.com/rust-lang/crates.io-index"
1836+checksum = "b0299020c3ef3f60f526a4f64ab4a3d4ce116b1acbf24cdd22da0068e5d81dc3"
1837+dependencies = [
1838+ "fontconfig-parser",
1839+ "log",
1840+ "memmap2",
1841+ "slotmap",
1842+ "tinyvec",
1843+ "ttf-parser 0.20.0",
1844+]
1845+
1846+[[package]]
1847+name = "fontdb"
1848+version = "0.23.0"
1849+source = "registry+https://github.com/rust-lang/crates.io-index"
1850+checksum = "457e789b3d1202543297a350643cf459f836cade38934e7a4cf6a39e7cde2905"
1851+dependencies = [
1852+ "fontconfig-parser",
1853+ "log",
1854+ "memmap2",
1855+ "slotmap",
1856+ "tinyvec",
1857+ "ttf-parser 0.25.1",
1858+]
1859+
1860+[[package]]
1861+name = "foreign-types"
1862+version = "0.5.0"
1863+source = "registry+https://github.com/rust-lang/crates.io-index"
1864+checksum = "d737d9aa519fb7b749cbc3b962edcf310a8dd1f4b67c91c4f83975dbdd17d965"
1865+dependencies = [
1866+ "foreign-types-macros",
1867+ "foreign-types-shared",
1868+]
1869+
1870+[[package]]
1871+name = "foreign-types-macros"
1872+version = "0.2.4"
1873+source = "registry+https://github.com/rust-lang/crates.io-index"
1874+checksum = "ea5190182e6915eb873ddbc16e23b711b6eb1f9c00a0d0a3a91b5f6228475225"
1875+dependencies = [
1876+ "proc-macro2",
1877+ "quote",
1878+ "syn 3.0.3",
1879+]
1880+
1881+[[package]]
1882+name = "foreign-types-shared"
1883+version = "0.3.1"
1884+source = "registry+https://github.com/rust-lang/crates.io-index"
1885+checksum = "aa9a19cbb55df58761df49b23516a86d432839add4af60fc256da840f66ed35b"
1886+
1887+[[package]]
1888+name = "form_urlencoded"
1889+version = "1.2.2"
1890+source = "registry+https://github.com/rust-lang/crates.io-index"
1891+checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf"
1892+dependencies = [
1893+ "percent-encoding",
1894+]
1895+
1896+[[package]]
1897+name = "freetype-sys"
1898+version = "0.20.1"
1899+source = "registry+https://github.com/rust-lang/crates.io-index"
1900+checksum = "0e7edc5b9669349acfda99533e9e0bcf26a51862ab43b08ee7745c55d28eb134"
1901+dependencies = [
1902+ "cc",
1903+ "libc",
1904+ "pkg-config",
1905+]
1906+
1907+[[package]]
1908+name = "futf"
1909+version = "0.1.5"
1910+source = "registry+https://github.com/rust-lang/crates.io-index"
1911+checksum = "df420e2e84819663797d1ec6544b13c5be84629e7bb00dc960d6917db2987843"
1912+dependencies = [
1913+ "mac",
1914+ "new_debug_unreachable",
1915+]
1916+
1917+[[package]]
1918+name = "futures"
1919+version = "0.3.33"
1920+source = "registry+https://github.com/rust-lang/crates.io-index"
1921+checksum = "a88cf1f829d945f548cf8fec32c61b1f202b6d93b45848602fc02af4b12ad218"
1922+dependencies = [
1923+ "futures-channel",
1924+ "futures-core",
1925+ "futures-executor",
1926+ "futures-io",
1927+ "futures-sink",
1928+ "futures-task",
1929+ "futures-util",
1930+]
1931+
1932+[[package]]
1933+name = "futures-channel"
1934+version = "0.3.33"
1935+source = "registry+https://github.com/rust-lang/crates.io-index"
1936+checksum = "262590f4fe6afeb0bc83be1daa64e52657fe185690a958af7f3ad0e92085c5ae"
1937+dependencies = [
1938+ "futures-core",
1939+ "futures-sink",
1940+]
1941+
1942+[[package]]
1943+name = "futures-core"
1944+version = "0.3.33"
1945+source = "registry+https://github.com/rust-lang/crates.io-index"
1946+checksum = "2cd50c473c80f6d7c3670a752354b8e569b1a7cbfdc0419ec88e5edad85e0dc7"
1947+
1948+[[package]]
1949+name = "futures-executor"
1950+version = "0.3.33"
1951+source = "registry+https://github.com/rust-lang/crates.io-index"
1952+checksum = "6754879cc9f2c66f88c6e5c35344bb0bdb0708b0352b1201815667c7eabc7458"
1953+dependencies = [
1954+ "futures-core",
1955+ "futures-task",
1956+ "futures-util",
1957+]
1958+
1959+[[package]]
1960+name = "futures-io"
1961+version = "0.3.33"
1962+source = "registry+https://github.com/rust-lang/crates.io-index"
1963+checksum = "4577ecaa3c4f96589d473f679a71b596316f6641bc350038b962a5daf0085d7a"
1964+
1965+[[package]]
1966+name = "futures-lite"
1967+version = "1.13.0"
1968+source = "registry+https://github.com/rust-lang/crates.io-index"
1969+checksum = "49a9d51ce47660b1e808d3c990b4709f2f415d928835a17dfd16991515c46bce"
1970+dependencies = [
1971+ "fastrand 1.9.0",
1972+ "futures-core",
1973+ "futures-io",
1974+ "memchr",
1975+ "parking",
1976+ "pin-project-lite",
1977+ "waker-fn",
1978+]
1979+
1980+[[package]]
1981+name = "futures-lite"
1982+version = "2.6.1"
1983+source = "registry+https://github.com/rust-lang/crates.io-index"
1984+checksum = "f78e10609fe0e0b3f4157ffab1876319b5b0db102a2c60dc4626306dc46b44ad"
1985+dependencies = [
1986+ "fastrand 2.5.0",
1987+ "futures-core",
1988+ "futures-io",
1989+ "parking",
1990+ "pin-project-lite",
1991+]
1992+
1993+[[package]]
1994+name = "futures-macro"
1995+version = "0.3.33"
1996+source = "registry+https://github.com/rust-lang/crates.io-index"
1997+checksum = "2d6d3cde68c518367be28956066ddfef33813991b77a55005a69dae04bf3b10b"
1998+dependencies = [
1999+ "proc-macro2",
2000+ "quote",
Cargo.tomladded+18 -0
@@ -0,0 +1,18 @@
1+[workspace]
2+resolver = "3"
3+members = ["crates/engine", "crates/engine-hw", "crates/app"]
4+# Vendored third-party (see [patch.crates-io]); not ours to build or test.
5+exclude = ["vendor/cros-libva", "vendor/cros-codecs"]
6+
7+[workspace.package]
8+version = "0.1.0"
9+edition = "2024"
10+
11+# Two upstream crates vendored verbatim except for one clearly marked fix each,
12+# both blockers on this machine and both still unfixed upstream as of 0.0.6/0.0.13:
13+# cros-libva - fails to build against libva >= 1.23 headers
14+# cros-codecs - probes VA-API with a 16x16 context that Mesa radeonsi refuses
15+# Drop `vendor/` entirely once released versions handle both.
16+[patch.crates-io]
17+cros-libva = { path = "vendor/cros-libva" }
18+cros-codecs = { path = "vendor/cros-codecs" }
crates/app/Cargo.tomladded+13 -0
@@ -0,0 +1,13 @@
1+[package]
2+name = "app"
3+version.workspace = true
4+edition.workspace = true
5+
6+[[bin]]
7+name = "app"
8+path = "src/main.rs"
9+
10+[dependencies]
11+engine = { path = "../engine" }
12+gpui = "0.2.2"
13+image = "0.25"
crates/app/src/main.rsadded+102 -0
@@ -0,0 +1,102 @@
1+use std::sync::Arc;
2+use std::sync::mpsc::{Receiver, TryRecvError};
3+
4+use engine::{DecodeSession, Frame};
5+use gpui::{
6+ App, Application, Bounds, Context, RenderImage, TitlebarOptions, Window, WindowBounds,
7+ WindowOptions, div, img, prelude::*, px, rgb, size,
8+};
9+
10+struct Player {
11+ rx: Receiver<Frame>,
12+ image: Option<Arc<RenderImage>>,
13+ finished: bool,
14+}
15+
16+impl Player {
17+ /// Takes at most one frame per rendered frame; the decoder's channel is
18+ /// bounded so it simply waits for us.
19+ fn pump(&mut self, window: &mut Window) {
20+ match self.rx.try_recv() {
21+ Ok(frame) => {
22+ let buf =
23+ image::RgbaImage::from_raw(frame.width, frame.height, frame.bgra)
24+ .expect("frame buffer sized width*height*4");
25+ let next = Arc::new(RenderImage::new(vec![image::Frame::new(buf)]));
26+ if let Some(old) = self.image.replace(next) {
27+ // Every RenderImage gets a fresh id and its own atlas tile:
28+ // without this the sprite atlas grows for the whole video.
29+ let _ = window.drop_image(old);
30+ }
31+ }
32+ Err(TryRecvError::Empty) => {}
33+ Err(TryRecvError::Disconnected) => self.finished = true,
34+ }
35+ }
36+}
37+
38+impl Render for Player {
39+ fn render(&mut self, window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
40+ self.pump(window);
41+ if !self.finished {
42+ window.request_animation_frame();
43+ }
44+
45+ div()
46+ .size_full()
47+ .bg(rgb(0x101010))
48+ .flex()
49+ .justify_center()
50+ .items_center()
51+ .children(
52+ self.image
53+ .clone()
54+ .map(|i| img(i).size_full().object_fit(gpui::ObjectFit::Contain)),
55+ )
56+ }
57+}
58+
59+fn main() {
60+ let Some(path) = std::env::args().nth(1) else {
61+ eprintln!("usage: app <video.mp4>");
62+ std::process::exit(2);
63+ };
64+ let (meta, rx) = match DecodeSession::open(&path) {
65+ Ok(v) => v,
66+ Err(e) => {
67+ eprintln!("cannot open {path}: {e}");
68+ std::process::exit(1);
69+ }
70+ };
71+ println!(
72+ "{path}: {}x{} @ {:.2} fps, {} samples",
73+ meta.width, meta.height, meta.frame_rate, meta.frame_count
74+ );
75+
76+ Application::new().run(move |cx: &mut App| {
77+ let bounds = Bounds::centered(
78+ None,
79+ size(px(meta.width as f32), px(meta.height as f32)),
80+ cx,
81+ );
82+ cx.open_window(
83+ WindowOptions {
84+ window_bounds: Some(WindowBounds::Windowed(bounds)),
85+ titlebar: Some(TitlebarOptions {
86+ title: Some("video_editor".into()),
87+ ..Default::default()
88+ }),
89+ ..Default::default()
90+ },
91+ |_, cx| {
92+ cx.new(|_| Player {
93+ rx,
94+ image: None,
95+ finished: false,
96+ })
97+ },
98+ )
99+ .unwrap();
100+ cx.activate(true);
101+ });
102+}
crates/engine-hw/Cargo.tomladded+16 -0
@@ -0,0 +1,16 @@
1+[package]
2+name = "engine-hw"
3+version.workspace = true
4+edition.workspace = true
5+
6+# cdylib only: this is the one artifact allowed to link libva/gbm/drm. The app
7+# dlopens it and keeps working when it is missing.
8+[lib]
9+name = "engine_hw"
10+crate-type = ["cdylib"]
11+
12+[dependencies]
13+engine = { path = "../engine" }
14+cros-codecs = { version = "0.0.6", features = ["vaapi"] }
15+# Same version cros-codecs already pulls in; we allocate output frames ourselves.
16+gbm = { version = "0.15", default-features = false, features = ["drm-support"] }
crates/engine-hw/src/lib.rsadded+374 -0
@@ -0,0 +1,374 @@
1+//! VA-API H.264 decode, shipped as a `dlopen`-able plugin so the main binary
2+//! never gets a DT_NEEDED on libva/gbm/drm. Every entry point is `extern "C"`,
3+//! catches unwinds and reports failure as a null pointer or a negative code:
4+//! the caller's contract is "any failure means use the software decoder".
5+//!
6+//! ponytail: that guarantee rests on `panic = "unwind"`. Building this crate with
7+//! `panic = "abort"` would turn a driver bug into a killed app; the upgrade path
8+//! is running the decoder in a child process instead of in-process.
9+
10+use std::collections::VecDeque;
11+use std::ffi::{CStr, c_char, c_void};
12+use std::panic::{AssertUnwindSafe, catch_unwind};
13+use std::path::{Path, PathBuf};
14+use std::rc::Rc;
15+
16+use cros_codecs::backend::vaapi::decoder::VaapiBackend;
17+use cros_codecs::decoder::stateless::h264::H264;
18+use cros_codecs::decoder::stateless::{DecodeError, StatelessDecoder, StatelessVideoDecoder};
19+use cros_codecs::decoder::{BlockingMode, DecodedHandle, DecoderEvent, StreamInfo};
20+use cros_codecs::image_processing::nv12_to_i420;
21+use cros_codecs::libva::{Display, Image, VA_FOURCC_NV12, VAImageFormat};
22+use cros_codecs::video_frame::frame_pool::{FramePool, PooledVideoFrame};
23+use cros_codecs::video_frame::generic_dma_video_frame::GenericDmaVideoFrame;
24+use cros_codecs::video_frame::{UV_PLANE, Y_PLANE};
25+use cros_codecs::{Fourcc, FrameLayout, PlaneLayout, Resolution};
26+use gbm::{BufferObjectFlags, Format as GbmFormat};
27+
28+use engine::demux::Demuxer;
29+use engine::hw::{VhFrame, VhMeta};
30+
31+type PooledFrame = PooledVideoFrame<GenericDmaVideoFrame>;
32+type Decoder = StatelessDecoder<H264, VaapiBackend<PooledFrame>>;
33+type Handle = <Decoder as StatelessVideoDecoder>::Handle;
34+
35+/// Ceiling on decode/drain iterations that make no progress. VA-API in blocking
36+/// mode should always either hand back an event or accept input; this only
37+/// exists so a misbehaving driver returns an error instead of hanging the app.
38+const STALL_LIMIT: u32 = 10_000;
39+
40+struct Session {
41+ decoder: Decoder,
42+ /// NV12 descriptor for `vaGetImage`, queried once at open.
43+ nv12_format: VAImageFormat,
44+ pool: FramePool<GenericDmaVideoFrame>,
45+ demuxer: Demuxer,
46+ meta: VhMeta,
47+ ready: VecDeque<Handle>,
48+ /// Remaining bytes of the access unit currently being fed, if any.
49+ pending: Vec<u8>,
50+ timestamp: u64,
51+ flushed: bool,
52+ /// Tightly packed I420 handed out through [`VhFrame`]; reused every frame,
53+ /// which is exactly why the pointers are only valid until the next call.
54+ out: Vec<u8>,
55+ luma: usize,
56+ chroma: usize,
57+}
58+
59+/// Mesa's GBM cannot allocate an NV12 buffer object at all (measured on
60+/// radeonsi: every flag/modifier combination returns NULL), so we allocate one
61+/// linear single-plane R8 buffer big enough for luma + chroma and describe the
62+/// NV12 layout inside it ourselves. VA-API imports it as one DRM-PRIME object
63+/// with two planes at known offsets, which is exactly what the descriptor in
64+/// `GenericDmaVideoFrame` emits.
65+fn alloc_nv12(
66+ gbm: &gbm::Device<std::fs::File>,
67+ coded: Resolution,
68+) -> Result<GenericDmaVideoFrame, String> {
69+ let rows = coded.height + coded.height.div_ceil(2);
70+ let bo = gbm
71+ .create_buffer_object::<()>(coded.width, rows, GbmFormat::R8, BufferObjectFlags::LINEAR)
72+ .map_err(|e| format!("gbm R8 {}x{rows} allocation failed: {e}", coded.width))?;
73+ let pitch = bo.stride().map_err(|e| e.to_string())? as usize;
74+ let fd = bo.fd().map_err(|e| e.to_string())?;
75+ GenericDmaVideoFrame::new(
76+ vec![std::fs::File::from(fd)],
77+ FrameLayout {
78+ format: (Fourcc::from(b"NV12"), 0 /* DRM_FORMAT_MOD_LINEAR */),
79+ size: coded,
80+ planes: vec![
81+ PlaneLayout {
82+ buffer_index: 0,
83+ offset: 0,
84+ stride: pitch,
85+ },
86+ PlaneLayout {
87+ buffer_index: 0,
88+ offset: pitch * coded.height as usize,
89+ stride: pitch,
90+ },
91+ ],
92+ },
93+ )
94+}
95+
96+/// First render node that gives us both a VA display and a GBM device. Which
97+/// node is the right one is a per-machine question, so we probe rather than
98+/// hardcode renderD128.
99+fn open_devices() -> Option<(Rc<Display>, gbm::Device<std::fs::File>)> {
100+ let mut nodes: Vec<PathBuf> = std::fs::read_dir("/dev/dri")
101+ .ok()?
102+ .flatten()
103+ .map(|e| e.path())
104+ .filter(|p| {
105+ p.file_name()
106+ .and_then(|n| n.to_str())
107+ .is_some_and(|n| n.starts_with("renderD"))
108+ })
109+ .collect();
110+ nodes.sort();
111+ nodes.into_iter().find_map(|node| {
112+ let display = Display::open_drm_display(&node).ok()?;
113+ let file = std::fs::OpenOptions::new()
114+ .read(true)
115+ .write(true)
116+ .open(&node)
117+ .ok()?;
118+ let gbm = gbm::Device::new(file).ok()?;
119+ Some((display, gbm))
120+ })
121+}
122+
123+impl Session {
124+ fn open(path: &Path) -> Option<Self> {
125+ let (meta, demuxer) = Demuxer::open(path).ok()?;
126+ let (display, gbm) = open_devices()?;
127+ let nv12_format = display
128+ .query_image_formats()
129+ .ok()?
130+ .into_iter()
131+ .find(|f| f.fourcc == VA_FOURCC_NV12)?;
132+ let decoder = Decoder::new_vaapi(display, BlockingMode::Blocking).ok()?;
133+ let pool = FramePool::new(move |info: &StreamInfo| {
134+ alloc_nv12(&gbm, info.coded_resolution).expect("output frame allocation failed")
135+ });
136+ Some(Self {
137+ decoder,
138+ nv12_format,
139+ pool,
140+ demuxer,
141+ meta: VhMeta {
142+ width: meta.width,
143+ height: meta.height,
144+ frame_rate: meta.frame_rate,
145+ frame_count: meta.frame_count,
146+ },
147+ ready: VecDeque::new(),
148+ pending: Vec::new(),
149+ timestamp: 0,
150+ flushed: false,
151+ out: Vec::new(),
152+ luma: 0,
153+ chroma: 0,
154+ })
155+ }
156+
157+ /// Pumps the decoder until one picture is ready. `Ok(false)` is clean EOF.
158+ fn pump(&mut self) -> Result<bool, String> {
159+ let mut stalls = 0u32;
160+ loop {
161+ // Stop draining as soon as we have a picture: every handle we hold
162+ // keeps a pool buffer out of circulation.
163+ while self.ready.is_empty() {
164+ match self.decoder.next_event() {
165+ Some(DecoderEvent::FrameReady(handle)) => self.ready.push_back(handle),
166+ Some(DecoderEvent::FormatChanged) => {
167+ let info = self
168+ .decoder
169+ .stream_info()
170+ .ok_or("format changed without stream info")?
171+ .clone();
172+ self.pool.resize(&info);
173+ }
174+ None => break,
175+ }
176+ }
177+ if let Some(handle) = self.ready.pop_front() {
178+ self.emit(handle);
179+ return Ok(true);
180+ }
181+ if self.flushed {
182+ return Ok(false);
183+ }
184+
185+ if self.pending.is_empty() {
186+ match self.demuxer.next_access_unit() {
187+ Ok(Some(au)) => self.pending = au,
188+ Ok(None) => {
189+ self.decoder.flush().map_err(|e| e.to_string())?;
190+ self.flushed = true;
191+ continue;
192+ }
193+ Err(e) => return Err(e.to_string()),
194+ }
195+ }
196+
197+ let Self {
198+ decoder,
199+ pool,
200+ pending,
201+ timestamp,
202+ ..
203+ } = self;
204+ match decoder.decode(*timestamp, pending, &mut || pool.alloc()) {
205+ Ok(0) => return Err("decoder consumed no input".into()),
206+ Ok(n) => {
207+ pending.drain(..n.min(pending.len()));
208+ if pending.is_empty() {
209+ *timestamp += 1;
210+ }
211+ stalls = 0;
212+ }
213+ // Both mean "handle pending events, then resubmit the same data".
214+ Err(DecodeError::CheckEvents) | Err(DecodeError::NotEnoughOutputBuffers(_)) => {
215+ stalls += 1;
216+ if stalls > STALL_LIMIT {
217+ return Err("decoder stalled waiting for output buffers".into());
218+ }
219+ }
220+ Err(e) => return Err(e.to_string()),
221+ }
222+ }
223+ }
224+
225+ /// Copies a decoded NV12 surface into `self.out` as packed I420.
226+ fn emit(&mut self, handle: Handle) {
227+ let res = handle.display_resolution();
228+ let (w, h) = (res.width as usize, res.height as usize);
229+ let (cw, ch) = (w.div_ceil(2), h.div_ceil(2));
230+ if self.luma != w * h || self.chroma != cw * ch {
231+ self.luma = w * h;
232+ self.chroma = cw * ch;
233+ self.out = vec![0u8; self.luma + 2 * self.chroma];
234+ }
235+ self.meta.width = res.width;
236+ self.meta.height = res.height;
237+
238+ // Read back with vaGetImage rather than mapping our own DMA-BUF: on a
239+ // discrete GPU that buffer lives in VRAM and a CPU read of it runs at
240+ // ~44 MB/s over the PCIe BAR (measured), which costs 350 ms/frame. The
241+ // driver copies into host-visible memory for us instead.
242+ // Cheap no-op in blocking mode, but pixels must never be read early.
243+ let _ = DecodedHandle::sync(&handle);
244+ let borrowed = handle.borrow();
245+ let size = (w as u32, h as u32);
246+ let image = Image::create_from(borrowed.surface(), self.nv12_format, size, size)
247+ .expect("vaGetImage failed");
248+ let va = *image.image();
249+ let data: &[u8] = image.as_ref();
250+
251+ let (dst_y, rest) = self.out.split_at_mut(self.luma);
252+ let (dst_u, dst_v) = rest.split_at_mut(self.chroma);
253+ nv12_to_i420(
254+ &data[va.offsets[Y_PLANE] as usize..],
255+ va.pitches[Y_PLANE] as usize,
256+ dst_y,
257+ w,
258+ &data[va.offsets[UV_PLANE] as usize..],
259+ va.pitches[UV_PLANE] as usize,
260+ dst_u,
261+ cw,
262+ dst_v,
263+ cw,
264+ w,
265+ h,
266+ );
267+ }
268+
269+ fn fill(&self, out: &mut VhFrame) {
270+ let w = self.meta.width as usize;
271+ let cw = w.div_ceil(2);
272+ out.y = self.out.as_ptr();
273+ // SAFETY: `out` was sized to luma + 2 * chroma just above in `emit`.
274+ unsafe {
275+ out.u = self.out.as_ptr().add(self.luma);
276+ out.v = self.out.as_ptr().add(self.luma + self.chroma);
277+ }
278+ out.y_stride = w;
279+ out.u_stride = cw;
280+ out.v_stride = cw;
281+ out.width = self.meta.width;
282+ out.height = self.meta.height;
283+ }
284+}
285+
286+/// Opens `path` for hardware decode. Returns null on any failure at all: no
287+/// libva runtime, no render node, unsupported profile, unreadable file.
288+///
289+/// # Safety
290+/// `path` must be a valid NUL-terminated C string.
291+#[unsafe(no_mangle)]
292+pub unsafe extern "C" fn vh_open(path: *const c_char) -> *mut c_void {
293+ catch_unwind(AssertUnwindSafe(|| {
294+ if path.is_null() {
295+ return std::ptr::null_mut();
296+ }
297+ // SAFETY: caller-guaranteed NUL-terminated string, read before return.
298+ let path = unsafe { CStr::from_ptr(path) };
299+ let Ok(path) = path.to_str() else {
300+ return std::ptr::null_mut();
301+ };
302+ match Session::open(Path::new(path)) {
303+ Some(session) => Box::into_raw(Box::new(session)) as *mut c_void,
304+ None => std::ptr::null_mut(),
305+ }
306+ }))
307+ .unwrap_or(std::ptr::null_mut())
308+}
309+
310+/// Fills `out` with stream metadata. 0 on success, negative on failure.
311+///
312+/// # Safety
313+/// `session` must come from [`vh_open`] and `out` must be writable.
314+#[unsafe(no_mangle)]
315+pub unsafe extern "C" fn vh_meta(session: *mut c_void, out: *mut VhMeta) -> i32 {
316+ catch_unwind(AssertUnwindSafe(|| {
317+ if session.is_null() || out.is_null() {
318+ return -1;
319+ }
320+ // SAFETY: caller-guaranteed live session and writable destination.
321+ unsafe {
322+ let session = &*(session as *const Session);
323+ (*out).width = session.meta.width;
324+ (*out).height = session.meta.height;
325+ (*out).frame_rate = session.meta.frame_rate;
326+ (*out).frame_count = session.meta.frame_count;
327+ }
328+ 0
329+ }))
330+ .unwrap_or(-1)
331+}
332+
333+/// 1 when `out` holds the next picture in display order, 0 at clean end of
334+/// stream, negative on error. Plane pointers stay valid until the next call.
335+///
336+/// # Safety
337+/// `session` must come from [`vh_open`] and `out` must be writable.
338+#[unsafe(no_mangle)]
339+pub unsafe extern "C" fn vh_next_frame(session: *mut c_void, out: *mut VhFrame) -> i32 {
340+ catch_unwind(AssertUnwindSafe(|| {
341+ if session.is_null() || out.is_null() {
342+ return -1;
343+ }
344+ // SAFETY: caller-guaranteed live session and writable destination.
345+ let session = unsafe { &mut *(session as *mut Session) };
346+ match session.pump() {
347+ Ok(true) => {
348+ // SAFETY: `out` is non-null and writable per the contract.
349+ session.fill(unsafe { &mut *out });
350+ 1
351+ }
352+ Ok(false) => 0,
353+ Err(e) => {
354+ eprintln!("engine_hw: {e}");
355+ -2
356+ }
357+ }
358+ }))
359+ .unwrap_or(-1)
360+}
361+
362+/// Releases a session. Safe to call with null.
363+///
364+/// # Safety
365+/// `session` must come from [`vh_open`] and must not be used afterwards.
366+#[unsafe(no_mangle)]
367+pub unsafe extern "C" fn vh_close(session: *mut c_void) {
368+ let _ = catch_unwind(AssertUnwindSafe(|| {
369+ if !session.is_null() {
370+ // SAFETY: pointer came from `Box::into_raw` in `vh_open`.
371+ drop(unsafe { Box::from_raw(session as *mut Session) });
372+ }
373+ }));
374+}
crates/engine/Cargo.tomladded+10 -0
@@ -0,0 +1,10 @@
1+[package]
2+name = "engine"
3+version.workspace = true
4+edition.workspace = true
5+
6+# No UI dependency here, ever: the engine must stay reusable across front-ends.
7+[dependencies]
8+libloading = "0.8"
9+mp4 = "0.14"
10+rusty_h264 = { version = "0.8", default-features = false }
crates/engine/examples/dump_frame.rsadded+34 -0
@@ -0,0 +1,34 @@
1+//! Dump decoded frames as PPM for visual inspection.
2+//! Usage: cargo run -p engine --release --example dump_frame -- <video.mp4> <frame_index> <out.ppm>
3+
4+use std::env;
5+use std::fs::File;
6+use std::io::{BufWriter, Write};
7+
8+fn main() -> engine::Result<()> {
9+ let mut args = env::args().skip(1);
10+ let path = args
11+ .next()
12+ .ok_or("usage: dump_frame <video.mp4> <frame_index> <out.ppm>")?;
13+ let target: u32 = args.next().ok_or("missing frame index")?.parse()?;
14+ let out = args.next().ok_or("missing output path")?;
15+
16+ let (meta, rx) = engine::DecodeSession::open(&path)?;
17+ eprintln!(
18+ "{}x{} @ {:.2} fps",
19+ meta.width, meta.height, meta.frame_rate
20+ );
21+
22+ for frame in rx {
23+ if frame.index == target {
24+ let mut w = BufWriter::new(File::create(&out)?);
25+ writeln!(w, "P6\n{} {}\n255", frame.width, frame.height)?;
26+ for px in frame.bgra.chunks_exact(4) {
27+ w.write_all(&[px[2], px[1], px[0]])?; // BGRA -> RGB
28+ }
29+ eprintln!("wrote frame {target} to {out}");
30+ return Ok(());
31+ }
32+ }
33+ Err(format!("stream ended before frame {target}").into())
34+}
crates/engine/src/convert.rsadded+56 -0
@@ -0,0 +1,56 @@
1+//! I420 -> BGRA8 (straight alpha), BT.601 limited range.
2+
3+/// Converts a planar I420 frame (stride == width, chroma at half resolution)
4+/// into tightly packed BGRA8. Returns `width * height * 4` bytes.
5+pub fn i420_to_bgra(y: &[u8], u: &[u8], v: &[u8], width: usize, height: usize) -> Vec<u8> {
6+ let cw = width.div_ceil(2);
7+ let mut out = vec![0u8; width * height * 4];
8+
9+ for row in 0..height {
10+ let y_row = row * width;
11+ let c_row = (row / 2) * cw;
12+ for col in 0..width {
13+ let c = y[y_row + col] as i32 - 16;
14+ let ci = c_row + col / 2;
15+ let d = u[ci] as i32 - 128;
16+ let e = v[ci] as i32 - 128;
17+
18+ let r = ((298 * c + 409 * e + 128) >> 8).clamp(0, 255) as u8;
19+ let g = ((298 * c - 100 * d - 208 * e + 128) >> 8).clamp(0, 255) as u8;
20+ let b = ((298 * c + 516 * d + 128) >> 8).clamp(0, 255) as u8;
21+
22+ let o = (y_row + col) * 4;
23+ out[o] = b;
24+ out[o + 1] = g;
25+ out[o + 2] = r;
26+ out[o + 3] = 255;
27+ }
28+ }
29+ out
30+}
31+
32+#[cfg(test)]
33+mod tests {
34+ use super::*;
35+
36+ #[test]
37+ fn known_colors() {
38+ // 2x2 blocks so each shares one chroma sample.
39+ // Black (limited range Y=16), white (Y=235), and a saturated red.
40+ let cases: [([u8; 3], [u8; 3]); 3] = [
41+ ([16, 128, 128], [0, 0, 0]),
42+ ([235, 128, 128], [255, 255, 255]),
43+ ([82, 90, 240], [255, 0, 0]), // BT.601 red primary -> R=255,G~0,B~0
44+ ];
45+ for ([yv, uv, vv], [r, g, b]) in cases {
46+ let out = i420_to_bgra(&[yv; 4], &[uv], &[vv], 2, 2);
47+ assert_eq!(out.len(), 2 * 2 * 4);
48+ for px in out.chunks_exact(4) {
49+ assert!(px[0].abs_diff(b) <= 2, "B {} vs {}", px[0], b);
50+ assert!(px[1].abs_diff(g) <= 2, "G {} vs {}", px[1], g);
51+ assert!(px[2].abs_diff(r) <= 2, "R {} vs {}", px[2], r);
52+ assert_eq!(px[3], 255);
53+ }
54+ }
55+ }
56+}
crates/engine/src/decode.rsadded+130 -0
@@ -0,0 +1,130 @@
1+//! Background decode worker. Frames leave over a bounded channel so the caller's
2+//! thread (the UI thread) never blocks on decode and memory stays capped.
3+
4+use std::path::{Path, PathBuf};
5+use std::sync::mpsc::{Receiver, SyncSender, sync_channel};
6+use std::thread;
7+
8+use rusty_h264::Decoder;
9+
10+use crate::convert::i420_to_bgra;
11+use crate::demux::{Demuxer, VideoMeta};
12+use crate::hw::HwSession;
13+
14+/// One decoded picture, ready to hand to a renderer.
15+pub struct Frame {
16+ /// Position in decode order, starting at 0.
17+ pub index: u32,
18+ pub width: u32,
19+ pub height: u32,
20+ /// BGRA8, straight alpha, tightly packed.
21+ pub bgra: Vec<u8>,
22+}
23+
24+pub struct DecodeSession;
25+
26+impl DecodeSession {
27+ /// Opens `path`, returning stream metadata immediately and a receiver that
28+ /// yields frames as the worker decodes them. The worker stops when the
29+ /// receiver is dropped, at end of stream, or on the first decode error.
30+ pub fn open(path: impl AsRef<Path>) -> crate::Result<(VideoMeta, Receiver<Frame>)> {
31+ let path = path.as_ref().to_path_buf();
32+ let (meta, demuxer) = Demuxer::open(&path)?;
33+ // Small bound: a 720p BGRA frame is ~3.5 MB, so we must not let the
34+ // decoder run ahead of the display without limit.
35+ let (tx, rx) = sync_channel(2);
36+ thread::Builder::new()
37+ .name("decode".into())
38+ .spawn(move || {
39+ // The plugin has to be opened on the thread that uses it: its
40+ // VA-API state is not `Send`-safe across a later hand-off.
41+ if let Some(hw) = open_hw(&path) {
42+ eprintln!("decode backend: hardware (VA-API plugin)");
43+ if run_hw(hw, &tx) {
44+ return;
45+ }
46+ // A driver that opens but cannot decode a single frame is
47+ // still a fallback case, not a dead session.
48+ eprintln!("hardware decode failed before any frame, falling back to software");
49+ }
50+ eprintln!("decode backend: software (rusty_h264)");
51+ run(demuxer, tx)
52+ })?;
53+ Ok((meta, rx))
54+ }
55+}
56+
57+/// `None` when the software path must be used: forced by `VE_SW=1`, or the
58+/// plugin is absent/broken/unable to open this particular file.
59+fn open_hw(path: &PathBuf) -> Option<HwSession> {
60+ if std::env::var_os("VE_SW").is_some_and(|v| v == "1") {
61+ return None;
62+ }
63+ HwSession::open(path)
64+}
65+
66+/// Returns whether the session was handled; `false` only when hardware decode
67+/// failed without emitting a single frame, so software can still take over.
68+fn run_hw(mut hw: HwSession, tx: &SyncSender<Frame>) -> bool {
69+ let mut index = 0u32;
70+ loop {
71+ match hw.next_frame() {
72+ Ok(Some((y, u, v, width, height))) => {
73+ let frame = Frame {
74+ index,
75+ width,
76+ height,
77+ bgra: i420_to_bgra(y, u, v, width as usize, height as usize),
78+ };
79+ index += 1;
80+ if tx.send(frame).is_err() {
81+ return true; // consumer went away
82+ }
83+ }
84+ Ok(None) => return true,
85+ Err(e) => {
86+ if index == 0 {
87+ return false;
88+ }
89+ eprintln!("hardware decode error at frame {index}: {e}");
90+ return true;
91+ }
92+ }
93+ }
94+}
95+
96+fn run(mut demuxer: Demuxer, tx: SyncSender<Frame>) {
97+ let mut decoder = Decoder::new();
98+ let mut index = 0u32;
99+
100+ // ponytail: emits pictures in decode order. Fine for Baseline (no B-frames);
101+ // reordering streams need POC-sorted output before display.
102+ loop {
103+ let au = match demuxer.next_access_unit() {
104+ Ok(Some(au)) => au,
105+ Ok(None) => break,
106+ Err(e) => {
107+ eprintln!("demux error: {e}");
108+ break;
109+ }
110+ };
111+ let yuv = match decoder.decode(&au) {
112+ Ok(Some(yuv)) => yuv,
113+ Ok(None) => continue,
114+ Err(e) => {
115+ eprintln!("decode error at access unit {index}: {e}");
116+ break;
117+ }
118+ };
119+ let frame = Frame {
120+ index,
121+ width: yuv.width as u32,
122+ height: yuv.height as u32,
123+ bgra: i420_to_bgra(&yuv.y, &yuv.u, &yuv.v, yuv.width, yuv.height),
124+ };
125+ index += 1;
126+ if tx.send(frame).is_err() {
127+ break; // consumer went away
128+ }
129+ }
130+}
crates/engine/src/demux.rsadded+132 -0
@@ -0,0 +1,132 @@
1+//! MP4 demux: pulls the H.264 track out as Annex-B access units.
2+
3+use std::fs::File;
4+use std::io::BufReader;
5+use std::path::Path;
6+
7+use mp4::{MediaType, Mp4Reader};
8+
9+const START_CODE: [u8; 4] = [0, 0, 0, 1];
10+
11+#[derive(Debug, Clone, Copy, PartialEq)]
12+pub struct VideoMeta {
13+ pub width: u32,
14+ pub height: u32,
15+ pub frame_rate: f64,
16+ pub frame_count: u32,
17+}
18+
19+pub struct Demuxer {
20+ reader: Mp4Reader<BufReader<File>>,
21+ track_id: u32,
22+ sample_count: u32,
23+ /// Annex-B SPS+PPS, re-injected ahead of every sync sample.
24+ parameter_sets: Vec<u8>,
25+ next_sample: u32,
26+}
27+
28+impl Demuxer {
29+ pub fn open(path: &Path) -> crate::Result<(VideoMeta, Self)> {
30+ let file = File::open(path)?;
31+ let size = file.metadata()?.len();
32+ let reader = Mp4Reader::read_header(BufReader::new(file), size)?;
33+
34+ let track = reader
35+ .tracks()
36+ .values()
37+ .find(|t| matches!(t.media_type(), Ok(MediaType::H264)))
38+ .ok_or("no H.264 video track in file")?;
39+
40+ let track_id = track.track_id();
41+ let meta = VideoMeta {
42+ width: track.width() as u32,
43+ height: track.height() as u32,
44+ frame_rate: track.frame_rate(),
45+ frame_count: 0,
46+ };
47+ let mut parameter_sets = Vec::new();
48+ parameter_sets.extend_from_slice(&START_CODE);
49+ parameter_sets.extend_from_slice(track.sequence_parameter_set()?);
50+ parameter_sets.extend_from_slice(&START_CODE);
51+ parameter_sets.extend_from_slice(track.picture_parameter_set()?);
52+
53+ let sample_count = reader.sample_count(track_id)?;
54+ Ok((
55+ VideoMeta {
56+ frame_count: sample_count,
57+ ..meta
58+ },
59+ Self {
60+ reader,
61+ track_id,
62+ sample_count,
63+ parameter_sets,
64+ next_sample: 1, // sample ids are 1-based
65+ },
66+ ))
67+ }
68+
69+ /// Next access unit in decode order, Annex-B framed. `None` at end of track.
70+ pub fn next_access_unit(&mut self) -> crate::Result<Option<Vec<u8>>> {
71+ if self.next_sample > self.sample_count {
72+ return Ok(None);
73+ }
74+ let sample = self.reader.read_sample(self.track_id, self.next_sample)?;
75+ self.next_sample += 1;
76+ let Some(sample) = sample else {
77+ return Ok(None);
78+ };
79+
80+ let mut au = Vec::with_capacity(self.parameter_sets.len() + sample.bytes.len() + 16);
81+ if sample.is_sync {
82+ au.extend_from_slice(&self.parameter_sets);
83+ }
84+ append_annex_b(&sample.bytes, &mut au)?;
85+ Ok(Some(au))
86+ }
87+}
88+
89+/// avcC length-prefixed NALs -> Annex-B. Assumes a 4-byte length prefix, which
90+/// mp4 0.14 does not expose; a wrong guess misparses immediately, hence the check.
91+///
92+/// ponytail: hardcoded 4-byte NAL length prefix (lengthSizeMinusOne == 3). 1/2-byte
93+/// prefixes exist in the wild; upgrade path is parsing the avcC box from
94+/// `track.trak` instead of assuming.
95+fn append_annex_b(mut src: &[u8], out: &mut Vec<u8>) -> crate::Result<()> {
96+ while !src.is_empty() {
97+ if src.len() < 4 {
98+ return Err(format!("truncated NAL length prefix: {} bytes left", src.len()).into());
99+ }
100+ let len = u32::from_be_bytes([src[0], src[1], src[2], src[3]]) as usize;
101+ if len == 0 || len > src.len() - 4 {
102+ return Err(format!(
103+ "bad NAL length {len} with {} bytes remaining (not a 4-byte-prefixed avcC sample?)",
104+ src.len() - 4
105+ )
106+ .into());
107+ }
108+ out.extend_from_slice(&START_CODE);
109+ out.extend_from_slice(&src[4..4 + len]);
110+ src = &src[4 + len..];
111+ }
112+ Ok(())
113+}
114+
115+#[cfg(test)]
116+mod tests {
117+ use super::*;
118+
119+ #[test]
120+ fn splits_two_nals() {
121+ let mut out = Vec::new();
122+ append_annex_b(&[0, 0, 0, 2, 0x65, 0xAA, 0, 0, 0, 1, 0x41], &mut out).unwrap();
123+ assert_eq!(out, [0, 0, 0, 1, 0x65, 0xAA, 0, 0, 0, 1, 0x41]);
124+ }
125+
126+ #[test]
127+ fn rejects_misparse() {
128+ assert!(append_annex_b(&[0, 0, 0, 9, 0x65], &mut Vec::new()).is_err());
129+ assert!(append_annex_b(&[0, 0, 0], &mut Vec::new()).is_err());
130+ assert!(append_annex_b(&[0, 0, 0, 0], &mut Vec::new()).is_err());
131+ }
132+}
crates/engine/src/hw.rsadded+180 -0
@@ -0,0 +1,180 @@
1+//! Runtime-optional hardware decode plugin (`libengine_hw.so`).
2+//!
3+//! The plugin links libva/gbm/drm; this crate and the app binary must not, so
4+//! the only coupling is this C ABI plus a `dlopen`. Anything that goes wrong --
5+//! plugin missing, no VA-API runtime, no render node, unsupported stream --
6+//! leaves us with `None` and the caller falls back to the software decoder.
7+
8+use std::ffi::{CString, c_char, c_void};
9+use std::path::Path;
10+use std::sync::OnceLock;
11+
12+use libloading::Library;
13+
14+const LIB_NAME: &str = "libengine_hw.so";
15+
16+/// Stream metadata, C layout. Mirrors [`crate::VideoMeta`].
17+#[repr(C)]
18+#[derive(Default)]
19+pub struct VhMeta {
20+ pub width: u32,
21+ pub height: u32,
22+ pub frame_rate: f64,
23+ pub frame_count: u32,
24+}
25+
26+/// One decoded picture as planar I420. Pointers belong to the plugin and stay
27+/// valid only until the next `vh_next_frame`/`vh_close` on the same session.
28+#[repr(C)]
29+pub struct VhFrame {
30+ pub y: *const u8,
31+ pub u: *const u8,
32+ pub v: *const u8,
33+ pub y_stride: usize,
34+ pub u_stride: usize,
35+ pub v_stride: usize,
36+ pub width: u32,
37+ pub height: u32,
38+}
39+
40+impl Default for VhFrame {
41+ fn default() -> Self {
42+ Self {
43+ y: std::ptr::null(),
44+ u: std::ptr::null(),
45+ v: std::ptr::null(),
46+ y_stride: 0,
47+ u_stride: 0,
48+ v_stride: 0,
49+ width: 0,
50+ height: 0,
51+ }
52+ }
53+}
54+
55+struct Plugin {
56+ open: unsafe extern "C" fn(*const c_char) -> *mut c_void,
57+ meta: unsafe extern "C" fn(*mut c_void, *mut VhMeta) -> i32,
58+ next_frame: unsafe extern "C" fn(*mut c_void, *mut VhFrame) -> i32,
59+ close: unsafe extern "C" fn(*mut c_void),
60+ // Never dropped (lives in a static), so the fn pointers above stay valid.
61+ _lib: Library,
62+}
63+
64+fn plugin() -> Option<&'static Plugin> {
65+ static PLUGIN: OnceLock<Option<Plugin>> = OnceLock::new();
66+ PLUGIN.get_or_init(load).as_ref()
67+}
68+
69+fn load() -> Option<Plugin> {
70+ // Next to the executable first (cargo puts both in target/<profile>), then
71+ // whatever the dynamic linker's search path turns up.
72+ let beside_exe = std::env::current_exe()
73+ .ok()
74+ .and_then(|exe| exe.parent().map(|dir| dir.join(LIB_NAME)));
75+ let candidates = beside_exe
76+ .as_deref()
77+ .into_iter()
78+ .chain(std::iter::once(Path::new(LIB_NAME)));
79+
80+ for candidate in candidates {
81+ // SAFETY: loading a shared object runs its initialisers; we only ever
82+ // name our own plugin, and every symbol below is type-checked against
83+ // the definitions this crate shares with it.
84+ let lib = match unsafe { Library::new(candidate) } {
85+ Ok(lib) => lib,
86+ Err(_) => continue,
87+ };
88+ let plugin = unsafe {
89+ (|| {
90+ Some(Plugin {
91+ open: *lib.get(b"vh_open\0").ok()?,
92+ meta: *lib.get(b"vh_meta\0").ok()?,
93+ next_frame: *lib.get(b"vh_next_frame\0").ok()?,
94+ close: *lib.get(b"vh_close\0").ok()?,
95+ _lib: lib,
96+ })
97+ })()
98+ };
99+ if plugin.is_some() {
100+ return plugin;
101+ }
102+ }
103+ None
104+}
105+
106+/// An open hardware decode session. Dropping it closes the plugin session.
107+pub struct HwSession {
108+ plugin: &'static Plugin,
109+ handle: *mut c_void,
110+}
111+
112+impl HwSession {
113+ /// Probes the plugin against this very file: success means the driver,
114+ /// the render node and the stream's profile are all usable.
115+ pub fn open(path: &Path) -> Option<Self> {
116+ let plugin = plugin()?;
117+ let c_path = CString::new(path.as_os_str().as_encoded_bytes()).ok()?;
118+ // SAFETY: `c_path` is a valid NUL-terminated string alive for the call.
119+ let handle = unsafe { (plugin.open)(c_path.as_ptr()) };
120+ if handle.is_null() {
121+ return None;
122+ }
123+ Some(Self { plugin, handle })
124+ }
125+
126+ pub fn meta(&self) -> Option<VhMeta> {
127+ let mut meta = VhMeta::default();
128+ // SAFETY: `handle` came from `vh_open` and is still open.
129+ if unsafe { (self.plugin.meta)(self.handle, &mut meta) } < 0 {
130+ return None;
131+ }
132+ Some(meta)
133+ }
134+
135+ /// Next picture in display order as tightly packed I420 `(y, u, v)`.
136+ /// `Ok(None)` is clean end of stream.
137+ pub fn next_frame(&mut self) -> crate::Result<Option<(&[u8], &[u8], &[u8], u32, u32)>> {
138+ let mut frame = VhFrame::default();
139+ // SAFETY: `handle` is live; the plugin fills `frame` with pointers that
140+ // stay valid until the next call, which `&mut self` prevents overlapping.
141+ match unsafe { (self.plugin.next_frame)(self.handle, &mut frame) } {
142+ 0 => return Ok(None),
143+ 1 => {}
144+ code => return Err(format!("hardware decode failed (code {code})").into()),
145+ }
146+ let (w, h) = (frame.width as usize, frame.height as usize);
147+ let (cw, ch) = (w.div_ceil(2), h.div_ceil(2));
148+ if frame.y.is_null()
149+ || frame.u.is_null()
150+ || frame.v.is_null()
151+ || frame.y_stride != w
152+ || frame.u_stride != cw
153+ || frame.v_stride != cw
154+ {
155+ return Err("hardware plugin returned a non-packed I420 frame".into());
156+ }
157+ // SAFETY: plane pointers are non-null and the strides just checked above
158+ // pin each plane's length; the borrow ends before the next call.
159+ unsafe {
160+ Ok(Some((
161+ std::slice::from_raw_parts(frame.y, w * h),
162+ std::slice::from_raw_parts(frame.u, cw * ch),
163+ std::slice::from_raw_parts(frame.v, cw * ch),
164+ frame.width,
165+ frame.height,
166+ )))
167+ }
168+ }
169+}
170+
171+impl Drop for HwSession {
172+ fn drop(&mut self) {
173+ // SAFETY: `handle` came from `vh_open` and is closed exactly once.
174+ unsafe { (self.plugin.close)(self.handle) }
175+ }
176+}
177+
178+// The plugin session is used from one thread at a time (the decode worker) and
179+// never shared; VA-API state inside it is not `Sync`.
180+unsafe impl Send for HwSession {}
crates/engine/src/lib.rsadded+14 -0
@@ -0,0 +1,14 @@
1+//! Video engine: demux -> decode -> pixel convert. No UI dependencies.
2+
3+pub mod convert;
4+pub mod decode;
5+pub mod demux;
6+pub mod hw;
7+
8+pub use decode::{DecodeSession, Frame};
9+pub use demux::VideoMeta;
10+
11+/// Boxed error; the engine has few failure modes and every one of them is fatal
12+/// to the session, so a message is all a caller can act on.
13+pub type Error = Box<dyn std::error::Error + Send + Sync>;
14+pub type Result<T> = std::result::Result<T, Error>;
crates/engine/tests/decode_baseline.rsadded+39 -0
@@ -0,0 +1,39 @@
1+use std::path::PathBuf;
2+use std::time::Instant;
3+
4+use engine::DecodeSession;
5+
6+fn asset(name: &str) -> PathBuf {
7+ PathBuf::from(env!("CARGO_MANIFEST_DIR"))
8+ .join("../../assets")
9+ .join(name)
10+}
11+
12+#[test]
13+fn decodes_baseline_mp4() {
14+ let path = asset("test_baseline.mp4");
15+ let (meta, rx) = DecodeSession::open(&path).expect("open");
16+ assert_eq!((meta.width, meta.height), (1280, 720), "container dims");
17+ assert!(meta.frame_count > 0);
18+
19+ // Capped: pure-Rust 720p decode is slow in a debug test build.
20+ // Set DECODE_FRAMES to drain the whole stream (checks clean EOF).
21+ let want: usize = std::env::var("DECODE_FRAMES")
22+ .ok()
23+ .and_then(|v| v.parse().ok())
24+ .unwrap_or(10);
25+ let start = Instant::now();
26+ let mut frames = 0usize;
27+ for frame in rx.iter().take(want) {
28+ assert_eq!((frame.width, frame.height), (1280, 720));
29+ assert_eq!(frame.bgra.len(), 1280 * 720 * 4);
30+ assert_eq!(frame.index as usize, frames);
31+ frames += 1;
32+ }
33+ assert!(frames > 0, "no frames decoded");
34+ eprintln!(
35+ "{frames} frames in {:?} ({:?}/frame)",
36+ start.elapsed(),
37+ start.elapsed() / frames as u32
38+ );
39+}
crates/engine/tests/hw_decode.rsadded+110 -0
@@ -0,0 +1,110 @@
1+//! Hardware path checks. These need a built `libengine_hw.so` plus a working
2+//! VA-API driver, so they are `#[ignore]`d by default. Run them with:
3+//!
4+//! ```text
5+//! cargo build --workspace --release
6+//! LD_LIBRARY_PATH=target/release \
7+//! cargo test -p engine --release --test hw_decode -- --ignored --nocapture --test-threads=1
8+//! ```
9+//!
10+//! The comparison test pins [`DecodeSession`] to the software decoder itself
11+//! (it sets `VE_SW=1` in-process, hence the required `--test-threads=1`); the
12+//! hardware side goes through [`HwSession`] directly and can never silently be
13+//! a fallback.
14+
15+use std::path::{Path, PathBuf};
16+use std::time::Instant;
17+
18+use engine::DecodeSession;
19+use engine::convert::i420_to_bgra;
20+use engine::hw::HwSession;
21+
22+fn asset(name: &str) -> PathBuf {
23+ PathBuf::from(env!("CARGO_MANIFEST_DIR"))
24+ .join("../../assets")
25+ .join(name)
26+}
27+
28+fn open_hw(path: &Path) -> HwSession {
29+ HwSession::open(path).expect("no hardware decode plugin/driver available")
30+}
31+
32+/// Decodes the whole file through the plugin, returning (frame count, frame 30 as BGRA).
33+fn decode_all_hw(name: &str) -> (usize, Vec<u8>) {
34+ let path = asset(name);
35+ let mut hw = open_hw(&path);
36+ let meta = hw.meta().expect("meta");
37+ assert_eq!(
38+ (meta.width, meta.height),
39+ (1280, 720),
40+ "{name} container dims"
41+ );
42+
43+ let mut count = 0usize;
44+ let mut frame_30 = Vec::new();
45+ let start = Instant::now();
46+ while let Some((y, u, v, w, h)) = hw.next_frame().expect("hardware decode") {
47+ assert_eq!((w, h), (1280, 720), "{name} frame {count} dims");
48+ if count == 30 {
49+ frame_30 = i420_to_bgra(y, u, v, w as usize, h as usize);
50+ }
51+ count += 1;
52+ }
53+ eprintln!(
54+ "{name}: {count} hardware frames in {:?} ({:?}/frame)",
55+ start.elapsed(),
56+ start.elapsed() / count.max(1) as u32
57+ );
58+ (count, frame_30)
59+}
60+
61+/// The plugin must refuse junk by returning null, never by unwinding into us.
62+#[test]
63+#[ignore = "needs libengine_hw.so and a VA-API driver"]
64+fn rejects_unopenable_files() {
65+ assert!(HwSession::open(Path::new("/definitely/not/here.mp4")).is_none());
66+ assert!(HwSession::open(Path::new("/etc/hostname")).is_none(), "not an mp4");
67+}
68+
69+#[test]
70+#[ignore = "needs libengine_hw.so and a VA-API driver"]
71+fn hardware_decodes_baseline() {
72+ let (count, _) = decode_all_hw("test_baseline.mp4");
73+ assert_eq!(count, 150);
74+}
75+
76+#[test]
77+#[ignore = "needs libengine_hw.so and a VA-API driver"]
78+fn hardware_decodes_high_profile() {
79+ // B-frames: the plugin emits display order (DPB bumping happens inside
80+ // cros-codecs), so a clean run to EOF is the check we can make headlessly.
81+ let (count, _) = decode_all_hw("test_high.mp4");
82+ assert_eq!(count, 150);
83+}
84+
85+/// H.264 8-bit decode is bit-exact by conformance, so the two backends must
86+/// agree. A mismatch means a driver deviation and is reported, not swallowed.
87+#[test]
88+#[ignore = "needs libengine_hw.so and a VA-API driver"]
89+fn hardware_matches_software_on_frame_30() {
90+ let (_, hw) = decode_all_hw("test_baseline.mp4");
91+
92+ // Pin the comparison side to software ourselves: without this, running the
93+ // suite without VE_SW=1 would compare hardware against hardware and pass
94+ // vacuously. SAFETY: the suite is documented to run with --test-threads=1.
95+ unsafe { std::env::set_var("VE_SW", "1") };
96+
97+ let start = Instant::now();
98+ let (_, rx) = DecodeSession::open(asset("test_baseline.mp4")).expect("software open");
99+ let sw = rx
100+ .into_iter()
101+ .find(|f| f.index == 30)
102+ .expect("software frame 30")
103+ .bgra;
104+ eprintln!("software reached frame 30 in {:?}", start.elapsed());
105+
106+ assert_eq!(hw.len(), sw.len(), "frame size");
107+ let diff = hw.iter().zip(&sw).filter(|(a, b)| a != b).count();
108+ eprintln!("frame 30 differing bytes: {diff} / {}", hw.len());
109+ assert_eq!(diff, 0, "hardware and software decode disagree");
110+}
scripts/gen_fixtures.shadded+11 -0
@@ -0,0 +1,11 @@
1+#!/usr/bin/env bash
2+# Regenerates the gitignored test fixtures under assets/.
3+# Needs the ffmpeg CLI (dev tool only — the app itself never uses ffmpeg).
4+set -euo pipefail
5+cd "$(dirname "$0")/.."
6+mkdir -p assets
7+ffmpeg -y -f lavfi -i testsrc2=size=1280x720:rate=30:duration=5 \
8+ -c:v libx264 -profile:v baseline -pix_fmt yuv420p assets/test_baseline.mp4
9+ffmpeg -y -f lavfi -i testsrc2=size=1280x720:rate=30:duration=5 \
10+ -c:v libx264 -profile:v high -pix_fmt yuv420p assets/test_high.mp4
11+echo "fixtures written to assets/"
vendor/cros-codecs/.cargo/config.tomladded+6 -0
@@ -0,0 +1,6 @@
1+# When cross compiling outside of the chroot
2+# with --target aarch64-unknown-linux-gnu the
3+# linker needs to explicity defined for the
4+# examples to link.
5+[target.aarch64-unknown-linux-gnu]
6+linker = "aarch64-linux-gnu-gcc"
vendor/cros-codecs/.cargo_vcs_info.jsonadded+6 -0
@@ -0,0 +1,6 @@
1+{
2+ "git": {
3+ "sha1": "7a4211c57ac2e791412f40df2c22fd2cf81104f6"
4+ },
5+ "path_in_vcs": ""
6+}
\ No newline at end of file\ No newline at end of file
vendor/cros-codecs/.clippy.tomladded+2 -0
@@ -0,0 +1,2 @@
1+allow-unwrap-in-tests = true
2+allow-expect-in-tests = true
vendor/cros-codecs/.gitignoreadded+2 -0
@@ -0,0 +1,2 @@
1+/target
2+.nlsp-settings
vendor/cros-codecs/Android.bpadded+156 -0
@@ -0,0 +1,156 @@
1+package {
2+ default_applicable_licenses: ["system_cros-codecs_license"],
3+ // TODO(b/374841646): This is a temporary assignment.
4+ default_team: "trendy_team_arc_next",
5+}
6+
7+license {
8+ name: "system_cros-codecs_license",
9+ visibility: [":__subpackages__"],
10+ license_kinds: ["SPDX-license-identifier-BSD-3-Clause"],
11+ license_text: ["LICENSE"],
12+}
13+
14+rust_defaults {
15+ name: "libcros_codecs_defaults",
16+ crate_name: "cros_codecs",
17+ cargo_env_compat: true,
18+ cargo_pkg_version: "0.0.5",
19+ crate_root: "src/lib.rs",
20+ edition: "2021",
21+ rustlibs: [
22+ "libanyhow",
23+ "libcrc32fast",
24+ "libbyteorder",
25+ "libthiserror",
26+ "liblog_rust",
27+ "libgbm_rust",
28+ "libdrm_rust",
29+ "libdrm_fourcc",
30+ "libgbm_sys",
31+ "libnix",
32+ "libzerocopy",
33+ ],
34+ aliases: ["cros_libva:libva"],
35+ apex_available: [
36+ "//apex_available:platform",
37+ "//apex_available:anyapex",
38+ ],
39+ // TODO(b/382119688): Remove this.
40+ lints: "none",
41+
42+ product_available: true,
43+ vendor_available: true,
44+}
45+
46+rust_library {
47+ name: "libcros_codecs",
48+ defaults: ["libcros_codecs_defaults"],
49+ enabled: false,
50+ arch: {
51+ x86_64: {
52+ enabled: true,
53+ features: [
54+ "vaapi",
55+ "backend",
56+ ],
57+ rustlibs: ["libcros_libva"],
58+ },
59+ arm64: {
60+ enabled: true,
61+ features: [
62+ "v4l2",
63+ "backend",
64+ ],
65+ rustlibs: ["libv4l2r"],
66+ },
67+ },
68+}
69+
70+rust_test_host {
71+ name: "libcros_codecs_test",
72+ defaults: ["libcros_codecs_defaults"],
73+ rustlibs: ["libenv_logger"],
74+}
75+
76+rust_test {
77+ name: "ccdec_test",
78+ srcs: ["test/ccdec_test.rs"],
79+ test_suites: ["general-tests"],
80+ test_config: "test/AndroidTest.xml",
81+ rustlibs: [
82+ "libargh",
83+ "libcros_codecs",
84+ "libenv_logger",
85+ "liblog_rust",
86+ "libserde_json",
87+ ],
88+ data: [
89+ ":test_data",
90+ ],
91+ data_bins: ["ccdec"],
92+ // TODO(b/394365384): Group shared dependencies with rust_defaults
93+ enabled: false,
94+ arch: {
95+ x86_64: {
96+ enabled: true,
97+ features: [
98+ "vaapi",
99+ "backend",
100+ ],
101+ },
102+ arm64: {
103+ enabled: true,
104+ features: [
105+ "v4l2",
106+ "backend",
107+ ],
108+ },
109+ },
110+}
111+
112+rust_test {
113+ name: "ccdec",
114+ srcs: ["examples/ccdec/main.rs"],
115+ test_suites: ["general-tests"],
116+ rustlibs: [
117+ "libenv_logger",
118+ "libcros_codecs",
119+ "libargh",
120+ "libserde_json",
121+ ],
122+ // TODO(b/394365384): Group shared dependencies with rust_defaults
123+ enabled: false,
124+ arch: {
125+ x86_64: {
126+ enabled: true,
127+ features: [
128+ "vaapi",
129+ "backend",
130+ ],
131+ },
132+ arm64: {
133+ enabled: true,
134+ features: [
135+ "v4l2",
136+ "backend",
137+ ],
138+ },
139+ },
140+ test_harness: false,
141+}
142+
143+filegroup {
144+ name: "test_data",
145+ srcs: [
146+ "src/codec/av1/test_data/*",
147+ "src/codec/h264/test_data/*",
148+ "src/codec/h265/test_data/*",
149+ "src/codec/vp8/test_data/*",
150+ "src/codec/vp9/test_data/*",
151+ ],
152+ exclude_srcs: [
153+ "src/codec/**/gen_crcs.sh",
154+ "src/codec/**/README.md",
155+ ],
156+}
vendor/cros-codecs/CONTRIBUTING.mdadded+33 -0
@@ -0,0 +1,33 @@
1+# How to Contribute
2+
3+We'd love to accept your patches and contributions to this project.
4+
5+## Before you begin
6+
7+### Sign our Contributor License Agreement
8+
9+Contributions to this project must be accompanied by a
10+[Contributor License Agreement](https://cla.developers.google.com/about) (CLA).
11+You (or your employer) retain the copyright to your contribution; this simply
12+gives us permission to use and redistribute your contributions as part of the
13+project.
14+
15+If you or your current employer have already signed the Google CLA (even if it
16+was for a different project), you probably don't need to do it again.
17+
18+Visit <https://cla.developers.google.com/> to see your current agreements or to
19+sign a new one.
20+
21+### Review our Community Guidelines
22+
23+This project follows
24+[Google's Open Source Community Guidelines](https://opensource.google/conduct/).
25+
26+## Contribution process
27+
28+### Code Reviews
29+
30+All submissions, including submissions by project members, require review. We
31+use GitHub pull requests for this purpose. Consult
32+[GitHub Help](https://help.github.com/articles/about-pull-requests/) for more
33+information on using pull requests.
vendor/cros-codecs/Cargo.lockadded+847 -0
@@ -0,0 +1,847 @@
1+# This file is automatically @generated by Cargo.
2+# It is not intended for manual editing.
3+version = 3
4+
5+[[package]]
6+name = "aho-corasick"
7+version = "1.1.3"
8+source = "registry+https://github.com/rust-lang/crates.io-index"
9+checksum = "8e60d3430d3a69478ad0993f19238d2df97c507009a52b3c10addcd7f6bcb916"
10+dependencies = [
11+ "memchr",
12+]
13+
14+[[package]]
15+name = "anyhow"
16+version = "1.0.98"
17+source = "registry+https://github.com/rust-lang/crates.io-index"
18+checksum = "e16d2d3311acee920a9eb8d33b8cbc1787ce4a264e85f964c2404b969bdcd487"
19+
20+[[package]]
21+name = "argh"
22+version = "0.1.13"
23+source = "registry+https://github.com/rust-lang/crates.io-index"
24+checksum = "34ff18325c8a36b82f992e533ece1ec9f9a9db446bd1c14d4f936bac88fcd240"
25+dependencies = [
26+ "argh_derive",
27+ "argh_shared",
28+ "rust-fuzzy-search",
29+]
30+
31+[[package]]
32+name = "argh_derive"
33+version = "0.1.13"
34+source = "registry+https://github.com/rust-lang/crates.io-index"
35+checksum = "adb7b2b83a50d329d5d8ccc620f5c7064028828538bdf5646acd60dc1f767803"
36+dependencies = [
37+ "argh_shared",
38+ "proc-macro2",
39+ "quote",
40+ "syn",
41+]
42+
43+[[package]]
44+name = "argh_shared"
45+version = "0.1.13"
46+source = "registry+https://github.com/rust-lang/crates.io-index"
47+checksum = "a464143cc82dedcdc3928737445362466b7674b5db4e2eb8e869846d6d84f4f6"
48+dependencies = [
49+ "serde",
50+]
51+
52+[[package]]
53+name = "atty"
54+version = "0.2.14"
55+source = "registry+https://github.com/rust-lang/crates.io-index"
56+checksum = "d9b39be18770d11421cdb1b9947a45dd3f37e93092cbf377614828a319d5fee8"
57+dependencies = [
58+ "hermit-abi",
59+ "libc",
60+ "winapi",
61+]
62+
63+[[package]]
64+name = "bindgen"
65+version = "0.69.5"
66+source = "registry+https://github.com/rust-lang/crates.io-index"
67+checksum = "271383c67ccabffb7381723dea0672a673f292304fcb45c01cc648c7a8d58088"
68+dependencies = [
69+ "bitflags",
70+ "cexpr",
71+ "clang-sys",
72+ "itertools 0.12.1",
73+ "lazy_static",
74+ "lazycell",
75+ "log",
76+ "prettyplease",
77+ "proc-macro2",
78+ "quote",
79+ "regex",
80+ "rustc-hash",
81+ "shlex",
82+ "syn",
83+ "which",
84+]
85+
86+[[package]]
87+name = "bindgen"
88+version = "0.70.1"
89+source = "registry+https://github.com/rust-lang/crates.io-index"
90+checksum = "f49d8fed880d473ea71efb9bf597651e77201bdd4893efe54c9e5d65ae04ce6f"
91+dependencies = [
92+ "bitflags",
93+ "cexpr",
94+ "clang-sys",
95+ "itertools 0.13.0",
96+ "log",
97+ "prettyplease",
98+ "proc-macro2",
99+ "quote",
100+ "regex",
101+ "rustc-hash",
102+ "shlex",
103+ "syn",
104+]
105+
106+[[package]]
107+name = "bitflags"
108+version = "2.9.1"
109+source = "registry+https://github.com/rust-lang/crates.io-index"
110+checksum = "1b8e56985ec62d17e9c1001dc89c88ecd7dc08e47eba5ec7c29c7b5eeecde967"
111+
112+[[package]]
113+name = "bytemuck"
114+version = "1.23.1"
115+source = "registry+https://github.com/rust-lang/crates.io-index"
116+checksum = "5c76a5792e44e4abe34d3abf15636779261d45a7450612059293d1d2cfc63422"
117+dependencies = [
118+ "bytemuck_derive",
119+]
120+
121+[[package]]
122+name = "bytemuck_derive"
123+version = "1.9.3"
124+source = "registry+https://github.com/rust-lang/crates.io-index"
125+checksum = "7ecc273b49b3205b83d648f0690daa588925572cc5063745bfe547fe7ec8e1a1"
126+dependencies = [
127+ "proc-macro2",
128+ "quote",
129+ "syn",
130+]
131+
132+[[package]]
133+name = "byteorder"
134+version = "1.5.0"
135+source = "registry+https://github.com/rust-lang/crates.io-index"
136+checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b"
137+
138+[[package]]
139+name = "cexpr"
140+version = "0.6.0"
141+source = "registry+https://github.com/rust-lang/crates.io-index"
142+checksum = "6fac387a98bb7c37292057cffc56d62ecb629900026402633ae9160df93a8766"
143+dependencies = [
144+ "nom",
145+]
146+
147+[[package]]
148+name = "cfg-if"
149+version = "1.0.1"
150+source = "registry+https://github.com/rust-lang/crates.io-index"
151+checksum = "9555578bc9e57714c812a1f84e4fc5b4d21fcb063490c624de019f7464c91268"
152+
153+[[package]]
154+name = "cfg_aliases"
155+version = "0.1.1"
156+source = "registry+https://github.com/rust-lang/crates.io-index"
157+checksum = "fd16c4719339c4530435d38e511904438d07cce7950afa3718a84ac36c10e89e"
158+
159+[[package]]
160+name = "clang-sys"
161+version = "1.8.1"
162+source = "registry+https://github.com/rust-lang/crates.io-index"
163+checksum = "0b023947811758c97c59bf9d1c188fd619ad4718dcaa767947df1cadb14f39f4"
164+dependencies = [
165+ "glob",
166+ "libc",
167+ "libloading",
168+]
169+
170+[[package]]
171+name = "crc32fast"
172+version = "1.4.2"
173+source = "registry+https://github.com/rust-lang/crates.io-index"
174+checksum = "a97769d94ddab943e4510d138150169a2758b5ef3eb191a9ee688de3e23ef7b3"
175+dependencies = [
176+ "cfg-if",
177+]
178+
179+[[package]]
180+name = "cros-codecs"
181+version = "0.0.6"
182+dependencies = [
183+ "anyhow",
184+ "argh",
185+ "byteorder",
186+ "crc32fast",
187+ "cros-libva",
188+ "drm",
189+ "drm-fourcc",
190+ "env_logger",
191+ "gbm",
192+ "gbm-sys",
193+ "log",
194+ "nix",
195+ "serde_json",
196+ "thiserror",
197+ "v4l2r",
198+ "zerocopy",
199+]
200+
201+[[package]]
202+name = "cros-libva"
203+version = "0.0.12"
204+source = "registry+https://github.com/rust-lang/crates.io-index"
205+checksum = "902c9726e953b678595456bd38f95f31aaf1947c56dd9f4a2290f3f1eca4d228"
206+dependencies = [
207+ "bindgen 0.70.1",
208+ "bitflags",
209+ "log",
210+ "pkg-config",
211+ "regex",
212+ "thiserror",
213+]
214+
215+[[package]]
216+name = "drm"
217+version = "0.12.0"
218+source = "registry+https://github.com/rust-lang/crates.io-index"
219+checksum = "98888c4bbd601524c11a7ed63f814b8825f420514f78e96f752c437ae9cbb5d1"
220+dependencies = [
221+ "bitflags",
222+ "bytemuck",
223+ "drm-ffi",
224+ "drm-fourcc",
225+ "rustix",
226+]
227+
228+[[package]]
229+name = "drm-ffi"
230+version = "0.8.0"
231+source = "registry+https://github.com/rust-lang/crates.io-index"
232+checksum = "97c98727e48b7ccb4f4aea8cfe881e5b07f702d17b7875991881b41af7278d53"
233+dependencies = [
234+ "drm-sys",
235+ "rustix",
236+]
237+
238+[[package]]
239+name = "drm-fourcc"
240+version = "2.2.0"
241+source = "registry+https://github.com/rust-lang/crates.io-index"
242+checksum = "0aafbcdb8afc29c1a7ee5fbe53b5d62f4565b35a042a662ca9fecd0b54dae6f4"
243+
244+[[package]]
245+name = "drm-sys"
246+version = "0.7.0"
247+source = "registry+https://github.com/rust-lang/crates.io-index"
248+checksum = "fd39dde40b6e196c2e8763f23d119ddb1a8714534bf7d77fa97a65b0feda3986"
249+dependencies = [
250+ "libc",
251+ "linux-raw-sys 0.6.5",
252+]
253+
254+[[package]]
255+name = "either"
256+version = "1.15.0"
257+source = "registry+https://github.com/rust-lang/crates.io-index"
258+checksum = "48c757948c5ede0e46177b7add2e67155f70e33c07fea8284df6576da70b3719"
259+
260+[[package]]
261+name = "enumn"
262+version = "0.1.14"
263+source = "registry+https://github.com/rust-lang/crates.io-index"
264+checksum = "2f9ed6b3789237c8a0c1c505af1c7eb2c560df6186f01b098c3a1064ea532f38"
265+dependencies = [
266+ "proc-macro2",
267+ "quote",
268+ "syn",
269+]
270+
271+[[package]]
272+name = "env_logger"
273+version = "0.9.3"
274+source = "registry+https://github.com/rust-lang/crates.io-index"
275+checksum = "a12e6657c4c97ebab115a42dcee77225f7f482cdd841cf7088c657a42e9e00e7"
276+dependencies = [
277+ "atty",
278+ "humantime",
279+ "log",
280+ "regex",
281+ "termcolor",
282+]
283+
284+[[package]]
285+name = "errno"
286+version = "0.3.12"
287+source = "registry+https://github.com/rust-lang/crates.io-index"
288+checksum = "cea14ef9355e3beab063703aa9dab15afd25f0667c341310c1e5274bb1d0da18"
289+dependencies = [
290+ "libc",
291+ "windows-sys",
292+]
293+
294+[[package]]
295+name = "gbm"
296+version = "0.15.0"
297+source = "registry+https://github.com/rust-lang/crates.io-index"
298+checksum = "45bf55ba6dd53ad0ac115046ff999c5324c283444ee6e0be82454c4e8eb2f36a"
299+dependencies = [
300+ "bitflags",
301+ "drm",
302+ "drm-fourcc",
303+ "gbm-sys",
304+ "libc",
305+]
306+
307+[[package]]
308+name = "gbm-sys"
309+version = "0.3.1"
310+source = "registry+https://github.com/rust-lang/crates.io-index"
311+checksum = "a9cc2f64de9fa707b5c6b2d2f10d7a7e49e845018a9f5685891eb40d3bab2538"
312+dependencies = [
313+ "libc",
314+]
315+
316+[[package]]
317+name = "glob"
318+version = "0.3.2"
319+source = "registry+https://github.com/rust-lang/crates.io-index"
320+checksum = "a8d1add55171497b4705a648c6b583acafb01d58050a51727785f0b2c8e0a2b2"
321+
322+[[package]]
323+name = "hermit-abi"
324+version = "0.1.19"
325+source = "registry+https://github.com/rust-lang/crates.io-index"
326+checksum = "62b467343b94ba476dcb2500d242dadbb39557df889310ac77c5d99100aaac33"
327+dependencies = [
328+ "libc",
329+]
330+
331+[[package]]
332+name = "home"
333+version = "0.5.11"
334+source = "registry+https://github.com/rust-lang/crates.io-index"
335+checksum = "589533453244b0995c858700322199b2becb13b627df2851f64a2775d024abcf"
336+dependencies = [
337+ "windows-sys",
338+]
339+
340+[[package]]
341+name = "humantime"
342+version = "2.2.0"
343+source = "registry+https://github.com/rust-lang/crates.io-index"
344+checksum = "9b112acc8b3adf4b107a8ec20977da0273a8c386765a3ec0229bd500a1443f9f"
345+
346+[[package]]
347+name = "itertools"
348+version = "0.12.1"
349+source = "registry+https://github.com/rust-lang/crates.io-index"
350+checksum = "ba291022dbbd398a455acf126c1e341954079855bc60dfdda641363bd6922569"
351+dependencies = [
352+ "either",
353+]
354+
355+[[package]]
356+name = "itertools"
357+version = "0.13.0"
358+source = "registry+https://github.com/rust-lang/crates.io-index"
359+checksum = "413ee7dfc52ee1a4949ceeb7dbc8a33f2d6c088194d9f922fb8318faf1f01186"
360+dependencies = [
361+ "either",
362+]
363+
364+[[package]]
365+name = "itoa"
366+version = "1.0.15"
367+source = "registry+https://github.com/rust-lang/crates.io-index"
368+checksum = "4a5f13b858c8d314ee3e8f639011f7ccefe71f97f96e50151fb991f267928e2c"
369+
370+[[package]]
371+name = "lazy_static"
372+version = "1.5.0"
373+source = "registry+https://github.com/rust-lang/crates.io-index"
374+checksum = "bbd2bcb4c963f2ddae06a2efc7e9f3591312473c50c6685e1f298068316e66fe"
375+
376+[[package]]
377+name = "lazycell"
378+version = "1.3.0"
379+source = "registry+https://github.com/rust-lang/crates.io-index"
380+checksum = "830d08ce1d1d941e6b30645f1a0eb5643013d835ce3779a5fc208261dbe10f55"
381+
382+[[package]]
383+name = "libc"
384+version = "0.2.174"
385+source = "registry+https://github.com/rust-lang/crates.io-index"
386+checksum = "1171693293099992e19cddea4e8b849964e9846f4acee11b3948bcc337be8776"
387+
388+[[package]]
389+name = "libloading"
390+version = "0.8.8"
391+source = "registry+https://github.com/rust-lang/crates.io-index"
392+checksum = "07033963ba89ebaf1584d767badaa2e8fcec21aedea6b8c0346d487d49c28667"
393+dependencies = [
394+ "cfg-if",
395+ "windows-targets 0.53.2",
396+]
397+
398+[[package]]
399+name = "linux-raw-sys"
400+version = "0.4.15"
401+source = "registry+https://github.com/rust-lang/crates.io-index"
402+checksum = "d26c52dbd32dccf2d10cac7725f8eae5296885fb5703b261f7d0a0739ec807ab"
403+
404+[[package]]
405+name = "linux-raw-sys"
406+version = "0.6.5"
407+source = "registry+https://github.com/rust-lang/crates.io-index"
408+checksum = "2a385b1be4e5c3e362ad2ffa73c392e53f031eaa5b7d648e64cd87f27f6063d7"
409+
410+[[package]]
411+name = "log"
412+version = "0.4.27"
413+source = "registry+https://github.com/rust-lang/crates.io-index"
414+checksum = "13dc2df351e3202783a1fe0d44375f7295ffb4049267b0f3018346dc122a1d94"
415+
416+[[package]]
417+name = "memchr"
418+version = "2.7.5"
419+source = "registry+https://github.com/rust-lang/crates.io-index"
420+checksum = "32a282da65faaf38286cf3be983213fcf1d2e2a58700e808f83f4ea9a4804bc0"
421+
422+[[package]]
423+name = "minimal-lexical"
424+version = "0.2.1"
425+source = "registry+https://github.com/rust-lang/crates.io-index"
426+checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a"
427+
428+[[package]]
429+name = "nix"
430+version = "0.28.0"
431+source = "registry+https://github.com/rust-lang/crates.io-index"
432+checksum = "ab2156c4fce2f8df6c499cc1c763e4394b7482525bf2a9701c9d79d215f519e4"
433+dependencies = [
434+ "bitflags",
435+ "cfg-if",
436+ "cfg_aliases",
437+ "libc",
438+]
439+
440+[[package]]
441+name = "nom"
442+version = "7.1.3"
443+source = "registry+https://github.com/rust-lang/crates.io-index"
444+checksum = "d273983c5a657a70a3e8f2a01329822f3b8c8172b73826411a55751e404a0a4a"
445+dependencies = [
446+ "memchr",
447+ "minimal-lexical",
448+]
449+
450+[[package]]
451+name = "once_cell"
452+version = "1.21.3"
453+source = "registry+https://github.com/rust-lang/crates.io-index"
454+checksum = "42f5e15c9953c5e4ccceeb2e7382a716482c34515315f7b03532b8b4e8393d2d"
455+
456+[[package]]
457+name = "pkg-config"
458+version = "0.3.32"
459+source = "registry+https://github.com/rust-lang/crates.io-index"
460+checksum = "7edddbd0b52d732b21ad9a5fab5c704c14cd949e5e9a1ec5929a24fded1b904c"
461+
462+[[package]]
463+name = "prettyplease"
464+version = "0.2.34"
465+source = "registry+https://github.com/rust-lang/crates.io-index"
466+checksum = "6837b9e10d61f45f987d50808f83d1ee3d206c66acf650c3e4ae2e1f6ddedf55"
467+dependencies = [
468+ "proc-macro2",
469+ "syn",
470+]
471+
472+[[package]]
473+name = "proc-macro2"
474+version = "1.0.95"
475+source = "registry+https://github.com/rust-lang/crates.io-index"
476+checksum = "02b3e5e68a3a1a02aad3ec490a98007cbc13c37cbe84a3cd7b8e406d76e7f778"
477+dependencies = [
478+ "unicode-ident",
479+]
480+
481+[[package]]
482+name = "quote"
483+version = "1.0.40"
484+source = "registry+https://github.com/rust-lang/crates.io-index"
485+checksum = "1885c039570dc00dcb4ff087a89e185fd56bae234ddc7f056a945bf36467248d"
486+dependencies = [
487+ "proc-macro2",
488+]
489+
490+[[package]]
491+name = "regex"
492+version = "1.11.1"
493+source = "registry+https://github.com/rust-lang/crates.io-index"
494+checksum = "b544ef1b4eac5dc2db33ea63606ae9ffcfac26c1416a2806ae0bf5f56b201191"
495+dependencies = [
496+ "aho-corasick",
497+ "memchr",
498+ "regex-automata",
499+ "regex-syntax",
500+]
501+
502+[[package]]
503+name = "regex-automata"
504+version = "0.4.9"
505+source = "registry+https://github.com/rust-lang/crates.io-index"
506+checksum = "809e8dc61f6de73b46c85f4c96486310fe304c434cfa43669d7b40f711150908"
507+dependencies = [
508+ "aho-corasick",
509+ "memchr",
510+ "regex-syntax",
511+]
512+
513+[[package]]
514+name = "regex-syntax"
515+version = "0.8.5"
516+source = "registry+https://github.com/rust-lang/crates.io-index"
517+checksum = "2b15c43186be67a4fd63bee50d0303afffcef381492ebe2c5d87f324e1b8815c"
518+
519+[[package]]
520+name = "rust-fuzzy-search"
521+version = "0.1.1"
522+source = "registry+https://github.com/rust-lang/crates.io-index"
523+checksum = "a157657054ffe556d8858504af8a672a054a6e0bd9e8ee531059100c0fa11bb2"
524+
525+[[package]]
526+name = "rustc-hash"
527+version = "1.1.0"
528+source = "registry+https://github.com/rust-lang/crates.io-index"
529+checksum = "08d43f7aa6b08d49f382cde6a7982047c3426db949b1424bc4b7ec9ae12c6ce2"
530+
531+[[package]]
532+name = "rustix"
533+version = "0.38.44"
534+source = "registry+https://github.com/rust-lang/crates.io-index"
535+checksum = "fdb5bc1ae2baa591800df16c9ca78619bf65c0488b41b96ccec5d11220d8c154"
536+dependencies = [
537+ "bitflags",
538+ "errno",
539+ "libc",
540+ "linux-raw-sys 0.4.15",
541+ "windows-sys",
542+]
543+
544+[[package]]
545+name = "ryu"
546+version = "1.0.20"
547+source = "registry+https://github.com/rust-lang/crates.io-index"
548+checksum = "28d3b2b1366ec20994f1fd18c3c594f05c5dd4bc44d8bb0c1c632c8d6829481f"
549+
550+[[package]]
551+name = "serde"
552+version = "1.0.219"
553+source = "registry+https://github.com/rust-lang/crates.io-index"
554+checksum = "5f0e2c6ed6606019b4e29e69dbaba95b11854410e5347d525002456dbbb786b6"
555+dependencies = [
556+ "serde_derive",
557+]
558+
559+[[package]]
560+name = "serde_derive"
561+version = "1.0.219"
562+source = "registry+https://github.com/rust-lang/crates.io-index"
563+checksum = "5b0276cf7f2c73365f7157c8123c21cd9a50fbbd844757af28ca1f5925fc2a00"
564+dependencies = [
565+ "proc-macro2",
566+ "quote",
567+ "syn",
568+]
569+
570+[[package]]
571+name = "serde_json"
572+version = "1.0.140"
573+source = "registry+https://github.com/rust-lang/crates.io-index"
574+checksum = "20068b6e96dc6c9bd23e01df8827e6c7e1f2fddd43c21810382803c136b99373"
575+dependencies = [
576+ "itoa",
577+ "memchr",
578+ "ryu",
579+ "serde",
580+]
581+
582+[[package]]
583+name = "shlex"
584+version = "1.3.0"
585+source = "registry+https://github.com/rust-lang/crates.io-index"
586+checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64"
587+
588+[[package]]
589+name = "syn"
590+version = "2.0.103"
591+source = "registry+https://github.com/rust-lang/crates.io-index"
592+checksum = "e4307e30089d6fd6aff212f2da3a1f9e32f3223b1f010fb09b7c95f90f3ca1e8"
593+dependencies = [
594+ "proc-macro2",
595+ "quote",
596+ "unicode-ident",
597+]
598+
599+[[package]]
600+name = "termcolor"
601+version = "1.4.1"
602+source = "registry+https://github.com/rust-lang/crates.io-index"
603+checksum = "06794f8f6c5c898b3275aebefa6b8a1cb24cd2c6c79397ab15774837a0bc5755"
604+dependencies = [
605+ "winapi-util",
606+]
607+
608+[[package]]
609+name = "thiserror"
610+version = "1.0.69"
611+source = "registry+https://github.com/rust-lang/crates.io-index"
612+checksum = "b6aaf5339b578ea85b50e080feb250a3e8ae8cfcdff9a461c9ec2904bc923f52"
613+dependencies = [
614+ "thiserror-impl",
615+]
616+
617+[[package]]
618+name = "thiserror-impl"
619+version = "1.0.69"
620+source = "registry+https://github.com/rust-lang/crates.io-index"
621+checksum = "4fee6c4efc90059e10f81e6d42c60a18f76588c3d74cb83a0b242a2b6c7504c1"
622+dependencies = [
623+ "proc-macro2",
624+ "quote",
625+ "syn",
626+]
627+
628+[[package]]
629+name = "unicode-ident"
630+version = "1.0.18"
631+source = "registry+https://github.com/rust-lang/crates.io-index"
632+checksum = "5a5f39404a5da50712a4c1eecf25e90dd62b613502b7e925fd4e4d19b5c96512"
633+
634+[[package]]
635+name = "v4l2r"
636+version = "0.0.5"
637+source = "registry+https://github.com/rust-lang/crates.io-index"
638+checksum = "fe1d612d2df2a0802020c49a1b029282c45991cdfff1731b5fc61ed3dce4168a"
639+dependencies = [
640+ "anyhow",
641+ "bindgen 0.69.5",
642+ "bitflags",
643+ "enumn",
644+ "log",
645+ "nix",
646+ "thiserror",
647+]
648+
649+[[package]]
650+name = "which"
651+version = "4.4.2"
652+source = "registry+https://github.com/rust-lang/crates.io-index"
653+checksum = "87ba24419a2078cd2b0f2ede2691b6c66d8e47836da3b6db8265ebad47afbfc7"
654+dependencies = [
655+ "either",
656+ "home",
657+ "once_cell",
658+ "rustix",
659+]
660+
661+[[package]]
662+name = "winapi"
663+version = "0.3.9"
664+source = "registry+https://github.com/rust-lang/crates.io-index"
665+checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419"
666+dependencies = [
667+ "winapi-i686-pc-windows-gnu",
668+ "winapi-x86_64-pc-windows-gnu",
669+]
670+
671+[[package]]
672+name = "winapi-i686-pc-windows-gnu"
673+version = "0.4.0"
674+source = "registry+https://github.com/rust-lang/crates.io-index"
675+checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6"
676+
677+[[package]]
678+name = "winapi-util"
679+version = "0.1.9"
680+source = "registry+https://github.com/rust-lang/crates.io-index"
681+checksum = "cf221c93e13a30d793f7645a0e7762c55d169dbb0a49671918a2319d289b10bb"
682+dependencies = [
683+ "windows-sys",
684+]
685+
686+[[package]]
687+name = "winapi-x86_64-pc-windows-gnu"
688+version = "0.4.0"
689+source = "registry+https://github.com/rust-lang/crates.io-index"
690+checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f"
691+
692+[[package]]
693+name = "windows-sys"
694+version = "0.59.0"
695+source = "registry+https://github.com/rust-lang/crates.io-index"
696+checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b"
697+dependencies = [
698+ "windows-targets 0.52.6",
699+]
700+
701+[[package]]
702+name = "windows-targets"
703+version = "0.52.6"
704+source = "registry+https://github.com/rust-lang/crates.io-index"
705+checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973"
706+dependencies = [
707+ "windows_aarch64_gnullvm 0.52.6",
708+ "windows_aarch64_msvc 0.52.6",
709+ "windows_i686_gnu 0.52.6",
710+ "windows_i686_gnullvm 0.52.6",
711+ "windows_i686_msvc 0.52.6",
712+ "windows_x86_64_gnu 0.52.6",
713+ "windows_x86_64_gnullvm 0.52.6",
714+ "windows_x86_64_msvc 0.52.6",
715+]
716+
717+[[package]]
718+name = "windows-targets"
719+version = "0.53.2"
720+source = "registry+https://github.com/rust-lang/crates.io-index"
721+checksum = "c66f69fcc9ce11da9966ddb31a40968cad001c5bedeb5c2b82ede4253ab48aef"
722+dependencies = [
723+ "windows_aarch64_gnullvm 0.53.0",
724+ "windows_aarch64_msvc 0.53.0",
725+ "windows_i686_gnu 0.53.0",
726+ "windows_i686_gnullvm 0.53.0",
727+ "windows_i686_msvc 0.53.0",
728+ "windows_x86_64_gnu 0.53.0",
729+ "windows_x86_64_gnullvm 0.53.0",
730+ "windows_x86_64_msvc 0.53.0",
731+]
732+
733+[[package]]
734+name = "windows_aarch64_gnullvm"
735+version = "0.52.6"
736+source = "registry+https://github.com/rust-lang/crates.io-index"
737+checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3"
738+
739+[[package]]
740+name = "windows_aarch64_gnullvm"
741+version = "0.53.0"
742+source = "registry+https://github.com/rust-lang/crates.io-index"
743+checksum = "86b8d5f90ddd19cb4a147a5fa63ca848db3df085e25fee3cc10b39b6eebae764"
744+
745+[[package]]
746+name = "windows_aarch64_msvc"
747+version = "0.52.6"
748+source = "registry+https://github.com/rust-lang/crates.io-index"
749+checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469"
750+
751+[[package]]
752+name = "windows_aarch64_msvc"
753+version = "0.53.0"
754+source = "registry+https://github.com/rust-lang/crates.io-index"
755+checksum = "c7651a1f62a11b8cbd5e0d42526e55f2c99886c77e007179efff86c2b137e66c"
756+
757+[[package]]
758+name = "windows_i686_gnu"
759+version = "0.52.6"
760+source = "registry+https://github.com/rust-lang/crates.io-index"
761+checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b"
762+
763+[[package]]
764+name = "windows_i686_gnu"
765+version = "0.53.0"
766+source = "registry+https://github.com/rust-lang/crates.io-index"
767+checksum = "c1dc67659d35f387f5f6c479dc4e28f1d4bb90ddd1a5d3da2e5d97b42d6272c3"
768+
769+[[package]]
770+name = "windows_i686_gnullvm"
771+version = "0.52.6"
772+source = "registry+https://github.com/rust-lang/crates.io-index"
773+checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66"
774+
775+[[package]]
776+name = "windows_i686_gnullvm"
777+version = "0.53.0"
778+source = "registry+https://github.com/rust-lang/crates.io-index"
779+checksum = "9ce6ccbdedbf6d6354471319e781c0dfef054c81fbc7cf83f338a4296c0cae11"
780+
781+[[package]]
782+name = "windows_i686_msvc"
783+version = "0.52.6"
784+source = "registry+https://github.com/rust-lang/crates.io-index"
785+checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66"
786+
787+[[package]]
788+name = "windows_i686_msvc"
789+version = "0.53.0"
790+source = "registry+https://github.com/rust-lang/crates.io-index"
791+checksum = "581fee95406bb13382d2f65cd4a908ca7b1e4c2f1917f143ba16efe98a589b5d"
792+
793+[[package]]
794+name = "windows_x86_64_gnu"
795+version = "0.52.6"
796+source = "registry+https://github.com/rust-lang/crates.io-index"
797+checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78"
798+
799+[[package]]
800+name = "windows_x86_64_gnu"
801+version = "0.53.0"
802+source = "registry+https://github.com/rust-lang/crates.io-index"
803+checksum = "2e55b5ac9ea33f2fc1716d1742db15574fd6fc8dadc51caab1c16a3d3b4190ba"
804+
805+[[package]]
806+name = "windows_x86_64_gnullvm"
807+version = "0.52.6"
808+source = "registry+https://github.com/rust-lang/crates.io-index"
809+checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d"
810+
811+[[package]]
812+name = "windows_x86_64_gnullvm"
813+version = "0.53.0"
814+source = "registry+https://github.com/rust-lang/crates.io-index"
815+checksum = "0a6e035dd0599267ce1ee132e51c27dd29437f63325753051e71dd9e42406c57"
816+
817+[[package]]
818+name = "windows_x86_64_msvc"
819+version = "0.52.6"
820+source = "registry+https://github.com/rust-lang/crates.io-index"
821+checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec"
822+
823+[[package]]
824+name = "windows_x86_64_msvc"
825+version = "0.53.0"
826+source = "registry+https://github.com/rust-lang/crates.io-index"
827+checksum = "271414315aff87387382ec3d271b52d7ae78726f5d44ac98b4f4030c91880486"
828+
829+[[package]]
830+name = "zerocopy"
831+version = "0.8.26"
832+source = "registry+https://github.com/rust-lang/crates.io-index"
833+checksum = "1039dd0d3c310cf05de012d8a39ff557cb0d23087fd44cad61df08fc31907a2f"
834+dependencies = [
835+ "zerocopy-derive",
836+]
837+
838+[[package]]
839+name = "zerocopy-derive"
840+version = "0.8.26"
841+source = "registry+https://github.com/rust-lang/crates.io-index"
842+checksum = "9ecf5b4cc5364572d7f4c329661bcc82724222973f2cab6f050a4e5c22f75181"
843+dependencies = [
844+ "proc-macro2",
845+ "quote",
846+ "syn",
847+]
vendor/cros-codecs/Cargo.tomladded+123 -0
@@ -0,0 +1,123 @@
1+# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO
2+#
3+# When uploading crates to the registry Cargo will automatically
4+# "normalize" Cargo.toml files for maximal compatibility
5+# with all versions of Cargo and also rewrite `path` dependencies
6+# to registry (e.g., crates.io) dependencies.
7+#
8+# If you are reading this file be aware that the original Cargo.toml
9+# will likely look very different (and much more reasonable).
10+# See Cargo.toml.orig for the original contents.
11+
12+[package]
13+edition = "2021"
14+name = "cros-codecs"
15+version = "0.0.6"
16+authors = ["The ChromiumOS Authors"]
17+description = "Hardware-accelerated codecs for Linux"
18+readme = "README.md"
19+license = "BSD-3-Clause"
20+repository = "https://github.com/chromeos/cros-codecs"
21+
22+
23+
24+
25+[dependencies.anyhow]
26+version = "1.0.75"
27+optional = true
28+
29+[dependencies.byteorder]
30+version = "1.4.3"
31+optional = true
32+
33+[dependencies.crc32fast]
34+version = "1.3.2"
35+optional = true
36+
37+[dependencies.drm]
38+version = "0.12.0"
39+optional = true
40+
41+[dependencies.drm-fourcc]
42+version = "2.2.0"
43+optional = true
44+
45+[dependencies.gbm]
46+version = "0.15"
47+features = ["drm-support"]
48+optional = true
49+default-features = false
50+
51+[dependencies.gbm-sys]
52+version = "0.3.1"
53+optional = true
54+
55+[dependencies.libva]
56+version = "0.0.12"
57+optional = true
58+package = "cros-libva"
59+
60+[dependencies.log]
61+version = "0"
62+features = ["release_max_level_debug"]
63+
64+[dependencies.nix]
65+version = "0.28"
66+features = [
67+ "fs",
68+ "event",
69+ "poll",
70+ "mman",
71+ "ioctl",
72+]
73+optional = true
74+
75+[dependencies.thiserror]
76+version = "1.0.58"
77+optional = true
78+
79+[dependencies.v4l2r]
80+version = "0.0.5"
81+optional = true
82+package = "v4l2r"
83+
84+[dependencies.zerocopy]
85+version = "0.8.14"
86+features = ["derive"]
87+optional = true
88+
89+[dev-dependencies.argh]
90+version = "0.1.12"
91+
92+[dev-dependencies.env_logger]
93+version = "0.9.3"
94+
95+[dev-dependencies.serde_json]
96+version = "1.0.96"
97+
98+[features]
99+backend = [
100+ "anyhow",
101+ "byteorder",
102+ "thiserror",
103+ "crc32fast",
104+ "nix",
105+ "gbm",
106+ "gbm-sys",
107+ "drm",
108+ "drm-fourcc",
109+ "zerocopy",
110+]
111+default = []
112+v4l2 = [
113+ "v4l2r",
114+ "backend",
115+]
116+vaapi = [
117+ "libva",
118+ "backend",
119+]
120+
121+[lints.rust.unexpected_cfgs]
122+level = "warn"
123+priority = 0
vendor/cros-codecs/DIR_METADATAadded+13 -0
@@ -0,0 +1,13 @@
1+# Metadata information for this directory.
2+#
3+# For more information on DIR_METADATA files, see:
4+# https://source.chromium.org/chromium/infra/infra/+/HEAD:go/src/infra/tools/dirmd/README.md
5+#
6+# For the schema of this file, see Metadata message:
7+# https://source.chromium.org/chromium/infra/infra/+/HEAD:go/src/infra/tools/dirmd/proto/dir_metadata.proto
8+
9+buganizer {
10+ component_id: 168352 # ChromeOS > Platform > Graphics > Video
11+}
12+
13+team_email: "chromeos-gfx-video@google.com"
vendor/cros-codecs/LICENSEadded+26 -0
@@ -0,0 +1,26 @@
1+Copyright 2022 The ChromiumOS Authors
2+
3+Redistribution and use in source and binary forms, with or without modification,
4+are permitted provided that the following conditions are met:
5+
6+1. Redistributions of source code must retain the above copyright notice, this
7+ list of conditions and the following disclaimer.
8+
9+2. Redistributions in binary form must reproduce the above copyright notice,
10+ this list of conditions and the following disclaimer in the documentation
11+ and/or other materials provided with the distribution.
12+
13+3. Neither the name of the copyright holder nor the names of its contributors
14+ may be used to endorse or promote products derived from this software without
15+ specific prior written permission.
16+
17+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
18+ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
19+WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
20+DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
21+ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
22+(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
23+LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
24+ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25+(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
26+SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
vendor/cros-codecs/METADATAadded+16 -0
@@ -0,0 +1,16 @@
1+name: "cros-codecs"
2+description:
3+ "A lightweight, simple, low-dependency, and hopefully safe crate for "
4+ "hardware-accelerated video decoding and encoding on Linux."
5+
6+third_party {
7+homepage: "https://github.com/chromeos/cros-codecs"
8+ identifier {
9+ type: "Git"
10+ value: "https://github.com/chromeos/cros-codecs"
11+ primary_source: false
12+ }
13+
14+ last_upgrade_date { year: 2024 month: 12 day: 3 }
15+ license_type: NOTICE
16+}
vendor/cros-codecs/MODULE_LICENSE_BSDadded+0 -0
vendor/cros-codecs/OWNERSadded+10 -0
@@ -0,0 +1,10 @@
1+abodenha@google.com
2+bselma@google.com
3+hiroh@google.com
4+andrescj@google.com
5+greenjustin@google.com
6+nhebert@google.com
7+frkoenig@google.com
8+bchoobineh@google.com
9+pmolinalopez@google.com
10+hnt@google.com
vendor/cros-codecs/README.mdadded+71 -0
@@ -0,0 +1,71 @@
1+# Cros-codecs
2+
3+[<img alt="crates.io" src="https://img.shields.io/crates/v/cros-codecs">](https://crates.io/crates/cros-codecs)
4+[<img alt="docs.rs" src="https://img.shields.io/docsrs/cros-codecs">](https://docs.rs/cros-codecs/latest/cros_codecs/)
5+
6+A lightweight, simple, low-dependency, and hopefully safe crate for
7+hardware-accelerated video decoding and encoding on Linux.
8+
9+It is developed for use in ChromeOS (particularly
10+[crosvm](https://github.com/google/crosvm)), but has no dependency to ChromeOS
11+and should be usable anywhere.
12+
13+## Current features
14+
15+- Simple decoder API,
16+- VAAPI decoder support (using
17+ [cros-libva](https://github.com/chromeos/cros-libva)) for H.264, H.265, VP8,
18+ VP9 and AV1,
19+- VAAPI encoder support for H.264, VP9 and AV1,
20+- Stateful V4L2 encoder support.
21+
22+## Planned features
23+
24+- Stateful V4L2 decoder support,
25+- Stateless V4L2 decoder support,
26+- Support for more encoder codecs,
27+- C API to be used in non-Rust projects.
28+
29+## Non-goals
30+
31+- Support for systems other than Linux.
32+
33+## Example programs
34+
35+The `ccdec` example program can decode an encoded stream and write the decoded
36+frames to a file. As such it can be used for testing purposes.
37+
38+```shell
39+$ cargo build --examples
40+$ ./target/debug/examples/ccdec --help
41+Usage: ccdec <input> [--output <output>] --input-format <input-format> [--output-format <output-format>] [--compute-md5 <compute-md5>]
42+
43+Simple player using cros-codecs
44+
45+Positional Arguments:
46+ input input file
47+
48+Options:
49+ --output output file to write the decoded frames to
50+ --input-format input format to decode from.
51+ --output-format pixel format to decode into. Default: i420
52+ --compute-md5 whether to display the MD5 of the decoded stream, and at
53+ which granularity (stream or frame)
54+ --help display usage information
55+```
56+
57+## Testing
58+
59+Fluster can be used for testing, using the `ccdec` example program described
60+above. [This branch](https://github.com/Gnurou/fluster/tree/cros-codecs)
61+contains support for cros-codecs testing. Just make sure the `ccdec` binary is
62+in your `PATH`, and run Fluster using one of the `ccdec` decoders, e.g.
63+
64+```shell
65+python fluster.py run -d ccdec-H.264 -ts JVT-AVC_V1
66+```
67+
68+## Credits
69+
70+The majority of the code in the initial commit has been written by Daniel
71+Almeida as a VAAPI backend for crosvm, before being split into this crate.
vendor/cros-codecs/cargo_embargo.jsonadded+10 -0
@@ -0,0 +1,10 @@
1+{
2+ "package": {
3+ "cros-codecs": {
4+ "host_supported": false
5+ }
6+ },
7+ "product_available": true,
8+ "vendor_available": true,
9+ "run_cargo": false
10+}
vendor/cros-codecs/rustfmt.tomladded+3 -0
@@ -0,0 +1,3 @@
1+edition = "2021"
2+use_small_heuristics = "Max"
3+newline_style = "Unix"
vendor/cros-codecs/simple_test.pyadded+46 -0
@@ -0,0 +1,46 @@
1+import glob
2+import os
3+import subprocess
4+
5+CCDEC_BINARY_PATH = 'target/debug/examples/ccdec'
6+
7+def validate_decode(bitstream_path, codec):
8+ if not os.path.isfile(bitstream_path + '.md5'): # Missing golden, skip this vector
9+ return
10+
11+ with open(bitstream_path + '.md5', 'r') as golden_file:
12+ golden = golden_file.read()
13+
14+ ccdec_process = subprocess.run([CCDEC_BINARY_PATH, bitstream_path, '--frame-memory', 'prime', '--input-format', codec, '--output-format', 'nv12', '--compute-md5', 'frame'], capture_output=True)
15+ if ccdec_process.returncode != 0:
16+ print('Error running ccdec for bitstream ' + bitstream_path)
17+ print(ccdec_process.stderr.decode('utf-8'))
18+ return
19+
20+ test_output = ccdec_process.stdout.decode('utf-8')
21+ if test_output != golden:
22+ print('MD5 mistmatch on bitstream ' + bitstream_path)
23+ test_lines = test_output.split('\n')
24+ golden_lines = golden.split('\n')
25+ if len(test_lines) > len(golden_lines):
26+ print('Found more frames in ccdec output than expected')
27+ elif len(test_lines) < len(golden_lines):
28+ print('Found fewer frames in ccdec output than expected')
29+ else:
30+ for i in range(0, len(test_lines)):
31+ if test_lines[i] != golden_lines[i]:
32+ print('First mismatch on frame ' + str(i))
33+ print('Expected: ' + golden_lines[i])
34+ print('Got: ' + test_lines[i])
35+ break
36+
37+
38+if not os.path.isfile(CCDEC_BINARY_PATH):
39+ print('Error! ccdec not found. Have you compiled examples yet?')
40+
41+extensions = ['.h264', '.h265', '.av1', '.vp8', '.vp9', '.ivf']
42+for extension in extensions:
43+ for bitstream_path in glob.glob('src/codec/*/test_data/*' + extension):
44+ codec = bitstream_path[len('src/codec/'):]
45+ codec = codec[:codec.find('/')]
46+ validate_decode(bitstream_path, codec)
vendor/cros-codecs/src/backend.rsadded+16 -0
@@ -0,0 +1,16 @@
1+// Copyright 2023 The ChromiumOS Authors
2+// Use of this source code is governed by a BSD-style license that can be
3+// found in the LICENSE file.
4+
5+//! Shared code for codec backends.
6+//!
7+//! A backend is a provider of codec decoding or encoding, most likely hardware-accelerated like
8+//! VAAPI. This module contains backend-related code that is not tied to any particular codec and
9+//! can be shared between various parts of this crate.
10+
11+#[cfg(any(test, fuzzing))]
12+pub(crate) mod dummy;
13+#[cfg(feature = "v4l2")]
14+pub mod v4l2;
15+#[cfg(feature = "vaapi")]
16+pub mod vaapi;
vendor/cros-codecs/src/backend/dummy.rsadded+8 -0
@@ -0,0 +1,8 @@
1+// Copyright 2023 The ChromiumOS Authors
2+// Use of this source code is governed by a BSD-style license that can be
3+// found in the LICENSE file.
4+
5+//! This file contains a dummy backends whose only purpose is to let the codec
6+//! run so we can test it in isolation.
7+
8+pub(crate) mod decoder;
vendor/cros-codecs/src/backend/dummy/decoder.rsadded+149 -0
@@ -0,0 +1,149 @@
1+// Copyright 2022 The ChromiumOS Authors
2+// Use of this source code is governed by a BSD-style license that can be
3+// found in the LICENSE file.
4+
5+//! This file contains a dummy backend whose only purpose is to let the decoder
6+//! run so we can test it in isolation.
7+
8+use std::cell::RefCell;
9+use std::rc::Rc;
10+
11+use crate::decoder::stateless::PoolLayer;
12+use crate::decoder::stateless::StatelessCodec;
13+use crate::decoder::stateless::StatelessDecoderBackend;
14+use crate::decoder::stateless::StatelessDecoderBackendPicture;
15+use crate::decoder::stateless::TryFormat;
16+use crate::decoder::DecodedHandle;
17+use crate::decoder::DynHandle;
18+use crate::decoder::FramePool;
19+use crate::decoder::MappableHandle;
20+use crate::decoder::StreamInfo;
21+use crate::DecodedFormat;
22+use crate::Resolution;
23+
24+#[derive(Default)]
25+pub struct BackendHandle(());
26+
27+impl MappableHandle for BackendHandle {
28+ fn read(&mut self, _: &mut [u8]) -> anyhow::Result<()> {
29+ Ok(())
30+ }
31+
32+ fn image_size(&mut self) -> usize {
33+ 1
34+ }
35+}
36+
37+impl<'a> DynHandle for std::cell::RefMut<'a, BackendHandle> {
38+ fn dyn_mappable_handle<'b>(&'b mut self) -> anyhow::Result<Box<dyn MappableHandle + 'b>> {
39+ Ok(Box::<BackendHandle>::default())
40+ }
41+}
42+
43+pub struct Handle {
44+ pub handle: Rc<RefCell<BackendHandle>>,
45+}
46+
47+impl Clone for Handle {
48+ fn clone(&self) -> Self {
49+ Self { handle: Rc::clone(&self.handle) }
50+ }
51+}
52+
53+impl DecodedHandle for Handle {
54+ type Descriptor = ();
55+
56+ fn coded_resolution(&self) -> Resolution {
57+ Default::default()
58+ }
59+
60+ fn display_resolution(&self) -> Resolution {
61+ Default::default()
62+ }
63+
64+ fn timestamp(&self) -> u64 {
65+ 0
66+ }
67+
68+ fn dyn_picture<'a>(&'a self) -> Box<dyn DynHandle + 'a> {
69+ Box::new(self.handle.borrow())
70+ }
71+
72+ fn sync(&self) -> anyhow::Result<()> {
73+ Ok(())
74+ }
75+
76+ fn is_ready(&self) -> bool {
77+ true
78+ }
79+
80+ fn resource(&self) -> std::cell::Ref<()> {
81+ std::cell::Ref::map(self.handle.borrow(), |h| &h.0)
82+ }
83+}
84+
85+/// Dummy backend that can be used for any codec.
86+pub struct Backend {
87+ stream_info: StreamInfo,
88+}
89+
90+impl Backend {
91+ pub(crate) fn new() -> Self {
92+ Self {
93+ stream_info: StreamInfo {
94+ format: DecodedFormat::I420,
95+ min_num_frames: 4,
96+ coded_resolution: Resolution::from((320, 200)),
97+ display_resolution: Resolution::from((320, 200)),
98+ },
99+ }
100+ }
101+}
102+
103+impl FramePool for Backend {
104+ type Descriptor = ();
105+
106+ fn coded_resolution(&self) -> Resolution {
107+ Resolution::from((320, 200))
108+ }
109+
110+ fn set_coded_resolution(&mut self, _resolution: Resolution) {}
111+
112+ fn add_frames(&mut self, _descriptors: Vec<Self::Descriptor>) -> Result<(), anyhow::Error> {
113+ Ok(())
114+ }
115+
116+ fn num_free_frames(&self) -> usize {
117+ 4
118+ }
119+
120+ fn num_managed_frames(&self) -> usize {
121+ 4
122+ }
123+
124+ fn clear(&mut self) {}
125+}
126+
127+impl<Codec: StatelessCodec> StatelessDecoderBackendPicture<Codec> for Backend {
128+ type Picture = ();
129+}
130+
131+impl<Codec: StatelessCodec> TryFormat<Codec> for Backend {
132+ fn try_format(&mut self, _: &Codec::FormatInfo, _: DecodedFormat) -> anyhow::Result<()> {
133+ Ok(())
134+ }
135+}
136+
137+impl StatelessDecoderBackend for Backend {
138+ type Handle = Handle;
139+
140+ type FramePool = Self;
141+
142+ fn stream_info(&self) -> Option<&StreamInfo> {
143+ Some(&self.stream_info)
144+ }
145+
146+ fn frame_pool(&mut self, _: PoolLayer) -> Vec<&mut Self::FramePool> {
147+ vec![self]
148+ }
149+}
vendor/cros-codecs/src/backend/v4l2.rsadded+20 -0
@@ -0,0 +1,20 @@
1+// Copyright 2024 The ChromiumOS Authors
2+// Use of this source code is governed by a BSD-style license that can be
3+// found in the LICENSE file.
4+
5+//! V4L2 backend
6+
7+pub mod decoder;
8+pub mod encoder;
9+
10+impl From<v4l2r::PixelFormat> for crate::Fourcc {
11+ fn from(value: v4l2r::PixelFormat) -> Self {
12+ crate::Fourcc(value.to_u32())
13+ }
14+}
15+
16+impl From<crate::Fourcc> for v4l2r::PixelFormat {
17+ fn from(value: crate::Fourcc) -> Self {
18+ v4l2r::PixelFormat::from_u32(value.0)
19+ }
20+}
vendor/cros-codecs/src/backend/v4l2/decoder.rsadded+21 -0
@@ -0,0 +1,21 @@
1+// Copyright 2024 The ChromiumOS Authors
2+// Use of this source code is governed by a BSD-style license that can be
3+// found in the LICENSE file.
4+
5+#[cfg(feature = "v4l2")]
6+use crate::Rect;
7+use crate::Resolution;
8+
9+pub const ADDITIONAL_REFERENCE_FRAME_BUFFER: usize = 4;
10+
11+pub mod stateless;
12+
13+pub trait V4l2StreamInfo {
14+ /// Returns the minimum number of surfaces required to decode the stream.
15+ // name was chosen to match vaapi
16+ fn min_num_frames(&self) -> usize;
17+ /// Returns the coded size of the surfaces required to decode the stream.
18+ fn coded_size(&self) -> Resolution;
19+ /// Returns the visible rectangle within the coded size for the stream.
20+ fn visible_rect(&self) -> Rect;
21+}
vendor/cros-codecs/src/backend/v4l2/decoder/stateless.rsadded+154 -0
@@ -0,0 +1,154 @@
1+// Copyright 2024 The ChromiumOS Authors
2+// Use of this source code is governed by a BSD-style license that can be
3+// found in the LICENSE file.
4+
5+use std::cell::RefCell;
6+use std::rc::Rc;
7+use std::sync::Arc;
8+
9+use crate::backend::v4l2::decoder::V4l2StreamInfo;
10+use crate::decoder::stateless::NewStatelessDecoderError;
11+use crate::decoder::stateless::StatelessBackendResult;
12+use crate::decoder::stateless::StatelessDecoderBackend;
13+use crate::decoder::DecodedHandle;
14+use crate::decoder::StreamInfo;
15+use crate::device::v4l2::stateless::device::V4l2Device;
16+use crate::device::v4l2::stateless::request::V4l2Request;
17+use crate::video_frame::VideoFrame;
18+use crate::DecodedFormat;
19+use crate::Fourcc;
20+use crate::Resolution;
21+
22+pub struct V4l2Picture<V: VideoFrame> {
23+ request: Rc<RefCell<V4l2Request<V>>>,
24+ // To properly decode stream while output and capture queues
25+ // are processed independently it's required for v4l2 backend
26+ // to maintain DPB buffer recycling. The following vector
27+ // is used to prevent reference pictures to be reused while
28+ // current picture is still being decoded.
29+ ref_pictures: Option<Vec<Rc<RefCell<V4l2Picture<V>>>>>,
30+}
31+
32+impl<V: VideoFrame> V4l2Picture<V> {
33+ pub fn new(request: Rc<RefCell<V4l2Request<V>>>) -> Self {
34+ Self { request, ref_pictures: None }
35+ }
36+ pub fn video_frame(&self) -> Arc<V> {
37+ self.request.as_ref().borrow().result().capture_buffer.borrow().frame.clone()
38+ }
39+ pub fn timestamp(&self) -> u64 {
40+ self.request.as_ref().borrow().timestamp()
41+ }
42+ pub fn set_ref_pictures(
43+ &mut self,
44+ ref_pictures: Vec<Rc<RefCell<V4l2Picture<V>>>>,
45+ ) -> &mut Self {
46+ self.ref_pictures = Some(ref_pictures);
47+ self
48+ }
49+ pub fn sync(&mut self) -> &mut Self {
50+ self.request.as_ref().borrow_mut().sync();
51+ self.ref_pictures = None;
52+ self
53+ }
54+ pub fn request(&mut self) -> Rc<RefCell<V4l2Request<V>>> {
55+ self.request.clone()
56+ }
57+ pub fn drop_references(&mut self) {
58+ self.ref_pictures = None;
59+ }
60+}
61+
62+pub struct V4l2StatelessDecoderHandle<V: VideoFrame> {
63+ pub picture: Rc<RefCell<V4l2Picture<V>>>,
64+ pub stream_info: StreamInfo,
65+}
66+
67+impl<V: VideoFrame> Clone for V4l2StatelessDecoderHandle<V> {
68+ fn clone(&self) -> Self {
69+ Self { picture: Rc::clone(&self.picture), stream_info: self.stream_info.clone() }
70+ }
71+}
72+
73+impl<V: VideoFrame> DecodedHandle for V4l2StatelessDecoderHandle<V> {
74+ type Frame = V;
75+
76+ fn video_frame(&self) -> Arc<Self::Frame> {
77+ self.picture.borrow().video_frame()
78+ }
79+
80+ fn coded_resolution(&self) -> Resolution {
81+ self.stream_info.coded_resolution.clone()
82+ }
83+
84+ fn display_resolution(&self) -> Resolution {
85+ self.stream_info.display_resolution.clone()
86+ }
87+
88+ fn timestamp(&self) -> u64 {
89+ self.picture.borrow().timestamp()
90+ }
91+
92+ fn sync(&self) -> anyhow::Result<()> {
93+ self.picture.borrow_mut().sync();
94+ Ok(())
95+ }
96+
97+ fn is_ready(&self) -> bool {
98+ todo!();
99+ }
100+}
101+
102+pub struct V4l2StatelessDecoderBackend<V: VideoFrame> {
103+ pub device: V4l2Device<V>,
104+ pub stream_info: StreamInfo,
105+ pub frame_counter: u64,
106+}
107+
108+impl<V: VideoFrame> V4l2StatelessDecoderBackend<V> {
109+ pub fn new() -> Result<Self, NewStatelessDecoderError> {
110+ Ok(Self {
111+ device: V4l2Device::new()?,
112+ stream_info: StreamInfo {
113+ format: DecodedFormat::I420,
114+ min_num_frames: 0,
115+ coded_resolution: Resolution::from((0, 0)),
116+ display_resolution: Resolution::from((0, 0)),
117+ },
118+ frame_counter: 0,
119+ })
120+ }
121+
122+ pub(crate) fn new_sequence<StreamData>(
123+ &mut self,
124+ stream_params: &StreamData,
125+ fourcc: Fourcc,
126+ ) -> StatelessBackendResult<()>
127+ where
128+ for<'a> &'a StreamData: V4l2StreamInfo,
129+ {
130+ let coded_resolution = stream_params.coded_size().clone();
131+ let min_num_frames = stream_params.min_num_frames();
132+
133+ // TODO: Query the driver for the format
134+ self.stream_info.format = DecodedFormat::MM21;
135+ self.stream_info.display_resolution = Resolution::from(stream_params.visible_rect());
136+ self.stream_info.coded_resolution = coded_resolution;
137+ self.stream_info.min_num_frames = min_num_frames;
138+
139+ Ok(self.device.initialize_queues(fourcc, coded_resolution, min_num_frames as u32)?)
140+ }
141+}
142+
143+impl<V: VideoFrame> StatelessDecoderBackend for V4l2StatelessDecoderBackend<V> {
144+ type Handle = V4l2StatelessDecoderHandle<V>;
145+
146+ fn stream_info(&self) -> Option<&StreamInfo> {
147+ // TODO
148+ Some(&self.stream_info)
149+ }
150+
151+ fn reset_backend(&mut self) -> anyhow::Result<()> {
152+ Ok(self.device.reset_queues()?)
153+ }
154+}
vendor/cros-codecs/src/backend/v4l2/encoder.rsadded+1368 -0
@@ -0,0 +1,1368 @@
1+// Copyright 2024 The ChromiumOS Authors
2+// Use of this source code is governed by a BSD-style license that can be
3+// found in the LICENSE file.
4+
5+use std::collections::BTreeMap;
6+use std::fmt::Debug;
7+use std::marker::PhantomData;
8+use std::os::fd::AsRawFd;
9+use std::path::PathBuf;
10+use std::sync::Arc;
11+
12+use nix::sys::stat::fstat;
13+use thiserror::Error;
14+use v4l2r::bindings::v4l2_streamparm;
15+use v4l2r::controls::codec::VideoBitrate;
16+use v4l2r::controls::codec::VideoBitrateMode;
17+use v4l2r::controls::codec::VideoConstantQuality;
18+use v4l2r::controls::codec::VideoForceKeyFrame;
19+use v4l2r::controls::codec::VideoHeaderMode;
20+use v4l2r::controls::ExtControlTrait;
21+use v4l2r::controls::SafeExtControl;
22+use v4l2r::device::poller::DeviceEvent;
23+use v4l2r::device::poller::PollError;
24+use v4l2r::device::poller::Poller;
25+use v4l2r::device::queue::direction::Capture;
26+use v4l2r::device::queue::direction::Output;
27+use v4l2r::device::queue::dqbuf::DqBuffer;
28+use v4l2r::device::queue::qbuf::QBuffer;
29+use v4l2r::device::queue::BuffersAllocated;
30+use v4l2r::device::queue::CreateQueueError;
31+use v4l2r::device::queue::GetFreeBufferError;
32+use v4l2r::device::queue::GetFreeCaptureBuffer;
33+use v4l2r::device::queue::GetFreeOutputBuffer;
34+use v4l2r::device::queue::OutputQueueable;
35+use v4l2r::device::queue::OutputQueueableProvider;
36+use v4l2r::device::queue::Queue;
37+use v4l2r::device::queue::RequestBuffersError;
38+use v4l2r::device::AllocatedQueue;
39+use v4l2r::device::Device;
40+use v4l2r::device::DeviceConfig;
41+use v4l2r::device::Stream;
42+use v4l2r::device::TryDequeue;
43+use v4l2r::ioctl;
44+use v4l2r::ioctl::BufferFlags;
45+use v4l2r::ioctl::EncoderCommand;
46+use v4l2r::ioctl::StreamOnError;
47+use v4l2r::ioctl::V4l2BufferFromError;
48+use v4l2r::memory::BufferHandles;
49+use v4l2r::memory::DmaBufHandle;
50+use v4l2r::memory::MmapHandle;
51+use v4l2r::memory::PlaneHandle;
52+use v4l2r::memory::PrimitiveBufferHandles;
53+use v4l2r::memory::UserPtrHandle;
54+use v4l2r::nix::errno::Errno;
55+use v4l2r::nix::sys::time::TimeVal;
56+use v4l2r::Format;
57+use v4l2r::PixelFormat;
58+use v4l2r::QueueDirection;
59+use v4l2r::QueueType;
60+
61+use crate::encoder::stateful::BackendOutput;
62+use crate::encoder::stateful::BackendRequest;
63+use crate::encoder::stateful::BackendRequestId;
64+use crate::encoder::stateful::StatefulBackendError;
65+use crate::encoder::stateful::StatefulBackendResult;
66+use crate::encoder::stateful::StatefulVideoEncoderBackend;
67+use crate::encoder::CodedBitstreamBuffer;
68+use crate::encoder::EncodeError;
69+use crate::encoder::FrameMetadata;
70+use crate::encoder::RateControl;
71+use crate::encoder::Tunings;
72+use crate::utils::DmabufFrame;
73+use crate::utils::UserPtrFrame;
74+use crate::video_frame::V4l2VideoFrame;
75+use crate::video_frame::VideoFrame;
76+use crate::Fourcc;
77+use crate::FrameLayout;
78+use crate::Resolution;
79+
80+#[derive(Debug, Error)]
81+pub enum UnsupportedError {
82+ #[error("frame upscaling")]
83+ FrameUpscaling,
84+
85+ #[error("buffer lacking TIMESTAMP_COPY flag")]
86+ NoTimestampCopyFlag,
87+
88+ #[error("unsupported profile")]
89+ Profile,
90+}
91+
92+#[derive(Debug, Error)]
93+pub enum InitializationError {
94+ #[error(transparent)]
95+ Unsupported(UnsupportedError),
96+
97+ #[error("failed to create a CAPTURE queue: {0:?}")]
98+ CaptureQueueCreate(CreateQueueError),
99+
100+ #[error("failed to create a OUTPUT queue: {0:?}")]
101+ OutputQueueCreate(CreateQueueError),
102+
103+ #[error("failed to set format for CAPTURE: {0:?}")]
104+ SetFormatCapture(ioctl::SFmtError),
105+
106+ #[error("failed to set format for OUTPUT: {0:?}")]
107+ SetFormatOutput(ioctl::SFmtError),
108+
109+ #[error("failed to request CAPTURE buffers: {0:?}")]
110+ RequestBufferCatpure(RequestBuffersError),
111+
112+ #[error("failed to request OUTPUT buffers: {0:?}")]
113+ RequestBufferOutput(RequestBuffersError),
114+
115+ #[error("failed to stream on CAPTURE: {0:?}")]
116+ StreamOnCapture(StreamOnError),
117+
118+ #[error("failed to stream on OUTPUT: {0:?}")]
119+ StreamOnOutput(StreamOnError),
120+
121+ #[error(transparent)]
122+ EncoderStart(#[from] ioctl::EncoderCmdError),
123+
124+ #[error(transparent)]
125+ CreatePoller(v4l2r::nix::Error),
126+
127+ #[error(transparent)]
128+ SetSelection(ioctl::SSelectionError),
129+
130+ #[error(transparent)]
131+ Contro(#[from] ControlError),
132+}
133+
134+#[derive(Debug, Error)]
135+pub struct ControlError {
136+ which: &'static str,
137+ error: Errno,
138+}
139+
140+impl std::fmt::Display for ControlError {
141+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
142+ f.write_fmt(format_args!("failed to set '{}': {:?}", self.which, self.error))
143+ }
144+}
145+
146+#[derive(Debug, Error)]
147+pub enum BackendError {
148+ #[error(transparent)]
149+ Unsupported(UnsupportedError),
150+
151+ #[error(transparent)]
152+ GetFreeBufferError(#[from] GetFreeBufferError),
153+
154+ #[error(transparent)]
155+ QueueBitstreamBuffer(anyhow::Error),
156+
157+ #[error(transparent)]
158+ MapBitstreamBuffer(anyhow::Error),
159+
160+ #[error(transparent)]
161+ QueueFrameHandleError(anyhow::Error),
162+
163+ #[error(transparent)]
164+ DequeueBuffer(#[from] ioctl::DqBufError<V4l2BufferFromError>),
165+
166+ #[error("failed to map capture buffer: {0:?}")]
167+ FailedToMapCapture(Timestamp),
168+
169+ #[error(transparent)]
170+ DrainCommand(#[from] ioctl::EncoderCmdError),
171+
172+ #[error(transparent)]
173+ Poll(#[from] PollError),
174+
175+ #[error(transparent)]
176+ GetFormat(#[from] ioctl::GFmtError),
177+
178+ #[error(transparent)]
179+ Control(#[from] ControlError),
180+}
181+
182+pub type BackendResult<T> = std::result::Result<T, BackendError>;
183+
184+impl From<BackendError> for StatefulBackendError {
185+ fn from(value: BackendError) -> Self {
186+ StatefulBackendError::Other(anyhow::anyhow!(value))
187+ }
188+}
189+
190+impl From<BackendError> for EncodeError {
191+ fn from(value: BackendError) -> Self {
192+ EncodeError::StatefulBackendError(value.into())
193+ }
194+}
195+
196+/// Frame timestamp helper struct
197+#[repr(transparent)]
198+#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
199+pub struct Timestamp(pub u64);
200+
201+impl From<v4l2r::bindings::timeval> for Timestamp {
202+ fn from(value: v4l2r::bindings::timeval) -> Self {
203+ let timestamp = value.tv_sec.wrapping_mul(1_000_000);
204+ let timestamp = timestamp.wrapping_add(value.tv_usec);
205+ Timestamp(timestamp.max(0) as u64)
206+ }
207+}
208+
209+impl From<&Timestamp> for TimeVal {
210+ fn from(value: &Timestamp) -> Self {
211+ let tv_sec = (value.0 / 1_000_000).min(i64::MAX as u64);
212+ let tv_usec = (value.0 % 1_000_000).min(i64::MAX as u64);
213+ Self::new(tv_sec as i64, tv_usec as i64)
214+ }
215+}
216+
217+pub type OutputBuffer<'a, P> =
218+ <Queue<Output, BuffersAllocated<P>> as OutputQueueableProvider<'a, P>>::Queueable;
219+
220+/// Encoder input frame handle, that can be queued to OUTPUT queue.
221+pub trait OutputBufferHandle {
222+ type PrimitiveBufferHandles: PrimitiveBufferHandles;
223+
224+ fn queue(self, buffer: OutputBuffer<'_, Self::PrimitiveBufferHandles>) -> anyhow::Result<()>;
225+}
226+
227+pub trait AlwaysEntireBufferUsed {}
228+
229+impl AlwaysEntireBufferUsed for UserPtrFrame {}
230+
231+impl AlwaysEntireBufferUsed for DmabufFrame {}
232+
233+impl<V: VideoFrame> AlwaysEntireBufferUsed for V4l2VideoFrame<V> {}
234+
235+impl<T> OutputBufferHandle for T
236+where
237+ T: PrimitiveBufferHandles + AlwaysEntireBufferUsed,
238+{
239+ type PrimitiveBufferHandles = Self;
240+
241+ fn queue(self, buffer: OutputBuffer<'_, Self>) -> anyhow::Result<()> {
242+ let mut bytes_used = Vec::new();
243+ for i in 0..self.len() {
244+ let mut plane = v4l2r::bindings::v4l2_plane::default();
245+ self.fill_v4l2_plane(i, &mut plane);
246+ bytes_used.push(plane.length as usize);
247+ }
248+
249+ log::trace!("Queueing buffer bytes_used={bytes_used:?}");
250+ buffer.queue_with_handles(self, &bytes_used).unwrap();
251+ Ok(())
252+ }
253+}
254+
255+impl BufferHandles for UserPtrFrame {
256+ type SupportedMemoryType = v4l2r::memory::MemoryType;
257+
258+ fn fill_v4l2_plane(&self, index: usize, plane: &mut v4l2r::bindings::v4l2_plane) {
259+ let plane_layout = &self.layout.planes[index];
260+
261+ plane.m.userptr = self.buffers[plane_layout.buffer_index] as _;
262+ plane.data_offset = plane_layout.offset as _;
263+ plane.length = self.mem_layout.size() as _;
264+ }
265+
266+ fn len(&self) -> usize {
267+ self.layout.planes.len()
268+ }
269+}
270+
271+impl PrimitiveBufferHandles for UserPtrFrame {
272+ type HandleType = UserPtrHandle<[u8; 0]>;
273+ const MEMORY_TYPE: Self::SupportedMemoryType = v4l2r::memory::MemoryType::UserPtr;
274+}
275+
276+// SAFETY: Access to the frame is read only
277+unsafe impl Send for UserPtrFrame {}
278+
279+// SAFETY: Access to the frame is read only
280+unsafe impl Sync for UserPtrFrame {}
281+
282+impl BufferHandles for DmabufFrame {
283+ type SupportedMemoryType = v4l2r::memory::MemoryType;
284+
285+ fn fill_v4l2_plane(&self, index: usize, plane: &mut v4l2r::bindings::v4l2_plane) {
286+ let plane_layout = &self.layout.planes[index];
287+ let fd = &self.fds[plane_layout.buffer_index];
288+
289+ plane.m.fd = fd.as_raw_fd();
290+ plane.data_offset = plane_layout.offset as u32;
291+ plane.length = fstat(fd.as_raw_fd()).map(|stat| stat.st_size as u32).unwrap_or(0);
292+
293+ if plane.length == 0 {
294+ log::warn!("Failed to fstat proper plane size index={index}");
295+ }
296+ }
297+
298+ fn len(&self) -> usize {
299+ self.layout.planes.len()
300+ }
301+}
302+
303+impl PrimitiveBufferHandles for DmabufFrame {
304+ type HandleType = DmaBufHandle<std::fs::File>;
305+ const MEMORY_TYPE: Self::SupportedMemoryType = v4l2r::memory::MemoryType::DmaBuf;
306+}
307+
308+/// Encoder's coded specific trait enabling setting codec specific tunings
309+pub trait EncoderCodec {
310+ /// Set's [`Tunings`] for the [`v4l2r::device::Device`]
311+ fn apply_tunings(device: &Device, tunings: &Tunings) -> Result<(), ControlError>;
312+}
313+
314+/// Trait responsible for CAPTURE buffers of the encoder's [`V4L2Backend`]. Enable custom logic of
315+/// CAPTURE specific for device/client use case. Useful especially when MMAP buffer type is not
316+/// supported for CAPTURE queue. In such scenario the client may choose to implement this function
317+/// and use own logic for allocating DMABUF or USERPTR.
318+pub trait CaptureBuffers {
319+ /// [`PlaneHandle`] that is going to be used for CAPTURE buffers.
320+ type PlaneHandle: PlaneHandle;
321+
322+ /// Queues the buffer with [`CaptureBuffers::PlaneHandle`]s and returns true,
323+ /// otherwise if the buffer may not be queue returns false.
324+ fn queue(
325+ &mut self,
326+ buffer: QBuffer<
327+ Capture,
328+ Vec<Self::PlaneHandle>,
329+ Vec<Self::PlaneHandle>,
330+ &Queue<Capture, BuffersAllocated<Vec<Self::PlaneHandle>>>,
331+ >,
332+ ) -> anyhow::Result<bool>;
333+
334+ /// Maps the the buffer and returns its contents in form of [`Vec<u8>`]
335+ fn export(&self, buffer: DqBuffer<Capture, Vec<Self::PlaneHandle>>) -> anyhow::Result<Vec<u8>>;
336+}
337+
338+/// [`CaptureBuffers`] implementation for MMAP memory type
339+pub struct MmapingCapture;
340+
341+impl CaptureBuffers for MmapingCapture {
342+ type PlaneHandle = MmapHandle;
343+
344+ fn queue(
345+ &mut self,
346+ buffer: QBuffer<
347+ Capture,
348+ Vec<Self::PlaneHandle>,
349+ Vec<Self::PlaneHandle>,
350+ &Queue<Capture, BuffersAllocated<Vec<Self::PlaneHandle>>>,
351+ >,
352+ ) -> anyhow::Result<bool> {
353+ buffer.queue()?;
354+ Ok(true)
355+ }
356+
357+ fn export(&self, buffer: DqBuffer<Capture, Vec<Self::PlaneHandle>>) -> anyhow::Result<Vec<u8>> {
358+ let timestamp = Timestamp::from(buffer.data.timestamp());
359+ let Some(mapping) = buffer.get_plane_mapping(0) else {
360+ log::error!("CAPTURE: Failed to map buffer timestamp={timestamp:?}");
361+ return Err(BackendError::FailedToMapCapture(timestamp).into());
362+ };
363+
364+ let bytesused = *buffer.data.get_first_plane().bytesused as usize;
365+
366+ Ok(Vec::from(&mapping.data[..bytesused]))
367+ }
368+}
369+
370+/// V4L2 stateful encoder implementation
371+pub struct V4L2Backend<Handle, CaptureBufferz, Codec>
372+where
373+ Handle: OutputBufferHandle,
374+ CaptureBufferz: CaptureBuffers,
375+ Self: EncoderCodec,
376+{
377+ /// V4L2 encoder device
378+ device: Arc<Device>,
379+
380+ /// OUTPUT_MPLANE V4L2 queue
381+ output_queue: Queue<Output, BuffersAllocated<Handle::PrimitiveBufferHandles>>,
382+
383+ /// CAPTURE_MPLANE V4L2 queue
384+ capture_queue: Queue<Capture, BuffersAllocated<Vec<CaptureBufferz::PlaneHandle>>>,
385+
386+ /// [`CaptureBuffers`] implementation
387+ capture_buffers: CaptureBufferz,
388+
389+ /// Buffers that are currently processed by the encoder device
390+ currently_processed: BTreeMap<Timestamp, (BackendRequestId, FrameMetadata)>,
391+
392+ /// Currently set [`Tunings`] used to detected tunings change
393+ current_tunings: Tunings,
394+
395+ /// Device poller for implementing [`StatefulVideoEncoderBackend::sync`]
396+ poller: Poller,
397+
398+ _phantom: PhantomData<(Handle, Codec)>,
399+}
400+
401+impl<Handle, CaptureBufferz, Codec> V4L2Backend<Handle, CaptureBufferz, Codec>
402+where
403+ Handle: OutputBufferHandle,
404+ CaptureBufferz: CaptureBuffers,
405+ Self: EncoderCodec,
406+{
407+ /// Checks if the device has the given control and sets it to desired value if it's diffrent
408+ pub(crate) fn apply_ctrl<C>(
409+ device: &Device,
410+ name: &'static str,
411+ value: C,
412+ ) -> Result<(), ControlError>
413+ where
414+ C: ExtControlTrait<PAYLOAD = i32> + Into<i32>,
415+ {
416+ let mut current = SafeExtControl::<C>::from_value(0);
417+
418+ log::trace!("Trying to set control {name}");
419+ match ioctl::g_ext_ctrls(device, ioctl::CtrlWhich::Current, &mut current) {
420+ Ok(()) => (),
421+ Err(ioctl::ExtControlError {
422+ error_idx: _,
423+ error: ioctl::ExtControlErrorType::IoctlError(Errno::EINVAL),
424+ }) => {
425+ log::debug!("Setting/getting {name} control is not supported for this device");
426+ return Ok(());
427+ }
428+ Err(ioctl::ExtControlError {
429+ error_idx: _,
430+ error: ioctl::ExtControlErrorType::IoctlError(error),
431+ }) => {
432+ log::error!("Getting {name} control returned {:?}", error.desc());
433+ return Err(ControlError { which: name, error });
434+ }
435+ };
436+
437+ let desired: i32 = value.into();
438+ if current.value() == desired {
439+ log::debug!("Control {name} already has desired value");
440+ }
441+
442+ let mut value = SafeExtControl::<C>::from_value(desired);
443+
444+ match ioctl::s_ext_ctrls(device, ioctl::CtrlWhich::Current, &mut value) {
445+ Ok(()) => (),
446+ Err(ioctl::ExtControlError {
447+ error_idx: _,
448+ error: ioctl::ExtControlErrorType::IoctlError(Errno::EINVAL),
449+ }) => {
450+ log::debug!("Setting/getting {name} control is not supported for this device");
451+ return Ok(());
452+ }
453+ Err(ioctl::ExtControlError {
454+ error_idx: _,
455+ error: ioctl::ExtControlErrorType::IoctlError(error),
456+ }) => return Err(ControlError { which: name, error }),
457+ };
458+
459+ let value = value.value();
460+
461+ if value != desired {
462+ // TODO: raise error?
463+ log::warn!("Failed to set desired {name} (to: {desired}, is: {value})",);
464+ } else {
465+ log::trace!("Control {name} set correctly to {value}");
466+ }
467+
468+ Ok(())
469+ }
470+
471+ /// Sets the frame rate using S_PARM ioctl for the queue type on the device.
472+ pub(crate) fn apply_parm(device: &Device, queue_type: QueueType, framerate: u32) {
473+ let mut parm = v4l2_streamparm { type_: queue_type as u32, ..Default::default() };
474+
475+ let (num, denum) = if framerate != 0 { (1, framerate) } else { (0, 1) };
476+
477+ if matches!(queue_type, v4l2r::QueueType::VideoOutputMplane) {
478+ parm.parm.output.capability = 0;
479+ parm.parm.output.outputmode = 0;
480+ parm.parm.output.timeperframe.numerator = num;
481+ parm.parm.output.timeperframe.denominator = denum;
482+ } else {
483+ parm.parm.capture.capability = 0;
484+ parm.parm.capture.timeperframe.numerator = num;
485+ parm.parm.capture.timeperframe.denominator = denum;
486+ }
487+
488+ match v4l2r::ioctl::s_parm::<_, v4l2_streamparm>(device, parm) {
489+ Ok(parm) => match QueueType::n(parm.type_).as_ref().map(QueueType::direction) {
490+ // SAFETY: The type is set to output
491+ Some(QueueDirection::Output) => unsafe {
492+ log::debug!(
493+ "OUTPUT: Time per frame set to {}/{}",
494+ parm.parm.output.timeperframe.numerator,
495+ parm.parm.output.timeperframe.denominator,
496+ );
497+ },
498+ // SAFETY: The type is set to capture
499+ Some(QueueDirection::Capture) => unsafe {
500+ log::debug!(
501+ "CAPTURE: Time per frame set to {}/{}",
502+ parm.parm.capture.timeperframe.numerator,
503+ parm.parm.capture.timeperframe.denominator,
504+ );
505+ },
506+ _ => {}
507+ },
508+ Err(errno) => log::warn!("{:?}: Failed to set parm: {errno:?}", queue_type.direction()),
509+ }
510+ }
511+
512+ /// Sets the rate mode and bitrate params on the device.
513+ fn apply_rate_control(
514+ device: &Device,
515+ framerate: u32,
516+ rate_control: &RateControl,
517+ ) -> Result<(), ControlError> {
518+ Self::apply_parm(device, QueueType::VideoOutputMplane, framerate);
519+ Self::apply_parm(device, QueueType::VideoCaptureMplane, 1000);
520+
521+ Self::apply_ctrl(
522+ device,
523+ "bitrate mode",
524+ match rate_control {
525+ RateControl::ConstantBitrate(_) => VideoBitrateMode::ConstantBitrate,
526+ RateControl::ConstantQuality(_) => VideoBitrateMode::ConstantQuality,
527+ },
528+ )?;
529+
530+ if let Some(bitrate) = rate_control.bitrate_target() {
531+ Self::apply_ctrl(device, "bitrate", VideoBitrate(bitrate as i32))?;
532+ }
533+
534+ if let RateControl::ConstantQuality(qp) = rate_control {
535+ Self::apply_ctrl(device, "constant quality", VideoConstantQuality(*qp as i32))?;
536+ }
537+
538+ Ok(())
539+ }
540+
541+ /// Sets the crop.
542+ pub fn apply_selection(
543+ device: &Device,
544+ visible_size: Resolution,
545+ ) -> Result<(), ioctl::SSelectionError> {
546+ let rect =
547+ v4l2r::Rect { left: 0, top: 0, width: visible_size.width, height: visible_size.height };
548+
549+ log::trace!(
550+ "Trying to apply to selection to (left: {}, top: {}, width: {}, height: {})",
551+ rect.left,
552+ rect.top,
553+ rect.width,
554+ rect.height
555+ );
556+
557+ let rect = ioctl::s_selection::<_, v4l2r::Rect>(
558+ device,
559+ ioctl::SelectionType::Output,
560+ ioctl::SelectionTarget::Crop,
561+ rect,
562+ ioctl::SelectionFlags::empty(),
563+ )?;
564+
565+ if rect.left == 0
566+ && rect.top == 0
567+ && rect.width == visible_size.width
568+ && rect.height == visible_size.height
569+ {
570+ log::trace!("Selection set successfully");
571+ } else {
572+ log::warn!(
573+ "Driver set selection to (left: {}, top: {}, width: {}, height: {})",
574+ rect.left,
575+ rect.top,
576+ rect.width,
577+ rect.height
578+ );
579+ }
580+
581+ Ok(())
582+ }
583+
584+ /// Creates and sets up the backend instance using the given configuration
585+ pub fn create(
586+ device: Arc<Device>,
587+ capture_buffers: CaptureBufferz,
588+ fourcc: Fourcc,
589+ coded_size: Resolution,
590+ visible_size: Resolution,
591+ capture_pixfmt: v4l2r::PixelFormat,
592+ tunings: Tunings,
593+ ) -> Result<Self, InitializationError> {
594+ let mut capture_queue = Queue::get_capture_mplane_queue(device.clone())
595+ .map_err(InitializationError::CaptureQueueCreate)?;
596+
597+ let mut output_queue = Queue::get_output_mplane_queue(device.clone())
598+ .map_err(InitializationError::OutputQueueCreate)?;
599+
600+ // Coded buffer size multiplier. It's inteded to give head room for the encoder.
601+ const CODED_SIZE_MUL: u32 = 2;
602+
603+ // Default coded buffer size if bitrate control is not used.
604+ const DEFAULT_CODED_SIZE: u32 = 1_500_000;
605+
606+ let coded_buffer_size = tunings
607+ .rate_control
608+ .bitrate_target()
609+ .map(|e| e as u32 * CODED_SIZE_MUL)
610+ .unwrap_or(DEFAULT_CODED_SIZE);
611+
612+ let capture_format = Format {
613+ width: coded_size.width,
614+ height: coded_size.height,
615+ pixelformat: capture_pixfmt,
616+ plane_fmt: vec![v4l2r::PlaneLayout { sizeimage: coded_buffer_size, bytesperline: 0 }],
617+ };
618+
619+ let capture_format = capture_queue
620+ .set_format(capture_format)
621+ .map_err(InitializationError::SetFormatCapture)?;
622+
623+ // TODO: Map single planar formats to mutli planar format if single planar is not
624+ // supported.
625+ let output_pixfmt: PixelFormat = fourcc.0.into();
626+
627+ let output_format = Format {
628+ width: coded_size.width,
629+ height: coded_size.height,
630+ pixelformat: output_pixfmt,
631+ // Let the driver pick
632+ plane_fmt: vec![],
633+ };
634+
635+ let output_format =
636+ output_queue.set_format(output_format).map_err(InitializationError::SetFormatOutput)?;
637+
638+ log::debug!("CAPTURE queue format = {capture_format:#?}");
639+ log::debug!("OUTPUT queue format = {output_format:#?}");
640+
641+ Self::apply_rate_control(&device, tunings.framerate, &tunings.rate_control)?;
642+ Self::apply_tunings(&device, &tunings)?;
643+
644+ Self::apply_ctrl(&device, "header mode", VideoHeaderMode::JoinedWith1stFrame)?;
645+
646+ if visible_size.width > output_format.width || visible_size.height > output_format.height {
647+ return Err(InitializationError::Unsupported(UnsupportedError::FrameUpscaling));
648+ } else if visible_size.width != output_format.width
649+ || visible_size.height != output_format.height
650+ {
651+ log::info!("The frame visible size is not aligned to coded size, applying selection");
652+ if let Err(err) = Self::apply_selection(&device, visible_size) {
653+ log::error!("Failed to set selection: {err:?}");
654+ }
655+ }
656+
657+ log::debug!("CAPTURE: Requesting buffers");
658+ let capture_queue = capture_queue
659+ .request_buffers::<_>(16)
660+ .map_err(InitializationError::RequestBufferOutput)?;
661+
662+ log::debug!("OUTPUT: Requesting buffers");
663+ let output_queue = output_queue
664+ .request_buffers::<Handle::PrimitiveBufferHandles>(16)
665+ .map_err(InitializationError::RequestBufferOutput)?;
666+
667+ log::debug!("CAPTURE: Invoking stream on");
668+ capture_queue.stream_on().map_err(InitializationError::StreamOnCapture)?;
669+
670+ log::debug!("OUTPUT: Invoking stream on");
671+ output_queue.stream_on().map_err(InitializationError::StreamOnOutput)?;
672+
673+ log::debug!("Sending start command to encoder");
674+ ioctl::encoder_cmd::<_, ()>(&device, &EncoderCommand::Start)
675+ .map_err(InitializationError::EncoderStart)?;
676+
677+ let mut poller = Poller::new(device.clone()).map_err(InitializationError::CreatePoller)?;
678+
679+ poller
680+ .enable_event(DeviceEvent::CaptureReady)
681+ .map_err(InitializationError::CreatePoller)?;
682+
683+ Ok(Self {
684+ device,
685+ output_queue,
686+ capture_queue,
687+ capture_buffers,
688+ currently_processed: Default::default(),
689+ current_tunings: tunings,
690+ poller,
691+ _phantom: Default::default(),
692+ })
693+ }
694+
695+ pub fn output_format<T: TryFrom<v4l2r::bindings::v4l2_format>>(&self) -> BackendResult<T> {
696+ Ok(self.output_queue.get_format()?)
697+ }
698+
699+ fn poll_device(&mut self) -> BackendResult<()> {
700+ self.poller.poll(None)?;
701+
702+ Ok(())
703+ }
704+
705+ /// Attempts to queue all free CAPTURE buffer for filling with encoded bitstream
706+ fn queue_capture(&mut self) -> BackendResult<()> {
707+ while self.capture_queue.num_free_buffers() != 0 {
708+ let buffer = self.capture_queue.try_get_free_buffer()?;
709+ let buffer_index = buffer.index();
710+
711+ let queued =
712+ self.capture_buffers.queue(buffer).map_err(BackendError::QueueBitstreamBuffer)?;
713+
714+ if !queued {
715+ log::warn!("CAPTURE: Capture buffer was queued. Will retry later");
716+ break;
717+ }
718+
719+ log::trace!("CAPTURE: Queued new buffer index={}", buffer_index);
720+ }
721+
722+ Ok(())
723+ }
724+
725+ /// Tries to dequeue a CAPTURE buffer and transforms the buffer contents into [`BackendOutput`]
726+ fn dequeue_capture(&mut self) -> BackendResult<Option<BackendOutput>> {
727+ if self.capture_queue.num_queued_buffers() == 0 {
728+ // Don't dequeue if there is nothing to dequeue
729+ log::warn!("Polled while no buffer was queued on CAPTURE queue");
730+ return Ok(None);
731+ }
732+
733+ let buffer = match self.capture_queue.try_dequeue() {
734+ Ok(buffer) => buffer,
735+ Err(ioctl::DqBufError::IoctlError(
736+ err @ ioctl::DqBufIoctlError::NotReady | err @ ioctl::DqBufIoctlError::Eos,
737+ )) => {
738+ log::trace!("Dequeue result: {err:?}");
739+ return Ok(None);
740+ }
741+ Err(err) => return Err(err.into()),
742+ };
743+
744+ let timestamp = Timestamp::from(buffer.data.timestamp());
745+ log::debug!(
746+ "CAPTRUE: Dequeued buffer index={} timestamp={:?} is_last={} bytesused={}, flags={:?}",
747+ buffer.data.index(),
748+ timestamp,
749+ buffer.data.is_last(),
750+ *buffer.data.get_first_plane().bytesused,
751+ buffer.data.flags(),
752+ );
753+
754+ if *buffer.data.get_first_plane().bytesused == 0 {
755+ // Don't warn about empty lasty buffer
756+ if !buffer.data.is_last() {
757+ log::warn!("CAPTURE: Dequeued empty buffer. Skipping it.");
758+ }
759+ return Ok(None);
760+ }
761+
762+ if !buffer.data.flags().intersects(BufferFlags::TIMESTAMP_COPY) {
763+ log::error!("CAPTURE: Buffer does not have TIMESTAMP_COPY flag");
764+ return Err(BackendError::Unsupported(UnsupportedError::NoTimestampCopyFlag));
765+ }
766+
767+ let Some((request_id, meta)) = self.currently_processed.remove(&timestamp) else {
768+ log::error!("CAPTURE: Failed to find buffer timestamp={timestamp:?}");
769+ return Err(BackendError::FailedToMapCapture(timestamp));
770+ };
771+
772+ let bitstream =
773+ self.capture_buffers.export(buffer).map_err(BackendError::MapBitstreamBuffer)?;
774+
775+ let output =
776+ BackendOutput { request_id, buffer: CodedBitstreamBuffer::new(meta, bitstream) };
777+
778+ Ok(Some(output))
779+ }
780+
781+ /// Dequeues all processed OUTPUT buffers and drops them
782+ fn drain_output_queue(&mut self) -> BackendResult<()> {
783+ // Don't dequeue if there is nothing to dequeue
784+ while self.output_queue.num_queued_buffers() != 0 {
785+ match self.output_queue.try_dequeue() {
786+ Ok(buffer) => {
787+ log::debug!(
788+ "OUTPUT: Dequeued buffer index={} timestamp={:?}",
789+ buffer.data.index(),
790+ Timestamp::from(buffer.data.timestamp())
791+ );
792+ // Drop the finished buffer
793+ drop(buffer);
794+ }
795+ Err(ioctl::DqBufError::IoctlError(ioctl::DqBufIoctlError::NotReady)) => break,
796+ Err(ioctl::DqBufError::IoctlError(ioctl::DqBufIoctlError::Eos)) => {}
797+ Err(err) => return Err(err.into()),
798+ }
799+ }
800+
801+ Ok(())
802+ }
803+
804+ /// Takes the [`BackendRequest`] and queues it to OUTPUT queue
805+ fn handle_request(&mut self, request: BackendRequest<Handle>) -> BackendResult<()> {
806+ if self.current_tunings != request.tunings {
807+ log::debug!("Changing tunings to {:#?}", request.tunings);
808+ Self::apply_rate_control(
809+ &self.device,
810+ request.tunings.framerate,
811+ &request.tunings.rate_control,
812+ )?;
813+ Self::apply_tunings(&self.device, &request.tunings)?;
814+ self.current_tunings = request.tunings;
815+ }
816+
817+ let buffer = self.output_queue.try_get_free_buffer()?;
818+
819+ let timestamp = Timestamp(request.meta.timestamp);
820+ let buffer = buffer.set_timestamp(TimeVal::from(&timestamp));
821+
822+ let index = buffer.index();
823+
824+ if request.meta.force_keyframe {
825+ let mut force = SafeExtControl::<VideoForceKeyFrame>::from_value(1);
826+ ioctl::s_ext_ctrls(&self.device, ioctl::CtrlWhich::Current, &mut force).map_err(
827+ |error| ControlError { which: "force keyframe", error: error.error.into() },
828+ )?;
829+ }
830+
831+ request.handle.queue(buffer).map_err(BackendError::QueueFrameHandleError)?;
832+
833+ log::debug!("OUTPUT: Queued buffer index={} timestamp={:?}", index, timestamp);
834+
835+ // TODO: Use RequestId for this?
836+ self.currently_processed.insert(timestamp, (request.request_id, request.meta));
837+
838+ Ok(())
839+ }
840+
841+ /// Performs the essential processing ie. queues and dequeues the buffers from CAPTURE and
842+ /// OUTPUT queue.
843+ fn handle_buffers(&mut self) -> BackendResult<()> {
844+ self.queue_capture()?;
845+ self.drain_output_queue()?;
846+
847+ log::debug!(
848+ "Queue status: OUTPUT(free: {}, queued: {}) CAPTURE(free: {}, queued: {})",
849+ self.output_queue.num_free_buffers(),
850+ self.output_queue.num_queued_buffers(),
851+ self.capture_queue.num_free_buffers(),
852+ self.capture_queue.num_queued_buffers(),
853+ );
854+
855+ Ok(())
856+ }
857+}
858+
859+impl<Handle, CaptureBufferz, Codec> StatefulVideoEncoderBackend<Handle>
860+ for V4L2Backend<Handle, CaptureBufferz, Codec>
861+where
862+ Handle: OutputBufferHandle,
863+ CaptureBufferz: CaptureBuffers,
864+ Self: EncoderCodec,
865+{
866+ fn consume_request(
867+ &mut self,
868+ request: &mut Option<BackendRequest<Handle>>,
869+ ) -> StatefulBackendResult<()> {
870+ self.handle_buffers()?;
871+
872+ if self.output_queue.num_free_buffers() == 0 {
873+ return Ok(());
874+ }
875+
876+ let Some(request) = request.take() else {
877+ log::error!("StatefulEncoder passed an empty request");
878+ return Err(StatefulBackendError::InvalidInternalState);
879+ };
880+
881+ self.handle_request(request)?;
882+
883+ Ok(())
884+ }
885+
886+ fn sync(&mut self) -> StatefulBackendResult<()> {
887+ self.poll_device()?;
888+ Ok(())
889+ }
890+
891+ fn poll(&mut self) -> StatefulBackendResult<Option<BackendOutput>> {
892+ Ok(self.dequeue_capture()?)
893+ }
894+
895+ fn drain(&mut self) -> StatefulBackendResult<Vec<BackendOutput>> {
896+ if self.currently_processed.is_empty() {
897+ log::info!("Skipping drain sequence, nothing to drain.");
898+ return Ok(Vec::new());
899+ }
900+
901+ log::debug!(
902+ "Sending stop command to encoder. Currently processing count: {}",
903+ self.currently_processed.len()
904+ );
905+
906+ ioctl::encoder_cmd::<_, ()>(&self.device, &EncoderCommand::Stop(false))
907+ .map_err(BackendError::DrainCommand)?;
908+
909+ let mut drained_output = Vec::new();
910+ while !self.currently_processed.is_empty() {
911+ self.poll_device()?;
912+ self.handle_buffers()?;
913+
914+ if let Some(output) = self.dequeue_capture()? {
915+ drained_output.push(output);
916+ }
917+ }
918+
919+ // Dequeue is_last=true buffer
920+ if let Some(output) = self.dequeue_capture()? {
921+ drained_output.push(output);
922+ }
923+
924+ log::debug!("Sending start command to encoder");
925+ ioctl::encoder_cmd::<_, ()>(&self.device, &EncoderCommand::Start)
926+ .map_err(BackendError::DrainCommand)?;
927+
928+ log::debug!("Drain finished");
929+ Ok(drained_output)
930+ }
931+}
932+
933+pub fn find_device_with_capture(pixfmt: v4l2r::PixelFormat) -> Option<PathBuf> {
934+ const MAX_DEVICE_NO: usize = 128;
935+ for dev_no in 0..MAX_DEVICE_NO {
936+ let device_path = PathBuf::from(format!("/dev/video{dev_no}"));
937+ let Ok(device) = Device::open(&device_path, DeviceConfig::new()) else {
938+ continue;
939+ };
940+
941+ let device = Arc::new(device);
942+
943+ let Ok(queue) = Queue::get_capture_mplane_queue(device) else {
944+ continue;
945+ };
946+
947+ for fmt in queue.format_iter() {
948+ if fmt.pixelformat == pixfmt {
949+ return Some(device_path);
950+ }
951+ }
952+ }
953+
954+ None
955+}
956+
957+pub fn v4l2_format_to_frame_layout(format: &v4l2r::Format) -> FrameLayout {
958+ let mut layout = FrameLayout {
959+ format: (Fourcc::from(format.pixelformat.to_u32()), 0),
960+ size: Resolution { width: format.width, height: format.height },
961+ planes: format
962+ .plane_fmt
963+ .iter()
964+ .map(|plane| crate::PlaneLayout {
965+ buffer_index: 0,
966+ offset: 0,
967+ stride: plane.bytesperline as usize,
968+ })
969+ .collect(),
970+ };
971+
972+ // Patch FrameLayout
973+ match &format.pixelformat.to_fourcc() {
974+ b"NM12" if layout.planes.len() == 2 => {
975+ layout.planes[1].buffer_index = 1;
976+ }
977+ b"NV12" if layout.planes.len() == 1 => {}
978+ _ => panic!("Unknown format"),
979+ };
980+
981+ layout
982+}
983+
984+#[cfg(test)]
985+pub(crate) mod tests {
986+ use std::os::fd::AsFd;
987+ use std::os::fd::BorrowedFd;
988+ use std::os::fd::OwnedFd;
989+ use std::path::Path;
990+ use std::path::PathBuf;
991+
992+ use anyhow::Context;
993+ use v4l2r::device::queue::CaptureQueueable;
994+ use v4l2r::device::DeviceConfig;
995+ use v4l2r::memory::DmaBufSource;
996+
997+ use super::*;
998+
999+ use crate::backend::v4l2::encoder::CaptureBuffers;
1000+ use crate::encoder::simple_encode_loop;
1001+ use crate::encoder::stateful::StatefulEncoder;
1002+ use crate::encoder::tests::fill_test_frame_nm12;
1003+ use crate::encoder::tests::fill_test_frame_nv12;
1004+ use crate::encoder::tests::get_test_frame_t;
1005+
1006+ /// A simple wrapper for a GBM device node.
1007+ pub struct GbmDevice(std::fs::File);
1008+
1009+ impl AsFd for GbmDevice {
1010+ fn as_fd(&self) -> BorrowedFd<'_> {
1011+ self.0.as_fd()
1012+ }
1013+ }
1014+
1015+ impl drm::Device for GbmDevice {}
1016+
1017+ /// Simple helper methods for opening a `Card`.
1018+ impl GbmDevice {
1019+ pub fn open<P: AsRef<Path>>(path: P) -> std::io::Result<Self> {
1020+ std::fs::OpenOptions::new().read(true).write(true).open(path).map(GbmDevice)
1021+ }
1022+ }
1023+
1024+ pub struct BoCaptureBuffer {
1025+ bo: gbm::BufferObject<()>,
1026+ fd: OwnedFd,
1027+ len: u64,
1028+ }
1029+
1030+ impl AsRawFd for BoCaptureBuffer {
1031+ fn as_raw_fd(&self) -> std::os::unix::prelude::RawFd {
1032+ self.fd.as_raw_fd()
1033+ }
1034+ }
1035+
1036+ impl AsFd for BoCaptureBuffer {
1037+ fn as_fd(&self) -> BorrowedFd<'_> {
1038+ self.fd.as_fd()
1039+ }
1040+ }
1041+
1042+ impl DmaBufSource for BoCaptureBuffer {
1043+ fn len(&self) -> u64 {
1044+ self.len
1045+ }
1046+ }
1047+
1048+ impl std::fmt::Debug for BoCaptureBuffer {
1049+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1050+ f.debug_struct("BoCaptureBuffer").finish()
1051+ }
1052+ }
1053+
1054+ unsafe impl Sync for BoCaptureBuffer {}
1055+
1056+ unsafe impl Send for BoCaptureBuffer {}
1057+
1058+ // SAFETY: copied from gbm.h
1059+ pub const GBM_BO_USE_SW_READ_OFTEN: gbm::BufferObjectFlags =
1060+ unsafe { gbm::BufferObjectFlags::from_bits_truncate(1 << 9) };
1061+
1062+ // SAFETY: copied from gbm.h
1063+ pub const GBM_BO_USE_HW_VIDEO_ENCODER: gbm::BufferObjectFlags =
1064+ unsafe { gbm::BufferObjectFlags::from_bits_truncate(1 << 14) };
1065+
1066+ pub struct BoPoolAllocator {
1067+ gbm: Arc<gbm::Device<GbmDevice>>,
1068+ }
1069+
1070+ impl BoPoolAllocator {
1071+ pub fn new(gbm: Arc<gbm::Device<GbmDevice>>) -> Self {
1072+ Self { gbm }
1073+ }
1074+ }
1075+
1076+ impl CaptureBuffers for BoPoolAllocator {
1077+ type PlaneHandle = DmaBufHandle<BoCaptureBuffer>;
1078+
1079+ fn queue(
1080+ &mut self,
1081+ buffer: QBuffer<
1082+ Capture,
1083+ Vec<Self::PlaneHandle>,
1084+ Vec<Self::PlaneHandle>,
1085+ &Queue<Capture, BuffersAllocated<Vec<Self::PlaneHandle>>>,
1086+ >,
1087+ ) -> anyhow::Result<bool> {
1088+ let len = 2 * 1024 * 1024;
1089+
1090+ log::trace!("Allocating new bo");
1091+ let bo = self
1092+ .gbm
1093+ .create_buffer_object::<()>(
1094+ len as u32,
1095+ 1,
1096+ gbm::Format::R8,
1097+ GBM_BO_USE_HW_VIDEO_ENCODER | GBM_BO_USE_SW_READ_OFTEN,
1098+ )
1099+ .context("gbm_bo_create")?;
1100+
1101+ let fd = bo.fd_for_plane(0).unwrap();
1102+ let handle = BoCaptureBuffer { bo, fd, len };
1103+
1104+ buffer
1105+ .queue_with_handles(vec![DmaBufHandle(handle)])
1106+ .context("queue bo as dmabuf handle")?;
1107+
1108+ Ok(true)
1109+ }
1110+
1111+ fn export(
1112+ &self,
1113+ mut buffer: DqBuffer<Capture, Vec<Self::PlaneHandle>>,
1114+ ) -> anyhow::Result<Vec<u8>> {
1115+ let timestamp = Timestamp::from(buffer.data.timestamp());
1116+
1117+ let Some(mut handle) = buffer.take_handles() else {
1118+ log::error!("CAPTURE: Failed to map buffer timestamp={timestamp:?}");
1119+ return Err(BackendError::FailedToMapCapture(timestamp).into());
1120+ };
1121+
1122+ let Some(handle) = handle.pop() else {
1123+ log::error!("CAPTURE: Failed to map buffer timestamp={timestamp:?}");
1124+ return Err(BackendError::FailedToMapCapture(timestamp).into());
1125+ };
1126+
1127+ let bytesused = *buffer.data.get_first_plane().bytesused;
1128+
1129+ let mut content = Vec::with_capacity(bytesused as usize);
1130+
1131+ handle.0.bo.map(&self.gbm, 0, 0, bytesused, 1, |mapped| {
1132+ content.extend(mapped.buffer());
1133+ })??;
1134+
1135+ Ok(content)
1136+ }
1137+ }
1138+
1139+ pub struct TestMmapFrame {
1140+ meta: FrameMetadata,
1141+ frame_count: u64,
1142+ }
1143+
1144+ impl OutputBufferHandle for TestMmapFrame {
1145+ type PrimitiveBufferHandles = Vec<MmapHandle>;
1146+
1147+ fn queue(
1148+ self,
1149+ buffer: OutputBuffer<'_, Self::PrimitiveBufferHandles>,
1150+ ) -> anyhow::Result<()> {
1151+ if self.meta.layout.format == (Fourcc::from(b"NM12"), 0) {
1152+ let mut y_plane = buffer.get_plane_mapping(0).unwrap();
1153+ let mut uv_plane = buffer.get_plane_mapping(1).unwrap();
1154+
1155+ fill_test_frame_nm12(
1156+ self.meta.layout.size.width as usize,
1157+ self.meta.layout.size.height as usize,
1158+ [self.meta.layout.planes[0].stride, self.meta.layout.planes[1].stride],
1159+ get_test_frame_t(self.meta.timestamp, self.frame_count),
1160+ y_plane.as_mut(),
1161+ uv_plane.as_mut(),
1162+ );
1163+
1164+ buffer.queue(&[y_plane.len(), uv_plane.len()])?;
1165+ } else if self.meta.layout.format == (Fourcc::from(b"NV12"), 0) {
1166+ let mut plane = buffer.get_plane_mapping(0).unwrap();
1167+
1168+ let strides =
1169+ [self.meta.layout.planes[0].stride, self.meta.layout.planes[0].stride];
1170+ let offsets = [
1171+ self.meta.layout.planes[0].offset,
1172+ self.meta.layout.planes[0].stride * self.meta.layout.size.height as usize,
1173+ ];
1174+
1175+ fill_test_frame_nv12(
1176+ self.meta.layout.size.width as usize,
1177+ self.meta.layout.size.height as usize,
1178+ strides,
1179+ offsets,
1180+ get_test_frame_t(self.meta.timestamp, self.frame_count),
1181+ plane.as_mut(),
1182+ );
1183+
1184+ buffer.queue(&[plane.len()])?;
1185+ } else {
1186+ return Err(anyhow::anyhow!("unsupported format"));
1187+ }
1188+
1189+ Ok(())
1190+ }
1191+ }
1192+
1193+ /// Helper struct. Procedurally generate NV12 or NM12 frames for test purposes.
1194+ pub struct TestMmapFrameGenerator {
1195+ counter: u64,
1196+ max_count: u64,
1197+ frame_layout: FrameLayout,
1198+ }
1199+
1200+ impl TestMmapFrameGenerator {
1201+ pub fn new(max_count: u64, frame_layout: FrameLayout) -> Self {
1202+ Self { counter: 0, max_count, frame_layout }
1203+ }
1204+ }
1205+
1206+ impl Iterator for TestMmapFrameGenerator {
1207+ type Item = (FrameMetadata, TestMmapFrame);
1208+
1209+ fn next(&mut self) -> Option<Self::Item> {
1210+ if self.counter > self.max_count {
1211+ return None;
1212+ }
1213+
1214+ self.counter += 1;
1215+
1216+ let meta = FrameMetadata {
1217+ timestamp: self.counter,
1218+ layout: self.frame_layout.clone(),
1219+ force_keyframe: false,
1220+ };
1221+
1222+ let handle = TestMmapFrame { meta: meta.clone(), frame_count: self.max_count };
1223+
1224+ Some((meta, handle))
1225+ }
1226+ }
1227+
1228+ pub fn perform_v4l2_encoder_mmap_test<Codec>(
1229+ frame_count: u64,
1230+ mut encoder: StatefulEncoder<
1231+ TestMmapFrame,
1232+ V4L2Backend<TestMmapFrame, MmapingCapture, Codec>,
1233+ >,
1234+ coded_consumer: impl FnMut(CodedBitstreamBuffer),
1235+ ) where
1236+ V4L2Backend<TestMmapFrame, MmapingCapture, Codec>: EncoderCodec,
1237+ {
1238+ let format: v4l2r::Format = encoder.backend().output_format().unwrap();
1239+ let layout = v4l2_format_to_frame_layout(&format);
1240+ let mut frame_producer = TestMmapFrameGenerator::new(frame_count, layout);
1241+
1242+ simple_encode_loop(&mut encoder, &mut frame_producer, coded_consumer).expect("encode loop");
1243+ }
1244+
1245+ /// Helper struct. Procedurally generate NV12 or NM12 frames for test purposes.
1246+ pub struct TestDmabufFrameGenerator {
1247+ counter: u64,
1248+ max_count: u64,
1249+ coded_size: Resolution,
1250+ visible_size: Resolution,
1251+ gbm: Arc<gbm::Device<GbmDevice>>,
1252+ }
1253+
1254+ impl TestDmabufFrameGenerator {
1255+ pub fn new(
1256+ max_count: u64,
1257+ coded_size: Resolution,
1258+ visible_size: Resolution,
1259+ gbm: Arc<gbm::Device<GbmDevice>>,
1260+ ) -> Self {
1261+ Self { counter: 0, max_count, coded_size, visible_size, gbm }
1262+ }
1263+ }
1264+
1265+ impl Iterator for TestDmabufFrameGenerator {
1266+ type Item = (FrameMetadata, DmabufFrame);
1267+
1268+ fn next(&mut self) -> Option<Self::Item> {
1269+ if self.counter > self.max_count {
1270+ return None;
1271+ }
1272+
1273+ self.counter += 1;
1274+
1275+ let bo = self
1276+ .gbm
1277+ .create_buffer_object::<()>(
1278+ self.coded_size.width,
1279+ self.coded_size.height,
1280+ gbm::Format::Nv12,
1281+ GBM_BO_USE_HW_VIDEO_ENCODER,
1282+ )
1283+ .expect("create bo");
1284+
1285+ let plane_count = bo.plane_count().unwrap() as i32;
1286+ let fourcc = bo.format().unwrap();
1287+
1288+ if plane_count > 2 {
1289+ // NOTE: NV12 should be at most 2 plane.
1290+ panic!("Unsupported plane count for bo");
1291+ }
1292+
1293+ let mut fds: Vec<OwnedFd> = Vec::new();
1294+ let mut inodes: Vec<u64> = Vec::new();
1295+ let mut planes = Vec::new();
1296+
1297+ for plane in 0..(bo.plane_count().unwrap() as i32) {
1298+ let fd = bo.fd_for_plane(plane).unwrap();
1299+ let stat = fstat(fd.as_raw_fd()).unwrap();
1300+ let offset = bo.offset(plane as _).unwrap() as usize;
1301+ let stride = bo.stride_for_plane(plane as _).unwrap() as usize;
1302+ let buffer_index;
1303+
1304+ // Deduplicate fds
1305+ if let Some((index, _)) =
1306+ inodes.iter().enumerate().find(|(_, s)| **s == stat.st_ino)
1307+ {
1308+ buffer_index = index;
1309+ } else {
1310+ buffer_index = fds.len();
1311+ fds.push(fd);
1312+ inodes.push(stat.st_ino);
1313+ }
1314+
1315+ planes.push(crate::PlaneLayout { buffer_index, offset, stride })
1316+ }
1317+
1318+ let layout = FrameLayout {
1319+ format: (Fourcc::from(fourcc as u32), 0),
1320+ size: self.visible_size,
1321+ planes,
1322+ };
1323+ dbg!(&layout);
1324+
1325+ let meta = FrameMetadata {
1326+ timestamp: self.counter,
1327+ layout: layout.clone(),
1328+ force_keyframe: false,
1329+ };
1330+
1331+ let frame = DmabufFrame { fds, layout };
1332+
1333+ Some((meta, frame))
1334+ }
1335+ }
1336+
1337+ pub fn perform_v4l2_encoder_dmabuf_test<Codec>(
1338+ coded_size: Resolution,
1339+ visible_size: Resolution,
1340+ frame_count: u64,
1341+ gbm: Arc<gbm::Device<GbmDevice>>,
1342+ mut encoder: StatefulEncoder<DmabufFrame, V4L2Backend<DmabufFrame, BoPoolAllocator, Codec>>,
1343+ coded_consumer: impl FnMut(CodedBitstreamBuffer),
1344+ ) where
1345+ V4L2Backend<DmabufFrame, BoPoolAllocator, Codec>: EncoderCodec,
1346+ {
1347+ let format: v4l2r::Format = encoder.backend().output_format().unwrap();
1348+
1349+ let mut frame_producer =
1350+ TestDmabufFrameGenerator::new(frame_count, coded_size, visible_size, gbm).map(
1351+ |(meta, mut frame)| {
1352+ if frame.layout.format.0 == Fourcc::from(b"NV12")
1353+ && frame.layout.planes.len() == 2
1354+ && format.pixelformat == PixelFormat::from_fourcc(b"NV12")
1355+ && format.plane_fmt.len() == 1
1356+ {
1357+ // Remove last NV12 plane when GBM advertises 2 plaens and V4L2 expects a
1358+ // single frame.
1359+ frame.layout.planes.pop();
1360+ }
1361+
1362+ (meta, frame)
1363+ },
1364+ );
1365+
1366+ simple_encode_loop(&mut encoder, &mut frame_producer, coded_consumer).expect("encode loop");
1367+ }
1368+}
vendor/cros-codecs/src/backend/vaapi.rsadded+270 -0
@@ -0,0 +1,270 @@
1+// Copyright 2022 The ChromiumOS Authors
2+// Use of this source code is governed by a BSD-style license that can be
3+// found in the LICENSE file.
4+
5+//! VAAPI backend for both stateless decoders and encoders.
6+
7+use std::collections::HashSet;
8+use std::fmt::Debug;
9+use std::os::fd::AsRawFd;
10+
11+use anyhow::anyhow;
12+use libva::Display;
13+use libva::VAConfigAttrib;
14+use libva::VAConfigAttribType;
15+
16+use crate::utils::DmabufFrame;
17+use crate::utils::UserPtrFrame;
18+use crate::DecodedFormat;
19+
20+pub mod decoder;
21+pub mod encoder;
22+pub mod surface_pool;
23+
24+#[allow(dead_code)]
25+fn va_rt_format_to_string(va_rt_format: u32) -> String {
26+ String::from(match va_rt_format {
27+ libva::VA_RT_FORMAT_YUV420 => "YUV420",
28+ libva::VA_RT_FORMAT_YUV422 => "YUV422",
29+ libva::VA_RT_FORMAT_YUV444 => "YUV444",
30+ libva::VA_RT_FORMAT_YUV420_10 => "YUV420_10",
31+ libva::VA_RT_FORMAT_YUV420_12 => "YUV420_12",
32+ libva::VA_RT_FORMAT_YUV422_10 => "YUV422_10",
33+ libva::VA_RT_FORMAT_YUV422_12 => "YUV422_12",
34+ libva::VA_RT_FORMAT_YUV444_10 => "YUV444_10",
35+ libva::VA_RT_FORMAT_YUV444_12 => "YUV444_12",
36+ other => return format!("unknown VA rt_format {}", other),
37+ })
38+}
39+
40+#[allow(dead_code)]
41+#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
42+struct FormatMap {
43+ pub rt_format: u32,
44+ pub va_fourcc: u32,
45+ pub decoded_format: DecodedFormat,
46+}
47+
48+/// Maps a given VA_RT_FORMAT to a compatible decoded format in an arbitrary
49+/// preferred order.
50+#[allow(dead_code)]
51+const FORMAT_MAP: [FormatMap; 10] = [
52+ FormatMap {
53+ rt_format: libva::VA_RT_FORMAT_YUV420,
54+ va_fourcc: libva::VA_FOURCC_NV12,
55+ decoded_format: DecodedFormat::NV12,
56+ },
57+ FormatMap {
58+ rt_format: libva::VA_RT_FORMAT_YUV420,
59+ va_fourcc: libva::VA_FOURCC_I420,
60+ decoded_format: DecodedFormat::I420,
61+ },
62+ FormatMap {
63+ rt_format: libva::VA_RT_FORMAT_YUV422,
64+ va_fourcc: libva::VA_FOURCC_422H,
65+ decoded_format: DecodedFormat::I422,
66+ },
67+ FormatMap {
68+ rt_format: libva::VA_RT_FORMAT_YUV444,
69+ va_fourcc: libva::VA_FOURCC_444P,
70+ decoded_format: DecodedFormat::I444,
71+ },
72+ FormatMap {
73+ rt_format: libva::VA_RT_FORMAT_YUV420_10,
74+ va_fourcc: libva::VA_FOURCC_P010,
75+ decoded_format: DecodedFormat::I010,
76+ },
77+ FormatMap {
78+ rt_format: libva::VA_RT_FORMAT_YUV420_12,
79+ va_fourcc: libva::VA_FOURCC_P012,
80+ decoded_format: DecodedFormat::I012,
81+ },
82+ FormatMap {
83+ rt_format: libva::VA_RT_FORMAT_YUV422_10,
84+ va_fourcc: libva::VA_FOURCC_Y210,
85+ decoded_format: DecodedFormat::I210,
86+ },
87+ FormatMap {
88+ rt_format: libva::VA_RT_FORMAT_YUV422_12,
89+ va_fourcc: libva::VA_FOURCC_Y212,
90+ decoded_format: DecodedFormat::I212,
91+ },
92+ FormatMap {
93+ rt_format: libva::VA_RT_FORMAT_YUV444_10,
94+ va_fourcc: libva::VA_FOURCC_Y410,
95+ decoded_format: DecodedFormat::I410,
96+ },
97+ FormatMap {
98+ rt_format: libva::VA_RT_FORMAT_YUV444_12,
99+ va_fourcc: libva::VA_FOURCC_Y412,
100+ decoded_format: DecodedFormat::I412,
101+ },
102+];
103+
104+/// Returns a set of supported decoded formats given `rt_format`
105+#[allow(dead_code)]
106+fn supported_formats_for_rt_format(
107+ display: &Display,
108+ rt_format: u32,
109+ profile: i32,
110+ entrypoint: u32,
111+ image_formats: &[libva::VAImageFormat],
112+) -> anyhow::Result<HashSet<FormatMap>> {
113+ let mut attrs =
114+ vec![VAConfigAttrib { type_: VAConfigAttribType::VAConfigAttribRTFormat, value: 0 }];
115+
116+ display.get_config_attributes(profile, entrypoint, &mut attrs)?;
117+
118+ // See whether this RT_FORMAT is supported by the given VAProfile and
119+ // VAEntrypoint pair.
120+ if attrs[0].value == libva::VA_ATTRIB_NOT_SUPPORTED || attrs[0].value & rt_format == 0 {
121+ return Err(anyhow!(
122+ "rt_format {:?} not supported for profile {:?} and entrypoint {:?}",
123+ rt_format,
124+ profile,
125+ entrypoint
126+ ));
127+ }
128+
129+ let mut supported_formats = HashSet::new();
130+
131+ for format in FORMAT_MAP {
132+ if format.rt_format == rt_format {
133+ supported_formats.insert(format);
134+ }
135+ }
136+
137+ // Only retain those that the hardware can actually map into.
138+ supported_formats
139+ .retain(|&entry| image_formats.iter().any(|fmt| fmt.fourcc == entry.va_fourcc));
140+
141+ Ok(supported_formats)
142+}
143+
144+impl TryFrom<&libva::VAImageFormat> for DecodedFormat {
145+ type Error = anyhow::Error;
146+
147+ fn try_from(value: &libva::VAImageFormat) -> Result<Self, Self::Error> {
148+ match value.fourcc {
149+ libva::VA_FOURCC_I420 => Ok(DecodedFormat::I420),
150+ libva::VA_FOURCC_NV12 => Ok(DecodedFormat::NV12),
151+ libva::VA_FOURCC_P010 => Ok(DecodedFormat::I010),
152+ libva::VA_FOURCC_P012 => Ok(DecodedFormat::I012),
153+ libva::VA_FOURCC_Y210 => Ok(DecodedFormat::I210),
154+ libva::VA_FOURCC_Y212 => Ok(DecodedFormat::I212),
155+ libva::VA_FOURCC_Y410 => Ok(DecodedFormat::I410),
156+ libva::VA_FOURCC_Y412 => Ok(DecodedFormat::I412),
157+ _ => Err(anyhow!("Unsupported format")),
158+ }
159+ }
160+}
161+
162+impl libva::ExternalBufferDescriptor for UserPtrFrame {
163+ const MEMORY_TYPE: libva::MemoryType = libva::MemoryType::UserPtr;
164+ type DescriptorAttribute = libva::VASurfaceAttribExternalBuffers;
165+
166+ fn va_surface_attribute(&mut self) -> Self::DescriptorAttribute {
167+ let pitches = self
168+ .layout
169+ .planes
170+ .iter()
171+ .map(|p| p.stride as u32)
172+ .chain(std::iter::repeat(0))
173+ .take(4)
174+ .collect::<Vec<_>>()
175+ .try_into()
176+ .unwrap();
177+ let offsets = self
178+ .layout
179+ .planes
180+ .iter()
181+ .map(|p| p.offset as u32)
182+ .chain(std::iter::repeat(0))
183+ .take(4)
184+ .collect::<Vec<_>>()
185+ .try_into()
186+ .unwrap();
187+
188+ libva::VASurfaceAttribExternalBuffers {
189+ pixel_format: self.layout.format.0.into(),
190+ width: self.layout.size.width,
191+ height: self.layout.size.height,
192+ data_size: self.mem_layout.size() as u32,
193+ num_planes: self.layout.planes.len() as u32,
194+ pitches,
195+ offsets,
196+ buffers: self.buffers.as_mut_ptr() as *mut _,
197+ num_buffers: self.buffers.len() as u32,
198+ flags: 0,
199+ private_data: std::ptr::null_mut(),
200+ }
201+ }
202+}
203+
204+impl libva::ExternalBufferDescriptor for DmabufFrame {
205+ const MEMORY_TYPE: libva::MemoryType = libva::MemoryType::DrmPrime2;
206+ type DescriptorAttribute = libva::VADRMPRIMESurfaceDescriptor;
207+
208+ fn va_surface_attribute(&mut self) -> Self::DescriptorAttribute {
209+ let objects = self
210+ .fds
211+ .iter()
212+ .map(|fd| libva::VADRMPRIMESurfaceDescriptorObject {
213+ fd: fd.as_raw_fd(),
214+ size: nix::sys::stat::fstat(fd.as_raw_fd())
215+ .map(|stat| stat.st_size as u32)
216+ // If we don't have the information about the plane fd size, fallback to 0.
217+ // Libva seems to be *sometimes* "happy" with zero.
218+ .unwrap_or(0),
219+ // TODO should the descriptor be moved to individual objects?
220+ drm_format_modifier: self.layout.format.1,
221+ })
222+ .chain(std::iter::repeat(Default::default()))
223+ .take(4)
224+ .collect::<Vec<_>>()
225+ .try_into()
226+ .unwrap();
227+
228+ let layers = [
229+ libva::VADRMPRIMESurfaceDescriptorLayer {
230+ drm_format: self.layout.format.0.into(),
231+ num_planes: self.layout.planes.len() as u32,
232+ object_index: [0, 0, 0, 0],
233+ offset: self
234+ .layout
235+ .planes
236+ .iter()
237+ .map(|p| p.offset as u32)
238+ .chain(std::iter::repeat(0))
239+ .take(4)
240+ .collect::<Vec<_>>()
241+ .try_into()
242+ .unwrap(),
243+ pitch: self
244+ .layout
245+ .planes
246+ .iter()
247+ .map(|p| p.stride as u32)
248+ .chain(std::iter::repeat(0))
249+ .take(4)
250+ .collect::<Vec<_>>()
251+ .try_into()
252+ .unwrap(),
253+ },
254+ Default::default(),
255+ Default::default(),
256+ Default::default(),
257+ ];
258+
259+ libva::VADRMPRIMESurfaceDescriptor {
260+ // TODO should we match and use VA_FOURCC_* here?
261+ fourcc: self.layout.format.0.into(),
262+ width: self.layout.size.width,
263+ height: self.layout.size.height,
264+ num_objects: 1,
265+ objects,
266+ num_layers: 1,
267+ layers,
268+ }
269+ }
270+}
vendor/cros-codecs/src/backend/vaapi/decoder.rsadded+339 -0
@@ -0,0 +1,339 @@
1+// Copyright 2023 The ChromiumOS Authors
2+// Use of this source code is governed by a BSD-style license that can be
3+// found in the LICENSE file.
4+
5+use std::cell::RefCell;
6+use std::marker::PhantomData;
7+use std::rc::Rc;
8+use std::sync::Arc;
9+
10+use anyhow::anyhow;
11+use anyhow::Context as AnyhowContext;
12+use libva::{
13+ Buffer, Context, Display, Picture, PictureEnd, PictureNew, PictureSync, Surface,
14+ SurfaceMemoryDescriptor, VaError,
15+};
16+
17+use crate::decoder::stateless::StatelessBackendResult;
18+use crate::decoder::stateless::StatelessCodec;
19+use crate::decoder::stateless::StatelessDecoderBackend;
20+use crate::decoder::stateless::StatelessDecoderBackendPicture;
21+use crate::decoder::DecodedHandle as DecodedHandleTrait;
22+use crate::decoder::StreamInfo;
23+use crate::video_frame::VideoFrame;
24+use crate::DecodedFormat;
25+use crate::Rect;
26+use crate::Resolution;
27+
28+/// A decoded frame handle.
29+pub(crate) type DecodedHandle<V> = Rc<RefCell<VaapiDecodedHandle<V>>>;
30+
31+/// Gets the VASurfaceID for the given `picture`.
32+pub(crate) fn va_surface_id<V: VideoFrame>(
33+ handle: &Option<DecodedHandle<V>>,
34+) -> libva::VASurfaceID {
35+ match handle {
36+ None => libva::VA_INVALID_SURFACE,
37+ Some(handle) => handle.borrow().surface().id(),
38+ }
39+}
40+
41+impl<V: VideoFrame> DecodedHandleTrait for DecodedHandle<V> {
42+ type Frame = V;
43+
44+ fn video_frame(&self) -> Arc<Self::Frame> {
45+ self.borrow().backing_frame.clone()
46+ }
47+
48+ fn coded_resolution(&self) -> Resolution {
49+ self.borrow().surface().size().into()
50+ }
51+
52+ fn display_resolution(&self) -> Resolution {
53+ self.borrow().display_resolution
54+ }
55+
56+ fn timestamp(&self) -> u64 {
57+ self.borrow().timestamp()
58+ }
59+
60+ fn is_ready(&self) -> bool {
61+ self.borrow().state.is_ready().unwrap_or(true)
62+ }
63+
64+ fn sync(&self) -> anyhow::Result<()> {
65+ self.borrow_mut().sync().context("while syncing picture")?;
66+
67+ Ok(())
68+ }
69+}
70+
71+/// A trait for providing the basic information needed to setup libva for decoding.
72+pub(crate) trait VaStreamInfo {
73+ /// Returns the VA profile of the stream.
74+ fn va_profile(&self) -> anyhow::Result<i32>;
75+ /// Returns the RT format of the stream.
76+ #[allow(dead_code)]
77+ fn rt_format(&self) -> anyhow::Result<u32>;
78+ /// Returns the minimum number of surfaces required to decode the stream.
79+ fn min_num_surfaces(&self) -> usize;
80+ /// Returns the coded size of the surfaces required to decode the stream.
81+ fn coded_size(&self) -> Resolution;
82+ /// Returns the visible rectangle within the coded size for the stream.
83+ fn visible_rect(&self) -> Rect;
84+}
85+
86+/// Rendering state of a VA picture.
87+enum PictureState<M: SurfaceMemoryDescriptor> {
88+ Ready(Picture<PictureSync, Surface<M>>),
89+ Pending(Picture<PictureEnd, Surface<M>>),
90+ // Only set in sync when we take ownership of the VA picture.
91+ Invalid,
92+}
93+
94+impl<M: SurfaceMemoryDescriptor> PictureState<M> {
95+ /// Make sure that all pending operations on the picture have completed.
96+ fn sync(&mut self) -> Result<(), VaError> {
97+ let res;
98+
99+ (*self, res) = match std::mem::replace(self, PictureState::Invalid) {
100+ state @ PictureState::Ready(_) => (state, Ok(())),
101+ PictureState::Pending(picture) => match picture.sync() {
102+ Ok(picture) => (PictureState::Ready(picture), Ok(())),
103+ Err((e, picture)) => (PictureState::Pending(picture), Err(e)),
104+ },
105+ PictureState::Invalid => unreachable!(),
106+ };
107+
108+ res
109+ }
110+
111+ fn surface(&self) -> &Surface<M> {
112+ match self {
113+ PictureState::Ready(picture) => picture.surface(),
114+ PictureState::Pending(picture) => picture.surface(),
115+ PictureState::Invalid => unreachable!(),
116+ }
117+ }
118+
119+ fn timestamp(&self) -> u64 {
120+ match self {
121+ PictureState::Ready(picture) => picture.timestamp(),
122+ PictureState::Pending(picture) => picture.timestamp(),
123+ PictureState::Invalid => unreachable!(),
124+ }
125+ }
126+
127+ fn is_ready(&self) -> Result<bool, VaError> {
128+ match self {
129+ PictureState::Ready(_) => Ok(true),
130+ PictureState::Pending(picture) => picture
131+ .surface()
132+ .query_status()
133+ .map(|s| s == libva::VASurfaceStatus::VASurfaceReady),
134+ PictureState::Invalid => unreachable!(),
135+ }
136+ }
137+
138+ fn new_from_same_surface(&self, timestamp: u64) -> Picture<PictureNew, Surface<M>> {
139+ match &self {
140+ PictureState::Ready(picture) => Picture::new_from_same_surface(timestamp, picture),
141+ PictureState::Pending(picture) => Picture::new_from_same_surface(timestamp, picture),
142+ PictureState::Invalid => unreachable!(),
143+ }
144+ }
145+}
146+
147+/// VA-API backend handle.
148+///
149+/// This includes the VA picture which can be pending rendering or complete, as well as useful
150+/// meta-information.
151+pub struct VaapiDecodedHandle<V: VideoFrame> {
152+ backing_frame: Arc<V>,
153+ state: PictureState<<V as VideoFrame>::MemDescriptor>,
154+ /// Actual resolution of the visible rectangle in the decoded buffer.
155+ display_resolution: Resolution,
156+}
157+
158+impl<V: VideoFrame> VaapiDecodedHandle<V> {
159+ /// Creates a new pending handle on `surface_id`.
160+ fn new(picture: VaapiPicture<V>, display_resolution: Resolution) -> anyhow::Result<Self> {
161+ let backing_frame = picture.backing_frame;
162+ let picture = picture.picture.begin()?.render()?.end()?;
163+ Ok(Self {
164+ backing_frame: backing_frame,
165+ state: PictureState::Pending(picture),
166+ display_resolution: display_resolution,
167+ })
168+ }
169+
170+ fn sync(&mut self) -> Result<(), VaError> {
171+ self.state.sync()
172+ }
173+
174+ /// Creates a new picture from the surface backing the current one. Useful for interlaced
175+ /// decoding. TODO: Do we need this for other purposes? We don't intend to support interlaced.
176+ pub(crate) fn new_picture_from_same_surface(&self, timestamp: u64) -> VaapiPicture<V> {
177+ VaapiPicture {
178+ picture: self.state.new_from_same_surface(timestamp),
179+ backing_frame: self.backing_frame.clone(),
180+ }
181+ }
182+
183+ // LOCAL PATCH (see /Cargo.toml [patch.crates-io]): made public so a client can
184+ // read frames back with vaGetImage. Mapping the client-allocated DMA-BUF
185+ // directly is a 44 MB/s uncached PCIe read on a discrete GPU; the driver's own
186+ // copy path is ~100x faster.
187+ pub fn surface(&self) -> &Surface<<V as VideoFrame>::MemDescriptor> {
188+ self.state.surface()
189+ }
190+
191+ /// Returns the timestamp of this handle.
192+ fn timestamp(&self) -> u64 {
193+ self.state.timestamp()
194+ }
195+}
196+
197+pub struct VaapiBackend<V: VideoFrame> {
198+ pub display: Rc<Display>,
199+ pub context: Rc<Context>,
200+ stream_info: StreamInfo,
201+ // TODO: We should try to support context reuse
202+ _supports_context_reuse: bool,
203+ _phantom_data: PhantomData<V>,
204+}
205+
206+impl<V: VideoFrame> VaapiBackend<V> {
207+ pub(crate) fn new(display: Rc<libva::Display>, supports_context_reuse: bool) -> Self {
208+ // LOCAL PATCH (see /Cargo.toml [patch.crates-io]): upstream probes with a
209+ // 16x16 context, which Mesa radeonsi rejects with VA_STATUS_ERROR_UNIMPLEMENTED
210+ // (measured: 16x16 and 48x48 fail, 64x64 up succeed), and the `expect` below
211+ // then aborts. This placeholder is replaced by `new_sequence` anyway.
212+ let init_stream_info = StreamInfo {
213+ format: DecodedFormat::NV12,
214+ coded_resolution: Resolution::from((64, 64)),
215+ display_resolution: Resolution::from((64, 64)),
216+ min_num_frames: 1,
217+ };
218+ let config = display
219+ .create_config(
220+ vec![libva::VAConfigAttrib {
221+ type_: libva::VAConfigAttribType::VAConfigAttribRTFormat,
222+ value: libva::VA_RT_FORMAT_YUV420,
223+ }],
224+ libva::VAProfile::VAProfileH264Main,
225+ libva::VAEntrypoint::VAEntrypointVLD,
226+ )
227+ .expect("Could not create initial VAConfig!");
228+ let context = display
229+ .create_context::<<V as VideoFrame>::MemDescriptor>(
230+ &config,
231+ init_stream_info.coded_resolution.width,
232+ init_stream_info.coded_resolution.height,
233+ None,
234+ true,
235+ )
236+ .expect("Could not create initial VAContext!");
237+ Self {
238+ display: display,
239+ context: context,
240+ _supports_context_reuse: supports_context_reuse,
241+ stream_info: init_stream_info,
242+ _phantom_data: Default::default(),
243+ }
244+ }
245+
246+ pub(crate) fn new_sequence<StreamData>(
247+ &mut self,
248+ stream_params: &StreamData,
249+ ) -> StatelessBackendResult<()>
250+ where
251+ for<'a> &'a StreamData: VaStreamInfo,
252+ {
253+ self.stream_info.display_resolution = Resolution::from(stream_params.visible_rect());
254+ self.stream_info.coded_resolution = stream_params.coded_size().clone();
255+ self.stream_info.min_num_frames = stream_params.min_num_surfaces();
256+
257+ // TODO: Handle context re-use
258+ // TODO: We should obtain RT_FORMAT from stream_info
259+ let config = self
260+ .display
261+ .create_config(
262+ vec![libva::VAConfigAttrib {
263+ type_: libva::VAConfigAttribType::VAConfigAttribRTFormat,
264+ value: libva::VA_RT_FORMAT_YUV420,
265+ }],
266+ stream_params.va_profile().map_err(|_| anyhow!("Could not get VAProfile!"))?,
267+ libva::VAEntrypoint::VAEntrypointVLD,
268+ )
269+ .map_err(|_| anyhow!("Could not create VAConfig!"))?;
270+ let context = self
271+ .display
272+ .create_context::<<V as VideoFrame>::MemDescriptor>(
273+ &config,
274+ self.stream_info.coded_resolution.width,
275+ self.stream_info.coded_resolution.height,
276+ None,
277+ true,
278+ )
279+ .map_err(|_| anyhow!("Could not create VAContext!"))?;
280+ self.context = context;
281+
282+ Ok(())
283+ }
284+
285+ pub(crate) fn process_picture<Codec: StatelessCodec>(
286+ &mut self,
287+ picture: VaapiPicture<V>,
288+ ) -> StatelessBackendResult<<Self as StatelessDecoderBackend>::Handle>
289+ where
290+ Self: StatelessDecoderBackendPicture<Codec>,
291+ for<'a> &'a Codec::FormatInfo: VaStreamInfo,
292+ {
293+ Ok(Rc::new(RefCell::new(VaapiDecodedHandle::new(
294+ picture,
295+ self.stream_info.display_resolution.clone(),
296+ )?)))
297+ }
298+}
299+
300+/// Shortcut for pictures used for the VAAPI backend.
301+pub struct VaapiPicture<V: VideoFrame> {
302+ picture: Picture<PictureNew, Surface<V::MemDescriptor>>,
303+ backing_frame: Arc<V>,
304+}
305+
306+impl<V: VideoFrame> VaapiPicture<V> {
307+ pub fn new(timestamp: u64, context: Rc<Context>, backing_frame: V) -> Self {
308+ let display = context.display();
309+ let surface = backing_frame
310+ .to_native_handle(display)
311+ .expect("Failed to export video frame to vaapi picture!")
312+ .into();
313+ Self {
314+ backing_frame: Arc::new(backing_frame),
315+ picture: Picture::new(timestamp, context, surface),
316+ }
317+ }
318+
319+ pub fn surface(&self) -> &Surface<V::MemDescriptor> {
320+ self.picture.surface()
321+ }
322+
323+ pub fn add_buffer(&mut self, buffer: Buffer) {
324+ self.picture.add_buffer(buffer)
325+ }
326+}
327+
328+impl<V: VideoFrame> StatelessDecoderBackend for VaapiBackend<V> {
329+ type Handle = DecodedHandle<V>;
330+
331+ fn stream_info(&self) -> Option<&StreamInfo> {
332+ Some(&self.stream_info)
333+ }
334+
335+ fn reset_backend(&mut self) -> anyhow::Result<()> {
336+ //TODO(bchoobineh): Implement VAAPI DRC
337+ Ok(())
338+ }
339+}
vendor/cros-codecs/src/backend/vaapi/encoder.rsadded+651 -0
@@ -0,0 +1,651 @@
1+// Copyright 2024 The ChromiumOS Authors
2+// Use of this source code is governed by a BSD-style license that can be
3+// found in the LICENSE file.
4+
5+use std::any::Any;
6+use std::marker::PhantomData;
7+use std::rc::Rc;
8+
9+use anyhow::anyhow;
10+use libva::Config;
11+use libva::Context;
12+use libva::Display;
13+use libva::EncCodedBuffer;
14+use libva::MappedCodedBuffer;
15+use libva::Picture;
16+use libva::PictureEnd;
17+use libva::Surface;
18+use libva::SurfaceMemoryDescriptor;
19+use libva::UsageHint;
20+use libva::VAEntrypoint::VAEntrypointEncSlice;
21+use libva::VAEntrypoint::VAEntrypointEncSliceLP;
22+use libva::VAProfile;
23+use libva::VASurfaceStatus;
24+
25+use crate::backend::vaapi::surface_pool::PooledVaSurface;
26+use crate::backend::vaapi::surface_pool::VaSurfacePool;
27+use crate::backend::vaapi::FORMAT_MAP;
28+use crate::decoder::FramePool;
29+use crate::encoder::stateless::BackendPromise;
30+use crate::encoder::stateless::StatelessBackendError;
31+use crate::encoder::stateless::StatelessBackendResult;
32+use crate::encoder::stateless::StatelessEncoderBackendImport;
33+use crate::encoder::FrameMetadata;
34+use crate::encoder::RateControl;
35+use crate::encoder::Tunings;
36+use crate::video_frame::VideoFrame;
37+use crate::Fourcc;
38+use crate::Resolution;
39+
40+/// The number of frames that encoder backend should initialize scratch pool with.
41+const INITIAL_SCRATCH_POOL_SIZE: usize = 16;
42+/// The maximum size of scratch pool size, after which the backend will refure to allocate more
43+/// scratch frames.
44+const MAX_SCRATCH_POOL_SIZE: usize = INITIAL_SCRATCH_POOL_SIZE * 4;
45+
46+impl From<libva::VaError> for StatelessBackendError {
47+ fn from(value: libva::VaError) -> Self {
48+ Self::Other(value.into())
49+ }
50+}
51+
52+pub(crate) fn tunings_to_libva_rc<const CLAMP_MIN_QP: u32, const CLAMP_MAX_QP: u32>(
53+ tunings: &Tunings,
54+) -> StatelessBackendResult<libva::EncMiscParameterRateControl> {
55+ let bits_per_second = tunings.rate_control.bitrate_target().unwrap_or(0);
56+ let bits_per_second = u32::try_from(bits_per_second).map_err(|e| anyhow::anyhow!(e))?;
57+
58+ // At the moment we don't support variable bitrate therefore target 100%
59+ const TARGET_PERCENTAGE: u32 = 100;
60+
61+ // Window size in ms that the RC should apply to
62+ const WINDOW_SIZE: u32 = 1_500;
63+
64+ // Clamp minium QP
65+ let min_qp = tunings.min_quality.clamp(CLAMP_MIN_QP, CLAMP_MAX_QP);
66+
67+ let basic_unit_size = 0;
68+
69+ // Don't reset the rate controller
70+ const RESET: u32 = 0;
71+
72+ // Don't skip frames
73+ const DISABLE_FRAME_SKIP: u32 = 1;
74+
75+ // Allow bit stuffing
76+ const DISABLE_BIT_STUFFING: u32 = 0;
77+
78+ // Use default
79+ const MB_RATE_CONTROL: u32 = 0;
80+
81+ // SVC encoding is not supported for now
82+ const TEMPORAL_ID: u32 = 0;
83+
84+ // Don't ensure intraframe size
85+ const CFS_I_FRAMES: u32 = 0;
86+
87+ // We don't use hierarchical B frames currently
88+ const ENABLE_PARALLEL_BRC: u32 = 0;
89+
90+ // Disable dynamic scaling
91+ const ENABLE_DYNAMIC_SCALING: u32 = 0;
92+
93+ // Use default tolerance mode
94+ const FRAME_TOLERANCE_MODE: u32 = 0;
95+
96+ // ICQ mode is not used
97+ const ICQ_QUALITY_FACTOR: u32 = 0;
98+
99+ // Clamp maximum QP
100+ let max_qp = tunings.max_quality.clamp(CLAMP_MIN_QP, CLAMP_MAX_QP);
101+
102+ // Unsed
103+ const QUALITY_FACTOR: u32 = 0;
104+
105+ // No limits
106+ const TARGET_FRAME_SIZE: u32 = 0;
107+
108+ // If ConstantQuality is used then set to it's value, otherwise use middle
109+ let initial_qp = match tunings.rate_control {
110+ RateControl::ConstantQuality(qp) => qp.clamp(min_qp, max_qp),
111+ _ => (min_qp + max_qp) / 2,
112+ };
113+
114+ Ok(libva::EncMiscParameterRateControl::new(
115+ bits_per_second,
116+ TARGET_PERCENTAGE,
117+ WINDOW_SIZE,
118+ initial_qp,
119+ min_qp,
120+ basic_unit_size,
121+ libva::RcFlags::new(
122+ RESET,
123+ DISABLE_FRAME_SKIP,
124+ DISABLE_BIT_STUFFING,
125+ MB_RATE_CONTROL,
126+ TEMPORAL_ID,
127+ CFS_I_FRAMES,
128+ ENABLE_PARALLEL_BRC,
129+ ENABLE_DYNAMIC_SCALING,
130+ FRAME_TOLERANCE_MODE,
131+ ),
132+ ICQ_QUALITY_FACTOR,
133+ max_qp,
134+ QUALITY_FACTOR,
135+ TARGET_FRAME_SIZE,
136+ ))
137+}
138+
139+pub struct Reconstructed(PooledVaSurface<()>);
140+
141+impl Reconstructed {
142+ pub(crate) fn surface(&self) -> &Surface<()> {
143+ use std::borrow::Borrow;
144+ Borrow::<Surface<()>>::borrow(&self.0)
145+ }
146+
147+ pub(crate) fn surface_id(&self) -> u32 {
148+ self.surface().id()
149+ }
150+}
151+
152+pub struct VaapiBackend<M, H>
153+where
154+ M: SurfaceMemoryDescriptor,
155+ H: std::borrow::Borrow<Surface<M>> + 'static,
156+{
157+ /// VA config.
158+ #[allow(dead_code)]
159+ va_config: Config,
160+
161+ /// VA context used for encoding.
162+ context: Rc<Context>,
163+
164+ _va_profile: VAProfile::Type,
165+ scratch_pool: VaSurfacePool<()>,
166+ _phantom: PhantomData<(M, H)>,
167+}
168+
169+impl<M, H> VaapiBackend<M, H>
170+where
171+ M: SurfaceMemoryDescriptor,
172+ H: std::borrow::Borrow<Surface<M>>,
173+{
174+ pub fn new(
175+ display: Rc<Display>,
176+ va_profile: VAProfile::Type,
177+ fourcc: Fourcc,
178+ coded_size: Resolution,
179+ bitrate_control: u32,
180+ low_power: bool,
181+ ) -> StatelessBackendResult<Self> {
182+ let format_map = FORMAT_MAP
183+ .iter()
184+ .find(|&map| map.va_fourcc == fourcc.0)
185+ .ok_or_else(|| StatelessBackendError::UnsupportedFormat)?;
186+
187+ let rt_format = format_map.rt_format;
188+
189+ let va_config = display.create_config(
190+ vec![
191+ libva::VAConfigAttrib {
192+ type_: libva::VAConfigAttribType::VAConfigAttribRTFormat,
193+ value: rt_format,
194+ },
195+ libva::VAConfigAttrib {
196+ type_: libva::VAConfigAttribType::VAConfigAttribRateControl,
197+ value: bitrate_control,
198+ },
199+ ],
200+ va_profile,
201+ if low_power { VAEntrypointEncSliceLP } else { VAEntrypointEncSlice },
202+ )?;
203+
204+ let context = display.create_context::<M>(
205+ &va_config,
206+ coded_size.width,
207+ coded_size.height,
208+ None,
209+ true,
210+ )?;
211+
212+ let mut scratch_pool = VaSurfacePool::new(
213+ Rc::clone(&display),
214+ rt_format,
215+ Some(UsageHint::USAGE_HINT_ENCODER),
216+ coded_size,
217+ );
218+
219+ // TODO: Allow initial size to be changed
220+ scratch_pool.add_frames(vec![(); INITIAL_SCRATCH_POOL_SIZE])?;
221+
222+ Ok(Self {
223+ va_config,
224+ context,
225+ scratch_pool,
226+ _va_profile: va_profile,
227+ _phantom: Default::default(),
228+ })
229+ }
230+
231+ pub(crate) fn context(&self) -> &Rc<Context> {
232+ &self.context
233+ }
234+
235+ pub(crate) fn new_coded_buffer(
236+ &self,
237+ rate_control: &RateControl,
238+ ) -> StatelessBackendResult<EncCodedBuffer> {
239+ // Coded buffer size multiplier. It's inteded to give head room for the encoder.
240+ const CODED_SIZE_MUL: usize = 2;
241+
242+ // Default coded buffer size if bitrate control is not used.
243+ const DEFAULT_CODED_SIZE: usize = 1_500_000;
244+
245+ let coded_size = rate_control
246+ .bitrate_target()
247+ .map(|e| e as usize * CODED_SIZE_MUL)
248+ .unwrap_or(DEFAULT_CODED_SIZE);
249+
250+ Ok(self.context().create_enc_coded(coded_size)?)
251+ }
252+
253+ // Creates an empty surface that will be filled with reconstructed picture during encoding
254+ // which will be later used as frame reference
255+ pub(crate) fn new_scratch_picture(&mut self) -> StatelessBackendResult<Reconstructed> {
256+ if self.scratch_pool.num_free_frames() == 0 {
257+ if self.scratch_pool.num_managed_frames() >= MAX_SCRATCH_POOL_SIZE {
258+ log::error!("Scratch pool is exhausted and hit the size limit");
259+ return Err(StatelessBackendError::OutOfResources);
260+ }
261+
262+ log::debug!(
263+ "Scratch pool empty, allocating one more surface. (previous pool size: {})",
264+ self.scratch_pool.num_managed_frames()
265+ );
266+ self.scratch_pool.add_frames(vec![()])?;
267+ }
268+
269+ let surface =
270+ self.scratch_pool.get_surface().ok_or(StatelessBackendError::OutOfResources)?;
271+
272+ Ok(Reconstructed(surface))
273+ }
274+}
275+
276+impl<M, Handle> StatelessEncoderBackendImport<Handle, Handle> for VaapiBackend<M, Handle>
277+where
278+ M: SurfaceMemoryDescriptor,
279+ Handle: std::borrow::Borrow<Surface<M>>,
280+{
281+ fn import_picture(
282+ &mut self,
283+ _metadata: &FrameMetadata,
284+ handle: Handle,
285+ ) -> StatelessBackendResult<Handle> {
286+ Ok(handle)
287+ }
288+}
289+
290+impl<V: VideoFrame> StatelessEncoderBackendImport<V, Surface<V::MemDescriptor>>
291+ for VaapiBackend<V::MemDescriptor, Surface<V::MemDescriptor>>
292+{
293+ fn import_picture(
294+ &mut self,
295+ _metadata: &FrameMetadata,
296+ handle: V,
297+ ) -> StatelessBackendResult<Surface<V::MemDescriptor>> {
298+ Ok(handle.to_native_handle(self.context.display()).map_err(|err| anyhow!(err))?.into())
299+ }
300+}
301+
302+/// Vaapi's implementation of [`crate::encoder::stateless::BackendPromise`]
303+pub struct CodedOutputPromise<M, P>
304+where
305+ M: SurfaceMemoryDescriptor,
306+ P: std::borrow::Borrow<Surface<M>>,
307+{
308+ /// Currently processed picture/surface.
309+ handle: Picture<PictureEnd, P>,
310+
311+ /// Hold reference frames/object from being dropped while `handle` is processed.
312+ references: Vec<Rc<dyn Any>>,
313+
314+ // VaBuffer where the coded output will be present after processing
315+ // is finished.
316+ coded_buf: EncCodedBuffer,
317+
318+ /// Container for the request output. Moved from
319+ /// [`crate::encoder::stateless::StatelessVideoEncoderBackend`] request. The output will be
320+ /// appended to it.
321+ coded_output: Vec<u8>,
322+
323+ _phantom: PhantomData<M>,
324+}
325+
326+impl<M, P> CodedOutputPromise<M, P>
327+where
328+ M: SurfaceMemoryDescriptor,
329+ P: std::borrow::Borrow<Surface<M>>,
330+{
331+ pub fn new(
332+ handle: Picture<PictureEnd, P>,
333+ references: Vec<Rc<dyn Any>>,
334+ coded_buf: EncCodedBuffer,
335+ coded_output: Vec<u8>,
336+ ) -> Self {
337+ Self { handle, references, coded_buf, coded_output, _phantom: Default::default() }
338+ }
339+}
340+
341+impl<M, H> BackendPromise for CodedOutputPromise<M, H>
342+where
343+ M: SurfaceMemoryDescriptor,
344+ H: std::borrow::Borrow<Surface<M>>,
345+{
346+ type Output = Vec<u8>;
347+
348+ fn sync(mut self) -> StatelessBackendResult<Self::Output> {
349+ if let Err((err, _)) = self.handle.sync() {
350+ // TODO consider going back to PictureEnd
351+ return Err(err.into());
352+ }
353+
354+ // Drop all references as processing is finished
355+ self.references.clear();
356+
357+ // Map coded buffer and collect bitstream
358+ let coded = MappedCodedBuffer::new(&self.coded_buf)?;
359+ let mut bitstream = self.coded_output;
360+ for segment in coded.segments() {
361+ // TODO: Handle flags?
362+ // NOTE: on flags: 0-7 bits are average QP value
363+ if segment.bit_offset > 0 {
364+ log::warn!("unsupported bit_offset != 0 (yet)");
365+ }
366+ bitstream.extend(segment.buf)
367+ }
368+
369+ Ok(bitstream)
370+ }
371+
372+ fn is_ready(&self) -> bool {
373+ match self.handle.surface().query_status() {
374+ Ok(status) => status == VASurfaceStatus::VASurfaceReady,
375+ Err(_) => {
376+ // An error occurred while processing or checking the status of the underlying
377+ // processing, in both cases consider it is done. In either cases it will be
378+ // returned with [`sync`].
379+ true
380+ }
381+ }
382+ }
383+}
384+
385+#[cfg(test)]
386+pub(crate) mod tests {
387+ use std::borrow::Borrow;
388+
389+ use libva::VA_FOURCC_NV12;
390+ use libva::VA_FOURCC_P010;
391+
392+ use super::*;
393+ use crate::encoder::tests::fill_test_frame_nv12;
394+ use crate::encoder::tests::fill_test_frame_p010;
395+ use crate::encoder::tests::get_test_frame_t;
396+ use crate::encoder::FrameMetadata;
397+ use crate::FrameLayout;
398+
399+ fn map_surface<'a, M: SurfaceMemoryDescriptor>(
400+ display: &Rc<Display>,
401+ surface: &'a Surface<M>,
402+ fourcc: u32,
403+ ) -> libva::Image<'a> {
404+ let image_fmts = display.query_image_formats().unwrap();
405+ let image_fmt = image_fmts.into_iter().find(|f| f.fourcc == fourcc).unwrap();
406+
407+ libva::Image::create_from(surface, image_fmt, surface.size(), surface.size()).unwrap()
408+ }
409+
410+ fn map_surface_nv12<'a, M: SurfaceMemoryDescriptor>(
411+ display: &Rc<Display>,
412+ surface: &'a Surface<M>,
413+ ) -> libva::Image<'a> {
414+ map_surface(display, surface, VA_FOURCC_NV12)
415+ }
416+
417+ fn map_surface_p010<'a, M: SurfaceMemoryDescriptor>(
418+ display: &Rc<Display>,
419+ surface: &'a Surface<M>,
420+ ) -> libva::Image<'a> {
421+ map_surface(display, surface, VA_FOURCC_P010)
422+ }
423+
424+ /// Uploads raw NV12 to Surface
425+ pub fn upload_nv12_img<M: SurfaceMemoryDescriptor>(
426+ display: &Rc<Display>,
427+ surface: &Surface<M>,
428+ width: u32,
429+ height: u32,
430+ data: &[u8],
431+ ) {
432+ let mut image = map_surface_nv12(display, surface);
433+
434+ let va_image = *image.image();
435+ let dest = image.as_mut();
436+ let width = width as usize;
437+ let height = height as usize;
438+
439+ let mut src: &[u8] = data;
440+ let mut dst = &mut dest[va_image.offsets[0] as usize..];
441+
442+ // Copy luma
443+ for _ in 0..height {
444+ dst[..width].copy_from_slice(&src[..width]);
445+ dst = &mut dst[va_image.pitches[0] as usize..];
446+ src = &src[width..];
447+ }
448+
449+ // Advance to the offset of the chroma plane
450+ let mut src = &data[width * height..];
451+ let mut dst = &mut dest[va_image.offsets[1] as usize..];
452+
453+ let height = height / 2;
454+
455+ // Copy chroma
456+ for _ in 0..height {
457+ dst[..width].copy_from_slice(&src[..width]);
458+ dst = &mut dst[va_image.pitches[1] as usize..];
459+ src = &src[width..];
460+ }
461+
462+ surface.sync().unwrap();
463+ drop(image);
464+ }
465+
466+ /// Helper struct. [`Iterator`] to fetch frames from [`SurfacePool`].
467+ pub struct PooledFrameIterator {
468+ counter: u64,
469+ display: Rc<Display>,
470+ pool: VaSurfacePool<()>,
471+ frame_layout: FrameLayout,
472+ }
473+
474+ impl PooledFrameIterator {
475+ pub fn new(
476+ display: Rc<Display>,
477+ pool: VaSurfacePool<()>,
478+ frame_layout: FrameLayout,
479+ ) -> Self {
480+ Self { counter: 0, display, pool, frame_layout }
481+ }
482+ }
483+
484+ impl Iterator for PooledFrameIterator {
485+ type Item = (FrameMetadata, PooledVaSurface<()>);
486+
487+ fn next(&mut self) -> Option<Self::Item> {
488+ let handle = self.pool.get_surface().unwrap();
489+
490+ let meta = FrameMetadata {
491+ layout: self.frame_layout.clone(),
492+ force_keyframe: false,
493+ timestamp: self.counter,
494+ };
495+
496+ self.counter += 1;
497+
498+ Some((meta, handle))
499+ }
500+ }
501+
502+ /// Helper struct. Uses [`Iterator`] with raw chunks and uploads to pooled surface from
503+ /// [`SurfacePool`] to produce frames.
504+ pub struct NV12FrameProducer<'l, I>
505+ where
506+ I: Iterator<Item = &'l [u8]>,
507+ {
508+ raw_iterator: I,
509+ pool_iter: PooledFrameIterator,
510+ }
511+
512+ impl<'l, I> NV12FrameProducer<'l, I>
513+ where
514+ I: Iterator<Item = &'l [u8]>,
515+ {
516+ #[allow(dead_code)]
517+ pub fn new(
518+ raw_iterator: I,
519+ display: Rc<Display>,
520+ pool: VaSurfacePool<()>,
521+ frame_layout: FrameLayout,
522+ ) -> Self {
523+ Self { raw_iterator, pool_iter: PooledFrameIterator::new(display, pool, frame_layout) }
524+ }
525+ }
526+
527+ impl<'l, I> Iterator for NV12FrameProducer<'l, I>
528+ where
529+ I: Iterator<Item = &'l [u8]>,
530+ {
531+ type Item = (FrameMetadata, PooledVaSurface<()>);
532+
533+ fn next(&mut self) -> Option<Self::Item> {
534+ let raw = match self.raw_iterator.next() {
535+ Some(raw) => raw,
536+ None => return None,
537+ };
538+
539+ let (meta, handle) = self.pool_iter.next().unwrap();
540+
541+ let width = meta.layout.size.width;
542+ let height = meta.layout.size.height;
543+ debug_assert_eq!((width * height + width * height / 2) as usize, raw.len());
544+
545+ upload_nv12_img(&self.pool_iter.display, handle.borrow(), width, height, raw);
546+
547+ Some((meta, handle))
548+ }
549+ }
550+
551+ pub fn upload_test_frame_nv12<M: SurfaceMemoryDescriptor>(
552+ display: &Rc<Display>,
553+ surface: &Surface<M>,
554+ t: f32,
555+ ) {
556+ let mut image = map_surface_nv12(display, surface);
557+
558+ let (width, height) = image.display_resolution();
559+
560+ let offsets = image.image().offsets;
561+ let pitches = image.image().pitches;
562+
563+ fill_test_frame_nv12(
564+ width as usize,
565+ height as usize,
566+ [pitches[0] as usize, pitches[1] as usize],
567+ [offsets[0] as usize, offsets[1] as usize],
568+ t,
569+ image.as_mut(),
570+ );
571+
572+ drop(image);
573+ surface.sync().unwrap();
574+ }
575+
576+ pub fn upload_test_frame_p010<M: SurfaceMemoryDescriptor>(
577+ display: &Rc<Display>,
578+ surface: &Surface<M>,
579+ t: f32,
580+ ) {
581+ let mut image = map_surface_p010(display, surface);
582+
583+ let (width, height) = image.display_resolution();
584+
585+ let offsets = image.image().offsets;
586+ let pitches = image.image().pitches;
587+
588+ fill_test_frame_p010(
589+ width as usize,
590+ height as usize,
591+ [pitches[0] as usize, pitches[1] as usize],
592+ [offsets[0] as usize, offsets[1] as usize],
593+ t,
594+ image.as_mut(),
595+ );
596+
597+ drop(image);
598+ surface.sync().unwrap();
599+ }
600+
601+ /// Helper struct. Procedurally generate NV12 frames for test purposes.
602+ pub struct TestFrameGenerator {
603+ counter: u64,
604+ max_count: u64,
605+ pool_iter: PooledFrameIterator,
606+ display: Rc<Display>,
607+ fourcc: Fourcc,
608+ }
609+
610+ impl TestFrameGenerator {
611+ pub fn new(
612+ max_count: u64,
613+ display: Rc<Display>,
614+ pool: VaSurfacePool<()>,
615+ frame_layout: FrameLayout,
616+ ) -> Self {
617+ Self {
618+ counter: 0,
619+ max_count,
620+ fourcc: frame_layout.format.0,
621+ pool_iter: PooledFrameIterator::new(display.clone(), pool, frame_layout),
622+ display,
623+ }
624+ }
625+ }
626+
627+ impl Iterator for TestFrameGenerator {
628+ type Item = (FrameMetadata, PooledVaSurface<()>);
629+
630+ fn next(&mut self) -> Option<Self::Item> {
631+ if self.counter > self.max_count {
632+ return None;
633+ }
634+
635+ self.counter += 1;
636+
637+ let (meta, handle) = self.pool_iter.next().unwrap();
638+
639+ let surface: &Surface<()> = handle.borrow();
640+
641+ let t = get_test_frame_t(meta.timestamp, self.max_count);
642+ match self.fourcc.0 {
643+ VA_FOURCC_NV12 => upload_test_frame_nv12(&self.display, surface, t),
644+ VA_FOURCC_P010 => upload_test_frame_p010(&self.display, surface, t),
645+ _ => unreachable!(),
646+ }
647+
648+ Some((meta, handle))
649+ }
650+ }
651+}
vendor/cros-codecs/src/backend/vaapi/surface_pool.rsadded+225 -0
@@ -0,0 +1,225 @@
1+// Copyright 2023 The ChromiumOS Authors
2+// Use of this source code is governed by a BSD-style license that can be
3+// found in the LICENSE file.
4+
5+use std::borrow::Borrow;
6+use std::cell::RefCell;
7+use std::collections::BTreeMap;
8+use std::collections::VecDeque;
9+use std::rc::Rc;
10+use std::rc::Weak;
11+
12+use libva::Display;
13+use libva::Surface;
14+use libva::SurfaceMemoryDescriptor;
15+use libva::VASurfaceID;
16+
17+use crate::decoder::FramePool;
18+use crate::Resolution;
19+
20+/// A VA Surface obtained from a `[SurfacePool]`.
21+///
22+/// The surface will automatically be returned to its pool upon dropping, provided the pool still
23+/// exists and the surface is still compatible with it.
24+pub struct PooledVaSurface<M: SurfaceMemoryDescriptor> {
25+ surface: Option<Surface<M>>,
26+ pool: Weak<RefCell<VaSurfacePoolInner<M>>>,
27+}
28+
29+impl<M: SurfaceMemoryDescriptor> PooledVaSurface<M> {
30+ fn new(surface: Surface<M>, pool: &Rc<RefCell<VaSurfacePoolInner<M>>>) -> Self {
31+ Self { surface: Some(surface), pool: Rc::downgrade(pool) }
32+ }
33+
34+ /// Detach this surface from the pool. It will not be returned, and we can dispose of it
35+ /// freely.
36+ pub fn detach_from_pool(mut self) -> Surface<M> {
37+ // `unwrap` will never fail as `surface` is `Some` up to this point.
38+ let surface = self.surface.take().unwrap();
39+
40+ if let Some(pool) = self.pool.upgrade() {
41+ (*pool).borrow_mut().managed_surfaces.remove(&surface.id());
42+ }
43+
44+ surface
45+ }
46+}
47+
48+impl<M: SurfaceMemoryDescriptor> Borrow<Surface<M>> for PooledVaSurface<M> {
49+ fn borrow(&self) -> &Surface<M> {
50+ // `unwrap` will never fail as `surface` is `Some` until the object is dropped.
51+ self.surface.as_ref().unwrap()
52+ }
53+}
54+
55+impl<M: SurfaceMemoryDescriptor> AsRef<M> for PooledVaSurface<M> {
56+ fn as_ref(&self) -> &M {
57+ <Self as Borrow<Surface<M>>>::borrow(self).as_ref()
58+ }
59+}
60+
61+impl<M: SurfaceMemoryDescriptor> Drop for PooledVaSurface<M> {
62+ fn drop(&mut self) {
63+ // If the surface has not been detached...
64+ if let Some(surface) = self.surface.take() {
65+ // ... and the pool still exists...
66+ if let Some(pool) = self.pool.upgrade() {
67+ let mut pool_borrowed = (*pool).borrow_mut();
68+ // ... and the pool is still managing this surface, return it.
69+ if pool_borrowed.managed_surfaces.contains_key(&surface.id()) {
70+ pool_borrowed.surfaces.push_back(surface);
71+ return;
72+ }
73+ }
74+
75+ // The surface cannot be returned to the pool and can be gracefully dropped.
76+ log::debug!("Dropping stale surface: {}, ({:?})", surface.id(), surface.size())
77+ }
78+ }
79+}
80+
81+struct VaSurfacePoolInner<M: SurfaceMemoryDescriptor> {
82+ display: Rc<Display>,
83+ rt_format: u32,
84+ usage_hint: Option<libva::UsageHint>,
85+ coded_resolution: Resolution,
86+ surfaces: VecDeque<Surface<M>>,
87+ /// All the surfaces managed by this pool, indexed by their surface ID. We keep their
88+ /// resolution so we can remove them in case of a coded resolution change even if they
89+ /// are currently borrowed.
90+ managed_surfaces: BTreeMap<VASurfaceID, Resolution>,
91+}
92+
93+/// A surface pool to reduce the number of costly Surface allocations.
94+///
95+/// The pool only houses Surfaces that fits the pool's coded resolution.
96+/// Stale surfaces are dropped when either the pool resolution changes, or when
97+/// stale surfaces are retrieved.
98+///
99+/// This means that this pool is suitable for inter-frame DRC, as the stale
100+/// surfaces will gracefully be dropped, which is arguably better than the
101+/// alternative of having more than one pool active at a time.
102+pub struct VaSurfacePool<M: SurfaceMemoryDescriptor> {
103+ inner: Rc<RefCell<VaSurfacePoolInner<M>>>,
104+}
105+
106+impl<M: SurfaceMemoryDescriptor> VaSurfacePool<M> {
107+ /// Add a surface to the pool.
108+ ///
109+ /// This can be an entirely new surface, or one that has been previously obtained using
110+ /// `get_surface` and is returned.
111+ ///
112+ /// Returns an error (and the passed `surface` back) if the surface is not at least as
113+ /// large as the current coded resolution of the pool.
114+ #[allow(dead_code)]
115+ fn add_surface(&mut self, surface: Surface<M>) -> Result<(), Surface<M>> {
116+ let mut inner = (*self.inner).borrow_mut();
117+
118+ if Resolution::from(surface.size()).can_contain(inner.coded_resolution) {
119+ inner.managed_surfaces.insert(surface.id(), surface.size().into());
120+ inner.surfaces.push_back(surface);
121+ Ok(())
122+ } else {
123+ Err(surface)
124+ }
125+ }
126+
127+ /// Create a new pool.
128+ ///
129+ // # Arguments
130+ ///
131+ /// * `display` - the VA display to create the surfaces from.
132+ /// * `rt_format` - the VA RT format to use for the surfaces.
133+ /// * `usage_hint` - hint about how the surfaces from this pool will be used.
134+ /// * `coded_resolution` - resolution of the surfaces.
135+ pub fn new(
136+ display: Rc<Display>,
137+ rt_format: u32,
138+ usage_hint: Option<libva::UsageHint>,
139+ coded_resolution: Resolution,
140+ ) -> Self {
141+ Self {
142+ inner: Rc::new(RefCell::new(VaSurfacePoolInner {
143+ display,
144+ rt_format,
145+ usage_hint,
146+ coded_resolution,
147+ surfaces: VecDeque::new(),
148+ managed_surfaces: Default::default(),
149+ })),
150+ }
151+ }
152+
153+ /// Gets a free surface from the pool.
154+ pub fn get_surface(&mut self) -> Option<PooledVaSurface<M>> {
155+ let mut inner = (*self.inner).borrow_mut();
156+ let surface = inner.surfaces.pop_front();
157+
158+ // Make sure the invariant holds when debugging. Can save costly
159+ // debugging time during future refactors, if any.
160+ debug_assert!({
161+ match surface.as_ref() {
162+ Some(s) => Resolution::from(s.size()).can_contain(inner.coded_resolution),
163+ None => true,
164+ }
165+ });
166+
167+ surface.map(|s| PooledVaSurface::new(s, &self.inner))
168+ }
169+}
170+
171+impl<M: SurfaceMemoryDescriptor> FramePool for VaSurfacePool<M> {
172+ type Descriptor = M;
173+
174+ fn coded_resolution(&self) -> Resolution {
175+ (*self.inner).borrow().coded_resolution
176+ }
177+
178+ fn set_coded_resolution(&mut self, resolution: Resolution) {
179+ let mut inner = (*self.inner).borrow_mut();
180+
181+ inner.coded_resolution = resolution;
182+ inner.managed_surfaces.retain(|_, res| res.can_contain(resolution));
183+ inner.surfaces.retain(|s| Resolution::from(s.size()).can_contain(resolution));
184+ }
185+
186+ fn add_frames(&mut self, descriptors: Vec<Self::Descriptor>) -> Result<(), anyhow::Error> {
187+ let mut inner = (*self.inner).borrow_mut();
188+
189+ let surfaces = inner
190+ .display
191+ .create_surfaces(
192+ inner.rt_format,
193+ // Let the hardware decide the best internal format - we will get the desired fourcc
194+ // when creating the image.
195+ None,
196+ inner.coded_resolution.width,
197+ inner.coded_resolution.height,
198+ inner.usage_hint,
199+ descriptors,
200+ )
201+ .map_err(|e| anyhow::anyhow!(e))?;
202+
203+ for surface in &surfaces {
204+ inner.managed_surfaces.insert(surface.id(), surface.size().into());
205+ }
206+ inner.surfaces.extend(surfaces);
207+
208+ Ok(())
209+ }
210+
211+ fn num_free_frames(&self) -> usize {
212+ (*self.inner).borrow().surfaces.len()
213+ }
214+
215+ fn num_managed_frames(&self) -> usize {
216+ (*self.inner).borrow().managed_surfaces.len()
217+ }
218+
219+ fn clear(&mut self) {
220+ let mut pool = (*self.inner).borrow_mut();
221+
222+ pool.surfaces.clear();
223+ pool.managed_surfaces.clear();
224+ }
225+}
vendor/cros-codecs/src/bitstream_utils.rsadded+768 -0
@@ -0,0 +1,768 @@
1+// Copyright 2024 The ChromiumOS Authors
2+// Use of this source code is governed by a BSD-style license that can be
3+// found in the LICENSE file.
4+
5+use std::borrow::Cow;
6+use std::fmt;
7+use std::io::Cursor;
8+use std::io::Read;
9+use std::io::Seek;
10+use std::io::SeekFrom;
11+use std::io::Write;
12+use std::marker::PhantomData;
13+
14+use crate::codec::h264::parser::Nalu as H264Nalu;
15+use crate::codec::h265::parser::Nalu as H265Nalu;
16+
17+/// A bit reader for codec bitstreams. It properly handles emulation-prevention
18+/// bytes and stop bits for H264.
19+#[derive(Clone)]
20+pub(crate) struct BitReader<'a> {
21+ /// A reference into the next unread byte in the stream.
22+ data: Cursor<&'a [u8]>,
23+ /// Contents of the current byte. First unread bit starting at position 8 -
24+ /// num_remaining_bits_in_curr_bytes.
25+ curr_byte: u8,
26+ /// Number of bits remaining in `curr_byte`
27+ num_remaining_bits_in_curr_byte: usize,
28+ /// Used in emulation prevention byte detection.
29+ prev_two_bytes: u16,
30+ /// Number of emulation prevention bytes (i.e. 0x000003) we found.
31+ num_epb: usize,
32+ /// Whether or not we need emulation prevention logic.
33+ needs_epb: bool,
34+ /// How many bits have been read so far.
35+ position: u64,
36+}
37+
38+#[derive(Debug)]
39+pub(crate) enum GetByteError {
40+ OutOfBits,
41+}
42+
43+impl fmt::Display for GetByteError {
44+ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
45+ write!(f, "reader ran out of bits")
46+ }
47+}
48+
49+#[derive(Debug)]
50+pub(crate) enum ReadBitsError {
51+ TooManyBitsRequested(usize),
52+ GetByte(GetByteError),
53+ ConversionFailed,
54+}
55+
56+impl fmt::Display for ReadBitsError {
57+ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
58+ match self {
59+ ReadBitsError::TooManyBitsRequested(bits) => {
60+ write!(f, "more than 31 ({}) bits were requested", bits)
61+ }
62+ ReadBitsError::GetByte(_) => write!(f, "failed to advance the current byte"),
63+ ReadBitsError::ConversionFailed => {
64+ write!(f, "failed to convert read input to target type")
65+ }
66+ }
67+ }
68+}
69+
70+impl From<GetByteError> for ReadBitsError {
71+ fn from(err: GetByteError) -> Self {
72+ ReadBitsError::GetByte(err)
73+ }
74+}
75+
76+impl<'a> BitReader<'a> {
77+ pub fn new(data: &'a [u8], needs_epb: bool) -> Self {
78+ Self {
79+ data: Cursor::new(data),
80+ curr_byte: Default::default(),
81+ num_remaining_bits_in_curr_byte: Default::default(),
82+ prev_two_bytes: 0xffff,
83+ num_epb: Default::default(),
84+ needs_epb: needs_epb,
85+ position: 0,
86+ }
87+ }
88+
89+ /// Read a single bit from the stream.
90+ pub fn read_bit(&mut self) -> Result<bool, String> {
91+ let bit = self.read_bits::<u32>(1)?;
92+ match bit {
93+ 1 => Ok(true),
94+ 0 => Ok(false),
95+ _ => panic!("Unexpected value {}", bit),
96+ }
97+ }
98+
99+ /// Read up to 31 bits from the stream. Note that we don't want to read 32
100+ /// bits even though we're returning a u32 because that would break the
101+ /// read_bits_signed() function. 31 bits should be overkill for compressed
102+ /// header parsing anyway.
103+ pub fn read_bits<U: TryFrom<u32>>(&mut self, num_bits: usize) -> Result<U, String> {
104+ if num_bits > 31 {
105+ return Err(ReadBitsError::TooManyBitsRequested(num_bits).to_string());
106+ }
107+
108+ let mut bits_left = num_bits;
109+ let mut out = 0u32;
110+
111+ while self.num_remaining_bits_in_curr_byte < bits_left {
112+ out |= (self.curr_byte as u32) << (bits_left - self.num_remaining_bits_in_curr_byte);
113+ bits_left -= self.num_remaining_bits_in_curr_byte;
114+ self.move_to_next_byte().map_err(|err| err.to_string())?;
115+ }
116+
117+ out |= (self.curr_byte >> (self.num_remaining_bits_in_curr_byte - bits_left)) as u32;
118+ out &= (1 << num_bits) - 1;
119+ self.num_remaining_bits_in_curr_byte -= bits_left;
120+ self.position += num_bits as u64;
121+
122+ U::try_from(out).map_err(|_| ReadBitsError::ConversionFailed.to_string())
123+ }
124+
125+ /// Reads a two's complement signed integer of length |num_bits|.
126+ pub fn read_bits_signed<U: TryFrom<i32>>(&mut self, num_bits: usize) -> Result<U, String> {
127+ let mut out: i32 = self
128+ .read_bits::<u32>(num_bits)?
129+ .try_into()
130+ .map_err(|_| ReadBitsError::ConversionFailed.to_string())?;
131+ if out >> (num_bits - 1) != 0 {
132+ out |= -1i32 ^ ((1 << num_bits) - 1);
133+ }
134+
135+ U::try_from(out).map_err(|_| ReadBitsError::ConversionFailed.to_string())
136+ }
137+
138+ /// Reads an unsigned integer from the stream and checks if the stream is byte aligned.
139+ pub fn read_bits_aligned<U: TryFrom<u32>>(&mut self, num_bits: usize) -> Result<U, String> {
140+ if self.num_remaining_bits_in_curr_byte % 8 != 0 {
141+ return Err("Attempted unaligned read_le()".into());
142+ }
143+
144+ Ok(self.read_bits(num_bits).map_err(|err| err.to_string())?)
145+ }
146+
147+ /// Skip `num_bits` bits from the stream.
148+ pub fn skip_bits(&mut self, mut num_bits: usize) -> Result<(), String> {
149+ while num_bits > 0 {
150+ let n = std::cmp::min(num_bits, 31);
151+ self.read_bits::<u32>(n)?;
152+ num_bits -= n;
153+ }
154+
155+ Ok(())
156+ }
157+
158+ /// Returns the amount of bits left in the stream
159+ pub fn num_bits_left(&mut self) -> usize {
160+ let cur_pos = self.data.position();
161+ // This should always be safe to unwrap.
162+ let end_pos = self.data.seek(SeekFrom::End(0)).unwrap();
163+ let _ = self.data.seek(SeekFrom::Start(cur_pos));
164+ ((end_pos - cur_pos) as usize) * 8 + self.num_remaining_bits_in_curr_byte
165+ }
166+
167+ /// Returns the number of emulation-prevention bytes read so far.
168+ pub fn num_epb(&self) -> usize {
169+ self.num_epb
170+ }
171+
172+ /// Whether the stream still has RBSP data. Implements more_rbsp_data(). See
173+ /// the spec for more details.
174+ pub fn has_more_rsbp_data(&mut self) -> bool {
175+ if self.num_remaining_bits_in_curr_byte == 0 && self.move_to_next_byte().is_err() {
176+ // no more data at all in the rbsp
177+ return false;
178+ }
179+
180+ // If the next bit is the stop bit, then we should only see unset bits
181+ // until the end of the data.
182+ if (self.curr_byte & ((1 << (self.num_remaining_bits_in_curr_byte - 1)) - 1)) != 0 {
183+ return true;
184+ }
185+
186+ let mut buf = [0u8; 1];
187+ let orig_pos = self.data.position();
188+ while let Ok(_) = self.data.read_exact(&mut buf) {
189+ if buf[0] != 0 {
190+ self.data.set_position(orig_pos);
191+ return true;
192+ }
193+ }
194+ false
195+ }
196+
197+ /// Reads an Unsigned Exponential golomb coding number from the next bytes in the
198+ /// bitstream. This may advance the state of position within the bitstream even if the
199+ /// read operation is unsuccessful. See H264 Annex B specification 9.1 for details.
200+ pub fn read_ue<U: TryFrom<u32>>(&mut self) -> Result<U, String> {
201+ let mut num_bits = 0;
202+
203+ while self.read_bits::<u32>(1)? == 0 {
204+ num_bits += 1;
205+ if num_bits > 31 {
206+ return Err("invalid stream".into());
207+ }
208+ }
209+
210+ let value = ((1u32 << num_bits) - 1)
211+ .checked_add(self.read_bits::<u32>(num_bits)?)
212+ .ok_or::<String>("read number cannot fit in 32 bits".into())?;
213+
214+ U::try_from(value).map_err(|_| "conversion error".into())
215+ }
216+
217+ pub fn read_ue_bounded<U: TryFrom<u32>>(&mut self, min: u32, max: u32) -> Result<U, String> {
218+ let ue = self.read_ue()?;
219+ if ue > max || ue < min {
220+ Err(format!("Value out of bounds: expected {} - {}, got {}", min, max, ue))
221+ } else {
222+ Ok(U::try_from(ue).map_err(|_| String::from("Conversion error"))?)
223+ }
224+ }
225+
226+ pub fn read_ue_max<U: TryFrom<u32>>(&mut self, max: u32) -> Result<U, String> {
227+ self.read_ue_bounded(0, max)
228+ }
229+
230+ /// Reads a signed exponential golomb coding number. Instead of using two's
231+ /// complement, this scheme maps even integers to positive numbers and odd
232+ /// integers to negative numbers. The least significant bit indicates the
233+ /// sign. See H264 Annex B specification 9.1.1 for details.
234+ pub fn read_se<U: TryFrom<i32>>(&mut self) -> Result<U, String> {
235+ let ue = self.read_ue::<u32>()? as i32;
236+
237+ if ue % 2 == 0 {
238+ Ok(U::try_from(-(ue / 2)).map_err(|_| String::from("Conversion error"))?)
239+ } else {
240+ Ok(U::try_from(ue / 2 + 1).map_err(|_| String::from("Conversion error"))?)
241+ }
242+ }
243+
244+ pub fn read_se_bounded<U: TryFrom<i32>>(&mut self, min: i32, max: i32) -> Result<U, String> {
245+ let se = self.read_se()?;
246+ if se < min || se > max {
247+ Err(format!("Value out of bounds, expected between {}-{}, got {}", min, max, se))
248+ } else {
249+ Ok(U::try_from(se).map_err(|_| String::from("Conversion error"))?)
250+ }
251+ }
252+
253+ /// Read little endian multi-byte integer.
254+ pub fn read_le<U: TryFrom<u32>>(&mut self, num_bits: u8) -> Result<U, String> {
255+ let mut t = 0;
256+
257+ for i in 0..num_bits {
258+ let byte = self.read_bits_aligned::<u32>(8)?;
259+ t += byte << (i * 8)
260+ }
261+
262+ Ok(U::try_from(t).map_err(|_| String::from("Conversion error"))?)
263+ }
264+
265+ /// Return the position of this bitstream in bits.
266+ pub fn position(&self) -> u64 {
267+ self.position
268+ }
269+
270+ fn get_byte(&mut self) -> Result<u8, GetByteError> {
271+ let mut buf = [0u8; 1];
272+ self.data.read_exact(&mut buf).map_err(|_| GetByteError::OutOfBits)?;
273+ Ok(buf[0])
274+ }
275+
276+ fn move_to_next_byte(&mut self) -> Result<(), GetByteError> {
277+ let mut byte = self.get_byte()?;
278+
279+ if self.needs_epb {
280+ if self.prev_two_bytes == 0 && byte == 0x03 {
281+ // We found an epb
282+ self.num_epb += 1;
283+ // Read another byte
284+ byte = self.get_byte()?;
285+ // We need another 3 bytes before another epb can happen.
286+ self.prev_two_bytes = 0xffff;
287+ }
288+ self.prev_two_bytes = (self.prev_two_bytes << 8) | u16::from(byte);
289+ }
290+
291+ self.num_remaining_bits_in_curr_byte = 8;
292+ self.curr_byte = byte;
293+ Ok(())
294+ }
295+}
296+
297+/// Iterator over IVF packets.
298+pub struct IvfIterator<'a> {
299+ cursor: Cursor<&'a [u8]>,
300+}
301+
302+impl<'a> IvfIterator<'a> {
303+ pub fn new(data: &'a [u8]) -> Self {
304+ let mut cursor = Cursor::new(data);
305+
306+ // Skip the IVH header entirely.
307+ cursor.seek(std::io::SeekFrom::Start(32)).unwrap();
308+
309+ Self { cursor }
310+ }
311+}
312+
313+impl<'a> Iterator for IvfIterator<'a> {
314+ type Item = &'a [u8];
315+
316+ fn next(&mut self) -> Option<Self::Item> {
317+ // Make sure we have a header.
318+ let mut len_buf = [0u8; 4];
319+ self.cursor.read_exact(&mut len_buf).ok()?;
320+ let len = ((len_buf[3] as usize) << 24)
321+ | ((len_buf[2] as usize) << 16)
322+ | ((len_buf[1] as usize) << 8)
323+ | (len_buf[0] as usize);
324+
325+ // Skip PTS.
326+ self.cursor.seek(std::io::SeekFrom::Current(8)).ok()?;
327+
328+ let start = self.cursor.position() as usize;
329+ let _ = self.cursor.seek(std::io::SeekFrom::Current(len as i64)).ok()?;
330+ let end = self.cursor.position() as usize;
331+
332+ Some(&self.cursor.get_ref()[start..end])
333+ }
334+}
335+
336+/// Helper struct for synthesizing IVF file header
337+pub struct IvfFileHeader {
338+ pub magic: [u8; 4],
339+ pub version: u16,
340+ pub header_size: u16,
341+ pub codec: [u8; 4],
342+ pub width: u16,
343+ pub height: u16,
344+ pub framerate: u32,
345+ pub timescale: u32,
346+ pub frame_count: u32,
347+ pub unused: u32,
348+}
349+
350+impl Default for IvfFileHeader {
351+ fn default() -> Self {
352+ Self {
353+ magic: Self::MAGIC,
354+ version: 0,
355+ header_size: 32,
356+ codec: Self::CODEC_VP9,
357+ width: 320,
358+ height: 240,
359+ framerate: 1,
360+ timescale: 1000,
361+ frame_count: 1,
362+ unused: Default::default(),
363+ }
364+ }
365+}
366+
367+impl IvfFileHeader {
368+ pub const MAGIC: [u8; 4] = *b"DKIF";
369+ pub const CODEC_VP8: [u8; 4] = *b"VP80";
370+ pub const CODEC_VP9: [u8; 4] = *b"VP90";
371+ pub const CODEC_AV1: [u8; 4] = *b"AV01";
372+
373+ pub fn new(codec: [u8; 4], width: u16, height: u16, framerate: u32, frame_count: u32) -> Self {
374+ let default = Self::default();
375+
376+ Self {
377+ codec,
378+ width,
379+ height,
380+ framerate: framerate * default.timescale,
381+ frame_count,
382+ ..default
383+ }
384+ }
385+}
386+
387+impl IvfFileHeader {
388+ /// Writes header into writer
389+ pub fn writo_into(&self, writer: &mut impl std::io::Write) -> std::io::Result<()> {
390+ writer.write_all(&self.magic)?;
391+ writer.write_all(&self.version.to_le_bytes())?;
392+ writer.write_all(&self.header_size.to_le_bytes())?;
393+ writer.write_all(&self.codec)?;
394+ writer.write_all(&self.width.to_le_bytes())?;
395+ writer.write_all(&self.height.to_le_bytes())?;
396+ writer.write_all(&self.framerate.to_le_bytes())?;
397+ writer.write_all(&self.timescale.to_le_bytes())?;
398+ writer.write_all(&self.frame_count.to_le_bytes())?;
399+ writer.write_all(&self.unused.to_le_bytes())?;
400+
401+ Ok(())
402+ }
403+}
404+
405+/// Helper struct for synthesizing IVF frame header
406+pub struct IvfFrameHeader {
407+ pub frame_size: u32,
408+ pub timestamp: u64,
409+}
410+
411+impl IvfFrameHeader {
412+ /// Writes header into writer
413+ pub fn writo_into(&self, writer: &mut impl std::io::Write) -> std::io::Result<()> {
414+ writer.write_all(&self.frame_size.to_le_bytes())?;
415+ writer.write_all(&self.timestamp.to_le_bytes())?;
416+ Ok(())
417+ }
418+}
419+
420+/// Iterator NALUs in a bitstream.
421+pub struct NalIterator<'a, Nalu>(Cursor<&'a [u8]>, PhantomData<Nalu>);
422+
423+impl<'a, Nalu> NalIterator<'a, Nalu> {
424+ pub fn new(stream: &'a [u8]) -> Self {
425+ Self(Cursor::new(stream), PhantomData)
426+ }
427+}
428+
429+impl<'a> Iterator for NalIterator<'a, H264Nalu<'a>> {
430+ type Item = Cow<'a, [u8]>;
431+
432+ fn next(&mut self) -> Option<Self::Item> {
433+ H264Nalu::next(&mut self.0).map(|n| n.data).ok()
434+ }
435+}
436+
437+impl<'a> Iterator for NalIterator<'a, H265Nalu<'a>> {
438+ type Item = Cow<'a, [u8]>;
439+
440+ fn next(&mut self) -> Option<Self::Item> {
441+ H265Nalu::next(&mut self.0).map(|n| n.data).ok()
442+ }
443+}
444+
445+#[derive(Debug)]
446+pub enum BitWriterError {
447+ InvalidBitCount,
448+ Io(std::io::Error),
449+}
450+
451+impl fmt::Display for BitWriterError {
452+ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
453+ match self {
454+ BitWriterError::InvalidBitCount => write!(f, "invalid bit count"),
455+ BitWriterError::Io(x) => write!(f, "{}", x.to_string()),
456+ }
457+ }
458+}
459+
460+impl From<std::io::Error> for BitWriterError {
461+ fn from(err: std::io::Error) -> Self {
462+ BitWriterError::Io(err)
463+ }
464+}
465+
466+pub type BitWriterResult<T> = std::result::Result<T, BitWriterError>;
467+
468+pub struct BitWriter<W: Write> {
469+ out: W,
470+ nth_bit: u8,
471+ curr_byte: u8,
472+}
473+
474+impl<W: Write> BitWriter<W> {
475+ pub fn new(writer: W) -> Self {
476+ Self { out: writer, curr_byte: 0, nth_bit: 0 }
477+ }
478+
479+ /// Writes fixed bit size integer (up to 32 bit)
480+ pub fn write_f<T: Into<u32>>(&mut self, bits: usize, value: T) -> BitWriterResult<usize> {
481+ let value = value.into();
482+
483+ if bits > 32 {
484+ return Err(BitWriterError::InvalidBitCount);
485+ }
486+
487+ let mut written = 0;
488+ for bit in (0..bits).rev() {
489+ let bit = (1 << bit) as u32;
490+
491+ self.write_bit((value & bit) == bit)?;
492+ written += 1;
493+ }
494+
495+ Ok(written)
496+ }
497+
498+ /// Takes a single bit that will be outputed to [`std::io::Write`]
499+ pub fn write_bit(&mut self, bit: bool) -> BitWriterResult<()> {
500+ self.curr_byte |= (bit as u8) << (7u8 - self.nth_bit);
501+ self.nth_bit += 1;
502+
503+ if self.nth_bit == 8 {
504+ self.out.write_all(&[self.curr_byte])?;
505+ self.nth_bit = 0;
506+ self.curr_byte = 0;
507+ }
508+
509+ Ok(())
510+ }
511+
512+ /// Immediately outputs any cached bits to [`std::io::Write`]
513+ pub fn flush(&mut self) -> BitWriterResult<()> {
514+ if self.nth_bit != 0 {
515+ self.out.write_all(&[self.curr_byte])?;
516+ self.nth_bit = 0;
517+ self.curr_byte = 0;
518+ }
519+
520+ self.out.flush()?;
521+ Ok(())
522+ }
523+
524+ /// Returns `true` if ['Self`] hold data that wasn't written to [`std::io::Write`]
525+ pub fn has_data_pending(&self) -> bool {
526+ self.nth_bit != 0
527+ }
528+
529+ pub(crate) fn inner(&self) -> &W {
530+ &self.out
531+ }
532+
533+ pub(crate) fn inner_mut(&mut self) -> &mut W {
534+ &mut self.out
535+ }
536+}
537+
538+impl<W: Write> Drop for BitWriter<W> {
539+ fn drop(&mut self) {
540+ if let Err(e) = self.flush() {
541+ log::error!("Unable to flush bits {e:?}");
542+ }
543+ }
544+}
545+
546+#[cfg(test)]
547+mod tests {
548+ use super::*;
549+
550+ #[test]
551+ fn test_ivf_file_header() {
552+ let mut hdr = IvfFileHeader {
553+ version: 0,
554+ codec: IvfFileHeader::CODEC_VP9,
555+ width: 256,
556+ height: 256,
557+ framerate: 30_000,
558+ timescale: 1_000,
559+ frame_count: 1,
560+
561+ ..Default::default()
562+ };
563+
564+ let mut buf = Vec::new();
565+ hdr.writo_into(&mut buf).unwrap();
566+
567+ const EXPECTED: [u8; 32] = [
568+ 0x44, 0x4b, 0x49, 0x46, 0x00, 0x00, 0x20, 0x00, 0x56, 0x50, 0x39, 0x30, 0x00, 0x01,
569+ 0x00, 0x01, 0x30, 0x75, 0x00, 0x00, 0xe8, 0x03, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00,
570+ 0x00, 0x00, 0x00, 0x00,
571+ ];
572+
573+ assert_eq!(&buf, &EXPECTED);
574+
575+ hdr.width = 1920;
576+ hdr.height = 800;
577+ hdr.framerate = 24;
578+ hdr.timescale = 1;
579+ hdr.frame_count = 100;
580+
581+ buf.clear();
582+ hdr.writo_into(&mut buf).unwrap();
583+
584+ const EXPECTED2: [u8; 32] = [
585+ 0x44, 0x4b, 0x49, 0x46, 0x00, 0x00, 0x20, 0x00, 0x56, 0x50, 0x39, 0x30, 0x80, 0x07,
586+ 0x20, 0x03, 0x18, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x64, 0x00, 0x00, 0x00,
587+ 0x00, 0x00, 0x00, 0x00,
588+ ];
589+
590+ assert_eq!(&buf, &EXPECTED2);
591+ }
592+
593+ #[test]
594+ fn test_ivf_frame_header() {
595+ let mut hdr = IvfFrameHeader { frame_size: 199249, timestamp: 0 };
596+
597+ let mut buf = Vec::new();
598+ hdr.writo_into(&mut buf).unwrap();
599+
600+ const EXPECTED: [u8; 12] =
601+ [0x51, 0x0a, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00];
602+
603+ assert_eq!(&buf, &EXPECTED);
604+
605+ hdr.timestamp = 1;
606+ hdr.frame_size = 52;
607+
608+ buf.clear();
609+ hdr.writo_into(&mut buf).unwrap();
610+
611+ const EXPECTED2: [u8; 12] =
612+ [0x34, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00];
613+
614+ assert_eq!(&buf, &EXPECTED2);
615+ }
616+
617+ #[test]
618+ fn test_bitwriter_f1() {
619+ let mut buf = Vec::<u8>::new();
620+ {
621+ let mut writer = BitWriter::new(&mut buf);
622+ writer.write_f(1, true).unwrap();
623+ writer.write_f(1, false).unwrap();
624+ writer.write_f(1, false).unwrap();
625+ writer.write_f(1, false).unwrap();
626+ writer.write_f(1, true).unwrap();
627+ writer.write_f(1, true).unwrap();
628+ writer.write_f(1, true).unwrap();
629+ writer.write_f(1, true).unwrap();
630+ }
631+ assert_eq!(buf, vec![0b10001111u8]);
632+ }
633+
634+ #[test]
635+ fn test_bitwriter_f3() {
636+ let mut buf = Vec::<u8>::new();
637+ {
638+ let mut writer = BitWriter::new(&mut buf);
639+ writer.write_f(3, 0b100u8).unwrap();
640+ writer.write_f(3, 0b101u8).unwrap();
641+ writer.write_f(3, 0b011u8).unwrap();
642+ }
643+ assert_eq!(buf, vec![0b10010101u8, 0b10000000u8]);
644+ }
645+
646+ #[test]
647+ fn test_bitwriter_f4() {
648+ let mut buf = Vec::<u8>::new();
649+ {
650+ let mut writer = BitWriter::new(&mut buf);
651+ writer.write_f(4, 0b1000u8).unwrap();
652+ writer.write_f(4, 0b1011u8).unwrap();
653+ }
654+ assert_eq!(buf, vec![0b10001011u8]);
655+ }
656+
657+ // These tests are adapted from the chromium tests at media/video/h264_bit_reader_unitttest.cc
658+
659+ #[test]
660+ fn read_stream_without_escape_and_trailing_zero_bytes() {
661+ const RBSP: [u8; 6] = [0x01, 0x23, 0x45, 0x67, 0x89, 0xa0];
662+
663+ let mut reader = BitReader::new(&RBSP, true);
664+ assert_eq!(reader.read_bits::<u32>(1).unwrap(), 0);
665+ assert_eq!(reader.num_bits_left(), 47);
666+ assert!(reader.has_more_rsbp_data());
667+
668+ assert_eq!(reader.read_bits::<u32>(8).unwrap(), 0x02);
669+ assert_eq!(reader.num_bits_left(), 39);
670+ assert!(reader.has_more_rsbp_data());
671+
672+ assert_eq!(reader.read_bits::<u32>(31).unwrap(), 0x23456789);
673+ assert_eq!(reader.num_bits_left(), 8);
674+ assert!(reader.has_more_rsbp_data());
675+
676+ assert_eq!(reader.read_bits::<u32>(1).unwrap(), 1);
677+ assert_eq!(reader.num_bits_left(), 7);
678+ assert!(reader.has_more_rsbp_data());
679+
680+ assert_eq!(reader.read_bits::<u32>(1).unwrap(), 0);
681+ assert_eq!(reader.num_bits_left(), 6);
682+ assert!(!reader.has_more_rsbp_data());
683+ }
684+
685+ #[test]
686+ fn single_byte_stream() {
687+ const RBSP: [u8; 1] = [0x18];
688+
689+ let mut reader = BitReader::new(&RBSP, true);
690+ assert_eq!(reader.num_bits_left(), 8);
691+ assert!(reader.has_more_rsbp_data());
692+ assert_eq!(reader.read_bits::<u32>(4).unwrap(), 1);
693+ assert!(!reader.has_more_rsbp_data());
694+ }
695+
696+ #[test]
697+ fn stop_bit_occupy_full_byte() {
698+ const RBSP: [u8; 2] = [0xab, 0x80];
699+
700+ let mut reader = BitReader::new(&RBSP, true);
701+ assert_eq!(reader.num_bits_left(), 16);
702+ assert!(reader.has_more_rsbp_data());
703+
704+ assert_eq!(reader.read_bits::<u32>(8).unwrap(), 0xab);
705+ assert_eq!(reader.num_bits_left(), 8);
706+
707+ assert!(!reader.has_more_rsbp_data());
708+ }
709+
710+ // Check that read_ue behaves properly with input at the limits.
711+ #[test]
712+ fn read_ue() {
713+ // Regular value.
714+ let mut reader = BitReader::new(&[0b0001_1010], true);
715+ assert_eq!(reader.read_ue::<u32>().unwrap(), 12);
716+ assert_eq!(reader.data.position(), 1);
717+ assert_eq!(reader.num_remaining_bits_in_curr_byte, 1);
718+
719+ // 0 value.
720+ let mut reader = BitReader::new(&[0b1000_0000], true);
721+ assert_eq!(reader.read_ue::<u32>().unwrap(), 0);
722+ assert_eq!(reader.data.position(), 1);
723+ assert_eq!(reader.num_remaining_bits_in_curr_byte, 7);
724+
725+ // No prefix stop bit.
726+ let mut reader = BitReader::new(&[0b0000_0000], true);
727+ reader.read_ue::<u32>().unwrap_err();
728+
729+ // u32 max value: 31 0-bits, 1 bit marker, 31 bits 1-bits.
730+ let mut reader = BitReader::new(
731+ &[
732+ 0b0000_0000,
733+ 0b0000_0000,
734+ 0b0000_0000,
735+ 0b0000_0001,
736+ 0b1111_1111,
737+ 0b1111_1111,
738+ 0b1111_1111,
739+ 0b1111_1110,
740+ ],
741+ true,
742+ );
743+ assert_eq!(reader.read_ue::<u32>().unwrap(), 0xffff_fffe);
744+ assert_eq!(reader.data.position(), 8);
745+ assert_eq!(reader.num_remaining_bits_in_curr_byte, 1);
746+ }
747+
748+ // Check that emulation prevention is being handled correctly.
749+ #[test]
750+ fn skip_epb_when_enabled() {
751+ let mut reader = BitReader::new(&[0x00, 0x00, 0x03, 0x01], false);
752+ assert_eq!(reader.read_bits::<u32>(8).unwrap(), 0x00);
753+ assert_eq!(reader.read_bits::<u32>(8).unwrap(), 0x00);
754+ assert_eq!(reader.read_bits::<u32>(8).unwrap(), 0x03);
755+ assert_eq!(reader.read_bits::<u32>(8).unwrap(), 0x01);
756+
757+ let mut reader = BitReader::new(&[0x00, 0x00, 0x03, 0x01], true);
758+ assert_eq!(reader.read_bits::<u32>(8).unwrap(), 0x00);
759+ assert_eq!(reader.read_bits::<u32>(8).unwrap(), 0x00);
760+ assert_eq!(reader.read_bits::<u32>(8).unwrap(), 0x01);
761+ }
762+
763+ #[test]
764+ fn read_signed_bits() {
765+ let mut reader = BitReader::new(&[0b1111_0000], false);
766+ assert_eq!(reader.read_bits_signed::<i32>(4).unwrap(), -1);
767+ }
768+}
vendor/cros-codecs/src/c2_wrapper.rsadded+381 -0
@@ -0,0 +1,381 @@
1+// Copyright 2024 The ChromiumOS Authors
2+// Use of this source code is governed by a BSD-style license that can be
3+// found in the LICENSE file.
4+
5+use nix::errno::Errno;
6+use nix::sys::eventfd::EfdFlags;
7+use nix::sys::eventfd::EventFd;
8+
9+use thiserror::Error;
10+
11+use std::collections::VecDeque;
12+use std::marker::PhantomData;
13+use std::sync::atomic::AtomicU32;
14+use std::sync::Arc;
15+use std::sync::Mutex;
16+use std::thread;
17+use std::thread::JoinHandle;
18+use std::vec::Vec;
19+
20+use crate::decoder::StreamInfo;
21+use crate::video_frame::VideoFrame;
22+use crate::Fourcc;
23+
24+pub mod c2_decoder;
25+pub mod c2_encoder;
26+#[cfg(feature = "v4l2")]
27+pub mod c2_v4l2_decoder;
28+#[cfg(feature = "v4l2")]
29+pub mod c2_v4l2_encoder;
30+#[cfg(feature = "vaapi")]
31+pub mod c2_vaapi_decoder;
32+#[cfg(feature = "vaapi")]
33+pub mod c2_vaapi_encoder;
34+
35+#[derive(Debug, Default, PartialEq, Eq, Copy, Clone)]
36+pub enum DrainMode {
37+ // Not draining
38+ #[default]
39+ NoDrain = -1,
40+ // Drain the C2 component and signal an EOS. Currently we also change the state to stop.
41+ EOSDrain = 0,
42+ // Drain the C2 component, but keep accepting new jobs in the queue immediately after.
43+ NoEOSDrain = 1,
44+}
45+
46+#[derive(Debug)]
47+pub struct C2DecodeJob<V: VideoFrame> {
48+ // Compressed input data
49+ // TODO: Use VideoFrame for input too
50+ pub input: Vec<u8>,
51+ // Decompressed output frame. Note that this needs to be reference counted because we may still
52+ // use this frame as a reference frame even while we're displaying it.
53+ pub output: Option<Arc<V>>,
54+ pub drain: DrainMode,
55+ // TODO: Add output delay and color aspect support as needed.
56+}
57+
58+impl<V> Job for C2DecodeJob<V>
59+where
60+ V: VideoFrame,
61+{
62+ type Frame = V;
63+
64+ fn set_drain(&mut self, drain: DrainMode) {
65+ self.drain = drain;
66+ }
67+
68+ fn get_drain(&self) -> DrainMode {
69+ self.drain
70+ }
71+}
72+
73+impl<V: VideoFrame> Default for C2DecodeJob<V> {
74+ fn default() -> Self {
75+ Self { input: vec![], output: None, drain: DrainMode::NoDrain }
76+ }
77+}
78+
79+pub trait Job: Send + 'static {
80+ type Frame: VideoFrame;
81+
82+ fn set_drain(&mut self, drain: DrainMode) -> ();
83+ fn get_drain(&self) -> DrainMode;
84+}
85+
86+#[derive(Debug)]
87+pub struct C2EncodeJob<V: VideoFrame> {
88+ pub input: Option<V>,
89+ // TODO: Use VideoFrame for output too
90+ pub output: Vec<u8>,
91+ // In microseconds.
92+ pub timestamp: u64,
93+ // TODO: only support CBR right now, follow up with VBR support.
94+ pub bitrate: u64,
95+ // Framerate is actually negotiated, so the encoder can change this value
96+ // based on the timestamps of the frames it receives.
97+ pub framerate: Arc<AtomicU32>,
98+ pub drain: DrainMode,
99+}
100+
101+impl<V: VideoFrame> Default for C2EncodeJob<V> {
102+ fn default() -> Self {
103+ Self {
104+ input: None,
105+ output: vec![],
106+ timestamp: 0,
107+ bitrate: 0,
108+ framerate: Arc::new(AtomicU32::new(0)),
109+ drain: DrainMode::NoDrain,
110+ }
111+ }
112+}
113+
114+impl<V> Job for C2EncodeJob<V>
115+where
116+ V: VideoFrame,
117+{
118+ type Frame = V;
119+
120+ fn set_drain(&mut self, drain: DrainMode) {
121+ self.drain = drain;
122+ }
123+
124+ fn get_drain(&self) -> DrainMode {
125+ self.drain
126+ }
127+}
128+
129+#[derive(Debug, PartialEq, Eq, Copy, Clone)]
130+pub enum C2State {
131+ C2Running,
132+ C2Stopped,
133+ // Note that on state C2Error, stop() must be called before we can start()
134+ // again.
135+ C2Error,
136+}
137+
138+// This is not a very "Rust-y" way of doing error handling, but it will
139+// hopefully make the FFI easier to write. Numerical values taken from
140+// frameworks/av/media/codec2/core/include/C2.h
141+// TODO: Improve error handling by adding more statuses.
142+#[derive(Debug, PartialEq, Eq, Copy, Clone)]
143+pub enum C2Status {
144+ C2Ok = 0,
145+ C2BadState = 1, // EPERM
146+ C2BadValue = 22, // EINVAL
147+}
148+
149+// J should be either C2DecodeJob or C2EncodeJob.
150+pub trait C2Worker<J>
151+where
152+ J: Send + Job + 'static,
153+{
154+ type Options: Clone + Send + 'static;
155+
156+ fn new(
157+ input_fourcc: Fourcc,
158+ output_fourcc: Fourcc,
159+ awaiting_job_event: Arc<EventFd>,
160+ error_cb: Arc<Mutex<dyn FnMut(C2Status) + Send + 'static>>,
161+ work_done_cb: Arc<Mutex<dyn FnMut(J) + Send + 'static>>,
162+ work_queue: Arc<Mutex<VecDeque<J>>>,
163+ state: Arc<Mutex<C2State>>,
164+ framepool_hint_cb: Arc<Mutex<dyn FnMut(StreamInfo) + Send + 'static>>,
165+ alloc_cb: Arc<Mutex<dyn FnMut() -> Option<<J as Job>::Frame> + Send + 'static>>,
166+ options: Self::Options,
167+ ) -> Result<Self, String>
168+ where
169+ Self: Sized;
170+
171+ fn process_loop(&mut self);
172+}
173+
174+#[derive(Debug, Error)]
175+pub enum C2WrapperError {
176+ #[error("failed to create EventFd for awaiting job event: {0}")]
177+ AwaitingJobEventFd(Errno),
178+}
179+
180+// Note that we do not guarantee thread safety in C2CrosCodecsWrapper.
181+pub struct C2Wrapper<J, W>
182+where
183+ J: Send + Default + Job + 'static,
184+ W: C2Worker<J>,
185+{
186+ awaiting_job_event: Arc<EventFd>,
187+ input_fourcc: Fourcc,
188+ output_fourcc: Fourcc,
189+ error_cb: Arc<Mutex<dyn FnMut(C2Status) + Send + 'static>>,
190+ work_done_cb: Arc<Mutex<dyn FnMut(J) + Send + 'static>>,
191+ work_queue: Arc<Mutex<VecDeque<J>>>,
192+ state: Arc<Mutex<C2State>>,
193+ framepool_hint_cb: Arc<Mutex<dyn FnMut(StreamInfo) + Send + 'static>>,
194+ alloc_cb: Arc<Mutex<dyn FnMut() -> Option<<J as Job>::Frame> + Send + 'static>>,
195+ options: <W as C2Worker<J>>::Options,
196+ worker_thread: Option<JoinHandle<()>>,
197+ // The instance of V actually lives in the thread creation closure, not
198+ // this struct.
199+ _phantom: PhantomData<W>,
200+}
201+
202+impl<J, W> C2Wrapper<J, W>
203+where
204+ J: Send + Default + Job + 'static,
205+ W: C2Worker<J>,
206+{
207+ pub fn new(
208+ input_fourcc: Fourcc,
209+ output_fourcc: Fourcc,
210+ error_cb: impl FnMut(C2Status) + Send + 'static,
211+ work_done_cb: impl FnMut(J) + Send + 'static,
212+ framepool_hint_cb: impl FnMut(StreamInfo) + Send + 'static,
213+ alloc_cb: impl FnMut() -> Option<<J as Job>::Frame> + Send + 'static,
214+ options: <W as C2Worker<J>>::Options,
215+ ) -> Self {
216+ Self {
217+ awaiting_job_event: Arc::new(
218+ EventFd::from_flags(EfdFlags::EFD_SEMAPHORE)
219+ .map_err(C2WrapperError::AwaitingJobEventFd)
220+ .unwrap(),
221+ ),
222+ input_fourcc: input_fourcc,
223+ output_fourcc: output_fourcc,
224+ error_cb: Arc::new(Mutex::new(error_cb)),
225+ work_done_cb: Arc::new(Mutex::new(work_done_cb)),
226+ work_queue: Arc::new(Mutex::new(VecDeque::new())),
227+ state: Arc::new(Mutex::new(C2State::C2Stopped)),
228+ framepool_hint_cb: Arc::new(Mutex::new(framepool_hint_cb)),
229+ alloc_cb: Arc::new(Mutex::new(alloc_cb)),
230+ options: options,
231+ worker_thread: None,
232+ _phantom: Default::default(),
233+ }
234+ }
235+
236+ // This isn't part of C2, but it's convenient to check if our worker thread
237+ // is still running.
238+ pub fn is_alive(&self) -> bool {
239+ match &self.worker_thread {
240+ Some(worker_thread) => !worker_thread.is_finished(),
241+ None => false,
242+ }
243+ }
244+
245+ // Start the decoder/encoder.
246+ // State will be C2Running after this call.
247+ pub fn start(&mut self) -> C2Status {
248+ {
249+ let mut state = self.state.lock().unwrap();
250+ if *state != C2State::C2Stopped {
251+ (*self.error_cb.lock().unwrap())(C2Status::C2BadState);
252+ return C2Status::C2BadState;
253+ }
254+ *state = C2State::C2Running;
255+ }
256+
257+ let input_fourcc = self.input_fourcc.clone();
258+ let output_fourcc = self.output_fourcc.clone();
259+ let error_cb = self.error_cb.clone();
260+ let work_done_cb = self.work_done_cb.clone();
261+ let work_queue = self.work_queue.clone();
262+ let state = self.state.clone();
263+ let options = self.options.clone();
264+ let awaiting_job_event = self.awaiting_job_event.clone();
265+ let framepool_hint_cb = self.framepool_hint_cb.clone();
266+ let alloc_cb = self.alloc_cb.clone();
267+ self.worker_thread = Some(thread::spawn(move || {
268+ let worker = W::new(
269+ input_fourcc,
270+ output_fourcc,
271+ awaiting_job_event,
272+ error_cb.clone(),
273+ work_done_cb,
274+ work_queue,
275+ state.clone(),
276+ framepool_hint_cb,
277+ alloc_cb,
278+ options,
279+ );
280+ match worker {
281+ Ok(mut worker) => worker.process_loop(),
282+ Err(msg) => {
283+ log::debug!("Error instantiating C2Worker {}", msg);
284+ *state.lock().unwrap() = C2State::C2Error;
285+ (*error_cb.lock().unwrap())(C2Status::C2BadValue);
286+ }
287+ };
288+ }));
289+
290+ C2Status::C2Ok
291+ }
292+
293+ // Stop the decoder/encoder and abandon in-flight work.
294+ // C2's reset() function is equivalent for our purposes.
295+ // Note that in event of error, stop() must be called before we can start()
296+ // again. This is to ensure we clear out the work queue.
297+ // State will be C2Stopped after this call.
298+ pub fn stop(&mut self) -> C2Status {
299+ *self.state.lock().unwrap() = C2State::C2Stopped;
300+ let mut worker_thread: Option<JoinHandle<()>> = None;
301+ std::mem::swap(&mut worker_thread, &mut self.worker_thread);
302+ self.worker_thread = match worker_thread {
303+ Some(worker_thread) => {
304+ let _ = worker_thread.join();
305+ None
306+ }
307+ None => None,
308+ };
309+
310+ self.work_queue.lock().unwrap().drain(..);
311+
312+ self.awaiting_job_event.write(1).unwrap();
313+
314+ C2Status::C2Ok
315+ }
316+
317+ // Add work to the work queue.
318+ // State must be C2Running or this function is invalid.
319+ // State will remain C2Running.
320+ pub fn queue(&mut self, work_items: Vec<J>) -> C2Status {
321+ if *self.state.lock().unwrap() != C2State::C2Running {
322+ (*self.error_cb.lock().unwrap())(C2Status::C2BadState);
323+ return C2Status::C2BadState;
324+ }
325+
326+ self.work_queue.lock().unwrap().extend(work_items.into_iter());
327+
328+ self.awaiting_job_event.write(1).unwrap();
329+
330+ C2Status::C2Ok
331+ }
332+
333+ // Flush work from the queue and return it as |flushed_work|.
334+ // State will not change after this call.
335+ // TODO: Support different flush modes.
336+ pub fn flush(&mut self, flushed_work: &mut Vec<J>) -> C2Status {
337+ if *self.state.lock().unwrap() != C2State::C2Running {
338+ (*self.error_cb.lock().unwrap())(C2Status::C2BadState);
339+ return C2Status::C2BadState;
340+ }
341+
342+ let mut tmp = self.work_queue.lock().unwrap().drain(..).collect::<Vec<J>>();
343+ flushed_work.append(&mut tmp);
344+
345+ C2Status::C2Ok
346+ }
347+
348+ // Signal to the decoder/encoder that it does not need to wait for
349+ // additional work to begin processing. This is an unusual name for this
350+ // function, but it is the convention that C2 uses.
351+ // State must be C2Running or this function is invalid.
352+ // State will remain C2Running until the last frames drain, at which point
353+ // the state will change to C2Stopped.
354+ // TODO: Support different drain modes.
355+ pub fn drain(&mut self, mode: DrainMode) -> C2Status {
356+ if *self.state.lock().unwrap() != C2State::C2Running {
357+ (*self.error_cb.lock().unwrap())(C2Status::C2BadState);
358+ return C2Status::C2BadState;
359+ }
360+
361+ let mut drain_job: J = Default::default();
362+ drain_job.set_drain(mode);
363+ self.work_queue.lock().unwrap().push_back(drain_job);
364+
365+ self.awaiting_job_event.write(1).unwrap();
366+
367+ C2Status::C2Ok
368+ }
369+}
370+
371+// Instead of C2's release() function, we implement Drop and use RAII to
372+// accomplish the same thing
373+impl<J, W> Drop for C2Wrapper<J, W>
374+where
375+ J: Send + Default + Job + 'static,
376+ W: C2Worker<J>,
377+{
378+ fn drop(&mut self) {
379+ self.stop();
380+ }
381+}
vendor/cros-codecs/src/c2_wrapper/c2_decoder.rsadded+338 -0
@@ -0,0 +1,338 @@
1+// Copyright 2025 The ChromiumOS Authors
2+// Use of this source code is governed by a BSD-style license that can be
3+// found in the LICENSE file.
4+
5+use nix::errno::Errno;
6+use nix::sys::epoll::Epoll;
7+use nix::sys::epoll::EpollCreateFlags;
8+use nix::sys::epoll::EpollEvent;
9+use nix::sys::epoll::EpollFlags;
10+use nix::sys::epoll::EpollTimeout;
11+use nix::sys::eventfd::EventFd;
12+
13+use std::collections::VecDeque;
14+use std::marker::PhantomData;
15+use std::os::fd::AsFd;
16+#[cfg(feature = "vaapi")]
17+use std::path::PathBuf;
18+use std::sync::Arc;
19+use std::sync::Mutex;
20+use thiserror::Error;
21+
22+use crate::c2_wrapper::C2DecodeJob;
23+use crate::c2_wrapper::C2State;
24+use crate::c2_wrapper::C2Status;
25+use crate::c2_wrapper::C2Worker;
26+use crate::c2_wrapper::DrainMode;
27+use crate::c2_wrapper::Job;
28+use crate::decoder::stateless::DecodeError;
29+use crate::decoder::stateless::DynStatelessVideoDecoder;
30+use crate::decoder::DecoderEvent;
31+use crate::decoder::StreamInfo;
32+use crate::image_processing::convert_video_frame;
33+use crate::video_frame::frame_pool::FramePool;
34+use crate::video_frame::frame_pool::PooledVideoFrame;
35+#[cfg(feature = "vaapi")]
36+use crate::video_frame::gbm_video_frame::{GbmDevice, GbmUsage, GbmVideoFrame};
37+#[cfg(feature = "v4l2")]
38+use crate::video_frame::v4l2_mmap_video_frame::V4l2MmapVideoFrame;
39+use crate::video_frame::VideoFrame;
40+use crate::EncodedFormat;
41+use crate::Fourcc;
42+
43+#[derive(Debug, Error)]
44+pub enum C2DecoderPollErrorWrapper {
45+ #[error("failed to create Epoll: {0}")]
46+ Epoll(Errno),
47+ #[error("failed to add poll FDs to Epoll: {0}")]
48+ EpollAdd(Errno),
49+}
50+
51+pub trait C2DecoderBackend {
52+ type DecoderOptions: Clone + Send + 'static;
53+
54+ fn new(options: Self::DecoderOptions) -> Result<Self, String>
55+ where
56+ Self: Sized;
57+ fn supported_output_formats(&self) -> Vec<Fourcc>;
58+ // TODO: Support stateful video decoders.
59+ fn get_decoder<V: VideoFrame + 'static>(
60+ &mut self,
61+ input_format: EncodedFormat,
62+ ) -> Result<DynStatelessVideoDecoder<V>, String>;
63+}
64+
65+#[cfg(feature = "vaapi")]
66+type AuxiliaryVideoFrame = GbmVideoFrame;
67+#[cfg(feature = "v4l2")]
68+type AuxiliaryVideoFrame = V4l2MmapVideoFrame;
69+
70+// An "importing decoder" can directly import the DMA bufs we are getting, while a "converting
71+// decoder" is used for performing image processing routines to convert between the video hardware
72+// output and a pixel format that can be consumed by the GPU and display controller.
73+// TODO: Come up with a better name for these?
74+enum C2Decoder<V: VideoFrame> {
75+ ImportingDecoder(DynStatelessVideoDecoder<V>),
76+ ConvertingDecoder(DynStatelessVideoDecoder<PooledVideoFrame<AuxiliaryVideoFrame>>),
77+}
78+
79+pub struct C2DecoderWorker<V, B>
80+where
81+ V: VideoFrame,
82+ B: C2DecoderBackend,
83+{
84+ decoder: C2Decoder<V>,
85+ epoll_fd: Epoll,
86+ awaiting_job_event: Arc<EventFd>,
87+ auxiliary_frame_pool: Option<FramePool<AuxiliaryVideoFrame>>,
88+ error_cb: Arc<Mutex<dyn FnMut(C2Status) + Send + 'static>>,
89+ work_done_cb: Arc<Mutex<dyn FnMut(C2DecodeJob<V>) + Send + 'static>>,
90+ framepool_hint_cb: Arc<Mutex<dyn FnMut(StreamInfo) + Send + 'static>>,
91+ alloc_cb: Arc<Mutex<dyn FnMut() -> Option<V> + Send + 'static>>,
92+ work_queue: Arc<Mutex<VecDeque<C2DecodeJob<V>>>>,
93+ frame_num: u64,
94+ state: Arc<Mutex<C2State>>,
95+ _phantom: PhantomData<B>,
96+}
97+
98+impl<V, B> C2DecoderWorker<V, B>
99+where
100+ V: VideoFrame,
101+ B: C2DecoderBackend,
102+{
103+ // Processes events from the decoder. Primarily these are frame decoded events and DRCs.
104+ fn check_events(&mut self) {
105+ loop {
106+ let stream_info = match &self.decoder {
107+ C2Decoder::ImportingDecoder(decoder) => decoder.stream_info().map(|x| x.clone()),
108+ C2Decoder::ConvertingDecoder(decoder) => decoder.stream_info().map(|x| x.clone()),
109+ };
110+ match &mut self.decoder {
111+ C2Decoder::ImportingDecoder(decoder) => match decoder.next_event() {
112+ Some(DecoderEvent::FrameReady(frame)) => {
113+ frame.sync().unwrap();
114+ let mut job: C2DecodeJob<V> = Default::default();
115+ job.output = Some(frame.video_frame());
116+ (*self.work_done_cb.lock().unwrap())(job);
117+ }
118+ Some(DecoderEvent::FormatChanged) => match stream_info {
119+ Some(stream_info) => {
120+ (*self.framepool_hint_cb.lock().unwrap())(stream_info.clone());
121+ }
122+ None => {
123+ log::debug!("Could not get stream info after format change!");
124+ *self.state.lock().unwrap() = C2State::C2Error;
125+ (*self.error_cb.lock().unwrap())(C2Status::C2BadValue);
126+ }
127+ },
128+ _ => break,
129+ },
130+ C2Decoder::ConvertingDecoder(decoder) => match decoder.next_event() {
131+ Some(DecoderEvent::FrameReady(frame)) => {
132+ frame.sync().unwrap();
133+ let mut job: C2DecodeJob<V> = Default::default();
134+ let mut dst_frame =
135+ (*self.alloc_cb.lock().unwrap())().expect("Allocation failed!");
136+ let src_frame = &*frame.video_frame();
137+ if let Err(err) = convert_video_frame(src_frame, &mut dst_frame) {
138+ log::debug!("Error converting VideoFrame! {err}");
139+ *self.state.lock().unwrap() = C2State::C2Error;
140+ (*self.error_cb.lock().unwrap())(C2Status::C2BadValue);
141+ }
142+ job.output = Some(Arc::new(dst_frame));
143+ (*self.work_done_cb.lock().unwrap())(job);
144+ }
145+ Some(DecoderEvent::FormatChanged) => match stream_info {
146+ Some(stream_info) => {
147+ (*self.framepool_hint_cb.lock().unwrap())(stream_info.clone());
148+ self.auxiliary_frame_pool.as_mut().unwrap().resize(&stream_info);
149+ }
150+ None => {
151+ log::debug!("Could not get stream info after format change!");
152+ *self.state.lock().unwrap() = C2State::C2Error;
153+ (*self.error_cb.lock().unwrap())(C2Status::C2BadValue);
154+ }
155+ },
156+ _ => break,
157+ },
158+ }
159+ }
160+ }
161+}
162+
163+impl<V, B> C2Worker<C2DecodeJob<V>> for C2DecoderWorker<V, B>
164+where
165+ V: VideoFrame,
166+ B: C2DecoderBackend,
167+{
168+ type Options = <B as C2DecoderBackend>::DecoderOptions;
169+
170+ fn new(
171+ input_fourcc: Fourcc,
172+ output_fourcc: Fourcc,
173+ awaiting_job_event: Arc<EventFd>,
174+ error_cb: Arc<Mutex<dyn FnMut(C2Status) + Send + 'static>>,
175+ work_done_cb: Arc<Mutex<dyn FnMut(C2DecodeJob<V>) + Send + 'static>>,
176+ work_queue: Arc<Mutex<VecDeque<C2DecodeJob<V>>>>,
177+ state: Arc<Mutex<C2State>>,
178+ framepool_hint_cb: Arc<Mutex<dyn FnMut(StreamInfo) + Send + 'static>>,
179+ alloc_cb: Arc<Mutex<dyn FnMut() -> Option<V> + Send + 'static>>,
180+ options: Self::Options,
181+ ) -> Result<Self, String> {
182+ let mut backend = B::new(options)?;
183+ let backend_fourccs = backend.supported_output_formats();
184+ let (auxiliary_frame_pool, decoder) = if backend_fourccs.contains(&output_fourcc) {
185+ (
186+ None,
187+ C2Decoder::ImportingDecoder(
188+ backend.get_decoder(EncodedFormat::from(input_fourcc))?,
189+ ),
190+ )
191+ } else {
192+ #[cfg(feature = "vaapi")]
193+ {
194+ let gbm_device = Arc::new(
195+ GbmDevice::open(PathBuf::from("/dev/dri/renderD128"))
196+ .expect("Could not open GBM device!"),
197+ );
198+ let framepool = FramePool::new(move |stream_info: &StreamInfo| {
199+ // TODO: Query the driver for these alignment params.
200+ <Arc<GbmDevice> as Clone>::clone(&gbm_device)
201+ .new_frame(
202+ Fourcc::from(stream_info.format),
203+ stream_info.display_resolution.clone(),
204+ stream_info.coded_resolution.clone(),
205+ GbmUsage::Decode,
206+ )
207+ .expect("Could not allocate frame for auxiliary frame pool!")
208+ });
209+ (
210+ Some(framepool),
211+ C2Decoder::ConvertingDecoder(
212+ backend.get_decoder(EncodedFormat::from(input_fourcc))?,
213+ ),
214+ )
215+ }
216+ #[cfg(feature = "v4l2")]
217+ {
218+ let framepool = FramePool::new(move |stream_info: &StreamInfo| {
219+ V4l2MmapVideoFrame::new(
220+ Fourcc::from(stream_info.format),
221+ stream_info.display_resolution.clone(),
222+ )
223+ });
224+ (
225+ Some(framepool),
226+ C2Decoder::ConvertingDecoder(
227+ backend.get_decoder(EncodedFormat::from(input_fourcc))?,
228+ ),
229+ )
230+ }
231+ };
232+ Ok(Self {
233+ decoder: decoder,
234+ auxiliary_frame_pool: auxiliary_frame_pool,
235+ epoll_fd: Epoll::new(EpollCreateFlags::empty())
236+ .map_err(C2DecoderPollErrorWrapper::Epoll)
237+ .unwrap(),
238+ awaiting_job_event: awaiting_job_event,
239+ error_cb: error_cb,
240+ work_done_cb: work_done_cb,
241+ framepool_hint_cb: framepool_hint_cb,
242+ alloc_cb: alloc_cb,
243+ work_queue: work_queue,
244+ frame_num: 0,
245+ state: state,
246+ _phantom: Default::default(),
247+ })
248+ }
249+
250+ fn process_loop(&mut self) {
251+ self.epoll_fd = Epoll::new(EpollCreateFlags::empty())
252+ .map_err(C2DecoderPollErrorWrapper::Epoll)
253+ .unwrap();
254+ let _ = self
255+ .epoll_fd
256+ .add(
257+ match &self.decoder {
258+ C2Decoder::ImportingDecoder(decoder) => decoder.poll_fd(),
259+ C2Decoder::ConvertingDecoder(decoder) => decoder.poll_fd(),
260+ },
261+ EpollEvent::new(EpollFlags::EPOLLIN, 1),
262+ )
263+ .map_err(C2DecoderPollErrorWrapper::EpollAdd);
264+ self.epoll_fd
265+ .add(self.awaiting_job_event.as_fd(), EpollEvent::new(EpollFlags::EPOLLIN, 2))
266+ .map_err(C2DecoderPollErrorWrapper::EpollAdd)
267+ .unwrap();
268+
269+ while *self.state.lock().unwrap() == C2State::C2Running {
270+ // Poll for decoder events or pending job events.
271+ let mut events = [EpollEvent::empty()];
272+ let _nb_fds = self.epoll_fd.wait(&mut events, EpollTimeout::NONE).unwrap();
273+
274+ if events == [EpollEvent::new(EpollFlags::EPOLLIN, 2)] {
275+ self.awaiting_job_event.read().unwrap();
276+ }
277+
278+ // We want to try sending compressed buffers to the decoder regardless of what event
279+ // woke us up, because we either have new work, or we might more output buffers
280+ // available.
281+ let mut possible_job = (*self.work_queue.lock().unwrap()).pop_front();
282+ while let Some(mut job) = possible_job {
283+ if job.get_drain() != DrainMode::NoDrain {
284+ let flush_result = match &mut self.decoder {
285+ C2Decoder::ImportingDecoder(decoder) => decoder.flush(),
286+ C2Decoder::ConvertingDecoder(decoder) => decoder.flush(),
287+ };
288+ if let Err(_) = flush_result {
289+ log::debug!("Error handling drain request!");
290+ *self.state.lock().unwrap() = C2State::C2Error;
291+ (*self.error_cb.lock().unwrap())(C2Status::C2BadValue);
292+ } else {
293+ if job.get_drain() == DrainMode::EOSDrain {
294+ *self.state.lock().unwrap() = C2State::C2Stopped;
295+ }
296+ self.check_events();
297+ }
298+ break;
299+ } else {
300+ let bitstream = job.input.as_slice();
301+ let decode_result = match &mut self.decoder {
302+ C2Decoder::ImportingDecoder(decoder) => decoder.decode(
303+ self.frame_num,
304+ bitstream,
305+ &mut *self.alloc_cb.lock().unwrap(),
306+ ),
307+ C2Decoder::ConvertingDecoder(decoder) => {
308+ decoder.decode(self.frame_num, bitstream, &mut || {
309+ self.auxiliary_frame_pool.as_mut().unwrap().alloc()
310+ })
311+ }
312+ };
313+ match decode_result {
314+ Ok(num_bytes) => {
315+ self.frame_num += 1;
316+ if num_bytes != job.input.len() {
317+ job.input = (&job.input[num_bytes..]).to_vec();
318+ (*self.work_queue.lock().unwrap()).push_front(job);
319+ }
320+ }
321+ Err(DecodeError::NotEnoughOutputBuffers(_) | DecodeError::CheckEvents) => {
322+ (*self.work_queue.lock().unwrap()).push_front(job);
323+ break;
324+ }
325+ Err(e) => {
326+ log::debug!("Unhandled error message from decoder {e:?}");
327+ *self.state.lock().unwrap() = C2State::C2Error;
328+ (*self.error_cb.lock().unwrap())(C2Status::C2BadValue);
329+ break;
330+ }
331+ }
332+ }
333+ possible_job = (*self.work_queue.lock().unwrap()).pop_front();
334+ }
335+ self.check_events();
336+ }
337+ }
338+}
vendor/cros-codecs/src/c2_wrapper/c2_encoder.rsadded+272 -0
@@ -0,0 +1,272 @@
1+// Copyright 2025 The ChromiumOS Authors
2+// Use of this source code is governed by a BSD-style license that can be
3+// found in the LICENSE file.
4+
5+use nix::sys::epoll::Epoll;
6+use nix::sys::epoll::EpollCreateFlags;
7+use nix::sys::epoll::EpollEvent;
8+use nix::sys::epoll::EpollFlags;
9+use nix::sys::epoll::EpollTimeout;
10+use nix::sys::eventfd::EventFd;
11+
12+use std::collections::VecDeque;
13+use std::marker::PhantomData;
14+use std::os::fd::AsFd;
15+use std::sync::atomic::Ordering;
16+use std::sync::Arc;
17+use std::sync::Mutex;
18+use std::time::Duration;
19+
20+use crate::c2_wrapper::C2EncodeJob;
21+use crate::c2_wrapper::C2State;
22+use crate::c2_wrapper::C2Status;
23+use crate::c2_wrapper::C2Worker;
24+use crate::c2_wrapper::DrainMode;
25+use crate::c2_wrapper::Job;
26+use crate::decoder::StreamInfo;
27+use crate::encoder::FrameMetadata;
28+use crate::encoder::RateControl;
29+use crate::encoder::RateControl::ConstantBitrate;
30+use crate::encoder::RateControl::ConstantQuality;
31+use crate::encoder::Tunings;
32+use crate::encoder::VideoEncoder;
33+use crate::image_processing::convert_video_frame;
34+use crate::image_processing::extend_border_nv12;
35+#[cfg(feature = "v4l2")]
36+use crate::video_frame::V4l2VideoFrame;
37+use crate::video_frame::VideoFrame;
38+use crate::video_frame::UV_PLANE;
39+use crate::video_frame::Y_PLANE;
40+use crate::DecodedFormat;
41+use crate::EncodedFormat;
42+use crate::Fourcc;
43+use crate::Resolution;
44+
45+pub trait C2EncoderBackend {
46+ type EncoderOptions: Clone + Send + 'static;
47+
48+ fn new(options: Self::EncoderOptions) -> Result<Self, String>
49+ where
50+ Self: Sized;
51+
52+ // Returns a new encoder, the visible resolution, and the coded resolution.
53+ #[cfg(feature = "vaapi")]
54+ fn get_encoder<V: VideoFrame>(
55+ &mut self,
56+ input_format: DecodedFormat,
57+ output_format: EncodedFormat,
58+ ) -> Result<(Box<dyn VideoEncoder<V>>, Resolution, Resolution), String>;
59+ #[cfg(feature = "v4l2")]
60+ fn get_encoder<V: VideoFrame>(
61+ &mut self,
62+ input_format: DecodedFormat,
63+ output_format: EncodedFormat,
64+ ) -> Result<(Box<dyn VideoEncoder<V4l2VideoFrame<V>>>, Resolution, Resolution), String>;
65+}
66+
67+pub struct C2EncoderWorker<V, B>
68+where
69+ V: VideoFrame,
70+ B: C2EncoderBackend,
71+{
72+ #[cfg(feature = "vaapi")]
73+ encoder: Box<dyn VideoEncoder<V>>,
74+ #[cfg(feature = "v4l2")]
75+ encoder: Box<dyn VideoEncoder<V4l2VideoFrame<V>>>,
76+ awaiting_job_event: Arc<EventFd>,
77+ error_cb: Arc<Mutex<dyn FnMut(C2Status) + Send + 'static>>,
78+ work_done_cb: Arc<Mutex<dyn FnMut(C2EncodeJob<V>) + Send + 'static>>,
79+ alloc_cb: Arc<Mutex<dyn FnMut() -> Option<V> + Send + 'static>>,
80+ work_queue: Arc<Mutex<VecDeque<C2EncodeJob<V>>>>,
81+ in_flight_queue: VecDeque<C2EncodeJob<V>>,
82+ state: Arc<Mutex<C2State>>,
83+ current_tunings: Tunings,
84+ visible_resolution: Resolution,
85+ coded_resolution: Resolution,
86+ _phantom: PhantomData<B>,
87+}
88+
89+impl<V, B> C2EncoderWorker<V, B>
90+where
91+ V: VideoFrame,
92+ B: C2EncoderBackend,
93+{
94+ fn poll_complete_frames(&mut self) {
95+ loop {
96+ match self.encoder.poll() {
97+ Ok(Some(coded)) => {
98+ let mut job = self.in_flight_queue.pop_front().unwrap();
99+ job.output = coded.bitstream;
100+ (*self.work_done_cb.lock().unwrap())(job);
101+ }
102+ Err(err) => {
103+ log::debug!("Error during encode! {:?}", err);
104+ *self.state.lock().unwrap() = C2State::C2Error;
105+ (*self.error_cb.lock().unwrap())(C2Status::C2BadValue);
106+ break;
107+ }
108+ _ => break,
109+ }
110+ }
111+ }
112+}
113+
114+impl<V, B> C2Worker<C2EncodeJob<V>> for C2EncoderWorker<V, B>
115+where
116+ V: VideoFrame,
117+ B: C2EncoderBackend,
118+{
119+ type Options = B::EncoderOptions;
120+
121+ fn new(
122+ input_fourcc: Fourcc,
123+ output_fourcc: Fourcc,
124+ awaiting_job_event: Arc<EventFd>,
125+ error_cb: Arc<Mutex<dyn FnMut(C2Status) + Send + 'static>>,
126+ work_done_cb: Arc<Mutex<dyn FnMut(C2EncodeJob<V>) + Send + 'static>>,
127+ work_queue: Arc<Mutex<VecDeque<C2EncodeJob<V>>>>,
128+ state: Arc<Mutex<C2State>>,
129+ framepool_hint_cb: Arc<Mutex<dyn FnMut(StreamInfo) + Send + 'static>>,
130+ alloc_cb: Arc<Mutex<dyn FnMut() -> Option<V> + Send + 'static>>,
131+ options: Self::Options,
132+ ) -> Result<Self, String> {
133+ let mut backend = B::new(options)?;
134+ let (encoder, visible_resolution, coded_resolution) = backend
135+ .get_encoder(DecodedFormat::from(input_fourcc), EncodedFormat::from(output_fourcc))?;
136+ (*framepool_hint_cb.lock().unwrap())(StreamInfo {
137+ format: DecodedFormat::from(input_fourcc),
138+ coded_resolution: coded_resolution.clone(),
139+ display_resolution: visible_resolution.clone(),
140+ // Needs to be equal to the pipeline depth, which is decided by the client. Ideally, we
141+ // will never need these temp frames though if Gralloc works properly.
142+ min_num_frames: 0,
143+ });
144+
145+ Ok(Self {
146+ encoder: encoder,
147+ awaiting_job_event: awaiting_job_event,
148+ error_cb: error_cb,
149+ work_done_cb: work_done_cb,
150+ work_queue: work_queue,
151+ in_flight_queue: VecDeque::new(),
152+ state: state,
153+ alloc_cb: alloc_cb,
154+ current_tunings: Default::default(),
155+ visible_resolution: visible_resolution,
156+ coded_resolution: coded_resolution,
157+ _phantom: Default::default(),
158+ })
159+ }
160+
161+ fn process_loop(&mut self) {
162+ let epoll_fd = Epoll::new(EpollCreateFlags::empty()).expect("Failed to create Epoll");
163+ let _ = epoll_fd
164+ .add(self.awaiting_job_event.as_fd(), EpollEvent::new(EpollFlags::EPOLLIN, 1))
165+ .expect("Failed to add job event to Epoll");
166+
167+ while *self.state.lock().unwrap() == C2State::C2Running {
168+ let mut events = [EpollEvent::empty()];
169+ // We need an actual timeout because the encoder is poll based rather than async.
170+ let _ = epoll_fd
171+ .wait(&mut events, EpollTimeout::try_from(Duration::from_millis(10)).unwrap())
172+ .expect("Epoll wait failed");
173+ if events != [EpollEvent::new(EpollFlags::EPOLLIN, 1)] {
174+ self.poll_complete_frames();
175+ continue;
176+ }
177+
178+ self.awaiting_job_event.read().unwrap();
179+
180+ // Unlike the decoder, we can assume a 1:1 relationship between jobs in the work_queue
181+ // and wake-up events. The encoders are not asynchronous, so the only events we will
182+ // ever wake-up for are jobs being added to the work_queue.
183+ let mut job = (*self.work_queue.lock().unwrap())
184+ .pop_front()
185+ .expect("Missing job from work queue!");
186+ if job.get_drain() != DrainMode::NoDrain {
187+ if let Err(err) = self.encoder.drain() {
188+ log::debug!("Error draining encoder! {:?}", err);
189+ *self.state.lock().unwrap() = C2State::C2Error;
190+ (*self.error_cb.lock().unwrap())(C2Status::C2BadValue);
191+ break;
192+ }
193+ if job.get_drain() == DrainMode::EOSDrain {
194+ *self.state.lock().unwrap() = C2State::C2Stopped;
195+ }
196+ } else {
197+ let frame_y_stride = job.input.as_ref().unwrap().get_plane_pitch()[0];
198+ let frame_y_size = job.input.as_ref().unwrap().get_plane_size()[0];
199+ let can_import_frame = frame_y_stride == self.coded_resolution.width as usize
200+ && frame_y_size >= self.coded_resolution.get_area();
201+ let frame = if can_import_frame {
202+ job.input.take().unwrap()
203+ } else {
204+ let mut tmp = (*self.alloc_cb.lock().unwrap())().expect("Allocation failed!");
205+
206+ if let Err(_) = convert_video_frame(job.input.as_ref().unwrap(), &mut tmp) {
207+ log::debug!("Failed to copy input frame to properly aligned buffer!");
208+ *self.state.lock().unwrap() = C2State::C2Error;
209+ (*self.error_cb.lock().unwrap())(C2Status::C2BadValue);
210+ break;
211+ }
212+ {
213+ let tmp_mapping = tmp.map_mut().expect("Failed to map tmp frame!");
214+ let tmp_planes = tmp_mapping.get();
215+ extend_border_nv12(
216+ *tmp_planes[Y_PLANE].borrow_mut(),
217+ *tmp_planes[UV_PLANE].borrow_mut(),
218+ self.visible_resolution.width as usize,
219+ self.visible_resolution.height as usize,
220+ self.coded_resolution.width as usize,
221+ self.coded_resolution.height as usize,
222+ );
223+ }
224+
225+ tmp
226+ };
227+
228+ let curr_bitrate = match self.current_tunings.rate_control {
229+ ConstantBitrate(bitrate) => bitrate,
230+ ConstantQuality(_) => {
231+ log::debug!("CQ encoding not currently supported");
232+ *self.state.lock().unwrap() = C2State::C2Error;
233+ (*self.error_cb.lock().unwrap())(C2Status::C2BadValue);
234+ break;
235+ }
236+ };
237+ let new_framerate = job.framerate.load(Ordering::Relaxed);
238+ if job.bitrate != curr_bitrate || new_framerate != self.current_tunings.framerate {
239+ self.current_tunings.rate_control = RateControl::ConstantBitrate(job.bitrate);
240+ self.current_tunings.framerate = new_framerate;
241+ if let Err(err) = self.encoder.tune(self.current_tunings.clone()) {
242+ log::debug!("Error adjusting tunings! {:?}", err);
243+ *self.state.lock().unwrap() = C2State::C2Error;
244+ (*self.error_cb.lock().unwrap())(C2Status::C2BadValue);
245+ break;
246+ }
247+ };
248+
249+ let meta = FrameMetadata {
250+ timestamp: job.timestamp,
251+ layout: Default::default(),
252+ force_keyframe: false,
253+ };
254+ #[cfg(feature = "vaapi")]
255+ let encode_result = self.encoder.encode(meta, frame);
256+ #[cfg(feature = "v4l2")]
257+ let encode_result = self.encoder.encode(meta, V4l2VideoFrame(frame));
258+ match encode_result {
259+ Ok(_) => self.in_flight_queue.push_back(job),
260+ Err(err) => {
261+ log::debug!("Error encoding frame! {:?}", err);
262+ *self.state.lock().unwrap() = C2State::C2Error;
263+ (*self.error_cb.lock().unwrap())(C2Status::C2BadValue);
264+ break;
265+ }
266+ }
267+ }
268+
269+ self.poll_complete_frames();
270+ }
271+ }
272+}
vendor/cros-codecs/src/c2_wrapper/c2_v4l2_decoder.rsadded+60 -0
@@ -0,0 +1,60 @@
1+// Copyright 2025 The ChromiumOS Authors
2+// Use of this source code is governed by a BSD-style license that can be
3+// found in the LICENSE file.
4+
5+use std::path::PathBuf;
6+
7+use crate::c2_wrapper::c2_decoder::C2DecoderBackend;
8+use crate::decoder::stateless::av1::Av1;
9+use crate::decoder::stateless::h264::H264;
10+use crate::decoder::stateless::vp8::Vp8;
11+use crate::decoder::stateless::vp9::Vp9;
12+use crate::decoder::stateless::DynStatelessVideoDecoder;
13+use crate::decoder::stateless::StatelessDecoder;
14+use crate::decoder::stateless::StatelessVideoDecoder;
15+use crate::decoder::BlockingMode;
16+use crate::video_frame::VideoFrame;
17+use crate::EncodedFormat;
18+use crate::Fourcc;
19+
20+#[derive(Clone, Debug)]
21+pub struct C2V4L2DecoderOptions {
22+ // TODO: This is currently unused, but we should plumb it to V4L2Device initialization.
23+ pub video_device_path: Option<PathBuf>,
24+}
25+
26+pub struct C2V4L2Decoder {}
27+
28+impl C2DecoderBackend for C2V4L2Decoder {
29+ type DecoderOptions = C2V4L2DecoderOptions;
30+
31+ fn new(_options: C2V4L2DecoderOptions) -> Result<Self, String> {
32+ Ok(Self {})
33+ }
34+
35+ // TODO: Actually query the driver for this information.
36+ fn supported_output_formats(&self) -> Vec<Fourcc> {
37+ vec![Fourcc::from(b"MM21")]
38+ }
39+
40+ fn get_decoder<V: VideoFrame + 'static>(
41+ &mut self,
42+ format: EncodedFormat,
43+ ) -> Result<DynStatelessVideoDecoder<V>, String> {
44+ Ok(match format {
45+ EncodedFormat::AV1 => StatelessDecoder::<Av1, _>::new_v4l2(BlockingMode::NonBlocking)
46+ .map_err(|_| "Failed to instantiate AV1 decoder")?
47+ .into_trait_object(),
48+ EncodedFormat::H264 => StatelessDecoder::<H264, _>::new_v4l2(BlockingMode::NonBlocking)
49+ .map_err(|_| "Failed to instantiate H264 decoder")?
50+ .into_trait_object(),
51+ EncodedFormat::VP8 => StatelessDecoder::<Vp8, _>::new_v4l2(BlockingMode::NonBlocking)
52+ .map_err(|_| "Failed to instantiate VP8 decoder")?
53+ .into_trait_object(),
54+ EncodedFormat::VP9 => StatelessDecoder::<Vp9, _>::new_v4l2(BlockingMode::NonBlocking)
55+ .map_err(|_| "Failed to instantiate VP9 decoder")?
56+ .into_trait_object(),
57+ _ => return Err(format!("Unsupported format {format:?}")),
58+ })
59+ }
60+}
vendor/cros-codecs/src/c2_wrapper/c2_v4l2_encoder.rsadded+131 -0
@@ -0,0 +1,131 @@
1+// Copyright 2025 The ChromiumOS Authors
2+// Use of this source code is governed by a BSD-style license that can be
3+// found in the LICENSE file.
4+
5+use std::sync::Arc;
6+
7+use crate::backend::v4l2::encoder::find_device_with_capture;
8+use crate::backend::v4l2::encoder::MmapingCapture;
9+use crate::c2_wrapper::c2_encoder::C2EncoderBackend;
10+use crate::encoder::stateful::h264::v4l2::V4L2StatefulH264Encoder;
11+use crate::encoder::stateful::vp8::v4l2::V4L2StatefulVP8Encoder;
12+use crate::encoder::stateful::vp9::v4l2::V4L2StatefulVP9Encoder;
13+use crate::encoder::VideoEncoder;
14+use crate::video_frame::V4l2VideoFrame;
15+use crate::video_frame::VideoFrame;
16+use crate::DecodedFormat;
17+use crate::EncodedFormat;
18+use crate::Fourcc;
19+use crate::Resolution;
20+
21+use v4l2r::device::Device;
22+use v4l2r::device::DeviceConfig;
23+
24+fn v4l2_format_to_coded_size(format: &v4l2r::Format) -> Resolution {
25+ let stride = format.plane_fmt[0].bytesperline;
26+ let size = format.plane_fmt[0].sizeimage;
27+ Resolution { width: stride, height: size / stride }
28+}
29+
30+#[derive(Clone, Debug)]
31+pub struct C2V4L2EncoderOptions {
32+ pub output_fourcc: Fourcc,
33+ pub visible_resolution: Resolution,
34+}
35+
36+pub struct C2V4L2Encoder {
37+ visible_resolution: Resolution,
38+ device: Arc<Device>,
39+}
40+
41+impl C2EncoderBackend for C2V4L2Encoder {
42+ type EncoderOptions = C2V4L2EncoderOptions;
43+
44+ fn new(options: C2V4L2EncoderOptions) -> Result<Self, String> {
45+ let pixel_format = v4l2r::PixelFormat::from_u32(u32::from(options.output_fourcc));
46+ let device = find_device_with_capture(pixel_format)
47+ .ok_or("Could not find V4L2 device!".to_string())?;
48+ let device = Device::open(&device, DeviceConfig::new().non_blocking_dqbuf())
49+ .map_err(|err| format!("Error opening V4L2 device! {:?}", err))?;
50+ Ok(Self { visible_resolution: options.visible_resolution, device: Arc::new(device) })
51+ }
52+
53+ fn get_encoder<V: VideoFrame>(
54+ &mut self,
55+ input_format: DecodedFormat,
56+ output_format: EncodedFormat,
57+ ) -> Result<(Box<dyn VideoEncoder<V4l2VideoFrame<V>>>, Resolution, Resolution), String> {
58+ Ok(match output_format {
59+ EncodedFormat::H264 => {
60+ let mut encoder = V4L2StatefulH264Encoder::new(
61+ self.device.clone(),
62+ MmapingCapture,
63+ crate::encoder::h264::EncoderConfig {
64+ resolution: self.visible_resolution.clone(),
65+ ..Default::default()
66+ },
67+ Fourcc::from(input_format),
68+ self.visible_resolution.clone(),
69+ Default::default(),
70+ )
71+ .map_err(|err| format!("Error initializing encoder! {:?}", err))?;
72+ let coded_format = encoder
73+ .backend()
74+ .output_format()
75+ .map_err(|err| format!("Error querying backend format! {:?}", err))?;
76+ (
77+ Box::new(encoder),
78+ self.visible_resolution.clone(),
79+ v4l2_format_to_coded_size(&coded_format),
80+ )
81+ }
82+ EncodedFormat::VP8 => {
83+ let mut encoder = V4L2StatefulVP8Encoder::new(
84+ self.device.clone(),
85+ MmapingCapture,
86+ crate::encoder::vp8::EncoderConfig {
87+ resolution: self.visible_resolution.clone(),
88+ ..Default::default()
89+ },
90+ Fourcc::from(input_format),
91+ self.visible_resolution.clone(),
92+ Default::default(),
93+ )
94+ .map_err(|err| format!("Error initializing encoder! {:?}", err))?;
95+ let coded_format = encoder
96+ .backend()
97+ .output_format()
98+ .map_err(|err| format!("Error querying backend format! {:?}", err))?;
99+ (
100+ Box::new(encoder),
101+ self.visible_resolution.clone(),
102+ v4l2_format_to_coded_size(&coded_format),
103+ )
104+ }
105+ EncodedFormat::VP9 => {
106+ let mut encoder = V4L2StatefulVP9Encoder::new(
107+ self.device.clone(),
108+ MmapingCapture,
109+ crate::encoder::vp9::EncoderConfig {
110+ resolution: self.visible_resolution.clone(),
111+ ..Default::default()
112+ },
113+ Fourcc::from(input_format),
114+ self.visible_resolution.clone(),
115+ Default::default(),
116+ )
117+ .map_err(|err| format!("Error initializing encoder! {:?}", err))?;
118+ let coded_format = encoder
119+ .backend()
120+ .output_format()
121+ .map_err(|err| format!("Error querying backend format! {:?}", err))?;
122+ (
123+ Box::new(encoder),
124+ self.visible_resolution.clone(),
125+ v4l2_format_to_coded_size(&coded_format),
126+ )
127+ }
128+ _ => return Err(format!("Format not supported by V4L2! {:?}", output_format)),
129+ })
130+ }
131+}
vendor/cros-codecs/src/c2_wrapper/c2_vaapi_decoder.rsadded+86 -0
@@ -0,0 +1,86 @@
1+// Copyright 2025 The ChromiumOS Authors
2+// Use of this source code is governed by a BSD-style license that can be
3+// found in the LICENSE file.
4+
5+use std::path::PathBuf;
6+use std::rc::Rc;
7+
8+use crate::c2_wrapper::c2_decoder::C2DecoderBackend;
9+use crate::decoder::stateless::av1::Av1;
10+use crate::decoder::stateless::h264::H264;
11+use crate::decoder::stateless::h265::H265;
12+use crate::decoder::stateless::vp8::Vp8;
13+use crate::decoder::stateless::vp9::Vp9;
14+use crate::decoder::stateless::DynStatelessVideoDecoder;
15+use crate::decoder::stateless::StatelessDecoder;
16+use crate::decoder::stateless::StatelessVideoDecoder;
17+use crate::decoder::BlockingMode;
18+use crate::video_frame::VideoFrame;
19+use crate::EncodedFormat;
20+use crate::Fourcc;
21+
22+#[derive(Clone, Debug)]
23+pub struct C2VaapiDecoderOptions {
24+ pub libva_device_path: Option<PathBuf>,
25+}
26+
27+pub struct C2VaapiDecoder {
28+ display: Rc<libva::Display>,
29+}
30+
31+impl C2DecoderBackend for C2VaapiDecoder {
32+ type DecoderOptions = C2VaapiDecoderOptions;
33+
34+ fn new(options: C2VaapiDecoderOptions) -> Result<Self, String> {
35+ let display = match options.libva_device_path {
36+ Some(libva_device_path) => libva::Display::open_drm_display(libva_device_path.clone())
37+ .map_err(|_| format!("failed to open libva display {libva_device_path:?}"))?,
38+ None => libva::Display::open().ok_or("failed to open libva display")?,
39+ };
40+
41+ Ok(Self { display: display })
42+ }
43+
44+ // TODO: Actually query the driver for this information.
45+ fn supported_output_formats(&self) -> Vec<Fourcc> {
46+ vec![Fourcc::from(b"NV12")]
47+ }
48+
49+ fn get_decoder<V: VideoFrame + 'static>(
50+ &mut self,
51+ format: EncodedFormat,
52+ ) -> Result<DynStatelessVideoDecoder<V>, String> {
53+ Ok(match format {
54+ EncodedFormat::H264 => StatelessDecoder::<H264, _>::new_vaapi(
55+ self.display.clone(),
56+ BlockingMode::NonBlocking,
57+ )
58+ .map_err(|_| "Failed to instantiate H264 encoder")?
59+ .into_trait_object(),
60+ EncodedFormat::H265 => StatelessDecoder::<H265, _>::new_vaapi(
61+ self.display.clone(),
62+ BlockingMode::NonBlocking,
63+ )
64+ .map_err(|_| "Failed to instantiate H265 encoder")?
65+ .into_trait_object(),
66+ EncodedFormat::VP8 => StatelessDecoder::<Vp8, _>::new_vaapi(
67+ self.display.clone(),
68+ BlockingMode::NonBlocking,
69+ )
70+ .map_err(|_| "Failed to instantiate VP8 encoder")?
71+ .into_trait_object(),
72+ EncodedFormat::VP9 => StatelessDecoder::<Vp9, _>::new_vaapi(
73+ self.display.clone(),
74+ BlockingMode::NonBlocking,
75+ )
76+ .map_err(|_| "Failed to instantiate VP9 encoder")?
77+ .into_trait_object(),
78+ EncodedFormat::AV1 => StatelessDecoder::<Av1, _>::new_vaapi(
79+ self.display.clone(),
80+ BlockingMode::NonBlocking,
81+ )
82+ .map_err(|_| "Failed to instantiate AV1 encoder")?
83+ .into_trait_object(),
84+ })
85+ }
86+}
vendor/cros-codecs/src/c2_wrapper/c2_vaapi_encoder.rsadded+112 -0
@@ -0,0 +1,112 @@
1+// Copyright 2025 The ChromiumOS Authors
2+// Use of this source code is governed by a BSD-style license that can be
3+// found in the LICENSE file.
4+
5+use std::rc::Rc;
6+
7+use crate::c2_wrapper::c2_encoder::C2EncoderBackend;
8+use crate::encoder::av1::EncoderConfig as AV1EncoderConfig;
9+use crate::encoder::h264::EncoderConfig as H264EncoderConfig;
10+use crate::encoder::stateless::av1;
11+use crate::encoder::stateless::h264;
12+use crate::encoder::stateless::vp9;
13+use crate::encoder::vp9::EncoderConfig as VP9EncoderConfig;
14+use crate::encoder::VideoEncoder;
15+use crate::utils::align_up;
16+use crate::video_frame::VideoFrame;
17+use crate::BlockingMode;
18+use crate::DecodedFormat;
19+use crate::EncodedFormat;
20+use crate::Fourcc;
21+use crate::Resolution;
22+
23+#[derive(Clone, Debug)]
24+pub struct C2VaapiEncoderOptions {
25+ pub low_power: bool,
26+ pub visible_resolution: Resolution,
27+}
28+
29+pub struct C2VaapiEncoder {
30+ display: Rc<libva::Display>,
31+ low_power: bool,
32+ visible_resolution: Resolution,
33+ coded_resolution: Resolution,
34+}
35+
36+impl C2EncoderBackend for C2VaapiEncoder {
37+ type EncoderOptions = C2VaapiEncoderOptions;
38+
39+ fn new(options: C2VaapiEncoderOptions) -> Result<Self, String> {
40+ const VAAPI_WIDTH_ALIGN: u32 = 16;
41+ const VAAPI_HEIGHT_ALIGN: u32 = 16;
42+
43+ // TODO: Support alternative display paths
44+ let display = libva::Display::open().ok_or("Error opening LibVA display!".to_string())?;
45+ Ok(Self {
46+ display: display,
47+ low_power: options.low_power,
48+ visible_resolution: options.visible_resolution.clone(),
49+ // TODO: This really shouldn't be necessary, but for some reason minigbm gets the
50+ // vertical alignment wrong when we omit it :(
51+ coded_resolution: Resolution {
52+ width: align_up(options.visible_resolution.width, VAAPI_WIDTH_ALIGN),
53+ height: align_up(options.visible_resolution.height, VAAPI_HEIGHT_ALIGN),
54+ },
55+ })
56+ }
57+
58+ fn get_encoder<V: VideoFrame>(
59+ &mut self,
60+ input_format: DecodedFormat,
61+ output_format: EncodedFormat,
62+ ) -> Result<(Box<dyn VideoEncoder<V>>, Resolution, Resolution), String> {
63+ Ok(match output_format {
64+ EncodedFormat::H264 => {
65+ let encoder = h264::StatelessEncoder::new_vaapi(
66+ self.display.clone(),
67+ H264EncoderConfig {
68+ resolution: self.visible_resolution.clone(),
69+ ..Default::default()
70+ },
71+ Fourcc::from(input_format),
72+ self.visible_resolution.clone(),
73+ self.low_power,
74+ BlockingMode::Blocking,
75+ )
76+ .map_err(|err| format!("Error initializing encoder! {:?}", err))?;
77+ (Box::new(encoder), self.visible_resolution.clone(), self.coded_resolution.clone())
78+ }
79+ EncodedFormat::VP9 => {
80+ let encoder = vp9::StatelessEncoder::new_vaapi(
81+ self.display.clone(),
82+ VP9EncoderConfig {
83+ resolution: self.visible_resolution.clone(),
84+ ..Default::default()
85+ },
86+ Fourcc::from(input_format),
87+ self.visible_resolution.clone(),
88+ self.low_power,
89+ BlockingMode::Blocking,
90+ )
91+ .map_err(|err| format!("Error initializing encoder! {:?}", err))?;
92+ (Box::new(encoder), self.visible_resolution.clone(), self.coded_resolution.clone())
93+ }
94+ EncodedFormat::AV1 => {
95+ let encoder = av1::StatelessEncoder::new_vaapi(
96+ self.display.clone(),
97+ AV1EncoderConfig {
98+ resolution: self.visible_resolution.clone(),
99+ ..Default::default()
100+ },
101+ Fourcc::from(input_format),
102+ self.visible_resolution.clone(),
103+ self.low_power,
104+ BlockingMode::Blocking,
105+ )
106+ .map_err(|err| format!("Error initializing encoder! {:?}", err))?;
107+ (Box::new(encoder), self.visible_resolution.clone(), self.coded_resolution.clone())
108+ }
109+ _ => return Err(format!("Format not supported by V4L2! {:?}", output_format)),
110+ })
111+ }
112+}
vendor/cros-codecs/src/codec.rsadded+18 -0
@@ -0,0 +1,18 @@
1+// Copyright 2023 The ChromiumOS Authors
2+// Use of this source code is governed by a BSD-style license that can be
3+// found in the LICENSE file.
4+
5+//! Parsers for various kinds of encoded streams.
6+//!
7+//! This module does not provide any actual decoding tools - that's the job of the
8+//! [crate::decoder] module. However the parsers of this module are heavily used in order to
9+//! implement stateless decoding.
10+//!
11+//! There shall be no dependencies from other modules of this crate to this module, so that it
12+//! can be turned into a crate of its own if needed in the future.
13+
14+pub mod av1;
15+pub mod h264;
16+pub mod h265;
17+pub mod vp8;
18+pub mod vp9;
vendor/cros-codecs/src/codec/av1.rsadded+9 -0
@@ -0,0 +1,9 @@
1+// Copyright 2023 The ChromiumOS Authors
2+// Use of this source code is governed by a BSD-style license that can be
3+// found in the LICENSE file.
4+
5+mod helpers;
6+pub mod parser;
7+pub mod reader;
8+pub mod synthesizer;
9+pub mod writer;
vendor/cros-codecs/src/codec/av1/helpers.rsadded+178 -0
@@ -0,0 +1,178 @@
1+// Copyright 2023 The ChromiumOS Authors
2+// Use of this source code is governed by a BSD-style license that can be
3+// found in the LICENSE file.
4+
5+use crate::codec::av1::parser::NUM_REF_FRAMES;
6+
7+const DIV_LUT: [i32; 257] = [
8+ 16384, 16320, 16257, 16194, 16132, 16070, 16009, 15948, 15888, 15828, 15768, 15709, 15650,
9+ 15592, 15534, 15477, 15420, 15364, 15308, 15252, 15197, 15142, 15087, 15033, 14980, 14926,
10+ 14873, 14821, 14769, 14717, 14665, 14614, 14564, 14513, 14463, 14413, 14364, 14315, 14266,
11+ 14218, 14170, 14122, 14075, 14028, 13981, 13935, 13888, 13843, 13797, 13752, 13707, 13662,
12+ 13618, 13574, 13530, 13487, 13443, 13400, 13358, 13315, 13273, 13231, 13190, 13148, 13107,
13+ 13066, 13026, 12985, 12945, 12906, 12866, 12827, 12788, 12749, 12710, 12672, 12633, 12596,
14+ 12558, 12520, 12483, 12446, 12409, 12373, 12336, 12300, 12264, 12228, 12193, 12157, 12122,
15+ 12087, 12053, 12018, 11984, 11950, 11916, 11882, 11848, 11815, 11782, 11749, 11716, 11683,
16+ 11651, 11619, 11586, 11555, 11523, 11491, 11460, 11429, 11398, 11367, 11336, 11305, 11275,
17+ 11245, 11215, 11185, 11155, 11125, 11096, 11067, 11038, 11009, 10980, 10951, 10923, 10894,
18+ 10866, 10838, 10810, 10782, 10755, 10727, 10700, 10673, 10645, 10618, 10592, 10565, 10538,
19+ 10512, 10486, 10460, 10434, 10408, 10382, 10356, 10331, 10305, 10280, 10255, 10230, 10205,
20+ 10180, 10156, 10131, 10107, 10082, 10058, 10034, 10010, 9986, 9963, 9939, 9916, 9892, 9869,
21+ 9846, 9823, 9800, 9777, 9754, 9732, 9709, 9687, 9664, 9642, 9620, 9598, 9576, 9554, 9533, 9511,
22+ 9489, 9468, 9447, 9425, 9404, 9383, 9362, 9341, 9321, 9300, 9279, 9259, 9239, 9218, 9198, 9178,
23+ 9158, 9138, 9118, 9098, 9079, 9059, 9039, 9020, 9001, 8981, 8962, 8943, 8924, 8905, 8886, 8867,
24+ 8849, 8830, 8812, 8793, 8775, 8756, 8738, 8720, 8702, 8684, 8666, 8648, 8630, 8613, 8595, 8577,
25+ 8560, 8542, 8525, 8508, 8490, 8473, 8456, 8439, 8422, 8405, 8389, 8372, 8355, 8339, 8322, 8306,
26+ 8289, 8273, 8257, 8240, 8224, 8208, 8192,
27+];
28+
29+const DIV_LUT_BITS: u32 = 8;
30+const DIV_LUT_PREC_BITS: u32 = 14;
31+
32+/// Implements FloorLog2(x), which is defined to be the floor of the base 2
33+/// logarithm of the input x.
34+///
35+/// The input x will always be an integer, and will always be greater than or equal to 1.
36+/// This function extracts the location of the most significant bit in x.
37+pub fn floor_log2(mut x: u32) -> u32 {
38+ assert!(x > 0);
39+ let mut s = 0;
40+
41+ while x != 0 {
42+ x >>= 1;
43+ s += 1;
44+ }
45+
46+ s - 1
47+}
48+
49+/// Implements 5.9.3. Get relative distance function
50+pub fn get_relative_dist(enable_order_hint: bool, order_hint_bits: i32, a: i32, b: i32) -> i32 {
51+ if !enable_order_hint {
52+ 0
53+ } else {
54+ let diff = a - b;
55+ let m = 1 << (order_hint_bits - 1);
56+ (diff & (m - 1)) - (diff & m)
57+ }
58+}
59+
60+/// Implements find_latest_backward from section 7.8.
61+pub fn find_latest_backward(
62+ shifted_order_hints: &[i32; NUM_REF_FRAMES],
63+ used_frame: &[bool; NUM_REF_FRAMES],
64+ cur_frame_hint: i32,
65+ latest_order_hint: &mut i32,
66+) -> i32 {
67+ let mut _ref = -1;
68+
69+ for i in 0..NUM_REF_FRAMES {
70+ let hint = shifted_order_hints[i];
71+ if !used_frame[i] && hint >= cur_frame_hint && (_ref < 0 || hint >= *latest_order_hint) {
72+ _ref = i as i32;
73+ *latest_order_hint = hint;
74+ }
75+ }
76+
77+ _ref
78+}
79+
80+/// Implements find_earliest_backward from section 7.8.
81+pub fn find_earliest_backward(
82+ shifted_order_hints: &[i32; NUM_REF_FRAMES],
83+ used_frame: &[bool; NUM_REF_FRAMES],
84+ cur_frame_hint: i32,
85+ earliest_order_hint: &mut i32,
86+) -> i32 {
87+ let mut _ref = -1;
88+
89+ for i in 0..NUM_REF_FRAMES {
90+ let hint = shifted_order_hints[i];
91+ if !used_frame[i] && hint >= cur_frame_hint && (_ref < 0 || hint < *earliest_order_hint) {
92+ _ref = i as i32;
93+ *earliest_order_hint = hint;
94+ }
95+ }
96+
97+ _ref
98+}
99+
100+/// Implements find_latest_forward from section 7.8.
101+pub fn find_latest_forward(
102+ shifted_order_hints: &[i32; NUM_REF_FRAMES],
103+ used_frame: &[bool; NUM_REF_FRAMES],
104+ cur_frame_hint: i32,
105+ latest_order_hint: &mut i32,
106+) -> i32 {
107+ let mut _ref = -1;
108+ for i in 0..NUM_REF_FRAMES {
109+ let hint = shifted_order_hints[i];
110+ if !used_frame[i] && hint < cur_frame_hint && (_ref < 0 || hint >= *latest_order_hint) {
111+ _ref = i as i32;
112+ *latest_order_hint = hint;
113+ }
114+ }
115+
116+ _ref
117+}
118+
119+pub fn tile_log2(blk_size: u32, target: u32) -> u32 {
120+ let mut k = 0;
121+
122+ while (blk_size << k) < target {
123+ k += 1;
124+ }
125+
126+ k
127+}
128+
129+pub fn clip3(x: i32, y: i32, z: i32) -> i32 {
130+ if z < x {
131+ x
132+ } else if z > y {
133+ y
134+ } else {
135+ z
136+ }
137+}
138+
139+/// 5.9.29
140+pub fn inverse_recenter(r: i32, v: i32) -> i32 {
141+ if v > 2 * r {
142+ v
143+ } else if v & 1 != 0 {
144+ r - ((v + 1) >> 1)
145+ } else {
146+ r + (v >> 1)
147+ }
148+}
149+
150+/// Implements Round2. See 4.7: mathematical functions.
151+pub fn round2(x: u32, n: u32) -> u32 {
152+ (x + 2u32.pow(n - 1)) / 2u32.pow(n)
153+}
154+
155+/// Implements Round2Signed. See 4.7: mathematical functions.
156+pub fn round2signed(x: i32, n: u32) -> Result<i32, String> {
157+ if x >= 0 {
158+ i32::try_from(round2(x as u32, n)).map_err(|e| e.to_string())
159+ } else {
160+ let x = x as i64;
161+ let val = i32::try_from(round2(-x as u32, n)).map_err(|e| e.to_string())?;
162+ Ok(-val)
163+ }
164+}
165+
166+/// Implements 7.11.3.7. Resolve divisor process
167+pub fn resolve_divisor(d: i32) -> Result<(u32, i32), String> {
168+ let abs_d = u32::try_from(d.abs()).unwrap(); // abs cannot return a negative
169+ let n = floor_log2(abs_d);
170+ let e = abs_d - (1 << n);
171+
172+ let f = if n > DIV_LUT_BITS { round2(e, n - DIV_LUT_BITS) } else { e << (DIV_LUT_BITS - n) };
173+
174+ let div_shift = n + DIV_LUT_PREC_BITS;
175+ let div_factor = if d < 0 { -DIV_LUT[f as usize] } else { DIV_LUT[f as usize] };
176+
177+ Ok((div_shift, div_factor))
178+}
vendor/cros-codecs/src/codec/av1/parser.rsadded+4216 -0

Diff too large; view file

@@ -0,0 +1,4216 @@
1+// Copyright 2023 The ChromiumOS Authors
2+// Use of this source code is governed by a BSD-style license that can be
3+// found in the LICENSE file.
4+
5+use std::borrow::Cow;
6+use std::rc::Rc;
7+
8+use crate::codec::av1::helpers;
9+use crate::codec::av1::reader::Reader;
10+
11+pub const TOTAL_REFS_PER_FRAME: usize = 8;
12+pub const NUM_REF_FRAMES: usize = 8;
13+pub const REFS_PER_FRAME: usize = 7;
14+pub const MAX_SEGMENTS: usize = 8;
15+pub const SEG_LVL_ALT_Q: usize = 0;
16+pub const SEG_LVL_ALT_LF_Y_V: usize = 1;
17+pub const SEG_LVL_REF_FRAME: usize = 5;
18+pub const SEG_LVL_SKIP: usize = 6;
19+pub const SEG_LVL_GLOBAL_MV: usize = 7;
20+pub const SEG_LVL_MAX: usize = 8;
21+pub const MAX_TILE_COLS: usize = 64;
22+pub const MAX_TILE_ROWS: usize = 64;
23+pub const CDEF_MAX: usize = 1 << 3;
24+pub const MAX_NUM_PLANES: usize = 3;
25+pub const MAX_NUM_Y_POINTS: usize = 16;
26+pub const MAX_NUM_CB_POINTS: usize = 16;
27+pub const MAX_NUM_CR_POINTS: usize = 16;
28+pub const MAX_NUM_POS_LUMA: usize = 25;
29+pub const MAX_NUM_SPATIAL_LAYERS: usize = 4;
30+pub const MAX_NUM_TEMPORAL_LAYERS: usize = 8;
31+pub const MAX_NUM_OPERATING_POINTS: usize = MAX_NUM_SPATIAL_LAYERS * MAX_NUM_TEMPORAL_LAYERS;
32+pub const SELECT_SCREEN_CONTENT_TOOLS: usize = 2;
33+pub const SELECT_INTEGER_MV: usize = 2;
34+pub const PRIMARY_REF_NONE: u32 = 7;
35+pub const SUPERRES_DENOM_BITS: usize = 3;
36+pub const SUPERRES_DENOM_MIN: usize = 9;
37+pub const SUPERRES_NUM: usize = 8;
38+pub const MAX_TILE_WIDTH: u32 = 4096;
39+pub const MAX_TILE_HEIGHT: u32 = 2304;
40+pub const MAX_TILE_AREA: u32 = MAX_TILE_WIDTH * MAX_TILE_HEIGHT;
41+pub const RESTORATION_TILESIZE_MAX: u16 = 256;
42+pub const WARPEDMODEL_PREC_BITS: u32 = 16;
43+pub const WARP_PARAM_REDUCE_BITS: u32 = 6;
44+pub const GM_ABS_ALPHA_BITS: u32 = 12;
45+pub const GM_ALPHA_PREC_BITS: u32 = 15;
46+pub const GM_ABS_TRANS_ONLY_BITS: u32 = 9;
47+pub const GM_TRANS_ONLY_PREC_BITS: u32 = 3;
48+pub const GM_ABS_TRANS_BITS: u32 = 12;
49+pub const GM_TRANS_PREC_BITS: u32 = 6;
50+
51+// Same as Segmentation_Feature_Bits in the specification. See 5.9.14
52+pub const FEATURE_BITS: [u8; SEG_LVL_MAX] = [8, 6, 6, 6, 6, 3, 0, 0];
53+// Same as Segmentation_Feature_Signed in the specification. See 5.9.14
54+pub const FEATURE_SIGNED: [bool; SEG_LVL_MAX] = [true, true, true, true, true, false, false, false];
55+// Same as Segmentation_Feature_Max in the specification. See 5.9.14
56+pub const FEATURE_MAX: [i32; SEG_LVL_MAX] = [255, 63, 63, 63, 63, 7, 0, 0];
57+
58+/// Tells what should be done with the OBU after [`Parser::read_obu`] is called.
59+pub enum ObuAction<'a> {
60+ /// We should process the OBU normally.
61+ Process(Obu<'a>),
62+ /// We should drop this OBU and advance to the next one. The u32 is how much
63+ /// we should advance.
64+ Drop(u32),
65+}
66+
67+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord)]
68+pub enum ObuType {
69+ #[default]
70+ Reserved = 0,
71+ SequenceHeader = 1,
72+ TemporalDelimiter = 2,
73+ FrameHeader = 3,
74+ TileGroup = 4,
75+ Metadata = 5,
76+ Frame = 6,
77+ RedundantFrameHeader = 7,
78+ TileList = 8,
79+ Reserved2 = 9,
80+ Reserved3 = 10,
81+ Reserved4 = 11,
82+ Reserved5 = 12,
83+ Reserved6 = 13,
84+ Reserved7 = 14,
85+ Padding = 15,
86+}
87+
88+impl TryFrom<u32> for ObuType {
89+ type Error = String;
90+
91+ fn try_from(value: u32) -> Result<Self, Self::Error> {
92+ match value {
93+ 0 => Ok(ObuType::Reserved),
94+ 1 => Ok(ObuType::SequenceHeader),
95+ 2 => Ok(ObuType::TemporalDelimiter),
96+ 3 => Ok(ObuType::FrameHeader),
97+ 4 => Ok(ObuType::TileGroup),
98+ 5 => Ok(ObuType::Metadata),
99+ 6 => Ok(ObuType::Frame),
100+ 7 => Ok(ObuType::RedundantFrameHeader),
101+ 8 => Ok(ObuType::TileList),
102+ 9 => Ok(ObuType::Reserved2),
103+ 10 => Ok(ObuType::Reserved3),
104+ 11 => Ok(ObuType::Reserved4),
105+ 12 => Ok(ObuType::Reserved5),
106+ 13 => Ok(ObuType::Reserved6),
107+ 14 => Ok(ObuType::Reserved7),
108+ 15 => Ok(ObuType::Padding),
109+ _ => Err(format!("Invalid ObuType {}", value)),
110+ }
111+ }
112+}
113+
114+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord)]
115+pub enum Profile {
116+ #[default]
117+ Profile0 = 0,
118+ Profile1 = 1,
119+ Profile2 = 2,
120+}
121+
122+impl TryFrom<u32> for Profile {
123+ type Error = String;
124+
125+ fn try_from(value: u32) -> Result<Self, Self::Error> {
126+ match value {
127+ 0 => Ok(Profile::Profile0),
128+ 1 => Ok(Profile::Profile1),
129+ 2 => Ok(Profile::Profile2),
130+ _ => Err(format!("Invalid Profile {}", value)),
131+ }
132+ }
133+}
134+
135+#[derive(Clone, Debug, Default, PartialEq, Eq)]
136+pub struct ObuHeader {
137+ pub obu_type: ObuType,
138+ pub extension_flag: bool,
139+ pub has_size_field: bool,
140+ pub temporal_id: u32,
141+ pub spatial_id: u32,
142+}
143+
144+impl ObuHeader {
145+ /// Length in bytes
146+ #[allow(clippy::len_without_is_empty)]
147+ pub fn len(&self) -> usize {
148+ if self.extension_flag {
149+ 2
150+ } else {
151+ 1
152+ }
153+ }
154+}
155+
156+/// Contains the OBU header and a reference to its data. The OBU itself hasn't been parsed yet.
157+#[derive(Clone, Debug, Default, PartialEq, Eq)]
158+pub struct Obu<'a> {
159+ /// The OBU header.
160+ pub header: ObuHeader,
161+ /// Amount of bytes from the input consumed to parse this OBU.
162+ pub bytes_used: usize,
163+ /// The slice backing the OBU.
164+ data: Cow<'a, [u8]>,
165+}
166+
167+impl<'a> AsRef<[u8]> for Obu<'a> {
168+ fn as_ref(&self) -> &[u8] {
169+ self.data.as_ref()
170+ }
171+}
172+
173+/// A fully parsed OBU, with additional data when relevant.
174+pub enum ParsedObu<'a> {
175+ Reserved,
176+ SequenceHeader(Rc<SequenceHeaderObu>),
177+ TemporalDelimiter,
178+ FrameHeader(FrameHeaderObu),
179+ TileGroup(TileGroupObu<'a>),
180+ Metadata,
181+ Frame(FrameObu<'a>),
182+ RedundantFrameHeader,
183+ TileList,
184+ Reserved2,
185+ Reserved3,
186+ Reserved4,
187+ Reserved5,
188+ Reserved6,
189+ Reserved7,
190+ Padding,
191+}
192+
193+impl<'a> ParsedObu<'a> {
194+ pub fn obu_type(&self) -> ObuType {
195+ match self {
196+ ParsedObu::Reserved => ObuType::Reserved,
197+ ParsedObu::SequenceHeader(_) => ObuType::SequenceHeader,
198+ ParsedObu::TemporalDelimiter => ObuType::TemporalDelimiter,
199+ ParsedObu::FrameHeader(_) => ObuType::FrameHeader,
200+ ParsedObu::TileGroup(_) => ObuType::TileGroup,
201+ ParsedObu::Metadata => ObuType::Metadata,
202+ ParsedObu::Frame(_) => ObuType::Frame,
203+ ParsedObu::RedundantFrameHeader => ObuType::RedundantFrameHeader,
204+ ParsedObu::TileList => ObuType::TileList,
205+ ParsedObu::Reserved2 => ObuType::Reserved2,
206+ ParsedObu::Reserved3 => ObuType::Reserved3,
207+ ParsedObu::Reserved4 => ObuType::Reserved4,
208+ ParsedObu::Reserved5 => ObuType::Reserved5,
209+ ParsedObu::Reserved6 => ObuType::Reserved6,
210+ ParsedObu::Reserved7 => ObuType::Reserved7,
211+ ParsedObu::Padding => ObuType::Padding,
212+ }
213+ }
214+}
215+
216+#[derive(Clone, Debug, Default, PartialEq, Eq)]
217+pub struct Tile {
218+ /// Same as TileOffset in the specification.
219+ pub tile_offset: u32,
220+ /// Same as TileSize in the specification.
221+ pub tile_size: u32,
222+ /// Same as TileRow in the specification.
223+ pub tile_row: u32,
224+ /// Same as TileCol in the specification.
225+ pub tile_col: u32,
226+ // Same as MiRowStart in the specification.
227+ pub mi_row_start: u32,
228+ // Same as MiRowEnd in the specification.
229+ pub mi_row_end: u32,
230+ // Same as MiColStart in the specification.
231+ pub mi_col_start: u32,
232+ // Same as MiColEnd in the specification.
233+ pub mi_col_end: u32,
234+}
235+
236+#[derive(Clone, Debug, Default, PartialEq, Eq)]
237+pub struct TileGroupObu<'a> {
238+ /// The OBU backing this tile group.
239+ pub obu: Obu<'a>,
240+ /// Specifies whether tg_start and tg_end are present. If tg_start and
241+ /// tg_end are not present, this tile group covers the entire frame.
242+ pub tile_start_and_end_present_flag: bool,
243+ /// Specifies the zero-based index of the first tile in the current tile
244+ /// group.
245+ pub tg_start: u32,
246+ /// Specifies the zero-based index of the last tile in the current tile
247+ /// group.
248+ pub tg_end: u32,
249+ /// Contains the tiles in this tile group. Use `tile_offset`to index into
250+ /// the OBU data.
251+ ///
252+ /// The tiles in the Vec span from tg_start to tg_end.
253+ pub tiles: Vec<Tile>,
254+}
255+
256+#[derive(Clone, Debug, Default, PartialEq, Eq)]
257+pub struct OperatingPoint {
258+ /// Specifies the level that the coded video sequence conforms to when
259+ /// operating point i is selected.
260+ pub seq_level_idx: u8,
261+ /// Specifies the tier that the coded video sequence conforms to when
262+ /// operating point i is selected.
263+ pub seq_tier: u8,
264+ /// Specifies the value of operating_point_idc for the selected operating
265+ /// point.
266+ pub idc: u16,
267+ /// If set, indicates that there is a decoder model associated with
268+ /// operating point i. If not set, indicates that there is not a decoder
269+ /// model associated with operating point i.
270+ pub decoder_model_present_for_this_op: bool,
271+ /// Specifies the time interval between the arrival of the first bit in the
272+ /// smoothing buffer and the subsequent removal of the data that belongs to
273+ /// the first coded frame for operating point op, measured in units of
274+ /// 1/90000 seconds. The length of decoder_buffer_delay is specified by
275+ /// buffer_delay_length_minus_1 + 1, in bits.
276+ pub decoder_buffer_delay: u32,
277+ /// Specifies, in combination with decoder_buffer_delay\[ op \] syntax
278+ /// element, the first bit arrival time of frames to be decoded to the
279+ /// smoothing buffer. encoder_buffer_delay is measured in units of 1/90000
280+ /// seconds.
281+ pub encoder_buffer_delay: u32,
282+ /// If set, indicates that the smoothing buffer operates in low-delay mode
283+ /// for operating point op. In low-delay mode late decode times and buffer
284+ /// underflow are both permitted. If not set, indicates that the smoothing
285+ /// buffer operates in strict mode, where buffer underflow is not allowed.
286+ pub low_delay_mode_flag: bool,
287+ /// If set, indicates that initial_display_delay_minus_1 is specified for
288+ /// operating point i. If not set, indicates that
289+ /// initial_display_delay_minus_1 is not specified for operating point i.
290+ pub initial_display_delay_present_for_this_op: bool,
291+ /// Plus 1 specifies, for operating point i, the number of decoded frames
292+ /// that should be present in the buffer pool before the first presentable
293+ /// frame is displayed. This will ensure that all presentable frames in the
294+ /// sequence can be decoded at or before the time that they are scheduled
295+ /// for display. If not signaled then initial_display_delay_minus_1\[ i \] =
296+ /// BUFFER_POOL_MAX_SIZE - 1.
297+ pub initial_display_delay_minus_1: u32,
298+}
299+
300+#[derive(Clone, Debug, Default, PartialEq, Eq)]
301+pub struct TimingInfo {
302+ /// The number of time units of a clock operating at the frequency
303+ /// time_scale Hz that corresponds to one increment of a clock tick counter.
304+ /// A display clock tick, in seconds, is equal to num_units_in_display_tick
305+ /// divided by time_scale:
306+ pub num_units_in_display_tick: u32,
307+ /// The number of time units that pass in one second.
308+ pub time_scale: u32,
309+ /// If set, indicates that pictures should be displayed according to their
310+ /// output order with the number of ticks between two consecutive pictures
311+ /// (without dropping frames) specified by num_ticks_per_picture_minus_1 +
312+ /// 1. If not set, indicates that the interval between two consecutive
313+ /// pictures is not specified.
314+ pub equal_picture_interval: bool,
315+ /// Plus 1 specifies the number of clock ticks corresponding to output time
316+ /// between two consecutive pictures in the output order.
317+ pub num_ticks_per_picture_minus_1: u32,
318+}
319+
320+#[derive(Clone, Debug, Default, PartialEq, Eq)]
321+pub struct DecoderModelInfo {
322+ /// Plus 1 specifies the length of the decoder_buffer_delay and the
323+ /// encoder_buffer_delay syntax elements, in bits.
324+ pub buffer_delay_length_minus_1: u8,
325+ /// The number of time units of a decoding clock operating at the frequency
326+ /// time_scale Hz that corresponds to one increment of a clock tick counter:
327+ pub num_units_in_decoding_tick: u32,
328+ /// Plus 1 specifies the length of the buffer_removal_time syntax element,
329+ /// in bits.
330+ pub buffer_removal_time_length_minus_1: u8,
331+ /// Plus 1 specifies the length of the frame_presentation_time syntax
332+ /// element, in bits.
333+ pub frame_presentation_time_length_minus_1: u32,
334+}
335+
336+/// Defined by the “Color primaries” section of ISO/IEC 23091-4/ITU-T H.273
337+/// See 6.4.2
338+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord)]
339+pub enum ColorPrimaries {
340+ Bt709 = 1,
341+ #[default]
342+ Unspecified = 2,
343+ Bt470M = 4,
344+ Bt470bg = 5,
345+ Bt601 = 6,
346+ Smpte240 = 7,
347+ GenericFilm = 8,
348+ Bt2020 = 9,
349+ Xyz = 10,
350+ Smpte431 = 11,
351+ Smpte432 = 12,
352+ Ebu3213 = 22,
353+}
354+
355+impl TryFrom<u32> for ColorPrimaries {
356+ type Error = String;
357+
358+ fn try_from(value: u32) -> Result<Self, Self::Error> {
359+ match value {
360+ 1 => Ok(ColorPrimaries::Bt709),
361+ 2 => Ok(ColorPrimaries::Unspecified),
362+ 4 => Ok(ColorPrimaries::Bt470M),
363+ 5 => Ok(ColorPrimaries::Bt470bg),
364+ 6 => Ok(ColorPrimaries::Bt601),
365+ 7 => Ok(ColorPrimaries::Smpte240),
366+ 8 => Ok(ColorPrimaries::GenericFilm),
367+ 9 => Ok(ColorPrimaries::Bt2020),
368+ 10 => Ok(ColorPrimaries::Xyz),
369+ 11 => Ok(ColorPrimaries::Smpte431),
370+ 12 => Ok(ColorPrimaries::Smpte432),
371+ 22 => Ok(ColorPrimaries::Ebu3213),
372+ _ => Err(format!("Invalid ColorPrimaries {}", value)),
373+ }
374+ }
375+}
376+
377+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord)]
378+pub enum TransferCharacteristics {
379+ Reserved0 = 0,
380+ Bt709 = 1,
381+ #[default]
382+ Unspecified = 2,
383+ Reserved3 = 3,
384+ Bt470m = 4,
385+ Bt470bg = 5,
386+ Bt601 = 6,
387+ Smpte240 = 7,
388+ Linear = 8,
389+ Log100 = 9,
390+ Log100Sqrt10 = 10,
391+ Iec61966 = 11,
392+ Bt1361 = 12,
393+ Srgb = 13,
394+ Bt202010Bit = 14,
395+ Bt202012Bit = 15,
396+ Smpte2084 = 16,
397+ Smpte428 = 17,
398+ Hlg = 18,
399+}
400+
401+impl TryFrom<u32> for TransferCharacteristics {
402+ type Error = String;
403+
404+ fn try_from(value: u32) -> Result<Self, Self::Error> {
405+ match value {
406+ 0 => Ok(TransferCharacteristics::Reserved0),
407+ 1 => Ok(TransferCharacteristics::Bt709),
408+ 2 => Ok(TransferCharacteristics::Unspecified),
409+ 3 => Ok(TransferCharacteristics::Reserved3),
410+ 4 => Ok(TransferCharacteristics::Bt470m),
411+ 5 => Ok(TransferCharacteristics::Bt470bg),
412+ 6 => Ok(TransferCharacteristics::Bt601),
413+ 7 => Ok(TransferCharacteristics::Smpte240),
414+ 8 => Ok(TransferCharacteristics::Linear),
415+ 9 => Ok(TransferCharacteristics::Log100),
416+ 10 => Ok(TransferCharacteristics::Log100Sqrt10),
417+ 11 => Ok(TransferCharacteristics::Iec61966),
418+ 12 => Ok(TransferCharacteristics::Bt1361),
419+ 13 => Ok(TransferCharacteristics::Srgb),
420+ 14 => Ok(TransferCharacteristics::Bt202010Bit),
421+ 15 => Ok(TransferCharacteristics::Bt202012Bit),
422+ 16 => Ok(TransferCharacteristics::Smpte2084),
423+ 17 => Ok(TransferCharacteristics::Smpte428),
424+ 18 => Ok(TransferCharacteristics::Hlg),
425+ _ => Err(format!("Invalid TransferCharacteristics {}", value)),
426+ }
427+ }
428+}
429+
430+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord)]
431+pub enum BitDepth {
432+ #[default]
433+ Depth8 = 0,
434+ Depth10 = 1,
435+ Depth12 = 2,
436+}
437+
438+impl TryFrom<u32> for BitDepth {
439+ type Error = String;
440+
441+ fn try_from(value: u32) -> Result<Self, Self::Error> {
442+ match value {
443+ 0 => Ok(BitDepth::Depth8),
444+ 1 => Ok(BitDepth::Depth10),
445+ 2 => Ok(BitDepth::Depth12),
446+ _ => Err(format!("Invalid BitDepth {}", value)),
447+ }
448+ }
449+}
450+
451+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord)]
452+pub enum MatrixCoefficients {
453+ Identity = 0,
454+ Bt709 = 1,
455+ #[default]
456+ Unspecified = 2,
457+ Reserved3 = 3,
458+ Fcc = 4,
459+ Bt470bg = 5,
460+ Bt601 = 6,
461+ Smpte240 = 7,
462+ Ycgco = 8,
463+ Bt2020Ncl = 9,
464+ Bt2020Cl = 10,
465+ Smpte2085 = 11,
466+ ChromaDerivedNcl = 12,
467+ ChromaDerivedCl = 13,
468+ Ictcp = 14,
469+}
470+
471+impl TryFrom<u32> for MatrixCoefficients {
472+ type Error = String;
473+
474+ fn try_from(value: u32) -> Result<Self, Self::Error> {
475+ match value {
476+ 0 => Ok(MatrixCoefficients::Identity),
477+ 1 => Ok(MatrixCoefficients::Bt709),
478+ 2 => Ok(MatrixCoefficients::Unspecified),
479+ 3 => Ok(MatrixCoefficients::Reserved3),
480+ 4 => Ok(MatrixCoefficients::Fcc),
481+ 5 => Ok(MatrixCoefficients::Bt470bg),
482+ 6 => Ok(MatrixCoefficients::Bt601),
483+ 7 => Ok(MatrixCoefficients::Smpte240),
484+ 8 => Ok(MatrixCoefficients::Ycgco),
485+ 9 => Ok(MatrixCoefficients::Bt2020Ncl),
486+ 10 => Ok(MatrixCoefficients::Bt2020Cl),
487+ 11 => Ok(MatrixCoefficients::Smpte2085),
488+ 12 => Ok(MatrixCoefficients::ChromaDerivedNcl),
489+ 13 => Ok(MatrixCoefficients::ChromaDerivedCl),
490+ 14 => Ok(MatrixCoefficients::Ictcp),
491+ _ => Err(format!("Invalid MatrixCoefficients {}", value)),
492+ }
493+ }
494+}
495+
496+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord)]
497+pub enum ChromaSamplePosition {
498+ #[default]
499+ Unknown = 0,
500+ Vertical = 1,
501+ Colocated = 2,
502+ Reserved = 3,
503+}
504+
505+impl TryFrom<u32> for ChromaSamplePosition {
506+ type Error = String;
507+
508+ fn try_from(value: u32) -> Result<Self, Self::Error> {
509+ match value {
510+ 0 => Ok(ChromaSamplePosition::Unknown),
511+ 1 => Ok(ChromaSamplePosition::Vertical),
512+ 2 => Ok(ChromaSamplePosition::Colocated),
513+ 3 => Ok(ChromaSamplePosition::Reserved),
514+ _ => Err(format!("Invalid ChromaSamplePosition {}", value)),
515+ }
516+ }
517+}
518+
519+#[derive(Clone, Debug, Default, PartialEq, Eq)]
520+pub struct ColorConfig {
521+ /// Syntax elements which, together with seq_profile, determine the bit
522+ /// depth.
523+ pub high_bitdepth: bool,
524+ /// Syntax elements which, together with seq_profile, determine the bit
525+ /// depth.
526+ pub twelve_bit: bool,
527+ /// If set, indicates that the video does not contain U and V color planes.
528+ /// If not set, indicates that the video contains Y, U, and V color planes.
529+ pub mono_chrome: bool,
530+ /// If set, specifies that color_primaries, transfer_characteristics, and
531+ /// matrix_coefficients are present. If not set, specifies that
532+ /// color_primaries, transfer_characteristics and matrix_coefficients are
533+ /// not present.
534+ pub color_description_present_flag: bool,
535+ /// Defined by the “Color primaries” section of ISO/IEC 23091-4/ITU-T H.273.
536+ pub color_primaries: ColorPrimaries,
537+ /// Defined by the “Transfer characteristics” section of ISO/IEC
538+ /// 23091-4/ITU-T H.273.
539+ pub transfer_characteristics: TransferCharacteristics,
540+ /// Defined by the “Matrix coefficients” section of ISO/IEC 23091-4/ITU-T
541+ /// H.273.
542+ pub matrix_coefficients: MatrixCoefficients,
543+ /// Binary value that is associated with the VideoFullRangeFlag variable
544+ /// specified in ISO/IEC 23091-4/ITU- T H.273. color range equal to 0 shall
545+ /// be referred to as the studio swing representation and color range equal
546+ /// to 1 shall be referred to as the full swing representation for all
547+ /// intents relating to this specification.
548+ pub color_range: bool,
549+ /// Specify the chroma subsampling format
550+ pub subsampling_x: bool,
551+ /// Specify the chroma subsampling format
552+ pub subsampling_y: bool,
553+ /// Specifies the sample position for subsampled streams
554+ pub chroma_sample_position: ChromaSamplePosition,
555+ /// If set, indicates that the U and V planes may have separate delta
556+ /// quantizer values. If not set, indicates that the U and V planes will
557+ /// share the same delta quantizer value.
558+ pub separate_uv_delta_q: bool,
559+}
560+
561+#[derive(Clone, Debug, Default, PartialEq, Eq)]
562+pub struct SequenceHeaderObu {
563+ /// The OBU header from the OBU that generated this sequence.
564+ pub obu_header: ObuHeader,
565+ /// Specifies the features that can be used in the coded video sequence.
566+ pub seq_profile: Profile,
567+ /// If set, specifies that the coded video sequence contains only one coded
568+ /// frame. If not set, specifies that the coded video sequence contains one
569+ /// or more coded frames.
570+ pub still_picture: bool,
571+ /// Specifies that the syntax elements not needed by a still picture are
572+ /// omitted.
573+ pub reduced_still_picture_header: bool,
574+ /// Specifies the number of bits minus 1 used for transmitting the frame
575+ /// width syntax elements.
576+ pub frame_width_bits_minus_1: u8,
577+ /// Specifies the number of bits minus 1 used for transmitting the frame
578+ /// height syntax elements.
579+ pub frame_height_bits_minus_1: u8,
580+ /// Specifies the maximum frame width minus 1 for the frames represented by
581+ /// this sequence header.
582+ pub max_frame_width_minus_1: u16,
583+ /// Specifies the maximum frame height minus 1 for the frames represented by
584+ /// this sequence header.
585+ pub max_frame_height_minus_1: u16,
586+ /// Specifies whether frame id numbers are present in the coded video
587+ /// sequence.
588+ pub frame_id_numbers_present_flag: bool,
589+ /// Specifies the number of bits minus 2 used to encode delta_frame_id
590+ /// syntax elements.
591+ pub delta_frame_id_length_minus_2: u32,
592+ /// Used to calculate the number of bits used to encode the frame_id syntax
593+ /// element.
594+ pub additional_frame_id_length_minus_1: u32,
595+ /// When set, indicates that superblocks contain 128x128 luma samples. When
596+ /// not set, it indicates that superblocks contain 64x64 luma samples. (The
597+ /// number of contained chroma samples depends on subsampling_x and
598+ /// subsampling_y.)
599+ pub use_128x128_superblock: bool,
600+ /// When set, specifies that the use_filter_intra syntax element may be
601+ /// present. When not set, specifies that the use_filter_intra syntax
602+ /// element will not be present.
603+ pub enable_filter_intra: bool,
604+ /// Specifies whether the intra edge filtering process should be enabled.
605+ pub enable_intra_edge_filter: bool,
606+ /// When set, specifies that the mode info for inter blocks may contain the
607+ /// syntax element interintra. If not set, specifies that the syntax element
608+ /// interintra will not be present.
609+ pub enable_interintra_compound: bool,
610+ /// When set, specifies that the mode info for inter blocks may contain the
611+ /// syntax element compound_type. When not set, specifies that the syntax
612+ /// element compound_type will not be present.
613+ pub enable_masked_compound: bool,
614+ /// When set, indicates that the allow_warped_motion syntax element may be
615+ /// present. When not set, indicates that the allow_warped_motion syntax
616+ /// element will not be present.
617+ pub enable_warped_motion: bool,
618+ /// When set, indicates that tools based on the values of order hints may be
619+ /// used. When not set, indicates that tools based on order hints are
620+ /// disabled.
621+ pub enable_order_hint: bool,
622+ /// When set, indicates that the inter prediction filter type may be
623+ /// specified independently in the horizontal and vertical directions. If
624+ /// the flag is not set, only one filter type may be specified, which is
625+ /// then used in both directions.
626+ pub enable_dual_filter: bool,
627+ /// If set, indicates that the distance weights process may be used for
628+ /// inter prediction.
629+ pub enable_jnt_comp: bool,
630+ /// If set, indicates that the use_ref_frame_mvs syntax element may be
631+ /// present. If not set, indicates that the use_ref_frame_mvs syntax element
632+ /// will not be present.
633+ pub enable_ref_frame_mvs: bool,
634+ /// If not set, indicates that the seq_force_screen_content_tools syntax
635+ /// element will be present. If set, indicates that
636+ /// seq_force_screen_content_tools should be set equal to
637+ /// SELECT_SCREEN_CONTENT_TOOLS.
638+ pub seq_choose_screen_content_tools: bool,
639+ /// Equal to SELECT_SCREEN_CONTENT_TOOLS indicates that the
640+ /// allow_screen_content_tools syntax element will be present in the frame
641+ /// header. Otherwise, seq_force_screen_content_tools contains the value for
642+ /// allow_screen_content_tools.
643+ pub seq_force_screen_content_tools: u32,
644+ /// If not set, indicates that the seq_force_integer_mv syntax element will
645+ /// be present. If set, indicates that seq_force_integer_mv should be set
646+ /// equal to SELECT_INTEGER_MV.
647+ pub seq_choose_integer_mv: bool,
648+ /// Equal to SELECT_INTEGER_MV indicates that the force_integer_mv syntax
649+ /// element will be present in the frame header (providing
650+ /// allow_screen_content_tools is equal to 1). Otherwise,
651+ /// seq_force_integer_mv contains the value for force_integer_mv.
652+ pub seq_force_integer_mv: u32,
653+ /// Used to compute OrderHintBits.
654+ pub order_hint_bits_minus_1: i32,
655+ /// Specifies the number of bits used for the order_hint syntax element.
656+ pub order_hint_bits: i32,
657+ /// If set, specifies that the use_superres syntax element will be present
658+ /// in the uncompressed header. If not set, specifies that the use_superres
659+ /// syntax element will not be present (instead use_superres will be set to
660+ /// 0 in the uncompressed header without being read).
661+ pub enable_superres: bool,
662+ /// If set, specifies that cdef filtering may be enabled. If not set,
663+ /// specifies that cdef filtering is disabled.
664+ pub enable_cdef: bool,
665+ /// If set, specifies that loop restoration filtering may be enabled. If
666+ /// not set, specifies that loop restoration filtering is disabled.
667+ pub enable_restoration: bool,
668+ /// Specifies whether film grain parameters are present in the coded video
669+ /// sequence.
670+ pub film_grain_params_present: bool,
671+ /// Indicates the number of operating points minus 1 present in the coded
672+ /// video sequence. An operating point specifies which spatial and temporal
673+ /// layers should be decoded.
674+ pub operating_points_cnt_minus_1: u32,
675+ /// The set of operating points.
676+ pub operating_points: [OperatingPoint; MAX_NUM_OPERATING_POINTS],
677+ /// Specifies whether decoder model information is present in the coded
678+ /// video sequence.
679+ pub decoder_model_info_present_flag: bool,
680+ /// The decoder model info.
681+ pub decoder_model_info: DecoderModelInfo,
682+ /// Specifies whether initial display delay information is present in the
683+ /// coded video sequence.
684+ pub initial_display_delay_present_flag: bool,
685+ /// Specifies whether timing info is present in the coded video sequence.
686+ pub timing_info_present_flag: bool,
687+ /// The timing info.
688+ pub timing_info: TimingInfo,
689+ /// The color config.
690+ pub color_config: ColorConfig,
691+
692+ /* CamelCase variables in the specification */
693+ pub bit_depth: BitDepth,
694+ pub num_planes: u32,
695+}
696+
697+#[derive(Clone, Debug, Default, PartialEq, Eq)]
698+pub struct StreamInfo {
699+ pub seq_header: Rc<SequenceHeaderObu>,
700+ pub render_width: u32,
701+ pub render_height: u32,
702+}
703+
704+/// A TemporalDelimiterOBU
705+#[derive(Clone, Debug, Default, PartialEq, Eq)]
706+pub struct TemporalDelimiterObu {
707+ pub obu_header: ObuHeader,
708+}
709+
710+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord)]
711+pub enum InterpolationFilter {
712+ #[default]
713+ EightTap = 0,
714+ EightTapSmooth = 1,
715+ EightTapSharp = 2,
716+ Bilinear = 3,
717+ Switchable = 4,
718+}
719+
720+impl TryFrom<u32> for InterpolationFilter {
721+ type Error = String;
722+
723+ fn try_from(value: u32) -> Result<Self, Self::Error> {
724+ match value {
725+ 0 => Ok(InterpolationFilter::EightTap),
726+ 1 => Ok(InterpolationFilter::EightTapSmooth),
727+ 2 => Ok(InterpolationFilter::EightTapSharp),
728+ 3 => Ok(InterpolationFilter::Bilinear),
729+ 4 => Ok(InterpolationFilter::Switchable),
730+ _ => Err(format!("Invalid InterpolationFilter {}", value)),
731+ }
732+ }
733+}
734+
735+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord)]
736+pub enum TxModes {
737+ #[default]
738+ Only4x4 = 0,
739+ Largest = 1,
740+ Select = 2,
741+}
742+
743+impl TryFrom<u32> for TxModes {
744+ type Error = String;
745+
746+ fn try_from(value: u32) -> Result<Self, Self::Error> {
747+ match value {
748+ 0 => Ok(TxModes::Only4x4),
749+ 1 => Ok(TxModes::Largest),
750+ 2 => Ok(TxModes::Select),
751+ _ => Err(format!("Invalid TxModes {}", value)),
752+ }
753+ }
754+}
755+
756+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord)]
757+pub enum FrameRestorationType {
758+ #[default]
759+ None = 0,
760+ Wiener = 1,
761+ Sgrproj = 2,
762+ Switchable = 3,
763+}
764+
765+impl TryFrom<u32> for FrameRestorationType {
766+ type Error = String;
767+
768+ fn try_from(value: u32) -> Result<Self, Self::Error> {
769+ match value {
770+ 0 => Ok(FrameRestorationType::None),
771+ 1 => Ok(FrameRestorationType::Wiener),
772+ 2 => Ok(FrameRestorationType::Sgrproj),
773+ 3 => Ok(FrameRestorationType::Switchable),
774+ _ => Err(format!("Invalid FrameRestorationType {}", value)),
775+ }
776+ }
777+}
778+
779+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord)]
780+pub enum ReferenceFrameType {
781+ #[default]
782+ Intra = 0,
783+ Last = 1,
784+ Last2 = 2,
785+ Last3 = 3,
786+ Golden = 4,
787+ BwdRef = 5,
788+ AltRef2 = 6,
789+ AltRef = 7,
790+}
791+
792+impl TryFrom<u32> for ReferenceFrameType {
793+ type Error = String;
794+
795+ fn try_from(value: u32) -> Result<Self, Self::Error> {
796+ match value {
797+ 0 => Ok(ReferenceFrameType::Intra),
798+ 1 => Ok(ReferenceFrameType::Last),
799+ 2 => Ok(ReferenceFrameType::Last2),
800+ 3 => Ok(ReferenceFrameType::Last3),
801+ 4 => Ok(ReferenceFrameType::Golden),
802+ 5 => Ok(ReferenceFrameType::BwdRef),
803+ 6 => Ok(ReferenceFrameType::AltRef2),
804+ 7 => Ok(ReferenceFrameType::AltRef),
805+ _ => Err(format!("Invalid ReferenceFrameType {}", value)),
806+ }
807+ }
808+}
809+
810+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord)]
811+pub enum WarpModelType {
812+ #[default]
813+ Identity = 0,
814+ Translation = 1,
815+ RotZoom = 2,
816+ Affine = 3,
817+}
818+
819+impl TryFrom<u32> for WarpModelType {
820+ type Error = String;
821+
822+ fn try_from(value: u32) -> Result<Self, Self::Error> {
823+ match value {
824+ 0 => Ok(WarpModelType::Identity),
825+ 1 => Ok(WarpModelType::Translation),
826+ 2 => Ok(WarpModelType::RotZoom),
827+ 3 => Ok(WarpModelType::Affine),
828+ _ => Err(format!("Invalid WarpModelType {}", value)),
829+ }
830+ }
831+}
832+
833+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord)]
834+pub enum FrameType {
835+ #[default]
836+ KeyFrame = 0,
837+ InterFrame = 1,
838+ IntraOnlyFrame = 2,
839+ SwitchFrame = 3,
840+}
841+
842+impl TryFrom<u32> for FrameType {
843+ type Error = String;
844+
845+ fn try_from(value: u32) -> Result<Self, Self::Error> {
846+ match value {
847+ 0 => Ok(FrameType::KeyFrame),
848+ 1 => Ok(FrameType::InterFrame),
849+ 2 => Ok(FrameType::IntraOnlyFrame),
850+ 3 => Ok(FrameType::SwitchFrame),
851+ _ => Err(format!("Invalid FrameType {}", value)),
852+ }
853+ }
854+}
855+
856+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord)]
857+pub enum TxMode {
858+ #[default]
859+ Only4x4 = 0,
860+ Largest = 1,
861+ Select = 2,
862+}
863+
864+impl TryFrom<u32> for TxMode {
865+ type Error = String;
866+
867+ fn try_from(value: u32) -> Result<Self, Self::Error> {
868+ match value {
869+ 0 => Ok(TxMode::Only4x4),
870+ 1 => Ok(TxMode::Largest),
871+ 2 => Ok(TxMode::Select),
872+ _ => Err(format!("Invalid TxMode {}", value)),
873+ }
874+ }
875+}
876+
877+#[derive(Clone, Debug, Default, PartialEq, Eq)]
878+pub struct FrameObu<'a> {
879+ pub header: FrameHeaderObu,
880+ pub tile_group: TileGroupObu<'a>,
881+}
882+
883+/// A FrameHeaderOBU
884+#[derive(Clone, Debug, Default, PartialEq, Eq)]
885+pub struct FrameHeaderObu {
886+ /// The original OBU header. This may be from a FrameOBU or a FrameHeaderOBU
887+ /// directly.
888+ pub obu_header: ObuHeader,
889+ /// If set, indicates the frame indexed by frame_to_show_map_idx is to be
890+ /// output; If not set, indicates that further processing is required.
891+ pub show_existing_frame: bool,
892+ /// Specifies the frame to be output. It is only available if
893+ /// show_existing_frame is set.
894+ pub frame_to_show_map_idx: u8,
895+ /// Specifies the length of the frame_presentation_time syntax element, in
896+ /// bits.
897+ pub frame_presentation_time: u32,
898+ /// Provides the frame id number for the frame to output.
899+ pub display_frame_id: u32,
900+ /// Specifies the type of the frame
901+ pub frame_type: FrameType,
902+ /// If set, specifies that this frame should be immediately output once
903+ /// decoded. If not set specifies that this frame should not be
904+ /// immediately output. (It may be output later if a later uncompressed
905+ /// header uses show_existing_frame is set).
906+ pub show_frame: bool,
907+ /// When set, specifies that the frame may be output using the
908+ /// show_existing_frame mechanism. When not set, specifies that this frame
909+ /// will not be output using the show_existing_frame mechanism.
910+ pub showable_frame: bool,
911+ /// If set, indicates that error resilient mode is enabled;
912+ /// error_resilient_mode equal to 0 indicates that error resilient mode is
913+ /// disabled.
914+ pub error_resilient_mode: bool,
915+ /// Specifies whether the CDF update in the symbol decoding process should
916+ /// be disabled.
917+ pub disable_cdf_update: bool,
918+ /// When set, indicates that intra blocks may use palette encoding; When not
919+ /// set, indicates that palette encoding is never used.
920+ pub allow_screen_content_tools: u32,
921+ /// If set, specifies that motion vectors will always be integers. If not
922+ /// set, specifies that motion vectors can contain fractional bits.
923+ pub force_integer_mv: u32,
924+ /// Specifies the frame id number for the current frame. Frame id numbers
925+ /// are additional information that do not affect the decoding process, but
926+ /// provide decoders with a way of detecting missing reference frames so
927+ /// that appropriate action can be taken.
928+ pub current_frame_id: u32,
929+ /// If not set, specifies that the frame size is equal to the size in the
930+ /// sequence header. If set, specifies that the frame size will either be
931+ /// specified as the size of one of the reference frames, or computed from
932+ /// the frame_width_minus_1 and frame_height_minus_1 syntax elements.
933+ pub frame_size_override_flag: bool,
934+ /// Specifies OrderHintBits least significant bits of the expected output
935+ /// order for this frame.
936+ pub order_hint: u32,
937+ /// Specifies which reference frame contains the CDF values and other state
938+ /// that should be loaded at the start of the frame.
939+ pub primary_ref_frame: u32,
940+ /// If set, specifies that buffer_removal_time is present. If not set,
941+ /// specifies that buffer_removal_time is not present.
942+ pub buffer_removal_time_present_flag: bool,
943+ /// Specifies the frame removal time in units of DecCT clock ticks counted
944+ /// from the removal time of the last random access point for operating
945+ /// point opNum. buffer_removal_time is signaled as a fixed length unsigned
946+ /// integer with a length in bits given by
947+ /// buffer_removal_time_length_minus_1 + 1.
948+ pub buffer_removal_time: Vec<u32>,
949+ /// Contains a bitmask that specifies which reference frame slots will be
950+ /// updated with the current frame after it is decoded.
951+ pub refresh_frame_flags: u32,
952+ /// Specifies the expected output order hint for each reference frame.
953+ pub ref_order_hint: [u32; NUM_REF_FRAMES],
954+ /// If set, indicates that intra block copy may be used in this frame. If
955+ /// not set indicates that intra block copy is not allowed in this frame.
956+ pub allow_intrabc: bool,
957+ /// If set, indicates that only two reference frames are explicitly
958+ /// signaled. If not set, indicates that all reference frames are explicitly
959+ /// signaled.
960+ pub frame_refs_short_signaling: bool,
961+ /// Specifies the reference frame to use for LAST_FRAME.
962+ pub last_frame_idx: u8,
963+ /// Specifies the reference frame to use for GOLDEN_FRAME.
964+ pub gold_frame_idx: u8,
965+ /// Specifies which reference frames are used by inter frames
966+ pub ref_frame_idx: [u8; REFS_PER_FRAME],
967+ /// If not set, specifies that motion vectors are specified to quarter pel
968+ /// precision; If set, specifies that motion vectors are specified to eighth
969+ /// pel precision.
970+ pub allow_high_precision_mv: bool,
971+ /// If not set, specifies that only the SIMPLE motion mode will be used.
972+ pub is_motion_mode_switchable: bool,
973+ /// If set, specifies that motion vector information from a previous frame
974+ /// can be used when decoding the current frame. If not set, specifies that
975+ /// this information will not be used.
976+ pub use_ref_frame_mvs: bool,
977+ /// If set, indicates that the end of frame CDF update is disabled; If not
978+ /// set, indicates that the end of frame CDF update is enabled.
979+ pub disable_frame_end_update_cdf: bool,
980+ /// If set, indicates that the syntax element motion_mode may be present.
981+ /// If not set, indicates that the syntax element motion_mode will not be
982+ /// present
983+ pub allow_warped_motion: bool,
984+ /// If set, specifies that the frame is restricted to a reduced subset of
985+ /// the full set of transform types.
986+ pub reduced_tx_set: bool,
987+ /// If not set, means that the render width and height are inferred from the
988+ /// frame width and height. If set, means that the render width and height
989+ /// are explicitly coded.
990+ pub render_and_frame_size_different: bool,
991+ /// If not set, indicates that no upscaling is needed. If set, indicates
992+ /// that upscaling is needed.
993+ pub use_superres: bool,
994+ /// If set indicates that the filter selection is signaled at the block
995+ /// level; If not set, indicates that the filter selection is signaled at
996+ /// the frame level.
997+ pub is_filter_switchable: bool,
998+ /// The interpolation filter parameters.
999+ pub interpolation_filter: InterpolationFilter,
1000+ /// The loop filter parameters.
1001+ pub loop_filter_params: LoopFilterParams,
1002+ /// The quantization parameters.
1003+ pub quantization_params: QuantizationParams,
1004+ /// The segmentation parameters.
1005+ pub segmentation_params: SegmentationParams,
1006+ /// The tile info.
1007+ pub tile_info: TileInfo,
1008+ /// The CDEF parameters.
1009+ pub cdef_params: CdefParams,
1010+ /// The loop restoration parameters.
1011+ pub loop_restoration_params: LoopRestorationParams,
1012+ /// Used to compute TxMode.
1013+ pub tx_mode_select: u32,
1014+ /// If set specifies that the syntax element skip_mode will be present. If
1015+ /// not set, specifies that skip_mode will not be used for this frame.
1016+ pub skip_mode_present: bool,
1017+ /// If set, specifies that the mode info for inter blocks contains the
1018+ /// syntax element comp_mode that indicates whether to use single or
1019+ /// compound reference prediction. If not set, specifies that all inter
1020+ /// blocks will use single prediction.
1021+ pub reference_select: bool,
1022+ /// The global motion parameters.
1023+ pub global_motion_params: GlobalMotionParams,
1024+ /// The film grain parameters.
1025+ pub film_grain_params: FilmGrainParams,
1026+
1027+ /* CamelCase variables */
1028+ pub superres_denom: u32,
1029+ pub frame_is_intra: bool,
1030+ pub order_hints: [u32; NUM_REF_FRAMES],
1031+ pub ref_frame_sign_bias: [bool; NUM_REF_FRAMES],
1032+ pub coded_lossless: bool,
1033+ pub all_lossless: bool,
1034+ pub lossless_array: [bool; MAX_SEGMENTS],
1035+ pub seg_qm_level: [[u32; MAX_SEGMENTS]; 3],
1036+ pub upscaled_width: u32,
1037+ pub frame_width: u32,
1038+ pub frame_height: u32,
1039+ pub render_width: u32,
1040+ pub render_height: u32,
1041+ pub tx_mode: TxMode,
1042+ pub skip_mode_frame: [u32; 2],
1043+ pub mi_cols: u32,
1044+ pub mi_rows: u32,
1045+ pub header_bytes: usize,
1046+}
1047+
1048+#[derive(Clone, Debug, Default, PartialEq, Eq)]
1049+pub struct LoopFilterParams {
1050+ /// An array containing loop filter strength values. Different loop filter
1051+ /// strength values from the array are used depending on the image plane
1052+ /// being filtered, and the edge direction (vertical or horizontal) being
1053+ /// filtered.
1054+ pub loop_filter_level: [u8; 4],
1055+ /// Indicates the sharpness level. The loop_filter_level and
1056+ /// loop_filter_sharpness together determine when a block edge is filtered,
1057+ /// and by how much the filtering can change the sample values.
1058+ pub loop_filter_sharpness: u8,
1059+ /// If set, means that the filter level depends on the mode and reference
1060+ /// frame used to predict a block. If not set, means that the filter level
1061+ /// does not depend on the mode and reference frame.
1062+ pub loop_filter_delta_enabled: bool,
1063+ /// If set, means that additional syntax elements are present that specify
1064+ /// which mode and reference frame deltas are to be updated.
1065+ /// loop_filter_delta_update equal to 0 means that these syntax elements are
1066+ /// not present.
1067+ pub loop_filter_delta_update: bool,
1068+ /// Contains the adjustment needed for the filter level based on the chosen
1069+ /// reference frame. If this syntax element is not present, it maintains
1070+ /// its previous value.
1071+ pub loop_filter_ref_deltas: [i8; TOTAL_REFS_PER_FRAME],
1072+ /// Contains the adjustment needed for the filter level based on the chosen
1073+ /// mode. If this syntax element is not present in the, it maintains its
1074+ /// previous value.
1075+ pub loop_filter_mode_deltas: [i8; 2],
1076+ /// Specifies whether loop filter delta values are present.
1077+ pub delta_lf_present: bool,
1078+ /// Specifies the left shift which should be applied to decoded loop filter
1079+ /// delta values.
1080+ pub delta_lf_res: u8,
1081+ /// If set, specifies that separate loop filter deltas are sent for
1082+ /// horizontal luma edges, vertical luma edges, the U edges, and the V
1083+ /// edges. If not set, specifies that the same loop filter delta is used for
1084+ /// all edges.
1085+ pub delta_lf_multi: bool,
1086+}
1087+
1088+#[derive(Clone, Debug, Default, PartialEq, Eq)]
1089+pub struct QuantizationParams {
1090+ /// Indicates the base frame qindex. This is used for Y AC coefficients and
1091+ /// as the base value for the other quantizers.
1092+ pub base_q_idx: u32,
1093+ /// Indicates the base frame qindex. This is used for Y AC coefficients and
1094+ /// as the base value for the other quantizers.
1095+ pub diff_uv_delta: bool,
1096+ /// Specifies that the quantizer matrix will be used to compute quantizers.
1097+ pub using_qmatrix: bool,
1098+ /// Specifies the level in the quantizer matrix that should be used for luma
1099+ /// plane decoding.
1100+ pub qm_y: u32,
1101+ /// Specifies the level in the quantizer matrix that should be used for
1102+ /// chroma U plane decoding.
1103+ pub qm_u: u32,
1104+ /// Specifies the level in the quantizer matrix that should be used for
1105+ /// chroma V plane decoding.
1106+ pub qm_v: u32,
1107+ /// Specifies whether quantizer index delta values are present.
1108+ pub delta_q_present: bool,
1109+ /// Specifies the left shift which should be applied to decoded quantizer
1110+ /// index delta values.
1111+ pub delta_q_res: u32,
1112+ /// Same as DeltaQYDc
1113+ pub delta_q_y_dc: i32,
1114+ /// Same as DeltaQUDc
1115+ pub delta_q_u_dc: i32,
1116+ /// Same as DeltaQUAc
1117+ pub delta_q_u_ac: i32,
1118+ /// Same as DeltaQVDc
1119+ pub delta_q_v_dc: i32,
1120+ /// Same as DeltaQVAc
1121+ pub delta_q_v_ac: i32,
1122+}
1123+
1124+#[derive(Clone, Debug, Default, PartialEq, Eq)]
1125+pub struct SegmentationParams {
1126+ /// If set, indicates that this frame makes use of the segmentation tool; If
1127+ /// not set, indicates that the frame does not use segmentation.
1128+ pub segmentation_enabled: bool,
1129+ /// If set, indicates that the segmentation map are updated during the
1130+ /// decoding of this frame. If not set, means that the segmentation map from
1131+ /// the previous frame is used.
1132+ pub segmentation_update_map: bool,
1133+ /// If set, indicates that the updates to the segmentation map are coded
1134+ /// relative to the existing segmentation map. If not set, indicates that
1135+ /// the new segmentation map is coded without reference to the existing
1136+ /// segmentation map.
1137+ pub segmentation_temporal_update: bool,
1138+ /// If set, indicates that new parameters are about to be specified for each
1139+ /// segment. If not set, indicates that the segmentation parameters should
1140+ /// keep their existing values.
1141+ pub segmentation_update_data: bool,
1142+ /// If not set, indicates that the corresponding feature is unused and has
1143+ /// value equal to 0. If set, indicates that the feature value is coded.
1144+ pub feature_enabled: [[bool; SEG_LVL_MAX]; MAX_SEGMENTS],
1145+ /// Specifies the feature data for a segment feature.
1146+ pub feature_data: [[i16; SEG_LVL_MAX]; MAX_SEGMENTS],
1147+ /// Same as SegIdPreSkip
1148+ pub seg_id_pre_skip: bool,
1149+ /// Same as LastActiveSegId
1150+ pub last_active_seg_id: u8,
1151+}
1152+
1153+#[derive(Clone, Debug, PartialEq, Eq)]
1154+pub struct TileInfo {
1155+ /// If set, means that the tiles are uniformly spaced across the frame. (In
1156+ /// other words, all tiles are the same size except for the ones at the
1157+ /// right and bottom edge which can be smaller.) If not set, means that the
1158+ /// tile sizes are coded.
1159+ pub uniform_tile_spacing_flag: bool,
1160+ /// Used to compute TileColsLog2.
1161+ pub increment_tile_rows_log2: u32,
1162+ /// Specifies the width of a tile minus 1 in units of superblocks.
1163+ pub width_in_sbs_minus_1: [u32; MAX_TILE_COLS],
1164+ /// Specifies the height of a tile minus 1 in units of superblocks.
1165+ pub height_in_sbs_minus_1: [u32; MAX_TILE_ROWS],
1166+ /// Specifies which tile to use for the CDF update
1167+ pub context_update_tile_id: u32,
1168+ /// An array specifying the start column (in units of 4x4 luma samples) for
1169+ /// each tile across the image.
1170+ pub mi_col_starts: [u32; MAX_TILE_COLS + 1],
1171+ /// An array specifying the start row (in units of 4x4 luma samples) for
1172+ /// each tile down the image.
1173+ pub mi_row_starts: [u32; MAX_TILE_ROWS + 1],
1174+ /// Specifies the base 2 logarithm of the desired number of tiles down the
1175+ /// frame.
1176+ pub tile_cols_log2: u32,
1177+ /// Specifies the number of tiles across the frame.
1178+ pub tile_cols: u32,
1179+ /// Specifies the base 2 logarithm of the desired number of tiles down the
1180+ /// frame.
1181+ pub tile_rows_log2: u32,
1182+ /// Secifies the number of tiles down the frame
1183+ pub tile_rows: u32,
1184+ /// Specifies the number of bytes needed to code each tile size.
1185+ pub tile_size_bytes: u32,
1186+}
1187+
1188+impl Default for TileInfo {
1189+ fn default() -> Self {
1190+ Self {
1191+ uniform_tile_spacing_flag: Default::default(),
1192+ increment_tile_rows_log2: Default::default(),
1193+ width_in_sbs_minus_1: [0; MAX_TILE_COLS],
1194+ height_in_sbs_minus_1: [0; MAX_TILE_ROWS],
1195+ context_update_tile_id: Default::default(),
1196+ mi_col_starts: [0; MAX_TILE_COLS + 1],
1197+ mi_row_starts: [0; MAX_TILE_ROWS + 1],
1198+ tile_cols_log2: Default::default(),
1199+ tile_cols: Default::default(),
1200+ tile_rows_log2: Default::default(),
1201+ tile_rows: Default::default(),
1202+ tile_size_bytes: Default::default(),
1203+ }
1204+ }
1205+}
1206+
1207+#[derive(Clone, Debug, Default, PartialEq, Eq)]
1208+pub struct CdefParams {
1209+ /// Controls the amount of damping in the deringing filter.
1210+ pub cdef_damping: u32,
1211+ /// Specifies the number of bits needed to specify which CDEF filter to
1212+ /// apply.
1213+ pub cdef_bits: u32,
1214+ /// Specify the strength of the primary filter.
1215+ pub cdef_y_pri_strength: [u32; CDEF_MAX],
1216+ /// Specify the strength of the secondary filter.
1217+ pub cdef_y_sec_strength: [u32; CDEF_MAX],
1218+ /// Specify the strength of the primary filter.
1219+ pub cdef_uv_pri_strength: [u32; CDEF_MAX],
1220+ /// Specify the strength of the secondary filter.
1221+ pub cdef_uv_sec_strength: [u32; CDEF_MAX],
1222+}
1223+
1224+#[derive(Clone, Debug, Default, PartialEq, Eq)]
1225+pub struct LoopRestorationParams {
1226+ /// Specifies if the luma restoration size should be halved.
1227+ pub lr_unit_shift: u8,
1228+ /// Only present for 4:2:0 formats and specifies if the chroma size should
1229+ /// be half the luma size.
1230+ pub lr_uv_shift: u8,
1231+ /// Same as FrameRestorationType in the specification.
1232+ pub frame_restoration_type: [FrameRestorationType; MAX_NUM_PLANES],
1233+ /// Same as LoopRestorationSize in the specification.
1234+ pub loop_restoration_size: [u16; MAX_NUM_PLANES],
1235+ /// Same as UsesLr in the specification.
1236+ pub uses_lr: bool,
1237+ /// Same as UsesChromaLr in the specification.
1238+ pub uses_chroma_lr: bool,
1239+}
1240+
1241+#[derive(Clone, Debug, Default, PartialEq, Eq)]
1242+pub struct GlobalMotionParams {
1243+ /// Specifies whether global motion parameters are present for a particular
1244+ /// reference frame.
1245+ pub is_global: [bool; NUM_REF_FRAMES],
1246+ /// Specifies whether a particular reference frame uses rotation and zoom
1247+ /// global motion.
1248+ pub is_rot_zoom: [bool; NUM_REF_FRAMES],
1249+ /// Specifies whether a particular reference frame uses translation global
1250+ /// motion.
1251+ pub is_translation: [bool; NUM_REF_FRAMES],
1252+ /// gm_params\[ ref \]\[ j \] is set equal to SavedGmParams\[
1253+ /// frame_to_show_map_idx \]\[ ref \]\[ j \] for ref = LAST_FRAME..ALTREF_FRAME,
1254+ /// for j = 0..5.
1255+ pub gm_params: [[i32; 6]; NUM_REF_FRAMES],
1256+ /// Whether the parameters are valid (see warpValid and section 7.11.3.6)
1257+ pub warp_valid: [bool; NUM_REF_FRAMES],
1258+ /// Same as GmType.
1259+ pub gm_type: [WarpModelType; NUM_REF_FRAMES],
1260+}
1261+
1262+#[derive(Clone, Debug, Default, PartialEq, Eq)]
1263+pub struct FilmGrainParams {
1264+ /// If set, specifies that film grain should be added to this frame. If not
1265+ /// set, specifies that film grain should not be added.
1266+ pub apply_grain: bool,
1267+ /// Specifies the starting value for the pseudo-random numbers used during
1268+ /// film grain synthesis.
1269+ pub grain_seed: u16,
1270+ /// If set means that a new set of parameters should be sent. If not set,
1271+ /// means that the previous set of parameters should be used.
1272+ pub update_grain: bool,
1273+ /// Indicates which reference frame contains the film grain parameters to be
1274+ /// used for this frame.
1275+ pub film_grain_params_ref_idx: u8,
1276+ /// Specifies the number of points for the piece-wise linear scaling
1277+ /// function of the luma component.
1278+ pub num_y_points: u8,
1279+ /// Represents the x (luma value) coordinate for the i-th point of the
1280+ /// piecewise linear scaling function for luma component. The values are
1281+ /// signaled on the scale of 0..255. (In case of 10 bit video, these values
1282+ /// correspond to luma values divided by 4. In case of 12 bit video, these
1283+ /// values correspond to luma values divided by 16.)
1284+ pub point_y_value: [u8; MAX_NUM_Y_POINTS],
1285+ /// Pepresents the scaling (output) value for the i-th point of the
1286+ /// piecewise linear scaling function for luma component.
1287+ pub point_y_scaling: [u8; MAX_NUM_Y_POINTS],
1288+ /// Specifies that the chroma scaling is inferred from the luma scaling.
1289+ pub chroma_scaling_from_luma: bool,
1290+ /// Specifies the number of points for the piece-wise linear scaling
1291+ /// function of the cb component.
1292+ pub num_cb_points: u8,
1293+ /// Represents the x coordinate for the i-th point of the piece-wise linear
1294+ /// scaling function for cb component. The values are signaled on the scale
1295+ /// of 0..255.
1296+ pub point_cb_value: [u8; MAX_NUM_CB_POINTS],
1297+ /// Represents the scaling (output) value for the i-th point of the
1298+ /// piecewise linear scaling function for cb component.
1299+ pub point_cb_scaling: [u8; MAX_NUM_CB_POINTS],
1300+ /// Specifies represents the number of points for the piece-wise linear
1301+ /// scaling function of the cr component.
1302+ pub num_cr_points: u8,
1303+ /// Represents the x coordinate for the i-th point of the piece-wise linear
1304+ /// scaling function for cr component. The values are signaled on the scale
1305+ /// of 0..255.
1306+ pub point_cr_value: [u8; MAX_NUM_CR_POINTS],
1307+ /// Represents the scaling (output) value for the i-th point of the
1308+ /// piecewise linear scaling function for cr component.
1309+ pub point_cr_scaling: [u8; MAX_NUM_CR_POINTS],
1310+ /// Represents the shift – 8 applied to the values of the chroma component.
1311+ /// The grain_scaling_minus_8 can take values of 0..3 and determines the
1312+ /// range and quantization step of the standard deviation of film grain.
1313+ pub grain_scaling_minus_8: u8,
1314+ /// Specifies the number of auto-regressive coefficients for luma and chroma.
1315+ pub ar_coeff_lag: u32,
1316+ /// Specifies auto-regressive coefficients used for the Y plane.
1317+ pub ar_coeffs_y_plus_128: [u8; MAX_NUM_POS_LUMA],
1318+ /// Specifies auto-regressive coefficients used for the U plane.
1319+ pub ar_coeffs_cb_plus_128: [u8; MAX_NUM_POS_LUMA],
1320+ /// Specifies auto-regressive coefficients used for the V plane.
1321+ pub ar_coeffs_cr_plus_128: [u8; MAX_NUM_POS_LUMA],
1322+ /// Specifies the range of the auto-regressive coefficients. Values of 0, 1,
1323+ /// 2, and 3 correspond to the ranges for auto-regressive coefficients of
1324+ /// [-2, 2), [-1, 1), [-0.5, 0.5) and [-0.25, 0.25) respectively.
1325+ pub ar_coeff_shift_minus_6: u8,
1326+ /// Specifies how much the Gaussian random numbers should be scaled down
1327+ /// during the grain synthesis process.
1328+ pub grain_scale_shift: u8,
1329+ /// Represents a multiplier for the cb component used in derivation of the
1330+ /// input index to the cb component scaling function.
1331+ pub cb_mult: u8,
1332+ /// Represents a multiplier for the average luma component used in
1333+ /// derivation of the input index to the cb component scaling function.
1334+ pub cb_luma_mult: u8,
1335+ /// Represents an offset used in derivation of the input index to the cb
1336+ /// component scaling function.
1337+ pub cb_offset: u16,
1338+ /// Represents a multiplier for the cr component used in derivation of the
1339+ /// input index to the cr component scaling function.
1340+ pub cr_mult: u8,
1341+ /// Represents a multiplier for the average luma component used in
1342+ /// derivation of the input index to the cr component scaling function.
1343+ pub cr_luma_mult: u8,
1344+ /// Represents an offset used in derivation of the input index to the cr
1345+ /// component scaling function.
1346+ pub cr_offset: u16,
1347+ /// If set, indicates that the overlap between film grain blocks shall be
1348+ /// applied. If not set, indicates that the overlap between film grain
1349+ /// blocks shall not be applied.
1350+ pub overlap_flag: bool,
1351+ /// If set, indicates that clipping to the restricted (studio) range shall
1352+ /// be applied to the sample values after adding the film grain (see the
1353+ /// semantics for color_range for an explanation of studio swing). If not
1354+ /// set, indicates that clipping to the full range shall be applied to the
1355+ /// sample values after adding the film grain.
1356+ pub clip_to_restricted_range: bool,
1357+}
1358+
1359+/// Keeps track of the state of the reference frames in the parser. All
1360+/// variables are CamelCase.
1361+#[derive(Clone, Debug, Default, PartialEq, Eq)]
1362+struct ReferenceFrameInfo {
1363+ /// An array which is indexed by a reference picture slot number. A value of
1364+ /// true in the array signifies that the corresponding reference picture
1365+ /// slot is valid for use as a reference picture, while a value of false
1366+ /// signifies that the corresponding reference picture slot is not valid for
1367+ /// use as a reference picture.
1368+ ref_valid: bool,
1369+ /// Specifies the frame id for each reference frame.
1370+ ref_frame_id: u32,
1371+ /// See 7.20 Reference Frame Update Process.
1372+ ref_upscaled_width: u32,
1373+ /// See 7.20 Reference Frame Update Process.
1374+ ref_frame_width: u32,
1375+ /// See 7.20 Reference Frame Update Process.
1376+ ref_frame_height: u32,
1377+ /// See 7.20 Reference Frame Update Process.
1378+ ref_render_width: u32,
1379+ /// See 7.20 Reference Frame Update Process.
1380+ ref_render_height: u32,
1381+ /// See 7.20 Reference Frame Update Process.
1382+ ref_mi_cols: u32,
1383+ /// See 7.20 Reference Frame Update Process.
1384+ ref_mi_rows: u32,
1385+ /// See 7.20 Reference Frame Update Process.
1386+ ref_frame_type: FrameType,
1387+ /// See 7.20 Reference Frame Update Process.
1388+ ref_subsampling_x: bool,
1389+ /// See 7.20 Reference Frame Update Process.
1390+ ref_subsampling_y: bool,
1391+ /// See 7.20 Reference Frame Update Process.
1392+ ref_bit_depth: BitDepth,
1393+ /// See 7.20 Reference Frame Update Process.
1394+ ref_order_hint: u32,
1395+ /// The saved segmentation parameters.
1396+ segmentation_params: SegmentationParams,
1397+ /// The saved global motion parameters.
1398+ global_motion_params: GlobalMotionParams,
1399+ /// The saved loop filter parameters.
1400+ loop_filter_params: LoopFilterParams,
1401+ /// The saved film grain parameters.
1402+ film_grain_params: FilmGrainParams,
1403+ /// The saved tile info parameters.
1404+ tile_info: TileInfo,
1405+ display_frame_id: u32,
1406+ showable_frame: bool,
1407+}
1408+
1409+#[derive(Clone, Debug, Default)]
1410+pub struct AnnexBState {
1411+ pub temporal_unit_size: u32,
1412+ pub frame_unit_size: u32,
1413+ pub temporal_unit_consumed: u32,
1414+ pub frame_unit_consumed: u32,
1415+}
1416+
1417+#[derive(Clone, Debug)]
1418+enum StreamFormat {
1419+ LowOverhead,
1420+ AnnexB(AnnexBState),
1421+}
1422+
1423+#[derive(Debug)]
1424+pub struct Parser {
1425+ stream_format: StreamFormat,
1426+ operating_point: u32,
1427+ /// Same as SeenFrameHeader in the specification
1428+ seen_frame_header: bool,
1429+ operating_point_idc: u16,
1430+ should_probe_for_annexb: bool,
1431+ is_first_frame: bool,
1432+ ref_info: [ReferenceFrameInfo; NUM_REF_FRAMES],
1433+
1434+ /* CamelCase variables */
1435+ mi_cols: u32,
1436+ mi_rows: u32,
1437+ prev_frame_id: u32,
1438+ current_frame_id: u32,
1439+ mi_col_starts: [u32; MAX_TILE_COLS + 1],
1440+ mi_row_starts: [u32; MAX_TILE_ROWS + 1],
1441+ tile_cols_log2: u32,
1442+ tile_cols: u32,
1443+ tile_rows_log2: u32,
1444+ tile_rows: u32,
1445+ tile_size_bytes: u32,
1446+
1447+ /// We keep this to implement frame_header_copy() in the specification, and to fill in
1448+ /// StreamInfo render_width and render_height.
1449+ pub last_frame_header: Option<FrameHeaderObu>,
1450+ /// The last SequenceHeaderObu parsed.
1451+ pub sequence_header: Option<Rc<SequenceHeaderObu>>,
1452+}
1453+
1454+impl Parser {
1455+ /// Probes the input data for the Annex B format. Anything other than
1456+ /// Ok(true) refers to data in "low-overhead" format instead, as we are trying to parse
1457+ fn annexb_probe(data: &[u8]) -> Result<bool, String> {
1458+ let mut r = Reader::new(data);
1459+ let mut seen_sequence = false;
1460+ let mut seen_frame = false;
1461+
1462+ // Try reading the first TU and frame unit size
1463+ let temporal_unit_size = r.read_leb128()?;
1464+ if temporal_unit_size == 0 {
1465+ return Ok(false);
1466+ }
1467+
1468+ let frame_unit_size = r.read_leb128()?;
1469+ if frame_unit_size == 0 || frame_unit_size > temporal_unit_size {
1470+ return Ok(false);
1471+ }
1472+
1473+ let obu_length = r.read_leb128()?;
1474+ if obu_length == 0 || obu_length > frame_unit_size {
1475+ return Ok(false);
1476+ }
1477+
1478+ // The first OBU in the first frame_unit of each temporal_unit must
1479+ // be a temporal delimiter OBU (and this is the only place temporal
1480+ // delimiter OBUs can appear)
1481+ let header = Self::parse_obu_header(&mut r.clone())?;
1482+ if !matches!(header.obu_type, ObuType::TemporalDelimiter) {
1483+ return Ok(false);
1484+ }
1485+
1486+ // Try identifying a sequence and a frame.
1487+ r.0.skip_bits(obu_length as usize * 8)?;
1488+ let mut num_bytes_read = 0;
1489+
1490+ loop {
1491+ let obu_length = r.read_leb128()?;
1492+ let mut obu_reader = r.clone();
1493+
1494+ r.0.skip_bits(obu_length as usize * 8)?;
1495+ num_bytes_read += obu_length;
1496+
1497+ if !seen_sequence {
1498+ let header = Self::parse_obu_header(&mut obu_reader)?;
1499+ seen_sequence = matches!(header.obu_type, ObuType::SequenceHeader);
1500+ }
1501+
1502+ if !seen_frame {
1503+ let header = Self::parse_obu_header(&mut obu_reader)?;
1504+ seen_frame = matches!(header.obu_type, ObuType::Frame | ObuType::FrameHeader);
1505+ }
1506+
1507+ if seen_sequence && seen_frame {
1508+ // OK, enough evidence of Annex B format.
1509+ return Ok(true);
1510+ }
1511+
1512+ if num_bytes_read >= frame_unit_size {
1513+ // We read what we've identified as the first frame and yet no
1514+ // sequence and no actual frames were found.
1515+ return Ok(false);
1516+ }
1517+ }
1518+ }
1519+
1520+ fn compute_image_size(&mut self, fh: &mut FrameHeaderObu) {
1521+ fh.mi_cols = 2 * ((fh.frame_width + 7) >> 3);
1522+ fh.mi_rows = 2 * ((fh.frame_height + 7) >> 3);
1523+ self.mi_cols = fh.mi_cols;
1524+ self.mi_rows = fh.mi_rows;
1525+ }
1526+
1527+ // 5.9.8
1528+ fn parse_superres_params(
1529+ fh: &mut FrameHeaderObu,
1530+ r: &mut Reader,
1531+ seq: &SequenceHeaderObu,
1532+ ) -> Result<(), String> {
1533+ if seq.enable_superres {
1534+ fh.use_superres = r.0.read_bit()?;
1535+ } else {
1536+ fh.use_superres = false;
1537+ }
1538+
1539+ if fh.use_superres {
1540+ fh.superres_denom =
1541+ r.0.read_bits::<u32>(SUPERRES_DENOM_BITS)? + SUPERRES_DENOM_MIN as u32;
1542+ } else {
1543+ fh.superres_denom = SUPERRES_NUM as u32;
1544+ }
1545+
1546+ fh.upscaled_width = fh.frame_width;
1547+ fh.frame_width =
1548+ (fh.upscaled_width * SUPERRES_NUM as u32 + (fh.superres_denom / 2)) / fh.superres_denom;
1549+
1550+ Ok(())
1551+ }
1552+
1553+ // 7.8 verbatim.
1554+ fn set_frame_refs(
1555+ &self,
1556+ fh: &mut FrameHeaderObu,
1557+ ref_order_hint: &[u32; NUM_REF_FRAMES],
1558+ ) -> Result<(), String> {
1559+ let seq = self.sequence()?;
1560+ let mut ref_frame_idx = [-1i32; REFS_PER_FRAME];
1561+
1562+ ref_frame_idx[0] = fh.last_frame_idx.into();
1563+ ref_frame_idx[ReferenceFrameType::Golden as usize - ReferenceFrameType::Last as usize] =
1564+ fh.gold_frame_idx.into();
1565+
1566+ let mut used_frame = [false; NUM_REF_FRAMES];
1567+ used_frame[fh.last_frame_idx as usize] = true;
1568+ used_frame[fh.gold_frame_idx as usize] = true;
1569+
1570+ let cur_frame_hint = 1 << (seq.order_hint_bits - 1);
1571+ let mut shifted_order_hints = [0; NUM_REF_FRAMES];
1572+ for i in 0..NUM_REF_FRAMES {
1573+ shifted_order_hints[i] = cur_frame_hint
1574+ + helpers::get_relative_dist(
1575+ seq.enable_order_hint,
1576+ seq.order_hint_bits,
1577+ ref_order_hint[i].try_into().unwrap(),
1578+ fh.order_hint.try_into().unwrap(),
1579+ );
1580+ }
1581+
1582+ let mut latest_order_hint = shifted_order_hints[fh.last_frame_idx as usize];
1583+ if latest_order_hint >= cur_frame_hint {
1584+ return Err("It is a requirement of bitstream conformance that last_order_hint < cur_frame_hint".into());
1585+ }
1586+
1587+ let mut earliest_order_hint = shifted_order_hints[fh.gold_frame_idx as usize];
1588+ if earliest_order_hint >= cur_frame_hint {
1589+ return Err("It is a requirement of bitstream conformance that gold_order_hint < cur_frame_hint".into());
1590+ }
1591+
1592+ let ref_ = helpers::find_latest_backward(
1593+ &shifted_order_hints,
1594+ &used_frame,
1595+ cur_frame_hint,
1596+ &mut latest_order_hint,
1597+ );
1598+
1599+ if ref_ >= 0 {
1600+ ref_frame_idx
1601+ [ReferenceFrameType::AltRef as usize - ReferenceFrameType::Last as usize] = ref_;
1602+ used_frame[ref_ as usize] = true;
1603+ }
1604+
1605+ let ref_ = helpers::find_earliest_backward(
1606+ &shifted_order_hints,
1607+ &used_frame,
1608+ cur_frame_hint,
1609+ &mut earliest_order_hint,
1610+ );
1611+
1612+ if ref_ >= 0 {
1613+ ref_frame_idx
1614+ [ReferenceFrameType::BwdRef as usize - ReferenceFrameType::Last as usize] = ref_;
1615+ used_frame[ref_ as usize] = true;
1616+ }
1617+
1618+ let ref_ = helpers::find_earliest_backward(
1619+ &shifted_order_hints,
1620+ &used_frame,
1621+ cur_frame_hint,
1622+ &mut earliest_order_hint,
1623+ );
1624+
1625+ if ref_ >= 0 {
1626+ ref_frame_idx
1627+ [ReferenceFrameType::AltRef2 as usize - ReferenceFrameType::Last as usize] = ref_;
1628+ used_frame[ref_ as usize] = true;
1629+ }
1630+
1631+ const REF_FRAME_LIST: [usize; 5] = [
1632+ ReferenceFrameType::Last2 as usize - ReferenceFrameType::Last as usize,
1633+ ReferenceFrameType::Last3 as usize - ReferenceFrameType::Last as usize,
1634+ ReferenceFrameType::BwdRef as usize - ReferenceFrameType::Last as usize,
1635+ ReferenceFrameType::AltRef2 as usize - ReferenceFrameType::Last as usize,
1636+ ReferenceFrameType::AltRef as usize - ReferenceFrameType::Last as usize,
1637+ ];
1638+
1639+ #[allow(clippy::needless_range_loop)]
1640+ for i in 0..REFS_PER_FRAME - 2 {
1641+ let ref_frame = REF_FRAME_LIST[i];
1642+
1643+ if ref_frame_idx[ref_frame] < 0 {
1644+ let ref_ = helpers::find_latest_forward(
1645+ &shifted_order_hints,
1646+ &used_frame,
1647+ cur_frame_hint,
1648+ &mut latest_order_hint,
1649+ );
1650+
1651+ if ref_ >= 0 {
1652+ ref_frame_idx[ref_frame] = ref_;
1653+ used_frame[ref_ as usize] = true;
1654+ }
1655+ }
1656+ }
1657+
1658+ let mut ref_ = 0;
1659+ earliest_order_hint = shifted_order_hints[0];
1660+ #[allow(clippy::needless_range_loop)]
1661+ for i in 1..NUM_REF_FRAMES {
1662+ let hint = shifted_order_hints[i];
1663+ if hint < earliest_order_hint {
1664+ ref_ = i as u8;
1665+ earliest_order_hint = hint;
1666+ }
1667+ }
1668+
1669+ fh.ref_frame_idx
1670+ .iter_mut()
1671+ .zip(ref_frame_idx.iter().copied())
1672+ .for_each(|(dest, src)| *dest = if src < 0 { ref_ } else { src as u8 });
1673+
1674+ Ok(())
1675+ }
1676+
1677+ // 5.9.5.
1678+ fn parse_frame_size(&mut self, fh: &mut FrameHeaderObu, r: &mut Reader) -> Result<(), String> {
1679+ let seq = self.sequence()?;
1680+ if fh.frame_size_override_flag {
1681+ let n = seq.frame_width_bits_minus_1 + 1;
1682+ fh.frame_width = r.0.read_bits::<u32>(n as usize)? + 1;
1683+
1684+ let n = seq.frame_height_bits_minus_1 + 1;
1685+ fh.frame_height = r.0.read_bits::<u32>(n as usize)? + 1;
1686+ } else {
1687+ fh.frame_width = seq.max_frame_width_minus_1 as u32 + 1;
1688+ fh.frame_height = seq.max_frame_height_minus_1 as u32 + 1;
1689+ }
1690+
1691+ Self::parse_superres_params(fh, r, seq)?;
1692+ self.compute_image_size(fh);
1693+
1694+ Ok(())
1695+ }
1696+
1697+ fn parse_render_size(fh: &mut FrameHeaderObu, r: &mut Reader) -> Result<(), String> {
1698+ fh.render_and_frame_size_different = r.0.read_bit()?;
1699+ if fh.render_and_frame_size_different {
1700+ fh.render_width = r.0.read_bits::<u32>(16)? + 1;
1701+ fh.render_height = r.0.read_bits::<u32>(16)? + 1;
1702+ } else {
1703+ fh.render_width = fh.upscaled_width;
1704+ fh.render_height = fh.frame_height;
1705+ }
1706+ Ok(())
1707+ }
1708+
1709+ fn frame_size_with_refs(
1710+ &mut self,
1711+ fh: &mut FrameHeaderObu,
1712+ r: &mut Reader,
1713+ ) -> Result<(), String> {
1714+ let mut found_ref = false;
1715+ let seq = self.sequence()?;
1716+
1717+ for i in 0..REFS_PER_FRAME {
1718+ found_ref = r.0.read_bit()?;
1719+
1720+ if found_ref {
1721+ let rf = &self.ref_info[fh.ref_frame_idx[i] as usize];
1722+ fh.upscaled_width = rf.ref_upscaled_width;
1723+ fh.frame_width = fh.upscaled_width;
1724+ fh.frame_height = rf.ref_frame_height;
1725+ fh.render_width = rf.ref_render_width;
1726+ fh.render_height = rf.ref_render_height;
1727+ break;
1728+ }
1729+ }
1730+
1731+ if !found_ref {
1732+ self.parse_frame_size(fh, r)?;
1733+ Self::parse_render_size(fh, r)?;
1734+ } else {
1735+ Self::parse_superres_params(fh, r, seq)?;
1736+ self.compute_image_size(fh);
1737+ }
1738+
1739+ Ok(())
1740+ }
1741+
1742+ /// Skip the padding bits, ensuring that they actually make sense.
1743+ fn skip_and_check_trailing_bits(r: &mut Reader, obu: &Obu) -> Result<(), String> {
1744+ // We can't have that in parse_obu as per the spec, because the reader
1745+ // is not initialized on our design at that point, so move the check to
1746+ // inside this function.
1747+ if obu.data.len() == 0
1748+ || matches!(
1749+ obu.header.obu_type,
1750+ ObuType::TileList | ObuType::TileGroup | ObuType::Frame
1751+ )
1752+ {
1753+ return Ok(());
1754+ }
1755+ let num_trailing = obu.as_ref().len() as u64 * 8 - r.0.position();
1756+ r.read_trailing_bits(num_trailing)?;
1757+ Ok(())
1758+ }
1759+
1760+ fn parse_obu_header(r: &mut Reader) -> Result<ObuHeader, String> {
1761+ let _obu_forbidden_bit = r.0.read_bit()?;
1762+
1763+ let mut header = ObuHeader {
1764+ obu_type: ObuType::try_from(r.0.read_bits::<u32>(4)?)?,
1765+ extension_flag: r.0.read_bit()?,
1766+ has_size_field: r.0.read_bit()?,
1767+ temporal_id: Default::default(),
1768+ spatial_id: Default::default(),
1769+ };
1770+
1771+ let obu_reserved_1bit = r.0.read_bit()?;
1772+ assert!(!obu_reserved_1bit); // Must be set to zero as per spec.
1773+
1774+ if header.extension_flag {
1775+ header.temporal_id = r.0.read_bits::<u32>(3)?;
1776+ header.spatial_id = r.0.read_bits::<u32>(2)?;
1777+ let _ = r.0.read_bits::<u32>(3)?;
1778+ }
1779+
1780+ Ok(header)
1781+ }
1782+
1783+ /// Parses one OBU from `data`, which can be in Annex B or low-overhead
1784+ /// format.
1785+ ///
1786+ /// `None` may eventually be returned if the OBU is to be dropped.
1787+ pub fn read_obu<'a>(&mut self, data: &'a [u8]) -> Result<ObuAction<'a>, String> {
1788+ if data.is_empty() {
1789+ return Err("Empty data".into());
1790+ }
1791+
1792+ let mut reader = Reader::new(data);
1793+
1794+ if self.should_probe_for_annexb {
1795+ // Try probing for Annex B data.
1796+ self.stream_format = if matches!(Self::annexb_probe(data), Ok(true)) {
1797+ log::debug!("Parsing an Annex B stream");
1798+ StreamFormat::AnnexB(AnnexBState::default())
1799+ } else {
1800+ log::debug!("Parsing a low-overhead stream");
1801+ StreamFormat::LowOverhead
1802+ };
1803+
1804+ self.should_probe_for_annexb = false;
1805+ }
1806+
1807+ let obu_length: usize = if let StreamFormat::AnnexB(annexb_state) = &mut self.stream_format
1808+ {
1809+ // Read the length to skip to the start of the open_bitstream_unit()
1810+ // syntax element.
1811+ let obu_length = reader.current_annexb_obu_length(annexb_state)?;
1812+ match obu_length {
1813+ Some(length) => length,
1814+ None => return Ok(ObuAction::Drop(reader.consumed(0))),
1815+ }
1816+ } else {
1817+ 0
1818+ };
1819+
1820+ let start_pos = reader.consumed(0);
1821+
1822+ // Both "low-overhead" and Annex B are now at the same point, i.e.: a
1823+ // open_bitstream_unit() follows.
1824+ let header = Self::parse_obu_header(&mut reader)?;
1825+ if matches!(self.stream_format, StreamFormat::LowOverhead) {
1826+ assert!(header.has_size_field);
1827+ }
1828+
1829+ let obu_size: usize = if header.has_size_field {
1830+ reader.read_leb128()? as usize
1831+ } else {
1832+ /* trap any bugs when computing the final length */
1833+ obu_length
1834+ .checked_sub(1)
1835+ .ok_or::<String>("obu_length must be greater than 0".into())?
1836+ .checked_sub(usize::from(header.extension_flag))
1837+ .ok_or::<String>("obu_length too short".into())?
1838+ };
1839+
1840+ let consumed = reader.consumed(start_pos);
1841+
1842+ if let StreamFormat::AnnexB(annexb_state) = &mut self.stream_format {
1843+ annexb_state.temporal_unit_consumed += consumed;
1844+ annexb_state.frame_unit_consumed += consumed;
1845+
1846+ annexb_state.temporal_unit_consumed += u32::try_from(obu_size).unwrap();
1847+ annexb_state.frame_unit_consumed += u32::try_from(obu_size).unwrap();
1848+ }
1849+
1850+ assert!(reader.0.position() % 8 == 0);
1851+ let start_offset: usize = (reader.0.position() / 8).try_into().unwrap();
1852+
1853+ log::debug!(
1854+ "Identified OBU type {:?}, data size: {}, obu_size: {}",
1855+ header.obu_type,
1856+ start_offset + obu_size,
1857+ obu_size
1858+ );
1859+
1860+ if header.obu_type != ObuType::SequenceHeader
1861+ && header.obu_type != ObuType::TemporalDelimiter
1862+ && self.operating_point_idc != 0
1863+ && header.extension_flag
1864+ {
1865+ let in_temporal_layer = ((self.operating_point_idc >> header.temporal_id) & 1) != 0;
1866+ let in_spatial_layer = ((self.operating_point_idc >> (header.spatial_id + 8)) & 1) != 0;
1867+ if !in_temporal_layer || !in_spatial_layer {
1868+ log::debug!("Dropping obu as per drop_obu() in the specification",);
1869+ return Ok(ObuAction::Drop(reader.consumed(0)));
1870+ }
1871+ }
1872+
1873+ Ok(ObuAction::Process(Obu {
1874+ header,
1875+ data: Cow::from(&data[start_offset..start_offset + obu_size]),
1876+ bytes_used: start_offset + obu_size,
1877+ }))
1878+ }
1879+
1880+ fn parse_color_config(s: &mut SequenceHeaderObu, r: &mut Reader) -> Result<(), String> {
1881+ let cc = &mut s.color_config;
1882+
1883+ cc.high_bitdepth = r.0.read_bit()?;
1884+ if s.seq_profile as u32 == 2 && cc.high_bitdepth {
1885+ cc.twelve_bit = r.0.read_bit()?;
1886+ if cc.twelve_bit {
1887+ s.bit_depth = BitDepth::Depth12;
1888+ } else {
1889+ s.bit_depth = BitDepth::Depth10;
1890+ }
1891+ } else if s.seq_profile as u32 <= 2 {
1892+ s.bit_depth = if cc.high_bitdepth { BitDepth::Depth10 } else { BitDepth::Depth8 };
1893+ }
1894+
1895+ if s.seq_profile as u32 == 1 {
1896+ cc.mono_chrome = false;
1897+ } else {
1898+ cc.mono_chrome = r.0.read_bit()?;
1899+ }
1900+
1901+ if cc.mono_chrome {
1902+ s.num_planes = 1;
1903+ } else {
1904+ s.num_planes = 3;
1905+ }
1906+
1907+ cc.color_description_present_flag = r.0.read_bit()?;
1908+ if cc.color_description_present_flag {
1909+ cc.color_primaries = ColorPrimaries::try_from(r.0.read_bits::<u32>(8)?)?;
1910+ cc.transfer_characteristics =
1911+ TransferCharacteristics::try_from(r.0.read_bits::<u32>(8)?)?;
1912+ cc.matrix_coefficients = MatrixCoefficients::try_from(r.0.read_bits::<u32>(8)?)?;
1913+ } else {
1914+ cc.color_primaries = ColorPrimaries::Unspecified;
1915+ cc.transfer_characteristics = TransferCharacteristics::Unspecified;
1916+ cc.matrix_coefficients = MatrixCoefficients::Unspecified;
1917+ }
1918+
1919+ if cc.mono_chrome {
1920+ cc.color_range = r.0.read_bit()?;
1921+ cc.subsampling_x = true;
1922+ cc.subsampling_y = true;
1923+ cc.chroma_sample_position = ChromaSamplePosition::Unknown;
1924+ cc.separate_uv_delta_q = false;
1925+ return Ok(());
1926+ } else if matches!(cc.color_primaries, ColorPrimaries::Bt709)
1927+ && matches!(cc.transfer_characteristics, TransferCharacteristics::Srgb)
1928+ && matches!(cc.matrix_coefficients, MatrixCoefficients::Identity)
1929+ {
1930+ cc.color_range = true;
1931+ cc.subsampling_x = false;
1932+ cc.subsampling_y = false;
1933+ } else {
1934+ cc.color_range = r.0.read_bit()?;
1935+ if s.seq_profile as u32 == 0 {
1936+ cc.subsampling_x = true;
1937+ cc.subsampling_y = true;
1938+ } else if s.seq_profile as u32 == 1 {
1939+ cc.subsampling_x = false;
1940+ cc.subsampling_y = false;
1941+ } else if matches!(s.bit_depth, BitDepth::Depth12) {
1942+ cc.subsampling_x = r.0.read_bit()?;
1943+ if cc.subsampling_x {
1944+ cc.subsampling_y = r.0.read_bit()?;
1945+ } else {
1946+ cc.subsampling_y = false;
1947+ }
1948+ } else {
1949+ cc.subsampling_x = true;
1950+ cc.subsampling_y = false;
1951+ }
1952+
1953+ if cc.subsampling_x && cc.subsampling_y {
1954+ cc.chroma_sample_position =
1955+ ChromaSamplePosition::try_from(r.0.read_bits::<u32>(2)?)?;
1956+ }
1957+ }
1958+
1959+ cc.separate_uv_delta_q = r.0.read_bit()?;
1960+
1961+ Ok(())
1962+ }
1963+
1964+ fn parse_operating_parameters_info(
1965+ opi: &mut OperatingPoint,
1966+ r: &mut Reader,
1967+ buffer_delay_length_minus_1: u8,
1968+ ) -> Result<(), String> {
1969+ let n = buffer_delay_length_minus_1 + 1;
1970+ opi.decoder_buffer_delay = r.0.read_bits::<u32>(n as usize)?;
1971+ opi.encoder_buffer_delay = r.0.read_bits::<u32>(n as usize)?;
1972+ opi.low_delay_mode_flag = r.0.read_bit()?;
1973+ Ok(())
1974+ }
1975+
1976+ fn parse_decoder_model_info(dmi: &mut DecoderModelInfo, r: &mut Reader) -> Result<(), String> {
1977+ dmi.buffer_delay_length_minus_1 = r.0.read_bits::<u32>(5)? as u8;
1978+ dmi.num_units_in_decoding_tick = r.0.read_bits::<u32>(32)?;
1979+ dmi.buffer_removal_time_length_minus_1 = r.0.read_bits::<u32>(5)? as u8;
1980+ dmi.frame_presentation_time_length_minus_1 = r.0.read_bits::<u32>(5)?;
1981+ Ok(())
1982+ }
1983+
1984+ fn parse_timing_info(ti: &mut TimingInfo, r: &mut Reader) -> Result<(), String> {
1985+ ti.num_units_in_display_tick = r.0.read_bits::<u32>(32)?;
1986+ ti.time_scale = r.0.read_bits::<u32>(32)?;
1987+ ti.equal_picture_interval = r.0.read_bit()?;
1988+ if ti.equal_picture_interval {
1989+ ti.num_ticks_per_picture_minus_1 = r.read_uvlc()?;
1990+ }
1991+ Ok(())
1992+ }
1993+
1994+ /// Selects an operating point. Only call this after the Sequence OBU for
1995+ /// which the operating point should apply has been parsed.
1996+ pub fn choose_operating_point(&mut self, operating_point: u32) -> Result<(), String> {
1997+ if operating_point > self.sequence()?.operating_points_cnt_minus_1 {
1998+ return Err(format!(
1999+ "Invalid operating point {} (max {})",
2000+ operating_point,
vendor/cros-codecs/src/codec/av1/reader.rsadded+249 -0
@@ -0,0 +1,249 @@
1+// Copyright 2023 The ChromiumOS Authors
2+// Use of this source code is governed by a BSD-style license that can be
3+// found in the LICENSE file.
4+
5+use crate::bitstream_utils::BitReader;
6+
7+use crate::codec::av1::helpers;
8+
9+use super::parser::AnnexBState;
10+
11+pub(crate) struct Reader<'a>(pub BitReader<'a>);
12+
13+impl<'a> Reader<'a> {
14+ pub fn new(data: &'a [u8]) -> Self {
15+ Self(BitReader::new(data, false))
16+ }
17+
18+ /// Implements uvlc(): Variable length unsigned n-bit number appearing
19+ /// directly in the bitstream. See 4.10.3
20+ pub fn read_uvlc(&mut self) -> Result<u32, String> {
21+ let mut leading_zeroes = 0;
22+ loop {
23+ let done = self.0.read_bit()?;
24+
25+ if done {
26+ break;
27+ }
28+
29+ leading_zeroes += 1;
30+ }
31+
32+ if leading_zeroes >= 32 {
33+ return Ok(u32::MAX);
34+ }
35+
36+ let value = self.0.read_bits::<u32>(leading_zeroes)?;
37+ Ok(value + (1 << leading_zeroes) - 1)
38+ }
39+
40+ /// Implements leb128(): Unsigned integer represented by a variable number
41+ /// of little-endian bytes. See 4.10.5
42+ pub fn read_leb128(&mut self) -> Result<u32, String> {
43+ let mut value = 0u64;
44+
45+ for i in 0..8 {
46+ let byte = u64::from(self.0.read_bits_aligned::<u32>(8)?);
47+ value |= (byte & 0x7f) << (i * 7);
48+
49+ if byte & 0x80 == 0 {
50+ break;
51+ }
52+ }
53+
54+ Ok(value as u32)
55+ }
56+
57+ /// Implements su(n): Signed integer converted from an n bits unsigned
58+ /// integer in the bitstream. (The unsigned integer corresponds to the
59+ /// bottom n bits of the signed integer.). See 4.10.6
60+ pub fn read_su(&mut self, num_bits: usize) -> Result<i32, String> {
61+ let mut value: i32 = self
62+ .0
63+ .read_bits::<u32>(num_bits)?
64+ .try_into()
65+ .map_err(|_| String::from("Read more than 31 signed bits!"))?;
66+ let sign_mask = 1 << (num_bits - 1);
67+
68+ if (value & sign_mask) != 0 {
69+ value -= 2 * sign_mask;
70+ }
71+
72+ Ok(value)
73+ }
74+
75+ /// Implements ns(n): Unsigned encoded integer with maximum number of values
76+ /// n (i.e. output in range 0..n-1). See 4.10.7
77+ pub fn read_ns(&mut self, num_bits: usize) -> Result<u32, String> {
78+ let w = helpers::floor_log2(num_bits as u32) + 1;
79+ let m = (1 << w) - num_bits as u32;
80+ let v = self.0.read_bits::<u32>(
81+ usize::try_from(w).map_err(|_| String::from("Invalid num_bits"))? - 1,
82+ )?;
83+
84+ if v < m.into() {
85+ return Ok(v);
86+ }
87+
88+ let extra_bit = self.0.read_bit()?;
89+ Ok((v << 1) - u32::from(m) + u32::from(extra_bit))
90+ }
91+
92+ /// Implements 5.9.13: Delta quantizer syntax.
93+ pub fn read_delta_q(&mut self) -> Result<i32, String> {
94+ let delta_coded = self.0.read_bit()?;
95+
96+ if delta_coded {
97+ self.read_su(7)
98+ } else {
99+ Ok(0)
100+ }
101+ }
102+
103+ pub fn more_data_in_bitstream(&mut self) -> bool {
104+ self.0.num_bits_left() > 0
105+ }
106+
107+ pub(crate) fn consumed(&self, start_pos: u32) -> u32 {
108+ (self.0.position() / 8) as u32 - start_pos
109+ }
110+
111+ /// Get the length of the current OBU in AnnexB format.
112+ pub fn current_annexb_obu_length(
113+ &mut self,
114+ annexb_state: &mut AnnexBState,
115+ ) -> Result<Option<usize>, String> {
116+ if !self.more_data_in_bitstream() {
117+ return Ok(None);
118+ }
119+
120+ #[allow(clippy::comparison_chain)]
121+ if annexb_state.temporal_unit_consumed == annexb_state.temporal_unit_size {
122+ annexb_state.temporal_unit_size = 0;
123+ } else if annexb_state.temporal_unit_consumed > annexb_state.temporal_unit_size {
124+ return Err(format!(
125+ "temporal_unit_size is {} but we consumed {} bytes",
126+ annexb_state.temporal_unit_size, annexb_state.temporal_unit_consumed,
127+ ));
128+ }
129+
130+ if annexb_state.temporal_unit_size == 0 {
131+ annexb_state.temporal_unit_size = self.read_leb128()?;
132+ if annexb_state.temporal_unit_size == 0 {
133+ return Ok(None);
134+ }
135+ }
136+
137+ let start_pos = self.consumed(0);
138+
139+ #[allow(clippy::comparison_chain)]
140+ if annexb_state.frame_unit_consumed == annexb_state.frame_unit_size {
141+ annexb_state.frame_unit_size = 0;
142+ } else if annexb_state.frame_unit_consumed > annexb_state.frame_unit_size {
143+ return Err(format!(
144+ "frame_unit_size is {} but we consumed {} bytes",
145+ annexb_state.frame_unit_size, annexb_state.frame_unit_consumed,
146+ ));
147+ }
148+
149+ if annexb_state.frame_unit_size == 0 {
150+ annexb_state.frame_unit_size = self.read_leb128()?;
151+ if annexb_state.frame_unit_size == 0 {
152+ return Ok(None);
153+ }
154+ annexb_state.temporal_unit_consumed += self.consumed(start_pos);
155+ }
156+
157+ let start_pos = self.consumed(0);
158+ let obu_length = self.read_leb128()?;
159+ let consumed = self.consumed(start_pos);
160+
161+ annexb_state.temporal_unit_consumed += consumed;
162+ annexb_state.frame_unit_consumed += consumed;
163+
164+ Ok(Some(obu_length.try_into().unwrap()))
165+ }
166+
167+ /// Implements 5.3.4.
168+ pub fn read_trailing_bits(&mut self, mut num_bits: u64) -> Result<(), String> {
169+ let trailing_one_bit = self.0.read_bit()?;
170+ num_bits -= 1;
171+
172+ if !trailing_one_bit {
173+ return Err("bad padding: trailing_one_bit is not set".into());
174+ }
175+
176+ while num_bits > 0 {
177+ let trailing_zero_bit = self.0.read_bit()?;
178+ if trailing_zero_bit {
179+ return Err("bad padding: trailing_zero_bit is set".into());
180+ }
181+ num_bits -= 1;
182+ }
183+
184+ Ok(())
185+ }
186+
187+ fn decode_subexp(&mut self, num_syms: i32) -> Result<u32, String> {
188+ let mut i = 0;
189+ let mut mk = 0;
190+ let k = 3;
191+
192+ loop {
193+ let b2 = if i != 0 { k + i - 1 } else { k };
194+ let a = 1 << b2;
195+ if num_syms <= mk + 3 * a {
196+ let num_bits = num_syms - mk;
197+ let subexp_final_bits = self.read_ns(num_bits as usize)?;
198+ return Ok(subexp_final_bits);
199+ } else {
200+ let subexp_more_bits = self.0.read_bit()?;
201+ if subexp_more_bits {
202+ i += 1;
203+ mk += a;
204+ } else {
205+ let num_bits = b2 as usize;
206+ let subexp_bits = self.0.read_bits::<u32>(num_bits)?;
207+ return Ok(subexp_bits + mk as u32);
208+ }
209+ }
210+ }
211+ }
212+
213+ /// Implements 5.9.27.
214+ pub fn decode_unsigned_subexp_with_ref(&mut self, mx: i32, r: i32) -> Result<u32, String> {
215+ let v = self.decode_subexp(mx)?;
216+ if (r << 1) <= mx {
217+ Ok(helpers::inverse_recenter(r, v.try_into().unwrap()).try_into().unwrap())
218+ } else {
219+ let res = mx - 1 - helpers::inverse_recenter(mx - 1 - r, v.try_into().unwrap());
220+ Ok(res.try_into().unwrap())
221+ }
222+ }
223+
224+ /// Implements 5.9.26.
225+ pub fn decode_signed_subexp_with_ref(
226+ &mut self,
227+ low: i32,
228+ high: i32,
229+ r: i32,
230+ ) -> Result<i32, String> {
231+ let x = self.decode_unsigned_subexp_with_ref(high - low, r - low)?;
232+ Ok(i32::try_from(x).unwrap() + low)
233+ }
234+
235+ /// Implements 5.3.5 Byte alignment syntax
236+ pub fn byte_alignment(&mut self) -> Result<(), String> {
237+ while (self.0.position() & 7) != 0 {
238+ self.0.read_bit()?;
239+ }
240+
241+ Ok(())
242+ }
243+}
244+
245+impl<'a> Clone for Reader<'a> {
246+ fn clone(&self) -> Self {
247+ Self(self.0.clone())
248+ }
249+}
vendor/cros-codecs/src/codec/av1/synthesizer.rsadded+1796 -0
@@ -0,0 +1,1796 @@
1+// Copyright 2024 The ChromiumOS Authors
2+// Use of this source code is governed by a BSD-style license that can be
3+// found in the LICENSE file.
4+
5+use std::fmt;
6+use std::io::Write;
7+use std::num::TryFromIntError;
8+
9+use crate::codec::av1::helpers::clip3;
10+use crate::codec::av1::parser::BitDepth;
11+use crate::codec::av1::parser::ChromaSamplePosition;
12+use crate::codec::av1::parser::ColorPrimaries;
13+use crate::codec::av1::parser::FrameHeaderObu;
14+use crate::codec::av1::parser::FrameRestorationType;
15+use crate::codec::av1::parser::FrameType;
16+use crate::codec::av1::parser::InterpolationFilter;
17+use crate::codec::av1::parser::MatrixCoefficients;
18+use crate::codec::av1::parser::ObuHeader;
19+use crate::codec::av1::parser::ObuType;
20+use crate::codec::av1::parser::Profile;
21+use crate::codec::av1::parser::ReferenceFrameType;
22+use crate::codec::av1::parser::SequenceHeaderObu;
23+use crate::codec::av1::parser::TemporalDelimiterObu;
24+use crate::codec::av1::parser::TransferCharacteristics;
25+use crate::codec::av1::parser::TxMode;
26+use crate::codec::av1::parser::WarpModelType;
27+use crate::codec::av1::parser::FEATURE_BITS;
28+use crate::codec::av1::parser::FEATURE_MAX;
29+use crate::codec::av1::parser::FEATURE_SIGNED;
30+use crate::codec::av1::parser::MAX_NUM_OPERATING_POINTS;
31+use crate::codec::av1::parser::MAX_NUM_PLANES;
32+use crate::codec::av1::parser::MAX_SEGMENTS;
33+use crate::codec::av1::parser::NUM_REF_FRAMES;
34+use crate::codec::av1::parser::PRIMARY_REF_NONE;
35+use crate::codec::av1::parser::REFS_PER_FRAME;
36+use crate::codec::av1::parser::SEG_LVL_MAX;
37+use crate::codec::av1::parser::SELECT_INTEGER_MV;
38+use crate::codec::av1::parser::SELECT_SCREEN_CONTENT_TOOLS;
39+use crate::codec::av1::parser::SUPERRES_DENOM_BITS;
40+use crate::codec::av1::parser::SUPERRES_DENOM_MIN;
41+use crate::codec::av1::parser::SUPERRES_NUM;
42+use crate::codec::av1::parser::TOTAL_REFS_PER_FRAME;
43+use crate::codec::av1::writer::ObuWriter;
44+use crate::codec::av1::writer::ObuWriterError;
45+
46+mod private {
47+ pub trait ObuStruct {}
48+}
49+
50+impl private::ObuStruct for SequenceHeaderObu {}
51+
52+impl private::ObuStruct for TemporalDelimiterObu {}
53+
54+impl private::ObuStruct for FrameHeaderObu {}
55+
56+#[derive(Debug)]
57+pub enum SynthesizerError {
58+ Unsupported,
59+ InvalidSyntaxElementValue(&'static str),
60+ ConversionError(TryFromIntError),
61+ ObuWriter(ObuWriterError),
62+ Io(std::io::Error),
63+}
64+
65+impl fmt::Display for SynthesizerError {
66+ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
67+ match self {
68+ SynthesizerError::Unsupported => write!(f, "tried to synthesize unsupported settings"),
69+ SynthesizerError::InvalidSyntaxElementValue(x) => {
70+ write!(f, "invalid syntax element for value {}", x)
71+ }
72+ SynthesizerError::ConversionError(x) => write!(f, "{}", x.to_string()),
73+ SynthesizerError::ObuWriter(x) => write!(f, "{}", x.to_string()),
74+ SynthesizerError::Io(x) => write!(f, "{}", x.to_string()),
75+ }
76+ }
77+}
78+
79+impl From<TryFromIntError> for SynthesizerError {
80+ fn from(err: TryFromIntError) -> Self {
81+ SynthesizerError::ConversionError(err)
82+ }
83+}
84+
85+impl From<ObuWriterError> for SynthesizerError {
86+ fn from(err: ObuWriterError) -> Self {
87+ SynthesizerError::ObuWriter(err)
88+ }
89+}
90+
91+impl From<std::io::Error> for SynthesizerError {
92+ fn from(err: std::io::Error) -> Self {
93+ SynthesizerError::Io(err)
94+ }
95+}
96+
97+pub type SynthesizerResult<T> = Result<T, SynthesizerError>;
98+
99+pub struct Synthesizer<'o, O: private::ObuStruct, W: Write> {
100+ writer: ObuWriter<W>,
101+ obu: &'o O,
102+}
103+
104+impl<'o, O, W> Synthesizer<'o, O, W>
105+where
106+ O: private::ObuStruct,
107+ W: Write,
108+{
109+ fn new(writer: W, obu: &'o O) -> Self {
110+ Self { writer: ObuWriter::new(writer), obu }
111+ }
112+
113+ fn f<T: Into<u32>>(&mut self, bits: usize, value: T) -> SynthesizerResult<()> {
114+ let value: u32 = value.into();
115+ self.writer.write_f(bits, value)?;
116+ Ok(())
117+ }
118+
119+ fn leb128<T: Into<u32>>(&mut self, value: T) -> SynthesizerResult<()> {
120+ let value: u32 = value.into();
121+ self.writer.write_leb128(value, 0)?;
122+ Ok(())
123+ }
124+
125+ fn uvlc<T: Into<u32>>(&mut self, value: T) -> SynthesizerResult<()> {
126+ self.writer.write_uvlc(value)?;
127+ Ok(())
128+ }
129+
130+ fn su<T: Into<i32>>(&mut self, bits: usize, value: T) -> SynthesizerResult<()> {
131+ self.writer.write_su(bits, value)?;
132+ Ok(())
133+ }
134+
135+ #[cfg(any(test, debug_assertions))]
136+ fn invalid_element_value(&mut self, element: &'static str) -> SynthesizerResult<()> {
137+ Err(SynthesizerError::InvalidSyntaxElementValue(element))
138+ }
139+
140+ #[cfg(not(any(test, debug_assertions)))]
141+ fn invalid_element_value(&mut self, element: &'static str) -> SynthesizerResult<()> {
142+ log::error!("Invalid syntax element value: '{element}', expect corrupted bitstream");
143+ Ok(())
144+ }
145+
146+ /// Writes 5.3.2. OBU header syntax
147+ fn obu_header(&mut self, obu: &ObuHeader) -> SynthesizerResult<()> {
148+ self.f(1, /* obu_forbidden_bit */ 0u32)?;
149+ self.f(4, obu.obu_type as u32)?;
150+ self.f(1, obu.extension_flag)?;
151+ self.f(1, obu.has_size_field)?;
152+ self.f(1, /* obu_reserved_1bit */ 0u32)?;
153+
154+ if obu.extension_flag {
155+ self.obu_extension_header(obu)?;
156+ }
157+
158+ Ok(())
159+ }
160+
161+ /// Writes AV1 5.3.3. OBU extension header syntax
162+ fn obu_extension_header(&mut self, obu: &ObuHeader) -> SynthesizerResult<()> {
163+ // AV1 5.3.3
164+ self.f(3, obu.temporal_id)?;
165+ self.f(2, obu.spatial_id)?;
166+ self.f(3, /* extension_header_reserved_3bits */ 0u32)?;
167+
168+ Ok(())
169+ }
170+
171+ fn obu_size(&mut self, size: u32) -> SynthesizerResult<()> {
172+ self.leb128(size)
173+ }
174+
175+ /// Writes AV1 5.3.4. Trailing bits syntax
176+ fn trailing_bits(&mut self) -> SynthesizerResult<()> {
177+ self.f(1, /* trailing_one_bit */ 1u32)?;
178+ while !self.writer.aligned() {
179+ self.f(1, /* trailing_zero_bit */ 0u32)?;
180+ }
181+
182+ Ok(())
183+ }
184+}
185+
186+impl<'o, W> Synthesizer<'o, TemporalDelimiterObu, W>
187+where
188+ W: Write,
189+{
190+ pub fn synthesize(obu: &'o TemporalDelimiterObu, writer: W) -> SynthesizerResult<()> {
191+ let mut s = Self::new(writer, obu);
192+
193+ if obu.obu_header.obu_type != ObuType::TemporalDelimiter {
194+ s.invalid_element_value("obu_type")?;
195+ }
196+
197+ s.obu_header(&obu.obu_header)?;
198+
199+ if obu.obu_header.has_size_field {
200+ s.obu_size(0u32)?;
201+ }
202+
203+ Ok(())
204+ }
205+}
206+
207+impl<'o, W> Synthesizer<'o, SequenceHeaderObu, W>
208+where
209+ W: Write,
210+{
211+ pub fn synthesize(obu: &'o SequenceHeaderObu, mut writer: W) -> SynthesizerResult<()> {
212+ let mut s = Synthesizer::new(&mut writer, obu);
213+
214+ if obu.obu_header.obu_type != ObuType::SequenceHeader {
215+ s.invalid_element_value("obu_type")?;
216+ }
217+
218+ s.obu_header(&obu.obu_header)?;
219+
220+ if !obu.obu_header.has_size_field {
221+ s.sequence_header_obu()?;
222+ s.trailing_bits()?;
223+ return Ok(());
224+ }
225+
226+ let mut buf = Vec::<u8>::new();
227+ let mut buffered = Synthesizer::new(&mut buf, obu);
228+ buffered.sequence_header_obu()?;
229+ buffered.trailing_bits()?;
230+ drop(buffered);
231+
232+ s.obu_size(buf.len() as u32)?;
233+ drop(s);
234+
235+ writer.write_all(&buf)?;
236+
237+ Ok(())
238+ }
239+
240+ /// Writes AV1 5.5.1. General sequence header OBU syntax
241+ fn sequence_header_obu(&mut self) -> SynthesizerResult<()> {
242+ self.f(3, self.obu.seq_profile as u32)?;
243+ self.f(1, self.obu.still_picture)?;
244+ self.f(1, self.obu.reduced_still_picture_header)?;
245+
246+ if self.obu.reduced_still_picture_header {
247+ if self.obu.timing_info_present_flag {
248+ self.invalid_element_value("reduced_still_picture_header")?
249+ }
250+ if self.obu.timing_info_present_flag {
251+ self.invalid_element_value("timing_info_present_flag")?
252+ }
253+ if self.obu.initial_display_delay_present_flag {
254+ self.invalid_element_value("initial_display_delay_present_flag")?
255+ }
256+ if self.obu.operating_points_cnt_minus_1 != 0 {
257+ self.invalid_element_value("operating_points_cnt_minus_1")?
258+ }
259+ if self.obu.operating_points[0].idc != 0 {
260+ self.invalid_element_value("operating_point_idc")?
261+ }
262+
263+ self.f(5, self.obu.operating_points[0].seq_level_idx)?;
264+
265+ if self.obu.operating_points[0].decoder_model_present_for_this_op {
266+ self.invalid_element_value("decoder_model_present_for_this_op")?
267+ }
268+ if self.obu.operating_points[0].initial_display_delay_present_for_this_op {
269+ self.invalid_element_value("initial_display_delay_present_for_this_op")?
270+ }
271+ } else {
272+ self.f(1, self.obu.timing_info_present_flag)?;
273+ if self.obu.timing_info_present_flag {
274+ self.timing_info()?;
275+ self.f(1, self.obu.decoder_model_info_present_flag)?;
276+ if self.obu.decoder_model_info_present_flag {
277+ self.decoder_model_info()?;
278+ }
279+ } else if self.obu.decoder_model_info_present_flag {
280+ self.invalid_element_value("decoder_model_info_present_flag")?;
281+ }
282+
283+ self.f(1, self.obu.initial_display_delay_present_flag)?;
284+
285+ if self.obu.operating_points_cnt_minus_1 > MAX_NUM_OPERATING_POINTS as u32 {
286+ self.invalid_element_value("operating_points_cnt_minus_1")?;
287+ }
288+ self.f(5, self.obu.operating_points_cnt_minus_1)?;
289+ for i in 0..=self.obu.operating_points_cnt_minus_1 {
290+ let op = &self.obu.operating_points[i as usize];
291+
292+ self.f(12, op.idc)?;
293+ self.f(5, op.seq_level_idx)?;
294+ if op.seq_level_idx > 7 {
295+ self.f(1, op.seq_tier)?;
296+ } else if op.seq_tier != 0 {
297+ self.invalid_element_value("seq_tier")?;
298+ }
299+
300+ if self.obu.decoder_model_info_present_flag {
301+ self.f(1, op.decoder_model_present_for_this_op)?;
302+ if op.decoder_model_present_for_this_op {
303+ self.operating_parameters_info(i as usize)?;
304+ }
305+ } else if op.decoder_model_present_for_this_op {
306+ self.invalid_element_value("decoder_model_present_for_this_op")?;
307+ }
308+
309+ if self.obu.initial_display_delay_present_flag {
310+ self.f(1, op.initial_display_delay_present_for_this_op)?;
311+ if op.initial_display_delay_present_for_this_op {
312+ self.f(4, op.initial_display_delay_minus_1)?;
313+ }
314+ }
315+ }
316+ }
317+
318+ let bits = u16::BITS - self.obu.max_frame_width_minus_1.leading_zeros();
319+ if self.obu.frame_width_bits_minus_1 as u32 + 1 < bits {
320+ self.invalid_element_value("frame_width_bits_minus_1")?;
321+ }
322+
323+ let bits = u16::BITS - self.obu.max_frame_height_minus_1.leading_zeros();
324+ if self.obu.frame_height_bits_minus_1 as u32 + 1 < bits {
325+ self.invalid_element_value("frame_height_bits_minus_1")?;
326+ }
327+
328+ self.f(4, self.obu.frame_width_bits_minus_1)?;
329+ self.f(4, self.obu.frame_height_bits_minus_1)?;
330+
331+ let n = self.obu.frame_width_bits_minus_1 as usize + 1;
332+ if (n as u32) < u16::BITS - self.obu.max_frame_width_minus_1.leading_zeros() {
333+ self.invalid_element_value("max_frame_width_minus_1")?;
334+ }
335+ self.f(n, self.obu.max_frame_width_minus_1)?;
336+
337+ let n = self.obu.frame_height_bits_minus_1 as usize + 1;
338+ if (n as u32) < u16::BITS - self.obu.max_frame_height_minus_1.leading_zeros() {
339+ self.invalid_element_value("max_frame_height_minus_1")?;
340+ }
341+ self.f(n, self.obu.max_frame_height_minus_1)?;
342+
343+ if self.obu.reduced_still_picture_header {
344+ if self.obu.frame_id_numbers_present_flag {
345+ self.invalid_element_value("frame_id_numbers_present_flag")?;
346+ }
347+ } else {
348+ self.f(1, self.obu.frame_id_numbers_present_flag)?;
349+ }
350+
351+ if self.obu.frame_id_numbers_present_flag {
352+ self.f(4, self.obu.delta_frame_id_length_minus_2)?;
353+ self.f(3, self.obu.additional_frame_id_length_minus_1)?;
354+ }
355+
356+ self.f(1, self.obu.use_128x128_superblock)?;
357+ self.f(1, self.obu.enable_filter_intra)?;
358+ self.f(1, self.obu.enable_intra_edge_filter)?;
359+
360+ if self.obu.reduced_still_picture_header {
361+ if self.obu.enable_interintra_compound {
362+ self.invalid_element_value("enable_interintra_compound")?;
363+ }
364+ if self.obu.enable_masked_compound {
365+ self.invalid_element_value("enable_masked_compound")?;
366+ }
367+ if self.obu.enable_warped_motion {
368+ self.invalid_element_value("enable_warped_motion")?;
369+ }
370+ if self.obu.enable_dual_filter {
371+ self.invalid_element_value("enable_dual_filter")?;
372+ }
373+ if self.obu.enable_order_hint {
374+ self.invalid_element_value("enable_order_hint")?;
375+ }
376+ if self.obu.enable_jnt_comp {
377+ self.invalid_element_value("enable_jnt_comp")?;
378+ }
379+ if self.obu.enable_ref_frame_mvs {
380+ self.invalid_element_value("enable_ref_frame_mvs")?;
381+ }
382+ if self.obu.seq_force_screen_content_tools != SELECT_SCREEN_CONTENT_TOOLS as u32 {
383+ self.invalid_element_value("seq_force_screen_content_tools")?;
384+ }
385+ if self.obu.seq_force_integer_mv != SELECT_INTEGER_MV as u32 {
386+ self.invalid_element_value("seq_force_integer_mv")?;
387+ }
388+ if self.obu.order_hint_bits != 0 {
389+ self.invalid_element_value("OrderHintBits")?;
390+ }
391+ } else {
392+ self.f(1, self.obu.enable_interintra_compound)?;
393+ self.f(1, self.obu.enable_masked_compound)?;
394+ self.f(1, self.obu.enable_warped_motion)?;
395+ self.f(1, self.obu.enable_dual_filter)?;
396+ self.f(1, self.obu.enable_order_hint)?;
397+
398+ if self.obu.enable_order_hint {
399+ self.f(1, self.obu.enable_jnt_comp)?;
400+ self.f(1, self.obu.enable_ref_frame_mvs)?;
401+ } else {
402+ if self.obu.enable_jnt_comp {
403+ self.invalid_element_value("enable_jnt_comp")?;
404+ }
405+ if self.obu.enable_ref_frame_mvs {
406+ self.invalid_element_value("enable_ref_frame_mvs")?;
407+ }
408+ }
409+
410+ self.f(1, self.obu.seq_choose_screen_content_tools)?;
411+ if self.obu.seq_choose_screen_content_tools {
412+ if self.obu.seq_force_screen_content_tools != SELECT_SCREEN_CONTENT_TOOLS as u32 {
413+ self.invalid_element_value("seq_force_screen_content_tools")?;
414+ }
415+ } else {
416+ self.f(1, self.obu.seq_force_screen_content_tools)?;
417+ }
418+
419+ if self.obu.seq_force_screen_content_tools > 0 {
420+ self.f(1, self.obu.seq_choose_integer_mv)?;
421+ if self.obu.seq_choose_integer_mv {
422+ if self.obu.seq_force_integer_mv != SELECT_INTEGER_MV as u32 {
423+ self.invalid_element_value("seq_force_integer_mv")?;
424+ }
425+ } else {
426+ self.f(1, self.obu.seq_force_integer_mv)?;
427+ }
428+ } else if self.obu.seq_force_integer_mv != SELECT_INTEGER_MV as u32 {
429+ self.invalid_element_value("seq_force_integer_mv")?;
430+ }
431+
432+ if self.obu.enable_order_hint {
433+ self.f(3, self.obu.order_hint_bits_minus_1 as u32)?;
434+ if self.obu.order_hint_bits != self.obu.order_hint_bits_minus_1 + 1 {
435+ self.invalid_element_value("OrderHintBits")?;
436+ }
437+ } else if self.obu.order_hint_bits != 0 {
438+ self.invalid_element_value("OrderHintBits")?;
439+ }
440+ }
441+
442+ self.f(1, self.obu.enable_superres)?;
443+ self.f(1, self.obu.enable_cdef)?;
444+ self.f(1, self.obu.enable_restoration)?;
445+ self.color_config()?;
446+ self.f(1, self.obu.film_grain_params_present)?;
447+
448+ Ok(())
449+ }
450+
451+ /// Writes AV1 5.5.2. Color config syntax
452+ fn color_config(&mut self) -> SynthesizerResult<()> {
453+ let cc = &self.obu.color_config;
454+
455+ self.f(1, cc.high_bitdepth)?;
456+ if matches!(self.obu.seq_profile, Profile::Profile2) && cc.high_bitdepth {
457+ self.f(1, cc.twelve_bit)?;
458+
459+ if (cc.twelve_bit && self.obu.bit_depth != BitDepth::Depth12)
460+ || (!cc.twelve_bit && self.obu.bit_depth != BitDepth::Depth10)
461+ {
462+ self.invalid_element_value("BitDepth")?;
463+ }
464+ } else if self.obu.seq_profile <= Profile::Profile2
465+ && ((cc.high_bitdepth && self.obu.bit_depth != BitDepth::Depth10)
466+ || (!cc.high_bitdepth && self.obu.bit_depth != BitDepth::Depth8))
467+ {
468+ self.invalid_element_value("BitDepth")?;
469+ }
470+
471+ if matches!(self.obu.seq_profile, Profile::Profile1) {
472+ if cc.mono_chrome {
473+ self.invalid_element_value("mono_chrome")?;
474+ }
475+ } else {
476+ self.f(1, cc.mono_chrome)?;
477+ }
478+
479+ if (cc.mono_chrome && self.obu.num_planes != 1)
480+ || (!cc.mono_chrome && self.obu.num_planes != 3)
481+ {
482+ self.invalid_element_value("NumPlanes")?;
483+ }
484+
485+ self.f(1, cc.color_description_present_flag)?;
486+ if cc.color_description_present_flag {
487+ self.f(8, cc.color_primaries as u32)?;
488+ self.f(8, cc.transfer_characteristics as u32)?;
489+ self.f(8, cc.matrix_coefficients as u32)?;
490+ } else {
491+ if !matches!(cc.color_primaries, ColorPrimaries::Unspecified) {
492+ self.invalid_element_value("color_primaries")?;
493+ }
494+ if !matches!(cc.transfer_characteristics, TransferCharacteristics::Unspecified) {
495+ self.invalid_element_value("transfer_characteristics")?;
496+ }
497+ if !matches!(cc.matrix_coefficients, MatrixCoefficients::Unspecified) {
498+ self.invalid_element_value("matrix_coefficients")?;
499+ }
500+ }
501+
502+ if cc.mono_chrome {
503+ self.f(1, cc.color_range)?;
504+
505+ if !cc.subsampling_x {
506+ self.invalid_element_value("subsampling_x")?;
507+ }
508+ if !cc.subsampling_y {
509+ self.invalid_element_value("subsampling_y")?;
510+ }
511+ if !matches!(cc.chroma_sample_position, ChromaSamplePosition::Unknown) {
512+ self.invalid_element_value("chroma_sample_position")?;
513+ }
514+ if !matches!(cc.chroma_sample_position, ChromaSamplePosition::Unknown) {
515+ self.invalid_element_value("chroma_sample_position")?;
516+ }
517+ if cc.separate_uv_delta_q {
518+ self.invalid_element_value("separate_uv_delta_q")?;
519+ }
520+
521+ return Ok(());
522+ } else if matches!(cc.color_primaries, ColorPrimaries::Bt709)
523+ && matches!(cc.transfer_characteristics, TransferCharacteristics::Srgb)
524+ && matches!(cc.matrix_coefficients, MatrixCoefficients::Identity)
525+ {
526+ if !cc.color_range {
527+ self.invalid_element_value("color_range")?;
528+ }
529+ if cc.subsampling_x {
530+ self.invalid_element_value("subsampling_x")?;
531+ }
532+ if cc.subsampling_y {
533+ self.invalid_element_value("subsampling_y")?;
534+ }
535+ } else {
536+ self.f(1, cc.color_range)?;
537+
538+ match self.obu.seq_profile {
539+ Profile::Profile0 => {
540+ if !cc.subsampling_x {
541+ self.invalid_element_value("subsampling_x")?;
542+ }
543+ if !cc.subsampling_y {
544+ self.invalid_element_value("subsampling_y")?;
545+ }
546+ }
547+ Profile::Profile1 => {
548+ if cc.subsampling_x {
549+ self.invalid_element_value("subsampling_x")?;
550+ }
551+ if cc.subsampling_y {
552+ self.invalid_element_value("subsampling_y")?;
553+ }
554+ }
555+ _ => {
556+ if matches!(self.obu.bit_depth, BitDepth::Depth12) {
557+ self.f(1, cc.subsampling_x)?;
558+ if cc.subsampling_x {
559+ self.f(1, cc.subsampling_y)?;
560+ } else if cc.subsampling_y {
561+ self.invalid_element_value("subsampling_y")?;
562+ }
563+ } else {
564+ if !cc.subsampling_x {
565+ self.invalid_element_value("subsampling_x")?;
566+ }
567+ if cc.subsampling_y {
568+ self.invalid_element_value("subsampling_y")?;
569+ }
570+ }
571+ }
572+ }
573+
574+ if cc.subsampling_x && cc.subsampling_y {
575+ self.f(2, cc.chroma_sample_position as u32)?;
576+ }
577+ }
578+
579+ self.f(1, cc.separate_uv_delta_q)?;
580+
581+ Ok(())
582+ }
583+
584+ /// Writes AV1 5.5.3. Timing info syntax
585+ fn timing_info(&mut self) -> SynthesizerResult<()> {
586+ // AV1 5.5.3
587+ let ti = &self.obu.timing_info;
588+
589+ self.f(32, ti.num_units_in_display_tick)?;
590+ self.f(32, ti.time_scale)?;
591+ self.f(1, ti.equal_picture_interval)?;
592+ if ti.equal_picture_interval {
593+ self.uvlc(ti.num_ticks_per_picture_minus_1)?;
594+ }
595+
596+ Ok(())
597+ }
598+
599+ /// Writes AV1 5.5.4. Decoder model info syntax
600+ fn decoder_model_info(&mut self) -> SynthesizerResult<()> {
601+ let dm = &self.obu.decoder_model_info;
602+
603+ self.f(5, dm.buffer_delay_length_minus_1)?;
604+ self.f(32, dm.num_units_in_decoding_tick)?;
605+ self.f(5, dm.buffer_removal_time_length_minus_1)?;
606+ self.f(5, dm.frame_presentation_time_length_minus_1)?;
607+
608+ Ok(())
609+ }
610+
611+ /// Writes AV1 5.5.5. Operating parameters info syntax
612+ fn operating_parameters_info(&mut self, i: usize) -> SynthesizerResult<()> {
613+ let op = &self.obu.operating_points[i];
614+
615+ let n = usize::from(self.obu.decoder_model_info.buffer_delay_length_minus_1) + 1;
616+ self.f(n, op.decoder_buffer_delay)?;
617+ self.f(n, op.encoder_buffer_delay)?;
618+ self.f(1, op.low_delay_mode_flag)?;
619+
620+ Ok(())
621+ }
622+}
623+
624+impl<'o, W> Synthesizer<'o, FrameHeaderObu, W>
625+where
626+ W: Write,
627+{
628+ pub fn synthesize(
629+ obu: &'o FrameHeaderObu,
630+ sequence: &'o SequenceHeaderObu,
631+ mut writer: W,
632+ ) -> SynthesizerResult<()> {
633+ let mut s = Synthesizer::new(&mut writer, obu);
634+
635+ if obu.obu_header.obu_type != ObuType::FrameHeader {
636+ s.invalid_element_value("obu_type")?;
637+ }
638+
639+ s.obu_header(&obu.obu_header)?;
640+
641+ if !obu.obu_header.has_size_field {
642+ s.frame_header_obu(sequence)?;
643+ s.trailing_bits()?;
644+ return Ok(());
645+ }
646+
647+ let mut buf = Vec::<u8>::new();
648+ let mut buffered = Synthesizer::new(&mut buf, obu);
649+ buffered.frame_header_obu(sequence)?;
650+ buffered.trailing_bits()?;
651+ drop(buffered);
652+
653+ s.obu_size(buf.len() as u32)?;
654+ drop(s);
655+
656+ writer.write_all(&buf)?;
657+
658+ Ok(())
659+ }
660+
661+ /// Writes AV1 5.9.1. General frame header OBU syntax
662+ fn frame_header_obu(&mut self, sequence: &'o SequenceHeaderObu) -> SynthesizerResult<()> {
663+ self.uncompressed_header(sequence)
664+ }
665+
666+ /// Writes AV1 5.9.2. Uncompressed header syntax
667+ fn uncompressed_header(&mut self, sequence: &'o SequenceHeaderObu) -> SynthesizerResult<()> {
668+ const ALL_FRAMES: u32 = (1 << NUM_REF_FRAMES) - 1;
669+
670+ // idLen
671+ let id_len = usize::try_from(
672+ sequence.additional_frame_id_length_minus_1
673+ + sequence.delta_frame_id_length_minus_2
674+ + 3,
675+ )?;
676+
677+ if sequence.reduced_still_picture_header {
678+ if !self.obu.show_existing_frame {
679+ self.invalid_element_value("show_existing_frame")?;
680+ }
681+ if !matches!(self.obu.frame_type, FrameType::KeyFrame) {
682+ self.invalid_element_value("frame_type")?;
683+ }
684+ if !self.obu.show_frame {
685+ self.invalid_element_value("show_frame")?;
686+ }
687+ if !self.obu.showable_frame {
688+ self.invalid_element_value("showable_frame")?;
689+ }
690+ if !self.obu.frame_is_intra {
691+ self.invalid_element_value("FrameIsIntra")?;
692+ }
693+ } else {
694+ self.f(1, self.obu.show_existing_frame)?;
695+ if self.obu.show_existing_frame {
696+ self.f(3, self.obu.frame_to_show_map_idx)?;
697+
698+ if sequence.decoder_model_info_present_flag
699+ && !sequence.timing_info.equal_picture_interval
700+ {
701+ self.temporal_point_info(sequence)?;
702+ }
703+
704+ if sequence.frame_id_numbers_present_flag {
705+ self.f(id_len, self.obu.display_frame_id)?;
706+ }
707+ return Ok(());
708+ }
709+
710+ self.f(2, self.obu.frame_type as u32)?;
711+ if self.obu.frame_is_intra
712+ ^ matches!(self.obu.frame_type, FrameType::IntraOnlyFrame | FrameType::KeyFrame)
713+ {
714+ self.invalid_element_value("FrameIsIntra")?;
715+ }
716+
717+ self.f(1, self.obu.show_frame)?;
718+ if self.obu.show_frame
719+ && sequence.decoder_model_info_present_flag
720+ && !sequence.timing_info.equal_picture_interval
721+ {
722+ self.temporal_point_info(sequence)?;
723+ }
724+
725+ if self.obu.show_frame {
726+ if self.obu.showable_frame ^ !matches!(self.obu.frame_type, FrameType::KeyFrame) {
727+ self.invalid_element_value("showable_frame")?;
728+ }
729+ } else {
730+ self.f(1, self.obu.showable_frame)?;
731+ }
732+
733+ if matches!(self.obu.frame_type, FrameType::SwitchFrame)
734+ || (matches!(self.obu.frame_type, FrameType::KeyFrame) && self.obu.show_frame)
735+ {
736+ if !self.obu.error_resilient_mode {
737+ self.invalid_element_value("error_resilient_mode")?;
738+ }
739+ } else {
740+ self.f(1, self.obu.error_resilient_mode)?;
741+ }
742+ }
743+
744+ self.f(1, self.obu.disable_cdf_update)?;
745+ if sequence.seq_force_screen_content_tools == SELECT_SCREEN_CONTENT_TOOLS as u32 {
746+ self.f(1, self.obu.allow_screen_content_tools)?;
747+ } else if self.obu.allow_screen_content_tools != sequence.seq_force_screen_content_tools {
748+ self.invalid_element_value("allow_screen_content_tools")?;
749+ }
750+
751+ if self.obu.allow_screen_content_tools != 0 {
752+ if sequence.seq_force_integer_mv == SELECT_INTEGER_MV as u32 {
753+ self.f(1, self.obu.force_integer_mv)?;
754+ } else if self.obu.force_integer_mv != sequence.seq_force_integer_mv {
755+ self.invalid_element_value("force_integer_mv")?;
756+ }
757+ } else if self.obu.force_integer_mv != 0
758+ && !(self.obu.frame_is_intra && self.obu.force_integer_mv != 1)
759+ {
760+ self.invalid_element_value("force_integer_mv")?;
761+ }
762+
763+ if sequence.frame_id_numbers_present_flag {
764+ self.f(id_len, self.obu.current_frame_id)?;
765+ } else if self.obu.current_frame_id != 0 {
766+ self.invalid_element_value("current_frame_id")?;
767+ }
768+
769+ if matches!(self.obu.frame_type, FrameType::SwitchFrame) {
770+ if !self.obu.frame_size_override_flag {
771+ self.invalid_element_value("frame_size_override_flag")?;
772+ }
773+ } else if sequence.reduced_still_picture_header {
774+ if self.obu.frame_size_override_flag {
775+ self.invalid_element_value("frame_size_override_flag")?;
776+ }
777+ } else {
778+ self.f(1, self.obu.frame_size_override_flag)?;
779+ }
780+
781+ if sequence.order_hint_bits != 0 {
782+ if sequence.order_hint_bits != sequence.order_hint_bits_minus_1 + 1 {
783+ self.invalid_element_value("order_hint_bits_minus_1")?;
784+ }
785+
786+ self.f(sequence.order_hint_bits as usize, self.obu.order_hint)?;
787+ }
788+
789+ if self.obu.frame_is_intra || self.obu.error_resilient_mode {
790+ if self.obu.primary_ref_frame != PRIMARY_REF_NONE {
791+ self.invalid_element_value("primary_ref_frame")?;
792+ }
793+ } else {
794+ self.f(3, self.obu.primary_ref_frame)?;
795+ }
796+
797+ if sequence.decoder_model_info_present_flag {
798+ self.f(1, self.obu.buffer_removal_time_present_flag)?;
799+
800+ for op_num in 0..=sequence.operating_points_cnt_minus_1 {
801+ let op = &sequence.operating_points[op_num as usize];
802+ if op.decoder_model_present_for_this_op {
803+ let in_temporal_layer = (op.idc >> self.obu.obu_header.temporal_id) & 1 != 0;
804+ let in_spatial_layer =
805+ (op.idc >> (self.obu.obu_header.spatial_id + 8)) & 1 != 0;
806+
807+ if op.idc == 0 || (in_temporal_layer && in_spatial_layer) {
808+ let n = usize::from(
809+ sequence.decoder_model_info.buffer_removal_time_length_minus_1 + 1,
810+ );
811+
812+ self.f(n, op.decoder_buffer_delay)?;
813+ }
814+ }
815+ }
816+ }
817+
818+ if matches!(self.obu.frame_type, FrameType::SwitchFrame)
819+ || (matches!(self.obu.frame_type, FrameType::KeyFrame) && self.obu.show_frame)
820+ {
821+ if self.obu.refresh_frame_flags != ALL_FRAMES {
822+ self.invalid_element_value("refresh_frame_flags")?;
823+ }
824+ } else {
825+ self.f(8, self.obu.refresh_frame_flags)?;
826+ }
827+
828+ if (!self.obu.frame_is_intra || self.obu.refresh_frame_flags != ALL_FRAMES)
829+ && self.obu.error_resilient_mode
830+ && sequence.enable_order_hint
831+ {
832+ for i in 0..NUM_REF_FRAMES {
833+ self.f(sequence.order_hint_bits as usize, self.obu.ref_order_hint[i])?;
834+ }
835+ }
836+
837+ if self.obu.frame_is_intra {
838+ self.frame_size(sequence)?;
839+ self.render_size()?;
840+
841+ if self.obu.allow_screen_content_tools != 0
842+ && self.obu.upscaled_width == self.obu.frame_width
843+ {
844+ self.f(1, self.obu.allow_intrabc)?;
845+ }
846+ } else {
847+ if !sequence.enable_order_hint {
848+ if self.obu.frame_refs_short_signaling {
849+ self.invalid_element_value("frame_refs_short_signaling")?;
850+ }
851+ } else {
852+ self.f(1, self.obu.frame_refs_short_signaling)?;
853+ if self.obu.frame_refs_short_signaling {
854+ self.f(3, self.obu.last_frame_idx)?;
855+ self.f(3, self.obu.gold_frame_idx)?;
856+ }
857+ }
858+
859+ for i in 0..REFS_PER_FRAME {
860+ let ref_frame_idx = self.obu.ref_frame_idx[i] as u32;
861+ if !self.obu.frame_refs_short_signaling {
862+ self.f(3, ref_frame_idx)?;
863+ }
864+
865+ if sequence.frame_id_numbers_present_flag {
866+ let n = usize::try_from(sequence.delta_frame_id_length_minus_2 + 2)?;
867+
868+ let delta_frame_id_minus_1 = ((self.obu.current_frame_id - ref_frame_idx
869+ + (1 << id_len))
870+ % (1 << id_len))
871+ - 1;
872+
873+ self.f(n, delta_frame_id_minus_1)?;
874+ }
875+ }
876+
877+ if self.obu.frame_size_override_flag && !self.obu.error_resilient_mode {
878+ self.frame_size_with_refs()?;
879+ } else {
880+ self.frame_size(sequence)?;
881+ self.render_size()?;
882+ }
883+
884+ if self.obu.force_integer_mv != 0 {
885+ if !self.obu.allow_high_precision_mv {
886+ self.invalid_element_value("allow_high_precision_mv")?;
887+ }
888+ } else {
889+ self.f(1, self.obu.allow_high_precision_mv)?;
890+ }
891+
892+ self.read_interpolation_filter()?;
893+ self.f(1, self.obu.is_motion_mode_switchable)?;
894+
895+ if self.obu.error_resilient_mode || !sequence.enable_ref_frame_mvs {
896+ if self.obu.use_ref_frame_mvs {
897+ self.invalid_element_value("use_ref_frame_mvs")?;
898+ }
899+ } else {
900+ self.f(1, self.obu.use_ref_frame_mvs)?;
901+ }
902+ }
903+
904+ if sequence.reduced_still_picture_header || self.obu.disable_cdf_update {
905+ if !self.obu.disable_frame_end_update_cdf {
906+ self.invalid_element_value("disable_frame_end_update_cdf")?
907+ }
908+ } else {
909+ self.f(1, self.obu.disable_frame_end_update_cdf)?;
910+ }
911+
912+ self.tile_info()?;
913+ self.quantization_params(sequence)?;
914+ self.segmentation_params()?;
915+
916+ self.delta_q_params()?;
917+ self.delta_lf_params()?;
918+
919+ if self.obu.coded_lossless && self.obu.lossless_array != [true; MAX_SEGMENTS] {
920+ self.invalid_element_value("CodedLossless")?;
921+ }
922+
923+ if self.obu.all_lossless
924+ ^ (self.obu.coded_lossless && self.obu.frame_width == self.obu.upscaled_width)
925+ {
926+ self.invalid_element_value("AllLossless")?;
927+ }
928+
929+ self.loop_filter_params(sequence)?;
930+ self.cdef_params(sequence)?;
931+ self.lr_params(sequence)?;
932+ self.read_tx_mode()?;
933+ self.frame_reference_mode()?;
934+ self.skip_mode_params()?;
935+
936+ if self.obu.frame_is_intra
937+ || self.obu.error_resilient_mode
938+ || !sequence.enable_warped_motion
939+ {
940+ if self.obu.allow_warped_motion {
941+ self.invalid_element_value("allow_warped_motion")?;
942+ }
943+ } else {
944+ self.f(1, self.obu.allow_warped_motion)?;
945+ }
946+
947+ self.f(1, self.obu.reduced_tx_set)?;
948+
949+ self.global_motion_params()?;
950+ self.film_grain_params(sequence)?;
951+
952+ Ok(())
953+ }
954+
955+ /// Writes AV1 5.9.31. Temporal point info syntax
956+ fn temporal_point_info(&mut self, sequence: &'o SequenceHeaderObu) -> SynthesizerResult<()> {
957+ let n = usize::try_from(
958+ sequence.decoder_model_info.frame_presentation_time_length_minus_1 + 1,
959+ )?;
960+
961+ self.f(n, self.obu.frame_presentation_time)?;
962+
963+ Ok(())
964+ }
965+
966+ /// Writes AV1 5.9.5. Frame size syntax
967+ fn frame_size(&mut self, sequence: &'o SequenceHeaderObu) -> SynthesizerResult<()> {
968+ if self.obu.frame_size_override_flag {
969+ let n = sequence.frame_width_bits_minus_1 as usize + 1;
970+ self.f(n, self.obu.frame_width - 1)?;
971+ let n = sequence.frame_height_bits_minus_1 as usize + 1;
972+ self.f(n, self.obu.frame_height - 1)?;
973+ } else {
974+ if self.obu.frame_width != sequence.max_frame_width_minus_1 as u32 + 1 {
975+ self.invalid_element_value("FrameWidth")?;
976+ }
977+ if self.obu.frame_height != sequence.max_frame_height_minus_1 as u32 + 1 {
978+ self.invalid_element_value("FrameHeight")?;
979+ }
980+
981+ self.superres_params(sequence)?;
982+ }
983+
984+ Ok(())
985+ }
986+
987+ /// Writes AV1 5.9.6. Render size syntax
988+ fn render_size(&mut self) -> SynthesizerResult<()> {
989+ self.f(1, self.obu.render_and_frame_size_different)?;
990+
991+ if self.obu.render_and_frame_size_different {
992+ self.f(16, self.obu.render_width - 1)?;
993+ self.f(16, self.obu.render_height - 1)?;
994+ } else {
995+ if self.obu.render_width != self.obu.upscaled_width {
996+ self.invalid_element_value("RenderWidth")?;
997+ }
998+ if self.obu.render_height != self.obu.frame_height {
999+ self.invalid_element_value("RenderHeight")?;
1000+ }
1001+ }
1002+
1003+ Ok(())
1004+ }
1005+
1006+ /// Writes AV1 5.9.7. Frame size with refs syntax
1007+ fn frame_size_with_refs(&mut self) -> SynthesizerResult<()> {
1008+ log::error!("Syntax element frame_size_with_refs is unsupported");
1009+ Err(SynthesizerError::Unsupported)
1010+ }
1011+
1012+ /// Writes AV1 5.9.8. Superres params syntax
1013+ fn superres_params(&mut self, sequence: &'o SequenceHeaderObu) -> SynthesizerResult<()> {
1014+ if sequence.enable_superres {
1015+ self.f(1, self.obu.use_superres)?;
1016+ } else if self.obu.use_superres {
1017+ self.invalid_element_value("use_superres")?;
1018+ }
1019+
1020+ if self.obu.use_superres {
1021+ let coded_denom = self.obu.superres_denom - SUPERRES_DENOM_MIN as u32;
1022+
1023+ self.f(SUPERRES_DENOM_BITS, coded_denom)?;
1024+ } else if self.obu.superres_denom != SUPERRES_NUM as u32 {
1025+ self.invalid_element_value("superres_denom")?;
1026+ }
1027+
1028+ Ok(())
1029+ }
1030+
1031+ /// Writes AV1 5.9.10. Interpolation filter syntax
1032+ fn read_interpolation_filter(&mut self) -> SynthesizerResult<()> {
1033+ self.f(1, self.obu.is_filter_switchable)?;
1034+ if self.obu.is_filter_switchable {
1035+ if !matches!(self.obu.interpolation_filter, InterpolationFilter::Switchable) {
1036+ self.invalid_element_value("interpolation_filter")?;
1037+ }
1038+ } else {
1039+ self.f(2, self.obu.interpolation_filter as u32)?;
1040+ }
1041+
1042+ Ok(())
1043+ }
1044+
1045+ /// Writes AV1 5.9.11. Loop filter params syntax
1046+ fn loop_filter_params(&mut self, sequence: &'o SequenceHeaderObu) -> SynthesizerResult<()> {
1047+ if self.obu.coded_lossless || self.obu.allow_intrabc {
1048+ if !matches!(self.obu.loop_filter_params.loop_filter_level, [0, 0, _, _]) {
1049+ self.invalid_element_value("loop_filter_level")?;
1050+ }
1051+ if self.obu.loop_filter_params.loop_filter_ref_deltas != [1, 0, 0, 0, 0, -1, -1, -1] {
1052+ self.invalid_element_value("loop_filter_ref_deltas")?;
1053+ }
1054+ if self.obu.loop_filter_params.loop_filter_mode_deltas != [0, 0] {
1055+ self.invalid_element_value("loop_filter_mode_deltas")?;
1056+ }
1057+ return Ok(());
1058+ }
1059+
1060+ self.f(6, self.obu.loop_filter_params.loop_filter_level[0])?;
1061+ self.f(6, self.obu.loop_filter_params.loop_filter_level[1])?;
1062+ if sequence.num_planes > 1
1063+ && self.obu.loop_filter_params.loop_filter_level[0] != 0
1064+ && self.obu.loop_filter_params.loop_filter_level[1] != 0
1065+ {
1066+ self.f(6, self.obu.loop_filter_params.loop_filter_level[2])?;
1067+ self.f(6, self.obu.loop_filter_params.loop_filter_level[3])?;
1068+ }
1069+
1070+ self.f(3, self.obu.loop_filter_params.loop_filter_sharpness)?;
1071+ self.f(1, self.obu.loop_filter_params.loop_filter_delta_enabled)?;
1072+ if self.obu.loop_filter_params.loop_filter_delta_enabled {
1073+ self.f(1, self.obu.loop_filter_params.loop_filter_delta_update)?;
1074+ if self.obu.loop_filter_params.loop_filter_delta_update {
1075+ for i in 0..TOTAL_REFS_PER_FRAME {
1076+ // NOTE: Currently we have no way of checking if the value changed between
1077+ // frames, always update the value to make sure the decoder will recreate
1078+ // the same state.
1079+ const UPDATE_REF_DELTA: bool = true;
1080+ if UPDATE_REF_DELTA {
1081+ self.su(1 + 6, self.obu.loop_filter_params.loop_filter_ref_deltas[i])?;
1082+ }
1083+ }
1084+
1085+ for i in 0..2 {
1086+ // NOTE: Same as above
1087+ const UPDATE_MODE_DELTA: bool = true;
1088+ if UPDATE_MODE_DELTA {
1089+ self.su(1 + 6, self.obu.loop_filter_params.loop_filter_mode_deltas[i])?;
1090+ }
1091+ }
1092+ }
1093+ }
1094+
1095+ Ok(())
1096+ }
1097+
1098+ /// Writes AV1 5.9.12. Quantization params syntax
1099+ fn quantization_params(&mut self, sequence: &'o SequenceHeaderObu) -> SynthesizerResult<()> {
1100+ self.f(8, self.obu.quantization_params.base_q_idx)?;
1101+ self.read_delta_q(self.obu.quantization_params.delta_q_y_dc)?;
1102+ if sequence.num_planes > 1 {
1103+ if sequence.color_config.separate_uv_delta_q {
1104+ self.f(1, self.obu.quantization_params.diff_uv_delta)?;
1105+ } else if self.obu.quantization_params.diff_uv_delta {
1106+ self.invalid_element_value("diff_uv_delta")?;
1107+ };
1108+
1109+ self.read_delta_q(self.obu.quantization_params.delta_q_u_dc)?;
1110+ self.read_delta_q(self.obu.quantization_params.delta_q_u_ac)?;
1111+
1112+ if self.obu.quantization_params.diff_uv_delta {
1113+ self.read_delta_q(self.obu.quantization_params.delta_q_v_dc)?;
1114+ self.read_delta_q(self.obu.quantization_params.delta_q_v_ac)?;
1115+ } else {
1116+ if self.obu.quantization_params.delta_q_v_dc != 0 {
1117+ self.invalid_element_value("delta_q_v_dc")?;
1118+ }
1119+ if self.obu.quantization_params.delta_q_v_ac != 0 {
1120+ self.invalid_element_value("delta_q_v_ac")?;
1121+ }
1122+ }
1123+ } else {
1124+ if self.obu.quantization_params.delta_q_u_dc != 0 {
1125+ self.invalid_element_value("delta_q_u_dc")?;
1126+ }
1127+ if self.obu.quantization_params.delta_q_u_ac != 0 {
1128+ self.invalid_element_value("delta_q_u_ac")?;
1129+ }
1130+ if self.obu.quantization_params.delta_q_v_dc != 0 {
1131+ self.invalid_element_value("delta_q_v_dc")?;
1132+ }
1133+ if self.obu.quantization_params.delta_q_v_ac != 0 {
1134+ self.invalid_element_value("delta_q_v_ac")?;
1135+ }
1136+ }
1137+
1138+ self.f(1, self.obu.quantization_params.using_qmatrix)?;
1139+ if self.obu.quantization_params.using_qmatrix {
1140+ self.f(4, self.obu.quantization_params.qm_y)?;
1141+ self.f(4, self.obu.quantization_params.qm_u)?;
1142+
1143+ if !sequence.color_config.separate_uv_delta_q {
1144+ if self.obu.quantization_params.qm_v != self.obu.quantization_params.qm_u {
1145+ self.invalid_element_value("qm_v")?;
1146+ }
1147+ } else {
1148+ self.f(4, self.obu.quantization_params.qm_v)?;
1149+ }
1150+ }
1151+
1152+ Ok(())
1153+ }
1154+
1155+ /// Writes AV1 5.9.13. Delta quantizer syntax
1156+ fn read_delta_q(&mut self, delta_q: i32) -> SynthesizerResult<()> {
1157+ self.f(1, delta_q != 0)?;
1158+ if delta_q != 0 {
1159+ self.su(1 + 6, delta_q)?;
1160+ }
1161+ Ok(())
1162+ }
1163+
1164+ /// Writes AV1 5.9.14. Segmentation params syntax
1165+ fn segmentation_params(&mut self) -> SynthesizerResult<()> {
1166+ self.f(1, self.obu.segmentation_params.segmentation_enabled)?;
1167+ if self.obu.segmentation_params.segmentation_enabled {
1168+ if self.obu.primary_ref_frame == PRIMARY_REF_NONE {
1169+ if !self.obu.segmentation_params.segmentation_update_map {
1170+ self.invalid_element_value("segmentation_update_map")?;
1171+ }
1172+
1173+ if self.obu.segmentation_params.segmentation_temporal_update {
1174+ self.invalid_element_value("segmentation_temporal_update")?;
1175+ }
1176+
1177+ if !self.obu.segmentation_params.segmentation_update_data {
1178+ self.invalid_element_value("segmentation_update_data")?;
1179+ }
1180+ } else {
1181+ self.f(1, self.obu.segmentation_params.segmentation_update_map)?;
1182+ if self.obu.segmentation_params.segmentation_update_map {
1183+ self.f(1, self.obu.segmentation_params.segmentation_temporal_update)?;
1184+ }
1185+ self.f(1, self.obu.segmentation_params.segmentation_temporal_update)?;
1186+ }
1187+
1188+ if self.obu.segmentation_params.segmentation_update_data {
1189+ for i in 0..MAX_SEGMENTS {
1190+ for j in 0..SEG_LVL_MAX {
1191+ let feature_enabled = self.obu.segmentation_params.feature_enabled[i][j];
1192+ self.f(1, feature_enabled)?;
1193+
1194+ if feature_enabled {
1195+ let bits_to_read = FEATURE_BITS[j] as usize;
1196+ let limit = FEATURE_MAX[j];
1197+ let signed = FEATURE_SIGNED[j];
1198+
1199+ let value = i32::from(self.obu.segmentation_params.feature_data[i][j]);
1200+ if signed {
1201+ let clipped_value = clip3(-limit, limit, value);
1202+ self.su(bits_to_read + 1, clipped_value)?;
1203+ } else {
1204+ let clipped_value = clip3(0, limit, value);
1205+ self.f(bits_to_read, u32::try_from(clipped_value)?)?;
1206+ }
1207+ }
1208+ }
1209+ }
1210+ } else {
1211+ if self.obu.segmentation_params.feature_enabled
1212+ != [[false; SEG_LVL_MAX]; MAX_SEGMENTS]
1213+ {
1214+ self.invalid_element_value("feature_enabled")?;
1215+ }
1216+ if self.obu.segmentation_params.feature_data != [[0; SEG_LVL_MAX]; MAX_SEGMENTS] {
1217+ self.invalid_element_value("feature_data")?;
1218+ }
1219+ }
1220+ }
1221+
1222+ Ok(())
1223+ }
1224+
1225+ /// Writes AV1 5.9.15. Tile info syntax
1226+ fn tile_info(&mut self) -> SynthesizerResult<()> {
1227+ // From AV1 5.9.9. Compute image size function
1228+ self.f(1, self.obu.tile_info.uniform_tile_spacing_flag)?;
1229+ if self.obu.tile_info.uniform_tile_spacing_flag {
1230+ if self.obu.tile_info.tile_cols != 1
1231+ && self.obu.tile_info.tile_cols_log2 != 0
1232+ && self.obu.tile_info.tile_rows != 1
1233+ && self.obu.tile_info.tile_rows_log2 != 0
1234+ {
1235+ // TODO: Allow more then single tile
1236+ log::error!("Only 1x1 tiles frame is currently supported");
1237+ return Err(SynthesizerError::Unsupported);
1238+ }
1239+
1240+ const INCREMENT_TILE_COLS_LOG2: u32 = 0;
1241+ const INCREMENT_TILE_ROWS_LOG2: u32 = 0;
1242+
1243+ self.f(1, INCREMENT_TILE_COLS_LOG2)?;
1244+ self.f(1, INCREMENT_TILE_ROWS_LOG2)?;
1245+ } else {
1246+ // TODO
1247+ log::error!("Only uniformly sized tiles are currently supported");
1248+ return Err(SynthesizerError::Unsupported);
1249+ }
1250+
1251+ Ok(())
1252+ }
1253+
1254+ /// Writes AV1 5.9.17. Quantizer index delta parameters syntax
1255+ fn delta_q_params(&mut self) -> SynthesizerResult<()> {
1256+ if self.obu.quantization_params.base_q_idx > 0 {
1257+ self.f(1, self.obu.quantization_params.delta_q_present)?;
1258+
1259+ if self.obu.quantization_params.delta_q_present {
1260+ self.f(2, self.obu.quantization_params.delta_q_res)?;
1261+ }
1262+ } else if self.obu.quantization_params.delta_q_present {
1263+ self.invalid_element_value("delta_q_present")?;
1264+ }
1265+
1266+ Ok(())
1267+ }
1268+
1269+ /// Writes AV1 5.9.18. Loop filter delta parameters syntax
1270+ fn delta_lf_params(&mut self) -> SynthesizerResult<()> {
1271+ if self.obu.quantization_params.delta_q_present {
1272+ if self.obu.allow_intrabc {
1273+ self.f(1, self.obu.loop_filter_params.delta_lf_present)?;
1274+
1275+ if self.obu.loop_filter_params.delta_lf_present {
1276+ self.f(2, self.obu.loop_filter_params.delta_lf_res)?;
1277+ self.f(1, self.obu.loop_filter_params.delta_lf_multi)?;
1278+ }
1279+ } else if self.obu.loop_filter_params.delta_lf_present {
1280+ self.invalid_element_value("delta_lf_present")?;
1281+ }
1282+ }
1283+
1284+ Ok(())
1285+ }
1286+
1287+ /// Writes AV1 5.9.19. CDEF params syntax
1288+ fn cdef_params(&mut self, sequence: &'o SequenceHeaderObu) -> SynthesizerResult<()> {
1289+ if self.obu.coded_lossless || self.obu.allow_intrabc || !sequence.enable_cdef {
1290+ if self.obu.cdef_params.cdef_bits != 0 {
1291+ self.invalid_element_value("cdef_bits")?;
1292+ }
1293+
1294+ if self.obu.cdef_params.cdef_y_pri_strength[0] != 0 {
1295+ self.invalid_element_value("cdef_y_pri_strength")?;
1296+ }
1297+
1298+ if self.obu.cdef_params.cdef_y_sec_strength[0] != 0 {
1299+ self.invalid_element_value("cdef_y_sec_strength")?;
1300+ }
1301+
1302+ if self.obu.cdef_params.cdef_uv_pri_strength[0] != 0 {
1303+ self.invalid_element_value("cdef_uv_pri_strength")?;
1304+ }
1305+
1306+ if self.obu.cdef_params.cdef_uv_sec_strength[0] != 0 {
1307+ self.invalid_element_value("cdef_uv_sec_strength")?;
1308+ }
1309+
1310+ if self.obu.cdef_params.cdef_damping != 3 {
1311+ self.invalid_element_value("cdef_damping")?;
1312+ }
1313+
1314+ return Ok(());
1315+ }
1316+
1317+ self.f(2, self.obu.cdef_params.cdef_damping - 3)?;
1318+ self.f(2, self.obu.cdef_params.cdef_bits)?;
1319+
1320+ for i in 0..(1 << self.obu.cdef_params.cdef_bits) {
1321+ self.f(4, self.obu.cdef_params.cdef_y_pri_strength[i])?;
1322+
1323+ let mut cdef_y_sec_strength = self.obu.cdef_params.cdef_y_sec_strength[i];
1324+ if cdef_y_sec_strength == 4 {
1325+ cdef_y_sec_strength -= 1;
1326+ }
1327+
1328+ self.f(2, cdef_y_sec_strength)?;
1329+
1330+ if sequence.num_planes > 1 {
1331+ self.f(4, self.obu.cdef_params.cdef_uv_pri_strength[i])?;
1332+
1333+ let mut cdef_uv_sec_strength = self.obu.cdef_params.cdef_uv_sec_strength[i];
1334+ if cdef_uv_sec_strength == 4 {
1335+ cdef_uv_sec_strength -= 1;
1336+ }
1337+
1338+ self.f(2, cdef_uv_sec_strength)?;
1339+ }
1340+ }
1341+
1342+ Ok(())
1343+ }
1344+
1345+ /// Writes AV1 5.9.20. Loop restoration params syntax
1346+ fn lr_params(&mut self, sequence: &'o SequenceHeaderObu) -> SynthesizerResult<()> {
1347+ if self.obu.all_lossless || self.obu.allow_intrabc || !sequence.enable_restoration {
1348+ if self.obu.loop_restoration_params.frame_restoration_type
1349+ != [FrameRestorationType::None; MAX_NUM_PLANES]
1350+ {
1351+ self.invalid_element_value("frame_restoration_type")?;
1352+ }
1353+
1354+ if self.obu.loop_restoration_params.uses_lr {
1355+ self.invalid_element_value("uses_lr")?;
1356+ }
1357+
1358+ return Ok(());
1359+ }
1360+
1361+ let mut uses_lr = false;
1362+ let mut uses_chroma_lr = false;
1363+ for i in 0..MAX_NUM_PLANES {
1364+ let lr_type = self.obu.loop_restoration_params.frame_restoration_type[i];
1365+ self.f(2, lr_type as u32)?;
1366+
1367+ if lr_type != FrameRestorationType::None {
1368+ uses_lr = true;
1369+
1370+ if i > 0 {
1371+ uses_chroma_lr = true;
1372+ }
1373+ }
1374+ }
1375+
1376+ if uses_lr ^ self.obu.loop_restoration_params.uses_lr {
1377+ self.invalid_element_value("uses_lr")?;
1378+ }
1379+ if uses_chroma_lr ^ self.obu.loop_restoration_params.uses_chroma_lr {
1380+ self.invalid_element_value("uses_chroma_lr")?;
1381+ }
1382+
1383+ if uses_lr {
1384+ if sequence.use_128x128_superblock {
1385+ if self.obu.loop_restoration_params.lr_unit_shift == 0 {
1386+ self.invalid_element_value("lr_unit_shift")?;
1387+ }
1388+
1389+ self.f(1, self.obu.loop_restoration_params.lr_unit_shift - 1)?;
1390+ } else {
1391+ self.f(1, self.obu.loop_restoration_params.lr_unit_shift)?;
1392+ if self.obu.loop_restoration_params.lr_unit_shift != 0 {
1393+ self.f(1, self.obu.loop_restoration_params.lr_unit_shift > 1)?;
1394+ }
1395+ }
1396+
1397+ if sequence.color_config.subsampling_x
1398+ && sequence.color_config.subsampling_y
1399+ && uses_chroma_lr
1400+ {
1401+ self.f(1, self.obu.loop_restoration_params.lr_uv_shift)?;
1402+ } else if self.obu.loop_restoration_params.lr_uv_shift != 0 {
1403+ self.invalid_element_value("lr_uv_shift")?;
1404+ }
1405+ }
1406+
1407+ Ok(())
1408+ }
1409+
1410+ /// Writes AV1 5.9.21. TX mode syntax
1411+ fn read_tx_mode(&mut self) -> SynthesizerResult<()> {
1412+ if self.obu.coded_lossless {
1413+ if self.obu.tx_mode != TxMode::Only4x4 {
1414+ self.invalid_element_value("TxMode")?;
1415+ }
1416+ } else {
1417+ self.f(1, self.obu.tx_mode_select)?;
1418+
1419+ if (self.obu.tx_mode_select != 0 && self.obu.tx_mode != TxMode::Select)
1420+ || (self.obu.tx_mode_select == 0 && self.obu.tx_mode != TxMode::Largest)
1421+ {
1422+ self.invalid_element_value("TxMode")?;
1423+ }
1424+ }
1425+
1426+ Ok(())
1427+ }
1428+
1429+ /// Writes AV1 5.9.22. Skip mode params syntax
1430+ fn skip_mode_params(&mut self) -> SynthesizerResult<()> {
1431+ // TODO: Implement if needed
1432+ Ok(())
1433+ }
1434+
1435+ /// Writes AV1 5.9.23. Frame reference mode syntax
1436+ fn frame_reference_mode(&mut self) -> SynthesizerResult<()> {
1437+ if self.obu.frame_is_intra {
1438+ if self.obu.reference_select {
1439+ self.invalid_element_value("reference_select")?;
1440+ }
1441+ } else {
1442+ self.f(1, self.obu.reference_select)?;
1443+ }
1444+
1445+ Ok(())
1446+ }
1447+
1448+ /// Writes AV1 5.9.23. Frame reference mode syntax
1449+ fn global_motion_params(&mut self) -> SynthesizerResult<()> {
1450+ if self.obu.frame_is_intra {
1451+ return Ok(());
1452+ }
1453+
1454+ for ref_ in ReferenceFrameType::Last as usize..=ReferenceFrameType::AltRef as usize {
1455+ let is_global = self.obu.global_motion_params.is_global[ref_];
1456+ let is_rot_zoom = self.obu.global_motion_params.is_rot_zoom[ref_];
1457+ let is_translation = self.obu.global_motion_params.is_translation[ref_];
1458+ let gm_type = self.obu.global_motion_params.gm_type[ref_];
1459+
1460+ let expected_type = match (is_global, is_rot_zoom, is_translation) {
1461+ (false, _, _) => WarpModelType::Identity,
1462+ (true, true, _) => WarpModelType::RotZoom,
1463+ (true, false, true) => WarpModelType::Translation,
1464+ (true, false, false) => WarpModelType::Affine,
1465+ };
1466+
1467+ if expected_type != gm_type {
1468+ self.invalid_element_value("GmType")?;
1469+ }
1470+
1471+ self.f(1, is_global)?;
1472+ if is_global {
1473+ self.f(1, is_rot_zoom)?;
1474+ if is_rot_zoom {
1475+ } else {
1476+ self.f(1, is_translation)?;
1477+ }
1478+ }
1479+
1480+ if gm_type >= WarpModelType::RotZoom {
1481+ self.read_global_param(gm_type, ref_, 2)?;
1482+ self.read_global_param(gm_type, ref_, 3)?;
1483+ if gm_type == WarpModelType::Affine {
1484+ self.read_global_param(gm_type, ref_, 4)?;
1485+ self.read_global_param(gm_type, ref_, 5)?;
1486+ }
1487+ }
1488+
1489+ if gm_type >= WarpModelType::Translation {
1490+ self.read_global_param(gm_type, ref_, 0)?;
1491+ self.read_global_param(gm_type, ref_, 1)?;
1492+ }
1493+ }
1494+
1495+ Ok(())
1496+ }
1497+
1498+ /// Writes AV1 5.9.25. Global param syntax
1499+ fn read_global_param(
1500+ &mut self,
1501+ _gm_type: WarpModelType,
1502+ _ref_: usize,
1503+ _idx: u32,
1504+ ) -> SynthesizerResult<()> {
1505+ // TODO
1506+ log::warn!(
1507+ "Syntax element read_global_param() is not currently supported. Use GmType=IDENTITY"
1508+ );
1509+ Err(SynthesizerError::Unsupported)
1510+ }
1511+
1512+ /// Writes AV1 5.9.30. Film grain params syntax
1513+ fn film_grain_params(&mut self, sequence: &'o SequenceHeaderObu) -> SynthesizerResult<()> {
1514+ if !sequence.film_grain_params_present || (!self.obu.show_frame && !self.obu.showable_frame)
1515+ {
1516+ return Ok(());
1517+ }
1518+
1519+ self.f(1, self.obu.film_grain_params.apply_grain)?;
1520+ if !self.obu.film_grain_params.apply_grain {
1521+ return Ok(());
1522+ }
1523+
1524+ Err(SynthesizerError::Unsupported)
1525+ }
1526+}
1527+
1528+#[cfg(test)]
1529+mod tests {
1530+
1531+ use super::*;
1532+ use crate::codec::av1::parser::CdefParams;
1533+ use crate::codec::av1::parser::ChromaSamplePosition;
1534+ use crate::codec::av1::parser::ColorConfig;
1535+ use crate::codec::av1::parser::TileInfo;
1536+ use crate::codec::av1::parser::MAX_TILE_COLS;
1537+ use crate::codec::av1::parser::MAX_TILE_ROWS;
1538+
1539+ #[test]
1540+ fn sequence_header_obu_test25fps() {
1541+ // Extraced from ./src/codec/av1/test_data/test-25fps.ivf.av1
1542+ const SEQ_HDR_RAW: [u8; 13] =
1543+ [0x0a, 0x0b, 0x00, 0x00, 0x00, 0x04, 0x3c, 0xff, 0xbd, 0xff, 0xf9, 0x80, 0x40];
1544+
1545+ let seq_hdr = SequenceHeaderObu {
1546+ obu_header: ObuHeader {
1547+ obu_type: ObuType::SequenceHeader,
1548+ extension_flag: false,
1549+ has_size_field: true,
1550+ temporal_id: 0,
1551+ spatial_id: 0,
1552+ },
1553+
1554+ seq_profile: Profile::Profile0,
1555+ num_planes: 3,
1556+ still_picture: false,
1557+ reduced_still_picture_header: false,
1558+ timing_info_present_flag: false,
1559+ initial_display_delay_present_flag: false,
1560+ operating_points_cnt_minus_1: 0,
1561+ frame_width_bits_minus_1: 8,
1562+ frame_height_bits_minus_1: 7,
1563+ max_frame_width_minus_1: 319,
1564+ max_frame_height_minus_1: 239,
1565+ frame_id_numbers_present_flag: false,
1566+ use_128x128_superblock: true,
1567+ enable_filter_intra: true,
1568+ enable_intra_edge_filter: true,
1569+ enable_interintra_compound: true,
1570+ enable_masked_compound: true,
1571+ enable_warped_motion: true,
1572+ enable_dual_filter: true,
1573+ enable_order_hint: true,
1574+ enable_jnt_comp: true,
1575+ enable_ref_frame_mvs: true,
1576+ seq_choose_screen_content_tools: true,
1577+ seq_force_screen_content_tools: SELECT_SCREEN_CONTENT_TOOLS as u32,
1578+ seq_choose_integer_mv: true,
1579+ seq_force_integer_mv: SELECT_INTEGER_MV as u32,
1580+ order_hint_bits_minus_1: 6,
1581+ order_hint_bits: 7,
1582+ enable_superres: false,
1583+ enable_cdef: true,
1584+ enable_restoration: true,
1585+ color_config: ColorConfig {
1586+ high_bitdepth: false,
1587+ mono_chrome: false,
1588+ color_description_present_flag: false,
1589+ color_range: false,
1590+ subsampling_x: true,
1591+ subsampling_y: true,
1592+ chroma_sample_position: ChromaSamplePosition::Unknown,
1593+ separate_uv_delta_q: false,
1594+ ..Default::default()
1595+ },
1596+ film_grain_params_present: false,
1597+
1598+ ..Default::default()
1599+ };
1600+
1601+ let mut buf = Vec::<u8>::new();
1602+ Synthesizer::<'_, SequenceHeaderObu, _>::synthesize(&seq_hdr, &mut buf).unwrap();
1603+ assert_eq!(buf, SEQ_HDR_RAW);
1604+ }
1605+
1606+ #[test]
1607+ fn sequence_header_obu_av1_annexb() {
1608+ // Extraced from: ./src/codec/av1/test_data/av1-annexb.ivf.av1
1609+ const SEQ_HDR_RAW: [u8; 12] =
1610+ [0x0a, 0x0a, 0x00, 0x00, 0x00, 0x02, 0xaf, 0xff, 0xbf, 0xff, 0x30, 0x08];
1611+
1612+ let seq_hdr = SequenceHeaderObu {
1613+ obu_header: ObuHeader {
1614+ obu_type: ObuType::SequenceHeader,
1615+ extension_flag: false,
1616+ has_size_field: true,
1617+ temporal_id: 0,
1618+ spatial_id: 0,
1619+ },
1620+
1621+ seq_profile: Profile::Profile0,
1622+ num_planes: 3,
1623+ still_picture: false,
1624+ reduced_still_picture_header: false,
1625+ timing_info_present_flag: false,
1626+ initial_display_delay_present_flag: false,
1627+ operating_points_cnt_minus_1: 0,
1628+ frame_width_bits_minus_1: 5,
1629+ frame_height_bits_minus_1: 5,
1630+ max_frame_width_minus_1: 63,
1631+ max_frame_height_minus_1: 63,
1632+ frame_id_numbers_present_flag: false,
1633+ use_128x128_superblock: true,
1634+ enable_filter_intra: true,
1635+ enable_intra_edge_filter: true,
1636+ enable_interintra_compound: true,
1637+ enable_masked_compound: true,
1638+ enable_warped_motion: true,
1639+ enable_dual_filter: true,
1640+ enable_order_hint: true,
1641+ enable_jnt_comp: true,
1642+ enable_ref_frame_mvs: true,
1643+ seq_choose_screen_content_tools: true,
1644+ seq_force_screen_content_tools: SELECT_SCREEN_CONTENT_TOOLS as u32,
1645+ seq_choose_integer_mv: true,
1646+ seq_force_integer_mv: SELECT_INTEGER_MV as u32,
1647+ order_hint_bits_minus_1: 6,
1648+ order_hint_bits: 7,
1649+ enable_superres: false,
1650+ enable_cdef: true,
1651+ enable_restoration: true,
1652+ color_config: ColorConfig {
1653+ high_bitdepth: false,
1654+ mono_chrome: false,
1655+ color_description_present_flag: false,
1656+ color_range: false,
1657+ subsampling_x: true,
1658+ subsampling_y: true,
1659+ chroma_sample_position: ChromaSamplePosition::Unknown,
1660+ separate_uv_delta_q: false,
1661+ ..Default::default()
1662+ },
1663+ film_grain_params_present: false,
1664+
1665+ ..Default::default()
1666+ };
1667+
1668+ let mut buf = Vec::<u8>::new();
1669+ Synthesizer::<'_, SequenceHeaderObu, _>::synthesize(&seq_hdr, &mut buf).unwrap();
1670+ assert_eq!(buf, SEQ_HDR_RAW);
1671+ }
1672+
1673+ #[test]
1674+ fn temporal_delim_obu() {
1675+ const TD_RAW: [u8; 2] = [0x12, 0x00];
1676+
1677+ let td = TemporalDelimiterObu {
1678+ obu_header: ObuHeader {
1679+ obu_type: ObuType::TemporalDelimiter,
1680+ extension_flag: false,
1681+ has_size_field: true,
1682+ temporal_id: 0,
1683+ spatial_id: 0,
1684+ },
1685+ };
1686+
1687+ let mut buf = Vec::<u8>::new();
1688+ Synthesizer::<'_, TemporalDelimiterObu, _>::synthesize(&td, &mut buf).unwrap();
1689+
1690+ assert_eq!(buf, TD_RAW);
1691+ }
1692+
1693+ #[test]
1694+ fn frame_header_obu() {
1695+ let _ = env_logger::try_init();
1696+
1697+ const WIDTH: u32 = 512;
1698+ const HEIGHT: u32 = 512;
1699+
1700+ let seq = SequenceHeaderObu {
1701+ obu_header: ObuHeader {
1702+ obu_type: ObuType::SequenceHeader,
1703+ extension_flag: false,
1704+ has_size_field: true,
1705+ temporal_id: 0,
1706+ spatial_id: 0,
1707+ },
1708+
1709+ seq_profile: Profile::Profile0,
1710+
1711+ frame_width_bits_minus_1: 16 - 1,
1712+ frame_height_bits_minus_1: 16 - 1,
1713+ max_frame_width_minus_1: (WIDTH - 1) as u16,
1714+ max_frame_height_minus_1: (HEIGHT - 1) as u16,
1715+
1716+ seq_force_integer_mv: SELECT_INTEGER_MV as u32,
1717+
1718+ enable_order_hint: true,
1719+ order_hint_bits: 8,
1720+ order_hint_bits_minus_1: 7,
1721+ num_planes: 3,
1722+
1723+ color_config: ColorConfig {
1724+ subsampling_x: true,
1725+ subsampling_y: true,
1726+ ..Default::default()
1727+ },
1728+
1729+ ..Default::default()
1730+ };
1731+
1732+ let frame = FrameHeaderObu {
1733+ obu_header: ObuHeader {
1734+ obu_type: ObuType::FrameHeader,
1735+ extension_flag: false,
1736+ has_size_field: true,
1737+ temporal_id: 0,
1738+ spatial_id: 0,
1739+ },
1740+
1741+ frame_type: FrameType::KeyFrame,
1742+ frame_is_intra: true,
1743+ primary_ref_frame: PRIMARY_REF_NONE,
1744+ refresh_frame_flags: 0xff,
1745+ error_resilient_mode: true,
1746+
1747+ reduced_tx_set: true,
1748+ tx_mode_select: 1,
1749+ tx_mode: TxMode::Select,
1750+
1751+ tile_info: TileInfo {
1752+ uniform_tile_spacing_flag: true,
1753+ tile_cols: 1,
1754+ tile_rows: 1,
1755+ tile_cols_log2: 0,
1756+ tile_rows_log2: 0,
1757+ width_in_sbs_minus_1: {
1758+ let mut value = [0u32; MAX_TILE_COLS];
1759+ value[0] = WIDTH / 64 - 1;
1760+ value
1761+ },
1762+ height_in_sbs_minus_1: {
1763+ let mut value = [0u32; MAX_TILE_ROWS];
1764+ value[0] = HEIGHT / 64 - 1;
1765+ value
1766+ },
1767+ ..Default::default()
1768+ },
1769+
1770+ cdef_params: CdefParams { cdef_damping: 3, ..Default::default() },
1771+
1772+ superres_denom: SUPERRES_NUM as u32,
1773+ upscaled_width: WIDTH,
1774+ frame_width: WIDTH,
1775+ frame_height: HEIGHT,
1776+ render_width: WIDTH,
1777+ render_height: HEIGHT,
1778+
1779+ ..Default::default()
1780+ };
1781+
1782+ let mut buf = Vec::<u8>::new();
1783+ Synthesizer::<'_, SequenceHeaderObu, _>::synthesize(&seq, &mut buf).unwrap();
1784+
1785+ Synthesizer::<'_, FrameHeaderObu, _>::synthesize(&frame, &seq, &mut buf).unwrap();
1786+
1787+ // TODO actual test
1788+
1789+ let write_to_file = std::option_env!("CROS_CODECS_TEST_WRITE_TO_FILE") == Some("true");
1790+ if write_to_file {
1791+ let mut out = std::fs::File::create("frame_header_obu.av1").unwrap();
1792+ out.write_all(&buf).unwrap();
1793+ out.flush().unwrap();
1794+ }
1795+ }
1796+}
vendor/cros-codecs/src/codec/av1/writer.rsadded+199 -0
@@ -0,0 +1,199 @@
1+// Copyright 2024 The ChromiumOS Authors
2+// Use of this source code is governed by a BSD-style license that can be
3+// found in the LICENSE file.
4+
5+use std::fmt;
6+use std::io::Write;
7+
8+use crate::bitstream_utils::BitWriter;
9+use crate::bitstream_utils::BitWriterError;
10+
11+#[derive(Debug)]
12+pub enum ObuWriterError {
13+ BitWriterError(BitWriterError),
14+ UnalignedLeb128,
15+}
16+
17+impl fmt::Display for ObuWriterError {
18+ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
19+ match self {
20+ ObuWriterError::BitWriterError(x) => write!(f, "{}", x.to_string()),
21+ ObuWriterError::UnalignedLeb128 => {
22+ write!(f, "attempted to write leb128 on unaligned position")
23+ }
24+ }
25+ }
26+}
27+
28+impl From<BitWriterError> for ObuWriterError {
29+ fn from(err: BitWriterError) -> Self {
30+ ObuWriterError::BitWriterError(err)
31+ }
32+}
33+
34+pub type ObuWriterResult<T> = std::result::Result<T, ObuWriterError>;
35+
36+pub struct ObuWriter<W: Write>(BitWriter<W>);
37+
38+impl<W: Write> ObuWriter<W> {
39+ pub fn new(writer: W) -> Self {
40+ Self(BitWriter::new(writer))
41+ }
42+
43+ /// Writes fixed bit size integer. Corresponds to `f(n)` in AV1 spec defined in 4.10.2.
44+ pub fn write_f<T: Into<u32>>(&mut self, bits: usize, value: T) -> ObuWriterResult<usize> {
45+ self.0.write_f(bits, value).map_err(ObuWriterError::BitWriterError)
46+ }
47+
48+ /// Writes variable length unsigned n-bit number. Corresponds to `uvlc()` in AV1 spec
49+ /// defined in 4.10.3.
50+ pub fn write_uvlc<T: Into<u32>>(&mut self, value: T) -> ObuWriterResult<usize> {
51+ let value: u32 = value.into();
52+ if value == u32::MAX {
53+ return self.write_f(32, 0u32);
54+ }
55+
56+ let value = value + 1;
57+ let leading_zeros = (32 - value.leading_zeros()) as usize;
58+
59+ Ok(self.write_f(leading_zeros - 1, 0u32)? + self.write_f(leading_zeros, value)?)
60+ }
61+
62+ /// Writes unsigned little-endian n-byte integer. Corresponds to `le(n)` in AV1 spec
63+ /// defined in 4.10.4.
64+ pub fn write_le<T: Into<u32>>(&mut self, n: usize, value: T) -> ObuWriterResult<usize> {
65+ let value: u32 = value.into();
66+ let mut value = value.to_le();
67+
68+ for _ in 0..n {
69+ self.write_f(4, value & 0xff)?;
70+ value >>= 8;
71+ }
72+
73+ Ok(n)
74+ }
75+
76+ /// Writes unsigned integer represented by a variable number of little-endian bytes.
77+ /// Corresponds to `leb128()` in AV1 spec defined in 4.10.4.
78+ ///
79+ /// Note: Despite the name, the AV1 4.10.4 limits the value to [`u32::MAX`] = (1 << 32) - 1.
80+ pub fn write_leb128<T: Into<u32>>(
81+ &mut self,
82+ value: T,
83+ min_bytes: usize,
84+ ) -> ObuWriterResult<usize> {
85+ if !self.aligned() {
86+ return Err(ObuWriterError::UnalignedLeb128);
87+ }
88+
89+ let value: u32 = value.into();
90+ let mut value: u32 = value.to_le();
91+ let mut bytes = 0;
92+
93+ for _ in 0..8 {
94+ bytes += 1;
95+
96+ if value >= 0x7f || bytes < min_bytes {
97+ self.write_f(8, 0x80 | (value & 0x7f))?;
98+ value >>= 7;
99+ } else {
100+ self.write_f(8, value & 0x7f)?;
101+ break;
102+ }
103+ }
104+
105+ assert!(value < 0x7f);
106+
107+ Ok(bytes)
108+ }
109+
110+ pub fn write_su<T: Into<i32>>(&mut self, bits: usize, value: T) -> ObuWriterResult<usize> {
111+ let mut value: i32 = value.into();
112+ if value < 0 {
113+ value += 1 << bits;
114+ }
115+
116+ assert!(value >= 0);
117+ self.write_f(bits, value.unsigned_abs())
118+ }
119+
120+ pub fn aligned(&self) -> bool {
121+ !self.0.has_data_pending()
122+ }
123+}
124+
125+#[cfg(test)]
126+mod tests {
127+ use super::*;
128+ use crate::codec::av1::reader::Reader;
129+
130+ const TEST_VECTOR: &[u32] = &[
131+ // some random test values
132+ u32::MAX,
133+ 1,
134+ 2,
135+ 3,
136+ 4,
137+ 10,
138+ 20,
139+ 7312,
140+ 8832,
141+ 10123,
142+ 47457,
143+ 21390213,
144+ u32::MIN,
145+ u32::MAX - 1,
146+ ];
147+
148+ #[test]
149+ fn test_uvlc() {
150+ for &value in TEST_VECTOR {
151+ let mut buf = Vec::<u8>::new();
152+
153+ ObuWriter::new(&mut buf).write_uvlc(value).unwrap();
154+
155+ if value == u32::MAX {
156+ // force stop uvlc
157+ buf.push(0x80);
158+ }
159+
160+ let read = Reader::new(&buf).read_uvlc().unwrap();
161+
162+ assert_eq!(read, value, "failed testing {}", value);
163+ }
164+ }
165+
166+ #[test]
167+ fn test_leb128() {
168+ for &value in TEST_VECTOR {
169+ let mut buf = Vec::<u8>::new();
170+
171+ ObuWriter::new(&mut buf).write_leb128(value, 0).unwrap();
172+ let read = Reader::new(&buf).read_leb128().unwrap();
173+
174+ assert_eq!(read, value, "failed testing {}", value);
175+ }
176+ }
177+
178+ #[test]
179+ fn test_su() {
180+ let vector =
181+ TEST_VECTOR.iter().map(|e| *e as i32).chain(TEST_VECTOR.iter().map(|e| -(*e as i32)));
182+
183+ for value in vector {
184+ let bits = 32 - value.abs().leading_zeros() as usize + 1; // For sign
185+ if bits >= 32 {
186+ // Skip too big nubmers
187+ continue;
188+ }
189+
190+ let mut buf = Vec::<u8>::new();
191+
192+ ObuWriter::new(&mut buf).write_su(bits, value).unwrap();
193+
194+ let read = Reader::new(&buf).read_su(bits as usize).unwrap();
195+
196+ assert_eq!(read, value, "failed testing {}", value);
197+ }
198+ }
199+}
vendor/cros-codecs/src/codec/h264.rsadded+10 -0
@@ -0,0 +1,10 @@
1+// Copyright 2023 The ChromiumOS Authors
2+// Use of this source code is governed by a BSD-style license that can be
3+// found in the LICENSE file.
4+
5+pub mod dpb;
6+pub mod nalu;
7+pub mod nalu_writer;
8+pub mod parser;
9+pub mod picture;
10+pub mod synthesizer;
vendor/cros-codecs/src/codec/h264/dpb.rsadded+1243 -0
@@ -0,0 +1,1243 @@
1+// Copyright 2022 The ChromiumOS Authors
2+// Use of this source code is governed by a BSD-style license that can be
3+// found in the LICENSE file.
4+
5+use std::cell::Ref;
6+use std::cell::RefMut;
7+use std::fmt;
8+use std::rc::Rc;
9+
10+use log::debug;
11+
12+use crate::codec::h264::parser::MaxLongTermFrameIdx;
13+use crate::codec::h264::parser::RefPicMarkingInner;
14+use crate::codec::h264::parser::Sps;
15+use crate::codec::h264::picture::Field;
16+use crate::codec::h264::picture::FieldRank;
17+use crate::codec::h264::picture::IsIdr;
18+use crate::codec::h264::picture::PictureData;
19+use crate::codec::h264::picture::RcPictureData;
20+use crate::codec::h264::picture::Reference;
21+
22+pub type DpbPicRefList<'a, H> = Vec<&'a DpbEntry<H>>;
23+
24+/// All the reference picture lists used to decode a picture.
25+#[derive(Default)]
26+pub struct ReferencePicLists {
27+ /// Reference picture list for P slices. Retains the same meaning as in the
28+ /// specification. Points into the pictures stored in the DPB. Derived once
29+ /// per picture.
30+ pub ref_pic_list_p0: Vec<usize>,
31+ /// Reference picture list 0 for B slices. Retains the same meaning as in
32+ /// the specification. Points into the pictures stored in the DPB. Derived
33+ /// once per picture.
34+ pub ref_pic_list_b0: Vec<usize>,
35+ /// Reference picture list 1 for B slices. Retains the same meaning as in
36+ /// the specification. Points into the pictures stored in the DPB. Derived
37+ /// once per picture.
38+ pub ref_pic_list_b1: Vec<usize>,
39+}
40+
41+/// A single entry in the DPB.
42+#[derive(Clone)]
43+pub struct DpbEntry<T> {
44+ /// `PictureData` of the frame in this entry.
45+ pub pic: RcPictureData,
46+ /// Reference to the decoded frame, ensuring that it doesn't get reused while in the DPB.
47+ pub reference: Option<T>,
48+ /// Decoded frame promise. It will be set when the frame enters the DPB, and taken during the
49+ /// bump process.
50+ pub decoded_frame: Option<T>,
51+ /// Whether the picture is still waiting to be bumped and displayed.
52+ needed_for_output: bool,
53+}
54+
55+impl<T> DpbEntry<T> {
56+ /// Returns `true` is the entry is eligible to be bumped.
57+ ///
58+ /// An entry can be bumped if its `needed_for_output` flag is true and it is the first field of
59+ /// a frame which fields are all decoded.
60+ fn is_bumpable(&self) -> bool {
61+ if !self.needed_for_output {
62+ return false;
63+ }
64+
65+ let pic = self.pic.borrow();
66+ match pic.field {
67+ // Progressive frames in the DPB are fully decoded.
68+ Field::Frame => true,
69+ // Only return the first field of fully decoded interlaced frames.
70+ Field::Top | Field::Bottom => matches!(pic.field_rank(), FieldRank::First(..)),
71+ }
72+ }
73+}
74+
75+pub struct Dpb<T> {
76+ /// List of `PictureData` and backend handles to decoded pictures.
77+ entries: Vec<DpbEntry<T>>,
78+ /// The maximum number of pictures that can be stored.
79+ max_num_pics: usize,
80+ /// Indicates an upper bound for the number of frames buffers, in the
81+ /// decoded picture buffer (DPB), that are required for storing frames,
82+ /// complementary field pairs, and non-paired fields before output. It is a
83+ /// requirement of bitstream conformance that the maximum number of frames,
84+ /// complementary field pairs, or non-paired fields that precede any frame,
85+ /// complementary field pair, or non-paired field in the coded video
86+ /// sequence in decoding order and follow it in output order shall be less
87+ /// than or equal to max_num_reorder_frames.
88+ max_num_reorder_frames: usize,
89+ /// Whether we're decoding in interlaced mode. Interlaced support is
90+ /// inspired by the GStreamer implementation, in which frames are split if
91+ /// interlaced=1. This makes reference marking easier. We also decode both
92+ /// fields to the same frame, and this frame with both fields is outputted
93+ /// only once.
94+ interlaced: bool,
95+}
96+
97+#[derive(Debug)]
98+pub enum StorePictureError {
99+ DpbIsFull,
100+}
101+
102+impl fmt::Display for StorePictureError {
103+ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
104+ write!(f, "DPB is full")
105+ }
106+}
107+
108+impl std::error::Error for StorePictureError {}
109+
110+#[derive(Debug)]
111+pub enum MmcoError {
112+ NoShortTermPic,
113+ ExpectedMarked,
114+ ExpectedExisting,
115+ UnknownMmco(u8),
116+}
117+
118+impl fmt::Display for MmcoError {
119+ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
120+ match self {
121+ MmcoError::NoShortTermPic => {
122+ write!(f, "could not find ShortTerm picture to mark in the DPB")
123+ }
124+ MmcoError::ExpectedMarked => {
125+ write!(f, "a ShortTerm picture was expected to be marked for MMCO=3")
126+ }
127+ MmcoError::ExpectedExisting => {
128+ write!(f, "picture cannot be marked as nonexisting for MMCO=3")
129+ }
130+ MmcoError::UnknownMmco(x) => write!(f, "unknown MMCO: {}", x),
131+ }
132+ }
133+}
134+
135+impl std::error::Error for MmcoError {}
136+
137+impl<T: Clone> Dpb<T> {
138+ /// Returns an iterator over the underlying H264 pictures stored in the
139+ /// DPB.
140+ fn pictures(&self) -> impl Iterator<Item = Ref<'_, PictureData>> {
141+ self.entries.iter().map(|h| h.pic.borrow())
142+ }
143+
144+ /// Returns a mutable iterator over the underlying H264 pictures stored in
145+ /// the DPB.
146+ fn pictures_mut(&mut self) -> impl Iterator<Item = RefMut<'_, PictureData>> {
147+ self.entries.iter().map(|h| h.pic.borrow_mut())
148+ }
149+
150+ /// Returns the length of the DPB.
151+ pub fn len(&self) -> usize {
152+ self.entries.len()
153+ }
154+
155+ pub fn is_empty(&self) -> bool {
156+ self.len() == 0
157+ }
158+
159+ /// Get a reference to the whole DPB entries.
160+ pub fn entries(&self) -> &Vec<DpbEntry<T>> {
161+ &self.entries
162+ }
163+
164+ /// Set the DPB's limits in terms of maximum number or pictures.
165+ pub fn set_limits(&mut self, max_num_pics: usize, max_num_reorder_frames: usize) {
166+ self.max_num_pics = max_num_pics;
167+ self.max_num_reorder_frames = max_num_reorder_frames;
168+ }
169+
170+ /// Get a reference to the dpb's max num pics.
171+ pub fn max_num_pics(&self) -> usize {
172+ self.max_num_pics
173+ }
174+
175+ // Returns the number of reference frames, counting the first field only if
176+ // dealing with interlaced content.
177+ pub fn num_ref_frames(&self) -> usize {
178+ self.pictures().filter(|p| p.is_ref() && !p.is_second_field()).count()
179+ }
180+
181+ /// Get a reference to the dpb's interlaced mode.
182+ pub fn interlaced(&self) -> bool {
183+ self.interlaced
184+ }
185+
186+ /// Set the dpb's interlaced mode.
187+ pub fn set_interlaced(&mut self, interlaced: bool) {
188+ self.interlaced = interlaced;
189+ }
190+
191+ /// Find the short term reference picture with the lowest `frame_num_wrap`
192+ /// value.
193+ pub fn find_short_term_lowest_frame_num_wrap(&self) -> Option<&DpbEntry<T>> {
194+ let lowest = self
195+ .entries
196+ .iter()
197+ .filter(|h| {
198+ let p = h.pic.borrow();
199+ matches!(p.reference(), Reference::ShortTerm)
200+ })
201+ .min_by_key(|h| {
202+ let p = h.pic.borrow();
203+ p.frame_num_wrap
204+ });
205+
206+ lowest
207+ }
208+
209+ /// Mark all pictures in the DPB as unused for reference.
210+ pub fn mark_all_as_unused_for_ref(&mut self) {
211+ for mut picture in self.pictures_mut() {
212+ picture.set_reference(Reference::None, false);
213+ }
214+ }
215+
216+ /// Remove unused pictures from the DPB. A picture is not going to be used
217+ /// anymore if it's a) not a reference and b) not needed for output
218+ fn remove_unused(&mut self) {
219+ self.entries.retain(|entry| {
220+ let pic = entry.pic.borrow();
221+ let discard = !pic.is_ref() && !entry.needed_for_output;
222+
223+ if discard {
224+ log::debug!("Removing unused picture {:#?}", pic);
225+ }
226+
227+ !discard
228+ });
229+ }
230+
231+ /// Find a short term reference picture with the given `pic_num` value.
232+ fn find_short_term_with_pic_num_pos(&self, pic_num: i32) -> Option<usize> {
233+ let position = self
234+ .pictures()
235+ .position(|p| matches!(p.reference(), Reference::ShortTerm) && p.pic_num == pic_num);
236+
237+ log::debug!("find_short_term_with_pic_num: {}, found position {:?}", pic_num, position);
238+
239+ position
240+ }
241+
242+ /// Find a short term reference picture with the given `pic_num` value.
243+ pub fn find_short_term_with_pic_num(&self, pic_num: i32) -> Option<&DpbEntry<T>> {
244+ let position = self.find_short_term_with_pic_num_pos(pic_num)?;
245+ Some(&self.entries[position])
246+ }
247+
248+ /// Find a long term reference picture with the given `long_term_pic_num`
249+ /// value.
250+ fn find_long_term_with_long_term_pic_num_pos(&self, long_term_pic_num: u32) -> Option<usize> {
251+ let position = self.pictures().position(|p| {
252+ matches!(p.reference(), Reference::LongTerm) && p.long_term_pic_num == long_term_pic_num
253+ });
254+
255+ log::debug!(
256+ "find_long_term_with_long_term_pic_num: {}, found position {:?}",
257+ long_term_pic_num,
258+ position
259+ );
260+
261+ position
262+ }
263+
264+ /// Find a long term reference picture with the given `long_term_pic_num`
265+ /// value.
266+ pub fn find_long_term_with_long_term_pic_num(
267+ &self,
268+ long_term_pic_num: u32,
269+ ) -> Option<&DpbEntry<T>> {
270+ let position = self.find_long_term_with_long_term_pic_num_pos(long_term_pic_num)?;
271+ Some(&self.entries[position])
272+ }
273+
274+ /// Store `picture` and its backend handle in the DPB.
275+ pub fn store_picture(
276+ &mut self,
277+ picture: RcPictureData,
278+ handle: Option<T>,
279+ ) -> Result<(), StorePictureError> {
280+ let max_pics = if self.interlaced { self.max_num_pics * 2 } else { self.max_num_pics };
281+
282+ if self.entries.len() >= max_pics {
283+ return Err(StorePictureError::DpbIsFull);
284+ }
285+
286+ let pic = picture.borrow();
287+
288+ // C.4.2. Decoding of gaps in frame_num and storage of "non-existing"
289+ // pictures
290+ let needed_for_output = !pic.nonexisting;
291+
292+ debug!(
293+ "Stored picture POC {:?}, field {:?}, the DPB length is {:?}",
294+ pic.pic_order_cnt,
295+ pic.field,
296+ self.entries.len()
297+ );
298+ drop(pic);
299+
300+ self.entries.push(DpbEntry {
301+ pic: picture,
302+ reference: handle.clone(),
303+ decoded_frame: handle,
304+ needed_for_output,
305+ });
306+
307+ Ok(())
308+ }
309+
310+ /// Whether the DPB has an empty slot for a new picture.
311+ pub fn has_empty_frame_buffer(&self) -> bool {
312+ let count = if !self.interlaced {
313+ self.entries.len()
314+ } else {
315+ self.pictures()
316+ .filter(|pic| {
317+ matches!(pic.field_rank(), FieldRank::First(..))
318+ || (matches!(pic.field_rank(), FieldRank::Single)
319+ && pic.field == Field::Frame)
320+ })
321+ .count()
322+ };
323+
324+ count < self.max_num_pics
325+ }
326+
327+ /// Whether the DPB needs bumping, as described by clauses 1, 4, 5, 6 of
328+ /// C.4.5.3 "Bumping" process.
329+ pub fn needs_bumping(&self, to_insert: &PictureData) -> bool {
330+ // In C.4.5.3 we handle clauses 2 and 3 separately. All other clauses
331+ // check for an empty frame buffer first. Here we handle:
332+ // - There is no empty frame buffer and a empty frame buffer is
333+ // needed for storage of an inferred "non-existing" frame.
334+ //
335+ // - There is no empty frame buffer and an empty frame buffer is
336+ // needed for storage of a decoded (non-IDR) reference picture.
337+ //
338+ // - There is no empty frame buffer and the current picture is a non-
339+ // reference picture that is not the second field of a complementary
340+ // non-reference field pair and there are pictures in the DPB that
341+ // are marked as "needed for output" that precede the current
342+ // non-reference picture in output order.
343+ //
344+ // Clauses 2 and 3 are handled by H264Codec::handle_picture and
345+ // H264Codec::finish_picture, respectively.
346+ if self.has_empty_frame_buffer() {
347+ return false;
348+ }
349+
350+ if to_insert.nonexisting {
351+ return true;
352+ }
353+
354+ let non_idr_ref = to_insert.is_ref() && matches!(to_insert.is_idr, IsIdr::No);
355+ if non_idr_ref {
356+ return true;
357+ }
358+
359+ let lowest_poc = match self.find_lowest_poc_for_bumping() {
360+ Some(handle) => handle.pic.borrow().pic_order_cnt,
361+ None => return false,
362+ };
363+
364+ !to_insert.is_second_field_of_complementary_ref_pair()
365+ && to_insert.pic_order_cnt > lowest_poc
366+ }
367+
368+ /// Find the lowest POC in the DPB that can be bumped.
369+ fn find_lowest_poc_for_bumping(&self) -> Option<&DpbEntry<T>> {
370+ self.entries
371+ .iter()
372+ .filter(|entry| entry.is_bumpable())
373+ .min_by_key(|handle| handle.pic.borrow().pic_order_cnt)
374+ }
375+
376+ /// Find the lowest POC in the DPB that can be bumped and return a mutable reference.
377+ fn find_lowest_poc_for_bumping_mut(&mut self) -> Option<&mut DpbEntry<T>> {
378+ self.entries
379+ .iter_mut()
380+ .filter(|entry| entry.is_bumpable())
381+ .min_by_key(|handle| handle.pic.borrow().pic_order_cnt)
382+ }
383+
384+ /// Bump the dpb, returning a picture as per the bumping process described in C.4.5.3.
385+ /// Note that this picture will still be referenced by its pair, if any.
386+ fn bump(&mut self) -> Option<Option<T>> {
387+ let dpb_entry = self.find_lowest_poc_for_bumping_mut()?;
388+ let handle = dpb_entry.decoded_frame.take();
389+ let pic = dpb_entry.pic.borrow();
390+
391+ debug!("Bumping picture {:#?} from the dpb", pic);
392+
393+ dpb_entry.needed_for_output = false;
394+ // Lookup the second field entry and flip as well.
395+ // `find_lowest_poc_for_bumping_mut` always returns the first field, never the second.
396+ if let FieldRank::First(second_field) = pic.field_rank() {
397+ let second_field = second_field.upgrade();
398+ drop(pic);
399+ if let Some(second_field) =
400+ second_field.and_then(|f| self.entries.iter_mut().find(|e| Rc::ptr_eq(&f, &e.pic)))
401+ {
402+ second_field.needed_for_output = false;
403+ }
404+ }
405+
406+ Some(handle)
407+ }
408+
409+ /// Drains the DPB by continuously invoking the bumping process.
410+ pub fn drain(&mut self) -> Vec<Option<T>> {
411+ debug!("Draining the DPB.");
412+
413+ let mut pics = vec![];
414+
415+ while let Some(pic) = self.bump() {
416+ pics.push(pic);
417+ }
418+
419+ self.clear();
420+
421+ pics
422+ }
423+
424+ /// Clears the DPB, dropping all the pictures.
425+ pub fn clear(&mut self) {
426+ debug!("Clearing the DPB");
427+
428+ let max_num_pics = self.max_num_pics;
429+ let interlaced = self.interlaced;
430+
431+ *self = Default::default();
432+
433+ self.max_num_pics = max_num_pics;
434+ self.interlaced = interlaced;
435+ }
436+
437+ /// Returns an iterator of short term refs.
438+ pub fn short_term_refs_iter(&self) -> impl Iterator<Item = &DpbEntry<T>> {
439+ self.entries
440+ .iter()
441+ .filter(|&handle| matches!(handle.pic.borrow().reference(), Reference::ShortTerm))
442+ }
443+
444+ /// Returns an iterator of long term refs.
445+ pub fn long_term_refs_iter(&self) -> impl Iterator<Item = &DpbEntry<T>> {
446+ self.entries
447+ .iter()
448+ .filter(|&handle| matches!(handle.pic.borrow().reference(), Reference::LongTerm))
449+ }
450+
451+ pub fn update_pic_nums(
452+ &mut self,
453+ frame_num: u32,
454+ max_frame_num: u32,
455+ current_pic: &PictureData,
456+ ) {
457+ for mut pic in self.pictures_mut() {
458+ if !pic.is_ref() {
459+ continue;
460+ }
461+
462+ if *pic.reference() == Reference::LongTerm {
463+ pic.long_term_pic_num = if current_pic.field == Field::Frame {
464+ pic.long_term_frame_idx
465+ } else if current_pic.field == pic.field {
466+ 2 * pic.long_term_frame_idx + 1
467+ } else {
468+ 2 * pic.long_term_frame_idx
469+ };
470+ } else {
471+ pic.frame_num_wrap = if pic.frame_num > frame_num {
472+ pic.frame_num as i32 - max_frame_num as i32
473+ } else {
474+ pic.frame_num as i32
475+ };
476+
477+ pic.pic_num = if current_pic.field == Field::Frame {
478+ pic.frame_num_wrap
479+ } else if pic.field == current_pic.field {
480+ 2 * pic.frame_num_wrap + 1
481+ } else {
482+ 2 * pic.frame_num_wrap
483+ };
484+ }
485+ }
486+ }
487+
488+ /// Bumps the DPB if needed. DPB bumping is described on C.4.5.3.
489+ pub fn bump_as_needed(&mut self, current_pic: &PictureData) -> Vec<Option<T>> {
490+ let mut pics = vec![];
491+ while self.needs_bumping(current_pic) && self.len() >= self.max_num_reorder_frames {
492+ match self.bump() {
493+ Some(pic) => pics.push(pic),
494+ None => return pics,
495+ }
496+ self.remove_unused();
497+ }
498+
499+ pics
500+ }
501+
502+ // 8.2.5.3
503+ pub fn sliding_window_marking(&mut self, pic: &mut PictureData, sps: &Sps) {
504+ // If the current picture is a coded field that is the second field in
505+ // decoding order of a complementary reference field pair, and the first
506+ // field has been marked as "used for short-term reference", the current
507+ // picture and the complementary reference field pair are also marked as
508+ // "used for short-term reference".
509+ if let FieldRank::Second(other_field) = pic.field_rank() {
510+ if matches!(other_field.borrow().reference(), Reference::ShortTerm) {
511+ pic.set_reference(Reference::ShortTerm, false);
512+ return;
513+ }
514+ }
515+
516+ let mut num_ref_pics = self.num_ref_frames();
517+ let max_num_ref_frames = std::cmp::max(1, sps.max_num_ref_frames as usize);
518+
519+ if num_ref_pics < max_num_ref_frames {
520+ return;
521+ }
522+
523+ while num_ref_pics >= max_num_ref_frames {
524+ if let Some(to_unmark) = self.find_short_term_lowest_frame_num_wrap() {
525+ to_unmark.pic.borrow_mut().set_reference(Reference::None, true);
526+ num_ref_pics -= 1;
527+ } else {
528+ log::warn!("could not find a ShortTerm picture to unmark in the DPB");
529+ break;
530+ }
531+ }
532+
533+ self.remove_unused();
534+ }
535+
536+ pub fn mmco_op_1(
537+ &mut self,
538+ pic: &PictureData,
539+ marking: &RefPicMarkingInner,
540+ ) -> Result<(), MmcoError> {
541+ let pic_num_x = pic.pic_num - (marking.difference_of_pic_nums_minus1 as i32 + 1);
542+
543+ log::debug!("MMCO op 1 for pic_num_x {}", pic_num_x);
544+ log::trace!("Dpb state before MMCO=1: {:#?}", self);
545+
546+ let to_mark =
547+ self.find_short_term_with_pic_num(pic_num_x).ok_or(MmcoError::NoShortTermPic)?;
548+
549+ to_mark.pic.borrow_mut().set_reference(Reference::None, matches!(pic.field, Field::Frame));
550+
551+ Ok(())
552+ }
553+
554+ pub fn mmco_op_2(
555+ &mut self,
556+ pic: &PictureData,
557+ marking: &RefPicMarkingInner,
558+ ) -> Result<(), MmcoError> {
559+ log::debug!("MMCO op 2 for long_term_pic_num {}", marking.long_term_pic_num);
560+
561+ log::trace!("Dpb state before MMCO=2: {:#?}", self);
562+
563+ let to_mark = self
564+ .find_long_term_with_long_term_pic_num(marking.long_term_pic_num)
565+ .ok_or(MmcoError::NoShortTermPic)?;
566+
567+ to_mark.pic.borrow_mut().set_reference(Reference::None, matches!(pic.field, Field::Frame));
568+
569+ Ok(())
570+ }
571+
572+ pub fn mmco_op_3(
573+ &mut self,
574+ pic: &PictureData,
575+ marking: &RefPicMarkingInner,
576+ ) -> Result<(), MmcoError> {
577+ let pic_num_x = pic.pic_num - (marking.difference_of_pic_nums_minus1 as i32 + 1);
578+
579+ log::debug!("MMCO op 3 for pic_num_x {}", pic_num_x);
580+ log::trace!("Dpb state before MMCO=3: {:#?}", self);
581+
582+ let to_mark_as_long_pos =
583+ self.find_short_term_with_pic_num_pos(pic_num_x).ok_or(MmcoError::NoShortTermPic)?;
584+ let to_mark_as_long = &self.entries[to_mark_as_long_pos].pic;
585+
586+ if !matches!(to_mark_as_long.borrow().reference(), Reference::ShortTerm) {
587+ return Err(MmcoError::ExpectedMarked);
588+ }
589+
590+ if to_mark_as_long.borrow().nonexisting {
591+ return Err(MmcoError::ExpectedExisting);
592+ }
593+
594+ let to_mark_as_long_ptr = to_mark_as_long.as_ptr();
595+ let to_mark_as_long_other_field_ptr =
596+ to_mark_as_long.borrow().other_field().map(|f| f.as_ptr());
597+
598+ let long_term_frame_idx = marking.long_term_frame_idx;
599+
600+ for mut picture in self.pictures_mut() {
601+ let long_already_assigned = matches!(picture.reference(), Reference::LongTerm)
602+ && picture.long_term_frame_idx == long_term_frame_idx;
603+
604+ if long_already_assigned {
605+ let is_frame = matches!(picture.field, Field::Frame);
606+
607+ let is_complementary_field_pair = picture
608+ .other_field()
609+ .map(|f| {
610+ let pic = f.borrow();
611+ matches!(pic.reference(), Reference::LongTerm)
612+ && pic.long_term_frame_idx == long_term_frame_idx
613+ })
614+ .unwrap_or(false);
615+
616+ // When LongTermFrameIdx equal to
617+ // long_term_frame_idx is already assigned to a
618+ // long-term reference frame or a long-term
619+ // complementary reference field pair, that frame or
620+ // complementary field pair and both of its fields
621+ // are marked as "unused for reference"
622+ if is_frame || is_complementary_field_pair {
623+ picture.set_reference(Reference::None, true);
624+ break;
625+ }
626+
627+ // When LongTermFrameIdx is already assigned to a
628+ // reference field, and that reference field is not
629+ // part of a complementary field pair that includes
630+ // the picture specified by picNumX, that field is
631+ // marked as "unused for reference".
632+ let reference_field_is_not_part_of_pic_x = match picture.other_field() {
633+ None => true,
634+ Some(other_field) => {
635+ // Check that the fields do not reference one another.
636+ !std::ptr::eq(other_field.as_ptr(), to_mark_as_long_ptr)
637+ && to_mark_as_long_other_field_ptr
638+ .map(|p| !std::ptr::eq(p, &(*picture)))
639+ .unwrap_or(true)
640+ }
641+ };
642+
643+ if reference_field_is_not_part_of_pic_x {
644+ picture.set_reference(Reference::None, false);
645+ break;
646+ }
647+ }
648+ }
649+
650+ let is_frame = matches!(pic.field, Field::Frame);
651+ let to_mark_as_long = &self.entries[to_mark_as_long_pos].pic;
652+ to_mark_as_long.borrow_mut().set_reference(Reference::LongTerm, is_frame);
653+ to_mark_as_long.borrow_mut().long_term_frame_idx = long_term_frame_idx;
654+
655+ if let Some(other_field) = to_mark_as_long.borrow().other_field() {
656+ let mut other_field = other_field.borrow_mut();
657+ if matches!(other_field.reference(), Reference::LongTerm) {
658+ other_field.long_term_frame_idx = long_term_frame_idx;
659+
660+ log::debug!(
661+ "Assigned long_term_frame_idx {} to other_field {:#?}",
662+ long_term_frame_idx,
663+ &other_field
664+ );
665+ }
666+ }
667+
668+ Ok(())
669+ }
670+
671+ /// Returns the new `max_long_term_frame_idx`.
672+ pub fn mmco_op_4(&mut self, marking: &RefPicMarkingInner) -> MaxLongTermFrameIdx {
673+ log::debug!("MMCO op 4, max_long_term_frame_idx: {:?}", marking.max_long_term_frame_idx);
674+
675+ log::trace!("Dpb state before MMCO=4: {:#?}", self);
676+
677+ for mut dpb_pic in self
678+ .pictures_mut()
679+ .filter(|pic| matches!(pic.reference(), Reference::LongTerm))
680+ .filter(|pic| marking.max_long_term_frame_idx < pic.long_term_frame_idx)
681+ {
682+ dpb_pic.set_reference(Reference::None, false);
683+ }
684+
685+ marking.max_long_term_frame_idx
686+ }
687+
688+ /// Returns the new `max_long_term_frame_idx`.
689+ pub fn mmco_op_5(&mut self, pic: &mut PictureData) -> MaxLongTermFrameIdx {
690+ log::debug!("MMCO op 5, marking all pictures in the DPB as unused for reference");
691+ log::trace!("Dpb state before MMCO=5: {:#?}", self);
692+
693+ self.mark_all_as_unused_for_ref();
694+
695+ pic.has_mmco_5 = true;
696+
697+ // A picture including a memory_management_control_operation equal to 5
698+ // shall have frame_num constraints as described above and, after the
699+ // decoding of the current picture and the processing of the memory
700+ // management control operations, the picture shall be inferred to have
701+ // had frame_num equal to 0 for all subsequent use in the decoding
702+ // process, except as specified in clause 7.4.1.2.4.
703+ pic.frame_num = 0;
704+
705+ // When the current picture includes a
706+ // memory_management_control_operation equal to 5, after the decoding of
707+ // the current picture, tempPicOrderCnt is set equal to PicOrderCnt(
708+ // CurrPic ), TopFieldOrderCnt of the current picture (if any) is set
709+ // equal to TopFieldOrderCnt − tempPicOrderCnt, and BottomFieldOrderCnt
710+ // of the current picture (if any) is set equal to BottomFieldOrderCnt −
711+ // tempPicOrderCnt
712+ match pic.field {
713+ Field::Top => {
714+ pic.top_field_order_cnt = 0;
715+ pic.pic_order_cnt = 0;
716+ }
717+ Field::Bottom => {
718+ pic.bottom_field_order_cnt = 0;
719+ pic.pic_order_cnt = 0;
720+ }
721+ Field::Frame => {
722+ pic.top_field_order_cnt -= pic.pic_order_cnt;
723+ pic.bottom_field_order_cnt -= pic.pic_order_cnt;
724+ pic.pic_order_cnt =
725+ std::cmp::min(pic.top_field_order_cnt, pic.bottom_field_order_cnt);
726+ }
727+ }
728+
729+ MaxLongTermFrameIdx::NoLongTermFrameIndices
730+ }
731+
732+ pub fn mmco_op_6(&mut self, pic: &mut PictureData, marking: &RefPicMarkingInner) {
733+ let long_term_frame_idx = marking.long_term_frame_idx;
734+
735+ log::debug!("MMCO op 6, long_term_frame_idx: {}", long_term_frame_idx);
736+ log::trace!("Dpb state before MMCO=6: {:#?}", self);
737+
738+ for mut dpb_pic in self.pictures_mut() {
739+ // When a variable LongTermFrameIdx equal to long_term_frame_idx is
740+ // already assigned to a long-term reference frame or a long-term
741+ // complementary reference field pair, that frame or complementary
742+ // field pair and both of its fields are marked as "unused for
743+ // reference". When LongTermFrameIdx is already assigned to a
744+ // reference field, and that reference field is not part of a
745+ // complementary field pair that includes the current picture, that
746+ // field is marked as "unused for reference".
747+ if matches!(dpb_pic.reference(), Reference::LongTerm)
748+ && dpb_pic.long_term_frame_idx == long_term_frame_idx
749+ {
750+ let is_frame = matches!(dpb_pic.field, Field::Frame);
751+
752+ let is_complementary_ref_field_pair = dpb_pic
753+ .other_field()
754+ .map(|f| {
755+ let pic = f.borrow();
756+ matches!(pic.reference(), Reference::LongTerm)
757+ && pic.long_term_frame_idx == long_term_frame_idx
758+ })
759+ .unwrap_or(false);
760+
761+ dpb_pic.set_reference(Reference::None, is_frame || is_complementary_ref_field_pair);
762+
763+ break;
764+ }
765+ }
766+
767+ let is_frame = matches!(pic.field, Field::Frame);
768+
769+ let is_second_ref_field = match pic.field_rank() {
770+ FieldRank::Second(first_field)
771+ if *first_field.borrow().reference() == Reference::LongTerm =>
772+ {
773+ first_field.borrow_mut().long_term_frame_idx = long_term_frame_idx;
774+ true
775+ }
776+ _ => false,
777+ };
778+
779+ pic.set_reference(Reference::LongTerm, is_frame || is_second_ref_field);
780+ pic.long_term_frame_idx = long_term_frame_idx;
781+ }
782+
783+ #[cfg(debug_assertions)]
784+ fn debug_ref_list_p(ref_pic_list: &[&DpbEntry<T>], field_pic: bool) {
785+ debug!(
786+ "ref_list_p0: (ShortTerm|LongTerm, pic_num) {:?}",
787+ ref_pic_list
788+ .iter()
789+ .map(|h| {
790+ let p = h.pic.borrow();
791+ let reference = match p.reference() {
792+ Reference::None => panic!("Not a reference."),
793+ Reference::ShortTerm => "ShortTerm",
794+ Reference::LongTerm => "LongTerm",
795+ };
796+
797+ let field = if !p.is_second_field() { "First field" } else { "Second field" };
798+
799+ let field = format!("{}, {:?}", field, p.field);
800+
801+ let inner = match (field_pic, p.reference()) {
802+ (false, _) => ("pic_num", p.pic_num, field),
803+ (true, Reference::ShortTerm) => ("frame_num_wrap", p.frame_num_wrap, field),
804+ (true, Reference::LongTerm) => {
805+ ("long_term_frame_idx", p.long_term_frame_idx as i32, field)
806+ }
807+
808+ _ => panic!("Not a reference."),
809+ };
810+ (reference, inner)
811+ })
812+ .collect::<Vec<_>>()
813+ );
814+ }
815+
816+ #[cfg(debug_assertions)]
817+ fn debug_ref_list_b(ref_pic_list: &[&DpbEntry<T>], ref_pic_list_name: &str) {
818+ debug!(
819+ "{:?}: (ShortTerm|LongTerm, (POC|LongTermPicNum)) {:?}",
820+ ref_pic_list_name,
821+ ref_pic_list
822+ .iter()
823+ .map(|h| {
824+ let p = h.pic.borrow();
825+ let reference = match p.reference() {
826+ Reference::None => panic!("Not a reference."),
827+ Reference::ShortTerm => "ShortTerm",
828+ Reference::LongTerm => "LongTerm",
829+ };
830+
831+ let field = if !p.is_second_field() { "First field" } else { "Second field" };
832+
833+ let field = format!("{}, {:?}", field, p.field);
834+
835+ let inner = match p.reference() {
836+ Reference::ShortTerm => ("POC", p.pic_order_cnt, field),
837+ Reference::LongTerm => {
838+ ("LongTermPicNum", p.long_term_pic_num as i32, field)
839+ }
840+ _ => panic!("Not a reference!"),
841+ };
842+ (reference, inner)
843+ })
844+ .collect::<Vec<_>>()
845+ );
846+ }
847+
848+ fn sort_pic_num_descending(pics: &mut [&DpbEntry<T>]) {
849+ pics.sort_by_key(|h| std::cmp::Reverse(h.pic.borrow().pic_num));
850+ }
851+
852+ fn sort_frame_num_wrap_descending(pics: &mut [&DpbEntry<T>]) {
853+ pics.sort_by_key(|h| std::cmp::Reverse(h.pic.borrow().frame_num_wrap));
854+ }
855+
856+ fn sort_long_term_pic_num_ascending(pics: &mut [&DpbEntry<T>]) {
857+ pics.sort_by_key(|h| h.pic.borrow().long_term_pic_num);
858+ }
859+
860+ fn sort_long_term_frame_idx_ascending(pics: &mut [&DpbEntry<T>]) {
861+ pics.sort_by_key(|h| h.pic.borrow().long_term_frame_idx);
862+ }
863+
864+ fn sort_poc_descending(pics: &mut [&DpbEntry<T>]) {
865+ pics.sort_by_key(|h| std::cmp::Reverse(h.pic.borrow().pic_order_cnt));
866+ }
867+
868+ fn sort_poc_ascending(pics: &mut [&DpbEntry<T>]) {
869+ pics.sort_by_key(|h| h.pic.borrow().pic_order_cnt);
870+ }
871+
872+ // When the reference picture list RefPicList1 has more than one entry
873+ // and RefPicList1 is identical to the reference picture list
874+ // RefPicList0, the first two entries RefPicList1[0] and RefPicList1[1]
875+ // are switched.
876+ fn swap_b1_if_needed(b0: &DpbPicRefList<T>, b1: &mut DpbPicRefList<T>) {
877+ if b1.len() > 1 && b0.len() == b1.len() {
878+ let mut equals = true;
879+ for (x1, x2) in b0.iter().zip(b1.iter()) {
880+ if !Rc::ptr_eq(&x1.pic, &x2.pic) {
881+ equals = false;
882+ break;
883+ }
884+ }
885+
886+ if equals {
887+ b1.swap(0, 1);
888+ }
889+ }
890+ }
891+
892+ /// Copies from refFrameList(XShort|Long)Term into RefPicListX as per 8.2.4.2.5. Used when
893+ /// building the reference list for fields in interlaced decoding.
894+ fn init_ref_field_pic_list<'a>(
895+ mut field: Field,
896+ reference_type: Reference,
897+ ref_frame_list: &mut DpbPicRefList<'a, T>,
898+ ref_pic_list: &mut DpbPicRefList<'a, T>,
899+ ) {
900+ // When one field of a reference frame was not decoded or is not marked as "used for
901+ // (short|long)-term reference", the missing field is ignored and instead the next
902+ // available stored reference field of the chosen parity from the ordered list of frames
903+ // refFrameListX(Short|Long)Term is inserted into RefPicListX.
904+ ref_frame_list.retain(|h| {
905+ let p = h.pic.borrow();
906+ let skip = p.nonexisting || *p.reference() != reference_type;
907+ !skip
908+ });
909+
910+ while let Some(position) = ref_frame_list.iter().position(|h| {
911+ let p = h.pic.borrow();
912+ let found = p.field == field;
913+
914+ if found {
915+ field = field.opposite();
916+ }
917+
918+ found
919+ }) {
920+ let pic = ref_frame_list.remove(position);
921+ ref_pic_list.push(pic);
922+ }
923+
924+ ref_pic_list.append(ref_frame_list);
925+ }
926+
927+ /// 8.2.4.2.1 Initialization process for the reference picture list for P
928+ /// and SP slices in frames
929+ fn build_ref_pic_list_p(&self) -> DpbPicRefList<T> {
930+ let mut ref_pic_list_p0: Vec<_> =
931+ self.short_term_refs_iter().filter(|h| !h.pic.borrow().is_second_field()).collect();
932+
933+ Self::sort_pic_num_descending(&mut ref_pic_list_p0);
934+
935+ let num_short_term_refs = ref_pic_list_p0.len();
936+
937+ ref_pic_list_p0
938+ .extend(self.long_term_refs_iter().filter(|h| !h.pic.borrow().is_second_field()));
939+ Self::sort_long_term_pic_num_ascending(&mut ref_pic_list_p0[num_short_term_refs..]);
940+
941+ #[cfg(debug_assertions)]
942+ Self::debug_ref_list_p(&ref_pic_list_p0, false);
943+
944+ ref_pic_list_p0
945+ }
946+
947+ /// 8.2.4.2.2 Initialization process for the reference picture list for P
948+ /// and SP slices in fields
949+ fn build_ref_field_pic_list_p(&self, cur_pic: &PictureData) -> DpbPicRefList<T> {
950+ let mut ref_pic_list_p0 = vec![];
951+
952+ let mut ref_frame_list_0_short_term: Vec<_> = self.short_term_refs_iter().collect();
953+ Self::sort_frame_num_wrap_descending(&mut ref_frame_list_0_short_term);
954+
955+ let mut ref_frame_list_long_term: Vec<_> = self.long_term_refs_iter().collect();
956+ Self::sort_long_term_pic_num_ascending(&mut ref_frame_list_long_term);
957+
958+ // 8.2.4.2.5
959+ Self::init_ref_field_pic_list(
960+ cur_pic.field,
961+ Reference::ShortTerm,
962+ &mut ref_frame_list_0_short_term,
963+ &mut ref_pic_list_p0,
964+ );
965+ Self::init_ref_field_pic_list(
966+ cur_pic.field,
967+ Reference::LongTerm,
968+ &mut ref_frame_list_long_term,
969+ &mut ref_pic_list_p0,
970+ );
971+
972+ #[cfg(debug_assertions)]
973+ Self::debug_ref_list_p(&ref_pic_list_p0, true);
974+
975+ ref_pic_list_p0
976+ }
977+
978+ // 8.2.4.2.3 Initialization process for reference picture lists for B slices
979+ // in frames
980+ fn build_ref_pic_list_b(&self, cur_pic: &PictureData) -> (DpbPicRefList<T>, DpbPicRefList<T>) {
981+ let mut short_term_refs: Vec<_> =
982+ self.short_term_refs_iter().filter(|h| !h.pic.borrow().is_second_field()).collect();
983+
984+ // When pic_order_cnt_type is equal to 0, reference pictures that are
985+ // marked as "non-existing" as specified in clause 8.2.5.2 are not
986+ // included in either RefPicList0 or RefPicList1.
987+ if cur_pic.pic_order_cnt_type == 0 {
988+ short_term_refs.retain(|h| !h.pic.borrow().nonexisting);
989+ }
990+
991+ let mut ref_pic_list_b0 = vec![];
992+ let mut ref_pic_list_b1 = vec![];
993+ let mut remaining = vec![];
994+ // b0 contains three inner lists of pictures, i.e. [[0] [1] [2]]
995+ // [0]: short term pictures with POC < current, sorted by descending POC.
996+ // [1]: short term pictures with POC > current, sorted by ascending POC.
997+ // [2]: long term pictures sorted by ascending long_term_pic_num
998+ for &handle in &short_term_refs {
999+ let pic = handle.pic.borrow();
1000+
1001+ if pic.pic_order_cnt < cur_pic.pic_order_cnt {
1002+ ref_pic_list_b0.push(handle);
1003+ } else {
1004+ remaining.push(handle);
1005+ }
1006+ }
1007+
1008+ Self::sort_poc_descending(&mut ref_pic_list_b0);
1009+ Self::sort_poc_ascending(&mut remaining);
1010+ ref_pic_list_b0.append(&mut remaining);
1011+
1012+ let mut long_term_refs: Vec<_> = self
1013+ .long_term_refs_iter()
1014+ .filter(|h| !h.pic.borrow().nonexisting)
1015+ .filter(|h| !h.pic.borrow().is_second_field())
1016+ .collect();
1017+ Self::sort_long_term_pic_num_ascending(&mut long_term_refs);
1018+
1019+ ref_pic_list_b0.extend(long_term_refs.clone());
1020+
1021+ // b1 contains three inner lists of pictures, i.e. [[0] [1] [2]]
1022+ // [0]: short term pictures with POC > current, sorted by ascending POC.
1023+ // [1]: short term pictures with POC < current, sorted by descending POC.
1024+ // [2]: long term pictures sorted by ascending long_term_pic_num
1025+ for &handle in &short_term_refs {
1026+ let pic = handle.pic.borrow();
1027+
1028+ if pic.pic_order_cnt > cur_pic.pic_order_cnt {
1029+ ref_pic_list_b1.push(handle);
1030+ } else {
1031+ remaining.push(handle);
1032+ }
1033+ }
1034+
1035+ Self::sort_poc_ascending(&mut ref_pic_list_b1);
1036+ Self::sort_poc_descending(&mut remaining);
1037+
1038+ ref_pic_list_b1.extend(remaining);
1039+ ref_pic_list_b1.extend(long_term_refs);
1040+
1041+ // When the reference picture list RefPicList1 has more than one entry
1042+ // and RefPicList1 is identical to the reference picture list
1043+ // RefPicList0, the first two entries RefPicList1[0] and RefPicList1[1]
1044+ // are switched.
1045+ Self::swap_b1_if_needed(&ref_pic_list_b0, &mut ref_pic_list_b1);
1046+
1047+ #[cfg(debug_assertions)]
1048+ Self::debug_ref_list_b(&ref_pic_list_b0, "ref_pic_list_b0");
1049+ #[cfg(debug_assertions)]
1050+ Self::debug_ref_list_b(&ref_pic_list_b1, "ref_pic_list_b1");
1051+
1052+ (ref_pic_list_b0, ref_pic_list_b1)
1053+ }
1054+
1055+ /// 8.2.4.2.4 Initialization process for reference picture lists for B
1056+ /// slices in fields
1057+ fn build_ref_field_pic_list_b(
1058+ &self,
1059+ cur_pic: &PictureData,
1060+ ) -> (DpbPicRefList<T>, DpbPicRefList<T>) {
1061+ let mut ref_pic_list_b0 = vec![];
1062+ let mut ref_pic_list_b1 = vec![];
1063+ let mut ref_frame_list_0_short_term = vec![];
1064+ let mut ref_frame_list_1_short_term = vec![];
1065+
1066+ let mut remaining = vec![];
1067+
1068+ let mut short_term_refs: Vec<_> = self.short_term_refs_iter().collect();
1069+
1070+ // When pic_order_cnt_type is equal to 0, reference pictures that are
1071+ // marked as "non-existing" as specified in clause 8.2.5.2 are not
1072+ // included in either RefPicList0 or RefPicList1.
1073+ if cur_pic.pic_order_cnt_type == 0 {
1074+ short_term_refs.retain(|h| !h.pic.borrow().nonexisting);
1075+ }
1076+
1077+ // refFrameList0ShortTerm is comprised of two inner lists, [[0] [1]]
1078+ // [0]: short term pictures with POC <= current, sorted by descending POC
1079+ // [1]: short term pictures with POC > current, sorted by ascending POC
1080+ // NOTE 3 – When the current field follows in decoding order a coded
1081+ // field fldPrev with which together it forms a complementary reference
1082+ // field pair, fldPrev is included into the list refFrameList0ShortTerm
1083+ // using PicOrderCnt( fldPrev ) and the ordering method described in the
1084+ // previous sentence is applied.
1085+ for &handle in &short_term_refs {
1086+ let pic = handle.pic.borrow();
1087+
1088+ if pic.pic_order_cnt <= cur_pic.pic_order_cnt {
1089+ ref_frame_list_0_short_term.push(handle);
1090+ } else {
1091+ remaining.push(handle);
1092+ }
1093+ }
1094+
1095+ Self::sort_poc_descending(&mut ref_frame_list_0_short_term);
1096+ Self::sort_poc_ascending(&mut remaining);
1097+ ref_frame_list_0_short_term.append(&mut remaining);
1098+
1099+ // refFrameList1ShortTerm is comprised of two inner lists, [[0] [1]]
1100+ // [0]: short term pictures with POC > current, sorted by ascending POC
1101+ // [1]: short term pictures with POC <= current, sorted by descending POC
1102+ // NOTE 4 – When the current field follows in decoding order a coded
1103+ // field fldPrev with which together it forms a complementary reference
1104+ // field pair, fldPrev is included into the list refFrameList1ShortTerm
1105+ // using PicOrderCnt( fldPrev ) and the ordering method described in the
1106+ // previous sentence is applied.
1107+
1108+ for &handle in &short_term_refs {
1109+ let pic = handle.pic.borrow();
1110+
1111+ if pic.pic_order_cnt > cur_pic.pic_order_cnt {
1112+ ref_frame_list_1_short_term.push(handle);
1113+ } else {
1114+ remaining.push(handle);
1115+ }
1116+ }
1117+
1118+ Self::sort_poc_ascending(&mut ref_frame_list_1_short_term);
1119+ Self::sort_poc_descending(&mut remaining);
1120+ ref_frame_list_1_short_term.append(&mut remaining);
1121+
1122+ // refFrameListLongTerm: long term pictures sorted by ascending
1123+ // LongTermFrameIdx.
1124+ // NOTE 5 – When the current picture is the second field of a
1125+ // complementary field pair and the first field of the complementary
1126+ // field pair is marked as "used for long-term reference", the first
1127+ // field is included into the list refFrameListLongTerm. A reference
1128+ // entry in which only one field is marked as "used for long-term
1129+ // reference" is included into the list refFrameListLongTerm
1130+ let mut ref_frame_list_long_term: Vec<_> =
1131+ self.long_term_refs_iter().filter(|h| !h.pic.borrow().nonexisting).collect();
1132+
1133+ Self::sort_long_term_frame_idx_ascending(&mut ref_frame_list_long_term);
1134+
1135+ #[cfg(debug_assertions)]
1136+ Self::debug_ref_list_b(&ref_frame_list_0_short_term, "ref_frame_list_0_short_term");
1137+ #[cfg(debug_assertions)]
1138+ Self::debug_ref_list_b(&ref_frame_list_1_short_term, "ref_frame_list_1_short_term");
1139+ #[cfg(debug_assertions)]
1140+ Self::debug_ref_list_b(&ref_frame_list_long_term, "ref_frame_list_long_term");
1141+
1142+ // 8.2.4.2.5
1143+ let field = cur_pic.field;
1144+ Self::init_ref_field_pic_list(
1145+ field,
1146+ Reference::ShortTerm,
1147+ &mut ref_frame_list_0_short_term,
1148+ &mut ref_pic_list_b0,
1149+ );
1150+ Self::init_ref_field_pic_list(
1151+ field,
1152+ Reference::LongTerm,
1153+ &mut ref_frame_list_long_term,
1154+ &mut ref_pic_list_b0,
1155+ );
1156+
1157+ Self::init_ref_field_pic_list(
1158+ field,
1159+ Reference::ShortTerm,
1160+ &mut ref_frame_list_1_short_term,
1161+ &mut ref_pic_list_b1,
1162+ );
1163+ Self::init_ref_field_pic_list(
1164+ field,
1165+ Reference::LongTerm,
1166+ &mut ref_frame_list_long_term,
1167+ &mut ref_pic_list_b1,
1168+ );
1169+
1170+ // When the reference picture list RefPicList1 has more than one entry
1171+ // and RefPicList1 is identical to the reference picture list
1172+ // RefPicList0, the first two entries RefPicList1[0] and RefPicList1[1]
1173+ // are switched.
1174+ Self::swap_b1_if_needed(&ref_pic_list_b0, &mut ref_pic_list_b1);
1175+
1176+ #[cfg(debug_assertions)]
1177+ Self::debug_ref_list_b(&ref_pic_list_b0, "ref_pic_list_b0");
1178+ #[cfg(debug_assertions)]
1179+ Self::debug_ref_list_b(&ref_pic_list_b1, "ref_pic_list_b1");
1180+
1181+ (ref_pic_list_b0, ref_pic_list_b1)
1182+ }
1183+
1184+ /// Returns the lists of reference pictures for `pic`.
1185+ pub fn build_ref_pic_lists(&self, pic: &PictureData) -> ReferencePicLists {
1186+ let num_refs = self.pictures().filter(|p| p.is_ref() && !p.nonexisting).count();
1187+
1188+ // 8.2.4.2.1 ~ 8.2.4.2.4: When this process is invoked, there shall be
1189+ // at least one reference frame or complementary reference field pair
1190+ // that is currently marked as "used for reference" (i.e., as "used for
1191+ // short-term reference" or "used for long-term reference") and is not
1192+ // marked as "non-existing".
1193+ if num_refs == 0 {
1194+ return Default::default();
1195+ }
1196+
1197+ let (ref_pic_list_p0, (ref_pic_list_b0, ref_pic_list_b1)) =
1198+ if matches!(pic.field, Field::Frame) {
1199+ (self.build_ref_pic_list_p(), self.build_ref_pic_list_b(pic))
1200+ } else {
1201+ (self.build_ref_field_pic_list_p(pic), self.build_ref_field_pic_list_b(pic))
1202+ };
1203+
1204+ let dpb_start = self.entries.as_ptr();
1205+ let refs_to_index = |refs: Vec<_>| {
1206+ refs.into_iter()
1207+ .map(|r| r as *const DpbEntry<T>)
1208+ .map(|r| unsafe { r.offset_from(dpb_start) })
1209+ .map(|i| i as usize)
1210+ .collect()
1211+ };
1212+
1213+ ReferencePicLists {
1214+ ref_pic_list_p0: refs_to_index(ref_pic_list_p0),
1215+ ref_pic_list_b0: refs_to_index(ref_pic_list_b0),
1216+ ref_pic_list_b1: refs_to_index(ref_pic_list_b1),
1217+ }
1218+ }
1219+}
1220+
1221+impl<T> Default for Dpb<T> {
1222+ fn default() -> Self {
1223+ // See https://github.com/rust-lang/rust/issues/26925 on why this can't
1224+ // be derived.
1225+ Self {
1226+ entries: Default::default(),
1227+ max_num_pics: Default::default(),
1228+ max_num_reorder_frames: Default::default(),
1229+ interlaced: Default::default(),
1230+ }
1231+ }
1232+}
1233+
1234+impl<T> std::fmt::Debug for Dpb<T> {
1235+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1236+ let pics = self.entries.iter().map(|h| &h.pic).enumerate().collect::<Vec<_>>();
1237+ f.debug_struct("Dpb")
1238+ .field("pictures", &pics)
1239+ .field("max_num_pics", &self.max_num_pics)
1240+ .field("interlaced", &self.interlaced)
1241+ .finish()
1242+ }
1243+}
vendor/cros-codecs/src/codec/h264/nalu.rsadded+118 -0
@@ -0,0 +1,118 @@
1+// Copyright 2023 The ChromiumOS Authors
2+// Use of this source code is governed by a BSD-style license that can be
3+// found in the LICENSE file.
4+
5+use std::borrow::Cow;
6+use std::fmt::Debug;
7+use std::io::Cursor;
8+use std::io::Seek;
9+use std::io::SeekFrom;
10+
11+#[allow(clippy::len_without_is_empty)]
12+pub trait Header: Sized {
13+ /// Parse the NALU header, returning it.
14+ fn parse<T: AsRef<[u8]>>(cursor: &mut Cursor<T>) -> Result<Self, String>;
15+ /// Whether this header type indicates EOS.
16+ fn is_end(&self) -> bool;
17+ /// The length of the header.
18+ fn len(&self) -> usize;
19+}
20+
21+#[derive(Debug)]
22+pub struct Nalu<'a, U> {
23+ pub header: U,
24+ /// The mapping that backs this NALU. Possibly shared with the other NALUs
25+ /// in the Access Unit.
26+ pub data: Cow<'a, [u8]>,
27+
28+ pub size: usize,
29+ pub offset: usize,
30+}
31+
32+impl<'a, U> Nalu<'a, U>
33+where
34+ U: Debug + Header,
35+{
36+ /// Find the next Annex B encoded NAL unit.
37+ pub fn next(cursor: &mut Cursor<&'a [u8]>) -> Result<Nalu<'a, U>, String> {
38+ let bitstream = cursor.clone().into_inner();
39+ let pos = usize::try_from(cursor.position()).map_err(|err| err.to_string())?;
40+
41+ // Find the start code for this NALU
42+ let current_nalu_offset = match Nalu::<'a, U>::find_start_code(cursor, pos) {
43+ Some(offset) => offset,
44+ None => return Err("No NAL found".into()),
45+ };
46+
47+ let mut start_code_offset = pos + current_nalu_offset;
48+
49+ // If the preceding byte is 00, then we actually have a four byte SC,
50+ // i.e. 00 00 00 01 Where the first 00 is the "zero_byte()"
51+ if start_code_offset > 0 && cursor.get_ref()[start_code_offset - 1] == 00 {
52+ start_code_offset -= 1;
53+ }
54+
55+ // The NALU offset is its offset + 3 bytes to skip the start code.
56+ let nalu_offset = pos + current_nalu_offset + 3;
57+
58+ // Set the bitstream position to the start of the current NALU
59+ cursor.set_position(u64::try_from(nalu_offset).map_err(|err| err.to_string())?);
60+
61+ let hdr = U::parse(cursor)?;
62+
63+ // Find the start of the subsequent NALU.
64+ let mut next_nalu_offset = match Nalu::<'a, U>::find_start_code(cursor, nalu_offset) {
65+ Some(offset) => offset,
66+ None => {
67+ let cur_pos = cursor.position();
68+ let end_pos = cursor.seek(SeekFrom::End(0)).map_err(|err| err.to_string())?;
69+ let _ = cursor.seek(SeekFrom::Start(cur_pos)).map_err(|err| err.to_string())?;
70+ (end_pos - cur_pos) as usize
71+ } // Whatever data is left must be part of the current NALU
72+ };
73+
74+ while next_nalu_offset > 0 && cursor.get_ref()[nalu_offset + next_nalu_offset - 1] == 00 {
75+ // Discard trailing_zero_8bits
76+ next_nalu_offset -= 1;
77+ }
78+
79+ let nal_size = if hdr.is_end() {
80+ // the NALU is comprised of only the header
81+ hdr.len()
82+ } else {
83+ next_nalu_offset
84+ };
85+
86+ Ok(Nalu {
87+ header: hdr,
88+ data: Cow::from(&bitstream[start_code_offset..nalu_offset + nal_size]),
89+ size: nal_size,
90+ offset: nalu_offset - start_code_offset,
91+ })
92+ }
93+}
94+
95+impl<'a, U> Nalu<'a, U>
96+where
97+ U: Debug,
98+{
99+ fn find_start_code(data: &mut Cursor<&'a [u8]>, offset: usize) -> Option<usize> {
100+ // discard all zeroes until the start code pattern is found
101+ data.get_ref()[offset..].windows(3).position(|window| window == [0x00, 0x00, 0x01])
102+ }
103+
104+ pub fn into_owned(self) -> Nalu<'static, U> {
105+ Nalu {
106+ header: self.header,
107+ size: self.size,
108+ offset: self.offset,
109+ data: Cow::Owned(self.data.into_owned()),
110+ }
111+ }
112+}
113+
114+impl<'a, U> AsRef<[u8]> for Nalu<'a, U> {
115+ fn as_ref(&self) -> &[u8] {
116+ &self.data[self.offset..self.offset + self.size]
117+ }
118+}
vendor/cros-codecs/src/codec/h264/nalu_writer.rsadded+299 -0
@@ -0,0 +1,299 @@
1+// Copyright 2024 The ChromiumOS Authors
2+// Use of this source code is governed by a BSD-style license that can be
3+// found in the LICENSE file.
4+use std::fmt;
5+use std::io::Write;
6+
7+use crate::bitstream_utils::BitWriter;
8+use crate::bitstream_utils::BitWriterError;
9+
10+/// Internal wrapper over [`std::io::Write`] for possible emulation prevention
11+struct EmulationPrevention<W: Write> {
12+ out: W,
13+ prev_bytes: [Option<u8>; 2],
14+
15+ /// Emulation prevention enabled.
16+ ep_enabled: bool,
17+}
18+
19+impl<W: Write> EmulationPrevention<W> {
20+ fn new(writer: W, ep_enabled: bool) -> Self {
21+ Self { out: writer, prev_bytes: [None; 2], ep_enabled }
22+ }
23+
24+ fn write_byte(&mut self, curr_byte: u8) -> std::io::Result<()> {
25+ if self.prev_bytes[1] == Some(0x00) && self.prev_bytes[0] == Some(0x00) && curr_byte <= 0x03
26+ {
27+ self.out.write_all(&[0x00, 0x00, 0x03, curr_byte])?;
28+ self.prev_bytes = [None; 2];
29+ } else {
30+ if let Some(byte) = self.prev_bytes[1] {
31+ self.out.write_all(&[byte])?;
32+ }
33+
34+ self.prev_bytes[1] = self.prev_bytes[0];
35+ self.prev_bytes[0] = Some(curr_byte);
36+ }
37+
38+ Ok(())
39+ }
40+
41+ /// Writes a H.264 NALU header.
42+ fn write_header(&mut self, idc: u8, type_: u8) -> NaluWriterResult<()> {
43+ self.out.write_all(&[0x00, 0x00, 0x00, 0x01, (idc & 0b11) << 5 | (type_ & 0b11111)])?;
44+
45+ Ok(())
46+ }
47+
48+ fn has_data_pending(&self) -> bool {
49+ self.prev_bytes[0].is_some() || self.prev_bytes[1].is_some()
50+ }
51+}
52+
53+impl<W: Write> Write for EmulationPrevention<W> {
54+ fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
55+ if !self.ep_enabled {
56+ self.out.write_all(buf)?;
57+ return Ok(buf.len());
58+ }
59+
60+ for byte in buf {
61+ self.write_byte(*byte)?;
62+ }
63+
64+ Ok(buf.len())
65+ }
66+
67+ fn flush(&mut self) -> std::io::Result<()> {
68+ if let Some(byte) = self.prev_bytes[1].take() {
69+ self.out.write_all(&[byte])?;
70+ }
71+
72+ if let Some(byte) = self.prev_bytes[0].take() {
73+ self.out.write_all(&[byte])?;
74+ }
75+
76+ self.out.flush()
77+ }
78+}
79+
80+impl<W: Write> Drop for EmulationPrevention<W> {
81+ fn drop(&mut self) {
82+ if let Err(e) = self.flush() {
83+ log::error!("Unable to flush pending bytes {e:?}");
84+ }
85+ }
86+}
87+
88+#[derive(Debug)]
89+pub enum NaluWriterError {
90+ Overflow,
91+ Io(std::io::Error),
92+ BitWriterError(BitWriterError),
93+}
94+
95+impl fmt::Display for NaluWriterError {
96+ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
97+ match self {
98+ NaluWriterError::Overflow => write!(f, "value increment caused value overflow"),
99+ NaluWriterError::Io(x) => write!(f, "{}", x.to_string()),
100+ NaluWriterError::BitWriterError(x) => write!(f, "{}", x.to_string()),
101+ }
102+ }
103+}
104+
105+impl From<std::io::Error> for NaluWriterError {
106+ fn from(err: std::io::Error) -> Self {
107+ NaluWriterError::Io(err)
108+ }
109+}
110+
111+impl From<BitWriterError> for NaluWriterError {
112+ fn from(err: BitWriterError) -> Self {
113+ NaluWriterError::BitWriterError(err)
114+ }
115+}
116+
117+pub type NaluWriterResult<T> = std::result::Result<T, NaluWriterError>;
118+
119+/// A writer for H.264 bitstream. It is capable of outputing bitstream with
120+/// emulation-prevention.
121+pub struct NaluWriter<W: Write>(BitWriter<EmulationPrevention<W>>);
122+
123+impl<W: Write> NaluWriter<W> {
124+ pub fn new(writer: W, ep_enabled: bool) -> Self {
125+ Self(BitWriter::new(EmulationPrevention::new(writer, ep_enabled)))
126+ }
127+
128+ /// Writes fixed bit size integer (up to 32 bit) output with emulation
129+ /// prevention if enabled. Corresponds to `f(n)` in H.264 spec.
130+ pub fn write_f<T: Into<u32>>(&mut self, bits: usize, value: T) -> NaluWriterResult<usize> {
131+ self.0.write_f(bits, value).map_err(NaluWriterError::BitWriterError)
132+ }
133+
134+ /// An alias to [`Self::write_f`] Corresponds to `n(n)` in H.264 spec.
135+ pub fn write_u<T: Into<u32>>(&mut self, bits: usize, value: T) -> NaluWriterResult<usize> {
136+ self.write_f(bits, value)
137+ }
138+
139+ /// Writes a number in exponential golumb format.
140+ pub fn write_exp_golumb(&mut self, value: u32) -> NaluWriterResult<()> {
141+ let value = value.checked_add(1).ok_or(NaluWriterError::Overflow)?;
142+ let bits = 32 - value.leading_zeros() as usize;
143+ let zeros = bits - 1;
144+
145+ self.write_f(zeros, 0u32)?;
146+ self.write_f(bits, value)?;
147+
148+ Ok(())
149+ }
150+
151+ /// Writes a unsigned integer in exponential golumb format.
152+ /// Coresponds to `ue(v)` in H.264 spec.
153+ pub fn write_ue<T: Into<u32>>(&mut self, value: T) -> NaluWriterResult<()> {
154+ let value = value.into();
155+
156+ self.write_exp_golumb(value)
157+ }
158+
159+ /// Writes a signed integer in exponential golumb format.
160+ /// Coresponds to `se(v)` in H.264 spec.
161+ pub fn write_se<T: Into<i32>>(&mut self, value: T) -> NaluWriterResult<()> {
162+ let value: i32 = value.into();
163+ let abs_value: u32 = value.unsigned_abs();
164+
165+ if value <= 0 {
166+ self.write_ue(2 * abs_value)
167+ } else {
168+ self.write_ue(2 * abs_value - 1)
169+ }
170+ }
171+
172+ /// Returns `true` if ['Self`] hold data that wasn't written to [`std::io::Write`]
173+ pub fn has_data_pending(&self) -> bool {
174+ self.0.has_data_pending() || self.0.inner().has_data_pending()
175+ }
176+
177+ /// Writes a H.264 NALU header.
178+ pub fn write_header(&mut self, idc: u8, _type: u8) -> NaluWriterResult<()> {
179+ self.0.flush()?;
180+ self.0.inner_mut().write_header(idc, _type)?;
181+ Ok(())
182+ }
183+
184+ /// Returns `true` if next bits will be aligned to 8
185+ pub fn aligned(&self) -> bool {
186+ !self.0.has_data_pending()
187+ }
188+}
189+
190+#[cfg(test)]
191+mod tests {
192+ use super::*;
193+ use crate::bitstream_utils::BitReader;
194+
195+ #[test]
196+ fn simple_bits() {
197+ let mut buf = Vec::<u8>::new();
198+ {
199+ let mut writer = NaluWriter::new(&mut buf, false);
200+ writer.write_f(1, true).unwrap();
201+ writer.write_f(1, false).unwrap();
202+ writer.write_f(1, false).unwrap();
203+ writer.write_f(1, false).unwrap();
204+ writer.write_f(1, true).unwrap();
205+ writer.write_f(1, true).unwrap();
206+ writer.write_f(1, true).unwrap();
207+ writer.write_f(1, true).unwrap();
208+ }
209+ assert_eq!(buf, vec![0b10001111u8]);
210+ }
211+
212+ #[test]
213+ fn simple_first_few_ue() {
214+ fn single_ue(value: u32) -> Vec<u8> {
215+ let mut buf = Vec::<u8>::new();
216+ {
217+ let mut writer = NaluWriter::new(&mut buf, false);
218+ writer.write_ue(value).unwrap();
219+ }
220+ buf
221+ }
222+
223+ assert_eq!(single_ue(0), vec![0b10000000u8]);
224+ assert_eq!(single_ue(1), vec![0b01000000u8]);
225+ assert_eq!(single_ue(2), vec![0b01100000u8]);
226+ assert_eq!(single_ue(3), vec![0b00100000u8]);
227+ assert_eq!(single_ue(4), vec![0b00101000u8]);
228+ assert_eq!(single_ue(5), vec![0b00110000u8]);
229+ assert_eq!(single_ue(6), vec![0b00111000u8]);
230+ assert_eq!(single_ue(7), vec![0b00010000u8]);
231+ assert_eq!(single_ue(8), vec![0b00010010u8]);
232+ assert_eq!(single_ue(9), vec![0b00010100u8]);
233+ }
234+
235+ #[test]
236+ fn writer_reader() {
237+ let mut buf = Vec::<u8>::new();
238+ {
239+ let mut writer = NaluWriter::new(&mut buf, false);
240+ writer.write_ue(10u32).unwrap();
241+ writer.write_se(-42).unwrap();
242+ writer.write_se(3).unwrap();
243+ writer.write_ue(5u32).unwrap();
244+ }
245+
246+ let mut reader = BitReader::new(&buf, true);
247+
248+ assert_eq!(reader.read_ue::<u32>().unwrap(), 10);
249+ assert_eq!(reader.read_se::<i32>().unwrap(), -42);
250+ assert_eq!(reader.read_se::<i32>().unwrap(), 3);
251+ assert_eq!(reader.read_ue::<u32>().unwrap(), 5);
252+
253+ let mut buf = Vec::<u8>::new();
254+ {
255+ let mut writer = NaluWriter::new(&mut buf, false);
256+ writer.write_se(30).unwrap();
257+ writer.write_ue(100u32).unwrap();
258+ writer.write_se(-402).unwrap();
259+ writer.write_ue(50u32).unwrap();
260+ }
261+
262+ let mut reader = BitReader::new(&buf, true);
263+
264+ assert_eq!(reader.read_se::<i32>().unwrap(), 30);
265+ assert_eq!(reader.read_ue::<u32>().unwrap(), 100);
266+ assert_eq!(reader.read_se::<i32>().unwrap(), -402);
267+ assert_eq!(reader.read_ue::<u32>().unwrap(), 50);
268+ }
269+
270+ #[test]
271+ fn writer_emulation_prevention() {
272+ fn test(input: &[u8], bitstream: &[u8]) {
273+ let mut buf = Vec::<u8>::new();
274+ {
275+ let mut writer = NaluWriter::new(&mut buf, true);
276+ for byte in input {
277+ writer.write_f(8, *byte).unwrap();
278+ }
279+ }
280+ assert_eq!(buf, bitstream);
281+ {
282+ let mut reader = BitReader::new(&buf, true);
283+ for byte in input {
284+ assert_eq!(*byte, reader.read_bits::<u8>(8).unwrap());
285+ }
286+ }
287+ }
288+
289+ test(&[0x00, 0x00, 0x00], &[0x00, 0x00, 0x03, 0x00]);
290+ test(&[0x00, 0x00, 0x01], &[0x00, 0x00, 0x03, 0x01]);
291+ test(&[0x00, 0x00, 0x02], &[0x00, 0x00, 0x03, 0x02]);
292+ test(&[0x00, 0x00, 0x03], &[0x00, 0x00, 0x03, 0x03]);
293+
294+ test(&[0x00, 0x00, 0x00, 0x00], &[0x00, 0x00, 0x03, 0x00, 0x00]);
295+ test(&[0x00, 0x00, 0x00, 0x01], &[0x00, 0x00, 0x03, 0x00, 0x01]);
296+ test(&[0x00, 0x00, 0x00, 0x02], &[0x00, 0x00, 0x03, 0x00, 0x02]);
297+ test(&[0x00, 0x00, 0x00, 0x03], &[0x00, 0x00, 0x03, 0x00, 0x03]);
298+ }
299+}
vendor/cros-codecs/src/codec/h264/parser.rsadded+3023 -0

Diff too large; view file

@@ -0,0 +1,3023 @@
1+// Copyright 2022 The ChromiumOS Authors
2+// Use of this source code is governed by a BSD-style license that can be
3+// found in the LICENSE file.
4+
5+// Can't reasonably expect client code to consume everything that has been parsed.
6+#![allow(dead_code)]
7+
8+use std::collections::BTreeMap;
9+use std::io::Cursor;
10+use std::io::Read;
11+use std::io::Seek;
12+use std::io::SeekFrom;
13+use std::rc::Rc;
14+
15+use crate::bitstream_utils::BitReader;
16+use crate::codec::h264::nalu;
17+use crate::codec::h264::nalu::Header;
18+use crate::codec::h264::picture::Field;
19+
20+pub type Nalu<'a> = nalu::Nalu<'a, NaluHeader>;
21+
22+pub(super) const DEFAULT_4X4_INTRA: [u8; 16] =
23+ [6, 13, 13, 20, 20, 20, 28, 28, 28, 28, 32, 32, 32, 37, 37, 42];
24+
25+pub(super) const DEFAULT_4X4_INTER: [u8; 16] =
26+ [10, 14, 14, 20, 20, 20, 24, 24, 24, 24, 27, 27, 27, 30, 30, 34];
27+
28+pub(super) const DEFAULT_8X8_INTRA: [u8; 64] = [
29+ 6, 10, 10, 13, 11, 13, 16, 16, 16, 16, 18, 18, 18, 18, 18, 23, 23, 23, 23, 23, 23, 25, 25, 25,
30+ 25, 25, 25, 25, 27, 27, 27, 27, 27, 27, 27, 27, 29, 29, 29, 29, 29, 29, 29, 31, 31, 31, 31, 31,
31+ 31, 33, 33, 33, 33, 33, 36, 36, 36, 36, 38, 38, 38, 40, 40, 42,
32+];
33+
34+pub(super) const DEFAULT_8X8_INTER: [u8; 64] = [
35+ 9, 13, 13, 15, 13, 15, 17, 17, 17, 17, 19, 19, 19, 19, 19, 21, 21, 21, 21, 21, 21, 22, 22, 22,
36+ 22, 22, 22, 22, 24, 24, 24, 24, 24, 24, 24, 24, 25, 25, 25, 25, 25, 25, 25, 27, 27, 27, 27, 27,
37+ 27, 28, 28, 28, 28, 28, 30, 30, 30, 30, 32, 32, 32, 33, 33, 35,
38+];
39+
40+const MAX_PPS_COUNT: u16 = 256;
41+const MAX_SPS_COUNT: u8 = 32;
42+
43+/// The maximum number of pictures in the DPB, as per A.3.1, clause h)
44+const DPB_MAX_SIZE: usize = 16;
45+
46+#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
47+pub struct Point<T> {
48+ pub x: T,
49+ pub y: T,
50+}
51+
52+#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
53+pub struct Rect<T> {
54+ pub min: Point<T>,
55+ pub max: Point<T>,
56+}
57+
58+#[derive(Debug, PartialEq, Eq, Clone, Copy)]
59+pub enum NaluType {
60+ Unknown = 0,
61+ Slice = 1,
62+ SliceDpa = 2,
63+ SliceDpb = 3,
64+ SliceDpc = 4,
65+ SliceIdr = 5,
66+ Sei = 6,
67+ Sps = 7,
68+ Pps = 8,
69+ AuDelimiter = 9,
70+ SeqEnd = 10,
71+ StreamEnd = 11,
72+ FillerData = 12,
73+ SpsExt = 13,
74+ PrefixUnit = 14,
75+ SubsetSps = 15,
76+ DepthSps = 16,
77+ SliceAux = 19,
78+ SliceExt = 20,
79+ SliceDepth = 21,
80+}
81+
82+impl TryFrom<u8> for NaluType {
83+ type Error = String;
84+
85+ fn try_from(value: u8) -> Result<Self, Self::Error> {
86+ match value {
87+ 0 => Ok(NaluType::Unknown),
88+ 1 => Ok(NaluType::Slice),
89+ 2 => Ok(NaluType::SliceDpa),
90+ 3 => Ok(NaluType::SliceDpb),
91+ 4 => Ok(NaluType::SliceDpc),
92+ 5 => Ok(NaluType::SliceIdr),
93+ 6 => Ok(NaluType::Sei),
94+ 7 => Ok(NaluType::Sps),
95+ 8 => Ok(NaluType::Pps),
96+ 9 => Ok(NaluType::AuDelimiter),
97+ 10 => Ok(NaluType::SeqEnd),
98+ 11 => Ok(NaluType::StreamEnd),
99+ 12 => Ok(NaluType::FillerData),
100+ 13 => Ok(NaluType::SpsExt),
101+ 14 => Ok(NaluType::PrefixUnit),
102+ 15 => Ok(NaluType::SubsetSps),
103+ 16 => Ok(NaluType::DepthSps),
104+ 19 => Ok(NaluType::SliceAux),
105+ 20 => Ok(NaluType::SliceExt),
106+ 21 => Ok(NaluType::SliceDepth),
107+ _ => Err(format!("Invalid NaluType {}", value)),
108+ }
109+ }
110+}
111+
112+#[derive(Clone, Debug, Default, PartialEq, Eq)]
113+pub struct RefPicListModification {
114+ pub modification_of_pic_nums_idc: u8,
115+ /* if modification_of_pic_nums_idc == 0 || 1 */
116+ pub abs_diff_pic_num_minus1: u32,
117+ /* if modification_of_pic_nums_idc == 2 */
118+ pub long_term_pic_num: u32,
119+ /* if modification_of_pic_nums_idc == 4 || 5 */
120+ pub abs_diff_view_idx_minus1: u32,
121+}
122+
123+#[derive(Clone, Debug, Default, PartialEq, Eq)]
124+pub struct PredWeightTable {
125+ pub luma_log2_weight_denom: u8,
126+ pub chroma_log2_weight_denom: u8,
127+
128+ pub luma_weight_l0: [i16; 32],
129+ pub luma_offset_l0: [i8; 32],
130+
131+ /* if seq->ChromaArrayType != 0 */
132+ pub chroma_weight_l0: [[i16; 2]; 32],
133+ pub chroma_offset_l0: [[i8; 2]; 32],
134+
135+ /* if slice->slice_type % 5 == 1 */
136+ pub luma_weight_l1: [i16; 32],
137+ pub luma_offset_l1: [i16; 32],
138+
139+ /* and if seq->ChromaArrayType != 0 */
140+ pub chroma_weight_l1: [[i16; 2]; 32],
141+ pub chroma_offset_l1: [[i8; 2]; 32],
142+}
143+
144+/// Representation of `MaxLongTermFrameIdx`.
145+///
146+/// `MaxLongTermFrameIdx` is derived from `max_long_term_frame_idx_plus1`, an unsigned integer with
147+/// a special value indicating "no long-term frame indices". This type allows easy conversion
148+/// between the actual and "plus1" representation, while ensuring that the special value is always
149+/// handled by the code.
150+#[derive(Default, Debug, Clone, Copy, PartialEq, Eq)]
151+pub enum MaxLongTermFrameIdx {
152+ #[default]
153+ NoLongTermFrameIndices,
154+ Idx(u32),
155+}
156+
157+impl MaxLongTermFrameIdx {
158+ /// Create a value from `max_long_term_frame_idx_plus1`.
159+ pub fn from_value_plus1(max_long_term_frame_idx_plus1: u32) -> Self {
160+ match max_long_term_frame_idx_plus1 {
161+ 0 => Self::NoLongTermFrameIndices,
162+ i @ 1.. => Self::Idx(i - 1),
163+ }
164+ }
165+
166+ /// Convert this value to the representation used by `max_long_term_frame_idx_plus1`.
167+ pub fn to_value_plus1(self) -> u32 {
168+ match self {
169+ Self::NoLongTermFrameIndices => 0,
170+ Self::Idx(i) => i + 1,
171+ }
172+ }
173+}
174+
175+impl PartialEq<u32> for MaxLongTermFrameIdx {
176+ fn eq(&self, other: &u32) -> bool {
177+ match self {
178+ MaxLongTermFrameIdx::NoLongTermFrameIndices => false,
179+ MaxLongTermFrameIdx::Idx(idx) => idx.eq(other),
180+ }
181+ }
182+}
183+
184+impl PartialOrd<u32> for MaxLongTermFrameIdx {
185+ fn partial_cmp(&self, other: &u32) -> Option<std::cmp::Ordering> {
186+ match self {
187+ MaxLongTermFrameIdx::NoLongTermFrameIndices => Some(std::cmp::Ordering::Less),
188+ MaxLongTermFrameIdx::Idx(idx) => Some(idx.cmp(other)),
189+ }
190+ }
191+}
192+
193+#[derive(Clone, Debug, Default, PartialEq, Eq)]
194+pub struct RefPicMarkingInner {
195+ /// Specifies a control operation to be applied to affect the reference
196+ /// picture marking. The `memory_management_control_operation` syntax element
197+ /// is followed by data necessary for the operation specified by the value
198+ /// of `memory_management_control_operation`. The values and control
199+ /// operations associated with `memory_management_control_operation` are
200+ /// specified in Table 7-9
201+ pub memory_management_control_operation: u8,
202+
203+ /// Used (with memory_management_control_operation equal to 3 or 1) to
204+ /// assign a long-term frame index to a short-term reference picture or to
205+ /// mark a short-term reference picture as "unused for reference".
206+ pub difference_of_pic_nums_minus1: u32,
207+
208+ /// Used (with memory_management_control_operation equal to 2) to mark a
209+ /// long-term reference picture as "unused for reference".
210+ pub long_term_pic_num: u32,
211+
212+ /// Used (with memory_management_control_operation equal to 3 or 6) to
213+ /// assign a long-term frame index to a picture.
214+ pub long_term_frame_idx: u32,
215+
216+ /// Specifies the maximum value of long-term frame index allowed for
217+ /// long-term reference pictures (until receipt of another value of
218+ /// `max_long_term_frame_idx_plus1`).
219+ pub max_long_term_frame_idx: MaxLongTermFrameIdx,
220+}
221+
222+#[derive(Clone, Debug, Default, PartialEq, Eq)]
223+pub struct RefPicMarking {
224+ /// Specifies how the previously-decoded pictures in the decoded picture
225+ /// buffer are treated after decoding of an IDR picture. See Annex C.
226+ pub no_output_of_prior_pics_flag: bool,
227+
228+ /// If unset, specifies that the MaxLongTermFrameIdx variable is set equal
229+ /// to "no long-term frame indices" and that the IDR picture is marked as
230+ /// "used for short-term reference". If set, specifies that the
231+ /// MaxLongTermFrameIdx variable is set equal to 0 and that the current IDR
232+ /// picture is marked "used for long-term reference" and is assigned
233+ /// LongTermFrameIdx equal to 0.
234+ pub long_term_reference_flag: bool,
235+
236+ /// Selects the reference picture marking mode of the currently decoded
237+ /// picture as specified in Table 7-8.
238+ pub adaptive_ref_pic_marking_mode_flag: bool,
239+
240+ /// An Vec with additional data used in the marking process.
241+ pub inner: Vec<RefPicMarkingInner>,
242+}
243+
244+#[derive(Clone, Debug, Default, PartialEq, Eq)]
245+pub struct SliceHeader {
246+ /// Specifies the address of the first macroblock in the slice.
247+ pub first_mb_in_slice: u32,
248+
249+ /// Specifies the coding type of the slice according to Table 7-6.
250+ pub slice_type: SliceType,
251+
252+ // Specifies the picture parameter set in use
253+ pub pic_parameter_set_id: u8,
254+
255+ /// Specifies the colour plane associated with the current slice RBSP when
256+ /// `separate_colour_plane_flag` is set.
257+ pub colour_plane_id: u8,
258+
259+ /// Used as an identifier for pictures and shall be represented by
260+ /// `log2_max_frame_num_minus4 + 4` bits in the bitstream.
261+ pub frame_num: u16,
262+
263+ /// If set, specifies that the slice is a slice of a coded field. If not
264+ /// set, specifies that the slice is a slice of a coded frame.
265+ pub field_pic_flag: bool,
266+
267+ /// If set, specifies that the slice is part of a coded bottom field. If not
268+ /// set, specifies that the picture is a coded top field.
269+ pub bottom_field_flag: bool,
270+
271+ /// Identifies an IDR picture. The values of `idr_pic_id` in all the slices
272+ /// of an IDR picture shall remain unchanged. When two consecutive access
273+ /// units in decoding order are both IDR access units, the value of
274+ /// `idr_pic_id` in the slices of the first such IDR access unit shall
275+ /// differ from the `idr_pic_id` in the second such IDR access unit
276+ pub idr_pic_id: u16,
277+
278+ /// Specifies the picture order count modulo `MaxPicOrderCntLsb` for the top
279+ /// field of a coded frame or for a coded field. The length of the
280+ /// `pic_order_cnt_lsb` syntax element is
281+ /// `log2_max_pic_order_cnt_lsb_minus4` + 4 bits.
282+ pub pic_order_cnt_lsb: u16,
283+
284+ /// Specifies the picture order count difference between the bottom field
285+ /// and the top field of a coded frame as follows
286+ pub delta_pic_order_cnt_bottom: i32,
287+
288+ /// The first entry specifies the picture order count difference from the
289+ /// expected picture order count for the top field of a coded frame or for a
290+ /// coded field as specified in clause 8.2.1 The second entry specifies the
291+ /// picture order count difference from the expected picture order count for
292+ /// the bottom field of a coded frame specified in clause 8.2.1.
293+ pub delta_pic_order_cnt: [i32; 2],
294+
295+ /// This value is required by V4L2 stateless decode params so it is calculated
296+ /// by parser while processing slice header.
297+ pub pic_order_cnt_bit_size: usize,
298+
299+ /// Shall be equal to 0 for slices and slice data partitions belonging to
300+ /// the primary coded picture. The value of `redundant_pic_cnt shall` be
301+ /// greater than 0 for coded slices or coded slice data partitions of a
302+ /// redundant coded picture
303+ pub redundant_pic_cnt: u8,
304+
305+ /// Specifies the method used in the decoding process to derive motion
306+ /// vectors and reference indices for inter prediction >
307+ pub direct_spatial_mv_pred_flag: bool,
308+
309+ /// If set, specifies that the syntax element `num_ref_idx_l0_active_minus1`
310+ /// is present for P, SP, and B slices and that the syntax element
311+ /// `num_ref_idx_l1_active_minus1` is present for B slices. If not set,
312+ /// specifies that the syntax elements `num_ref_idx_l0_active_minus1` and
313+ /// `num_ref_idx_l1_active_minus1` are not present.
314+ pub num_ref_idx_active_override_flag: bool,
315+
316+ /// Specifies the maximum reference index for reference picture list 0 that
317+ /// shall be used to decode the slice.
318+ pub num_ref_idx_l0_active_minus1: u8,
319+
320+ /// Specifies the maximum reference index for reference picture list 1 that
321+ /// shall be used to decode the slice.
322+ pub num_ref_idx_l1_active_minus1: u8,
323+
324+ /// If set, specifies that the syntax element `modification_of_pic_nums_idc`
325+ /// is present for specifying reference picture list 0. If not set,
326+ /// specifies that this syntax element is not present.
327+ pub ref_pic_list_modification_flag_l0: bool,
328+
329+ /// Reference picture list 0 modification as parsed with the
330+ /// `ref_pic_list_modification()` process.
331+ pub ref_pic_list_modification_l0: Vec<RefPicListModification>,
332+
333+ /// If set, specifies that the syntax element `modification_of_pic_nums_idc`
334+ /// is present for specifying reference picture list 1. If not set,
335+ /// specifies that this syntax element is not present.
336+ pub ref_pic_list_modification_flag_l1: bool,
337+
338+ /// Reference picture list 1 modification as parsed with the
339+ /// `ref_pic_list_modification()` process.
340+ pub ref_pic_list_modification_l1: Vec<RefPicListModification>,
341+
342+ /// Prediction weight table as parsed using 7.3.3.2
343+ pub pred_weight_table: PredWeightTable,
344+
345+ /// Decoded reference picture marking parsed using 7.3.3.3
346+ pub dec_ref_pic_marking: RefPicMarking,
347+
348+ /// This value is required by V4L2 stateless decode params so it is calculated
349+ /// by parser while processing slice header.
350+ pub dec_ref_pic_marking_bit_size: usize,
351+
352+ /// Specifies the index for determining the initialization table used in the
353+ /// initialization process for context variables.
354+ pub cabac_init_idc: u8,
355+
356+ /// Specifies the initial value of QP Y to be used for all the macroblocks
357+ /// in the slice until modified by the value of `mb_qp_delta` in the
358+ /// macroblock layer. The initial QPY quantization parameter for the slice
359+ /// is computed using 7-30.
360+ pub slice_qp_delta: i8,
361+
362+ /// Specifies the decoding process to be used to decode P macroblocks in an
363+ /// SP slice.
364+ pub sp_for_switch_flag: bool,
365+
366+ /// Specifies the value of QSY for all the macroblocks in SP and SI slices.
367+ /// The QSY quantization parameter for the slice is computed using 7-31.
368+ pub slice_qs_delta: i8,
369+
370+ /// Specifies whether the operation of the deblocking filter shall be
371+ /// disabled across some block edges of the slice and specifies for which
372+ /// edges the filtering is disabled.
373+ pub disable_deblocking_filter_idc: u8,
374+
375+ /// Specifies the offset used in accessing the α and tC0 deblocking filter
376+ /// tables for filtering operations controlled by the macroblocks within the
377+ /// slice. From this value, the offset that shall be applied when addressing
378+ /// these tables shall be computed using 7-32.
379+ pub slice_alpha_c0_offset_div2: i8,
380+
381+ /// Specifies the offset used in accessing the β deblocking filter table for
382+ /// filtering operations controlled by the macroblocks within the slice.
383+ /// From this value, the offset that is applied when addressing the β table
384+ /// of the deblocking filter shall be computed using 7-33.
385+ pub slice_beta_offset_div2: i8,
386+
387+ /// Same as `MaxPicNum` in the specification.
388+ pub max_pic_num: u32,
389+
390+ /// Size of the slice_header() in bits
391+ pub header_bit_size: usize,
392+
393+ /// Number of emulation prevention bytes (EPB) in this slice_header()
394+ pub n_emulation_prevention_bytes: usize,
395+}
396+
397+impl SliceHeader {
398+ /// Returns the field that is coded by this header.
399+ pub fn field(&self) -> Field {
400+ if self.field_pic_flag {
401+ if self.bottom_field_flag {
402+ Field::Bottom
403+ } else {
404+ Field::Top
405+ }
406+ } else {
407+ Field::Frame
408+ }
409+ }
410+}
411+
412+pub struct SliceHeaderBuilder(SliceHeader);
413+
414+impl SliceHeaderBuilder {
415+ pub fn new(pps: &Pps) -> Self {
416+ SliceHeaderBuilder(SliceHeader {
417+ pic_parameter_set_id: pps.pic_parameter_set_id,
418+ ..Default::default()
419+ })
420+ }
421+
422+ pub fn slice_type(mut self, type_: SliceType) -> Self {
423+ self.0.slice_type = type_;
424+ self
425+ }
426+
427+ pub fn first_mb_in_slice(mut self, value: u32) -> Self {
428+ self.0.first_mb_in_slice = value;
429+ self
430+ }
431+
432+ pub fn pic_order_cnt_lsb(mut self, value: u16) -> Self {
433+ self.0.pic_order_cnt_lsb = value;
434+ self
435+ }
436+
437+ pub fn idr_pic_id(mut self, value: u16) -> Self {
438+ self.0.idr_pic_id = value;
439+ self
440+ }
441+
442+ pub fn num_ref_idx_active_override_flag(mut self, value: bool) -> Self {
443+ self.0.num_ref_idx_active_override_flag = value;
444+ self
445+ }
446+
447+ pub fn num_ref_idx_l0_active_minus1(mut self, value: u8) -> Self {
448+ self = self.num_ref_idx_active_override_flag(true);
449+ self.0.num_ref_idx_l0_active_minus1 = value;
450+ self
451+ }
452+
453+ pub fn num_ref_idx_l0_active(self, value: u8) -> Self {
454+ self.num_ref_idx_l0_active_minus1(value - 1)
455+ }
456+
457+ pub fn num_ref_idx_l1_active_minus1(mut self, value: u8) -> Self {
458+ self = self.num_ref_idx_active_override_flag(true);
459+ self.0.num_ref_idx_l1_active_minus1 = value;
460+ self
461+ }
462+
463+ pub fn num_ref_idx_l1_active(self, value: u8) -> Self {
464+ self.num_ref_idx_l1_active_minus1(value - 1)
465+ }
466+
467+ pub fn build(self) -> SliceHeader {
468+ self.0
469+ }
470+}
471+
472+/// A H264 slice. An integer number of macroblocks or macroblock pairs ordered
473+/// consecutively in the raster scan within a particular slice group
474+pub struct Slice<'a> {
475+ /// The slice header.
476+ pub header: SliceHeader,
477+ /// The NAL unit backing this slice.
478+ pub nalu: Nalu<'a>,
479+}
480+
481+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
482+/// See table 7-6 in the specification.
483+pub enum SliceType {
484+ P = 0,
485+ B = 1,
486+ I = 2,
487+ Sp = 3,
488+ Si = 4,
489+}
490+
491+impl TryFrom<u8> for SliceType {
492+ type Error = String;
493+
494+ fn try_from(value: u8) -> Result<Self, Self::Error> {
495+ match value {
496+ 0 => Ok(SliceType::P),
497+ 1 => Ok(SliceType::B),
498+ 2 => Ok(SliceType::I),
499+ 3 => Ok(SliceType::Sp),
500+ 4 => Ok(SliceType::Si),
501+ _ => Err(format!("Invalid SliceType {}", value)),
502+ }
503+ }
504+}
505+
506+impl SliceType {
507+ /// Whether this is a P slice. See table 7-6 in the specification.
508+ pub fn is_p(&self) -> bool {
509+ matches!(self, SliceType::P)
510+ }
511+
512+ /// Whether this is a B slice. See table 7-6 in the specification.
513+ pub fn is_b(&self) -> bool {
514+ matches!(self, SliceType::B)
515+ }
516+
517+ /// Whether this is an I slice. See table 7-6 in the specification.
518+ pub fn is_i(&self) -> bool {
519+ matches!(self, SliceType::I)
520+ }
521+
522+ /// Whether this is a SP slice. See table 7-6 in the specification.
523+ pub fn is_sp(&self) -> bool {
524+ matches!(self, SliceType::Sp)
525+ }
526+
527+ /// Whether this is a SI slice. See table 7-6 in the specification.
528+ pub fn is_si(&self) -> bool {
529+ matches!(self, SliceType::Si)
530+ }
531+}
532+
533+impl Default for SliceType {
534+ fn default() -> Self {
535+ Self::P
536+ }
537+}
538+
539+#[derive(Clone, Copy)]
540+#[repr(u8)]
541+pub enum Profile {
542+ Baseline = 66,
543+ Main = 77,
544+ Extended = 88,
545+ High = 100,
546+ High10 = 110,
547+ High422P = 122,
548+}
549+
550+impl TryFrom<u8> for Profile {
551+ type Error = String;
552+
553+ fn try_from(value: u8) -> Result<Self, Self::Error> {
554+ match value {
555+ 66 => Ok(Profile::Baseline),
556+ 77 => Ok(Profile::Main),
557+ 88 => Ok(Profile::Extended),
558+ 100 => Ok(Profile::High),
559+ 110 => Ok(Profile::High10),
560+ 122 => Ok(Profile::High422P),
561+ _ => Err(format!("Invalid Profile {}", value)),
562+ }
563+ }
564+}
565+
566+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord)]
567+pub enum Level {
568+ #[default]
569+ L1 = 10,
570+ L1B = 9,
571+ L1_1 = 11,
572+ L1_2 = 12,
573+ L1_3 = 13,
574+ L2_0 = 20,
575+ L2_1 = 21,
576+ L2_2 = 22,
577+ L3 = 30,
578+ L3_1 = 31,
579+ L3_2 = 32,
580+ L4 = 40,
581+ L4_1 = 41,
582+ L4_2 = 42,
583+ L5 = 50,
584+ L5_1 = 51,
585+ L5_2 = 52,
586+ L6 = 60,
587+ L6_1 = 61,
588+ L6_2 = 62,
589+}
590+
591+impl TryFrom<u8> for Level {
592+ type Error = String;
593+
594+ fn try_from(value: u8) -> Result<Self, Self::Error> {
595+ match value {
596+ 10 => Ok(Level::L1),
597+ 9 => Ok(Level::L1B),
598+ 11 => Ok(Level::L1_1),
599+ 12 => Ok(Level::L1_2),
600+ 13 => Ok(Level::L1_3),
601+ 20 => Ok(Level::L2_0),
602+ 21 => Ok(Level::L2_1),
603+ 22 => Ok(Level::L2_2),
604+ 30 => Ok(Level::L3),
605+ 31 => Ok(Level::L3_1),
606+ 32 => Ok(Level::L3_2),
607+ 40 => Ok(Level::L4),
608+ 41 => Ok(Level::L4_1),
609+ 42 => Ok(Level::L4_2),
610+ 50 => Ok(Level::L5),
611+ 51 => Ok(Level::L5_1),
612+ 52 => Ok(Level::L5_2),
613+ 60 => Ok(Level::L6),
614+ 61 => Ok(Level::L6_1),
615+ 62 => Ok(Level::L6_2),
616+ _ => Err(format!("Invalid Level {}", value)),
617+ }
618+ }
619+}
620+
621+/// A H264 Sequence Parameter Set. A syntax structure containing syntax elements
622+/// that apply to zero or more entire coded video sequences as determined by the
623+/// content of a seq_parameter_set_id syntax element found in the picture
624+/// parameter set referred to by the pic_parameter_set_id syntax element found
625+/// in each slice header.
626+#[derive(Debug, PartialEq, Eq)]
627+pub struct Sps {
628+ /// Identifies the sequence parameter set that is referred to by the picture
629+ /// parameter set
630+ pub seq_parameter_set_id: u8,
631+
632+ /// Profile to which the coded video sequence conforms
633+ pub profile_idc: u8,
634+
635+ /// Retains the same meaning as in the specification. See 7.4.2.1.1
636+ pub constraint_set0_flag: bool,
637+ /// Retains the same meaning as in the specification. See 7.4.2.1.1
638+ pub constraint_set1_flag: bool,
639+ /// Retains the same meaning as in the specification. See 7.4.2.1.1
640+ pub constraint_set2_flag: bool,
641+ /// Retains the same meaning as in the specification. See 7.4.2.1.1
642+ pub constraint_set3_flag: bool,
643+ /// Retains the same meaning as in the specification. See 7.4.2.1.1
644+ pub constraint_set4_flag: bool,
645+ /// Retains the same meaning as in the specification. See 7.4.2.1.1
646+ pub constraint_set5_flag: bool,
647+
648+ /// Level to which the coded video sequence conforms
649+ pub level_idc: Level,
650+
651+ /// Specifies the chroma sampling relative to the luma sampling as specified
652+ /// in clause 6.2.
653+ pub chroma_format_idc: u8,
654+
655+ /// Specifies whether the three colour components of the 4:4:4 chroma format
656+ /// are coded separately.
657+ pub separate_colour_plane_flag: bool,
658+
659+ /// Specifies the bit depth of the samples of the luma array and the value
660+ /// of the luma quantization parameter range offset QpBdOffsetY. See 7-3 and
661+ /// 7-4.
662+ pub bit_depth_luma_minus8: u8,
663+
664+ /// Specifies the bit depth of the samples of the chroma arrays and the
665+ /// value of the chroma quantization parameter range offset QpBdOffsetC. See
666+ /// 7-5 and 7-6.
667+ pub bit_depth_chroma_minus8: u8,
668+
669+ /// qpprime_y_zero_transform_bypass_flag equal to 1 specifies that, when
670+ /// QP′Y is equal to 0, a transform bypass operation for the transform
671+ /// coefficient decoding process and picture construction process prior to
672+ /// deblocking filter process as specified in clause 8.5 shall be applied.
673+ /// qpprime_y_zero_transform_bypass_flag equal to 0 specifies that the
674+ /// transform coefficient decoding process and picture construction process
675+ /// prior to deblocking filter process shall not use the transform bypass
676+ /// operation
677+ /// QP′Y is defined in 7-38 as QP′Y = QPY + QpBdOffsetY
678+ pub qpprime_y_zero_transform_bypass_flag: bool,
679+
680+ /// Whether `seq_scaling_list_present_flag[i]` for i = 0..7 or i = 0..11 is
681+ /// present or whether the sequence level scaling list shall be specified by
682+ /// Flat_4x4_16 for i = 0..5 and flat_8x8_16 for i = 6..11
683+ pub seq_scaling_matrix_present_flag: bool,
684+
685+ /// 4x4 Scaling list as read with 7.3.2.1.1.1
686+ pub scaling_lists_4x4: [[u8; 16]; 6],
687+ /// 8x8 Scaling list as read with 7.3.2.1.1.1
688+ pub scaling_lists_8x8: [[u8; 64]; 6],
689+
690+ /// Specifies the value of the variable MaxFrameNum that is used in
691+ /// frame_num related derivations as follows: MaxFrameNum = 2 ^
692+ /// (log2_max_frame_num_minus4 + 4 )
693+ pub log2_max_frame_num_minus4: u8,
694+
695+ /// Specifies the method to decode picture order count (as specified in
696+ /// clause 8.2.1)
697+ pub pic_order_cnt_type: u8,
698+
699+ /// Specifies the value of the variable MaxPicOrderCntLsb that is used in
700+ /// the decoding process for picture order count as specified in clause
701+ /// 8.2.1 as follows: MaxPicOrderCntLsb = 2 ^ (
702+ /// log2_max_pic_order_cnt_lsb_minus4 + 4 ).
703+ pub log2_max_pic_order_cnt_lsb_minus4: u8,
704+
705+ /// If true, specifies that `delta_pic_order_cnt[0]` and
706+ /// `delta_pic_order_cnt[1]` are not present in the slice headers of the
707+ /// sequence and shall be inferred to be equal to 0.
708+ /// If false, specifies that `delta_pic_order_cnt[0]` is present in the
709+ /// slice headers of the sequence and `delta_pic_order_cnt[1]` may be
710+ /// present in the slice headers of the sequence.
711+ pub delta_pic_order_always_zero_flag: bool,
712+
713+ /// Used to calculate the picture order count of a non-reference picture as
714+ /// specified in clause 8.2.1.
715+ pub offset_for_non_ref_pic: i32,
716+
717+ /// Used to calculate the picture order count of a bottom field as specified
718+ /// in clause 8.2.1.
719+ pub offset_for_top_to_bottom_field: i32,
720+
721+ /// Used in the decoding process for picture order count as specified in
722+ /// clause 8.2.1
723+ pub num_ref_frames_in_pic_order_cnt_cycle: u8,
724+
725+ /// An element of a list of num_ref_frames_in_pic_order_cnt_cycle values
726+ /// used in the decoding process for picture order count as specified in
727+ /// clause 8.2.
728+ pub offset_for_ref_frame: [i32; 255],
729+
730+ /// Specifies the maximum number of short-term and long-term reference
731+ /// frames, complementary reference field pairs, and non-paired reference
732+ /// fields that may be used by the decoding process for inter prediction of
733+ /// any picture in the coded video sequence. Also
734+ /// determines the size of the sliding window operation as specified in
735+ /// clause 8.2.5.3.
736+ pub max_num_ref_frames: u8,
737+
738+ /// Specifies the allowed values of frame_num as specified in clause 7.4.3
739+ /// and the decoding process in case of an inferred gap between values of
740+ /// frame_num as specified in clause 8.2.5.2
741+ pub gaps_in_frame_num_value_allowed_flag: bool,
742+
743+ /// Plus 1 specifies the width of each decoded picture in units of
744+ /// macroblocks.
745+ pub pic_width_in_mbs_minus1: u16,
746+ /// Plus 1 specifies the height in slice group map units of a decoded frame
747+ /// or field.
748+ pub pic_height_in_map_units_minus1: u16,
749+
750+ /// If true, specifies that every coded picture of the coded video sequence
751+ /// is a coded frame containing only frame macroblocks, else specifies that
752+ /// coded pictures of the coded video sequence may either be coded fields or
753+ /// coded frames.
754+ pub frame_mbs_only_flag: bool,
755+
756+ /// If true, specifies the possible use of switching between frame and field
757+ /// macroblocks within frames, else, specifies no switching between frame
758+ /// and field macroblocks within a picture.
759+ pub mb_adaptive_frame_field_flag: bool,
760+
761+ /// Specifies the method used in the derivation process for luma motion
762+ /// vectors for B_Skip, B_Direct_16x16 and B_Direct_8x8 as specified in
763+ /// clause 8.4.1.2.
764+ pub direct_8x8_inference_flag: bool,
765+
766+ /// If true, specifies that the frame cropping offset parameters follow next
767+ /// in the sequence parameter, else specifies that the frame cropping offset
768+ /// parameters are not present
769+ pub frame_cropping_flag: bool,
770+
771+ /// Specify the samples of the pictures in the coded video sequence that are
772+ /// output from the decoding process, in terms of a rectangular region
773+ /// specified in frame coordinates for output.
774+ pub frame_crop_left_offset: u32,
775+ /// Specify the samples of the pictures in the coded video sequence that are
776+ /// output from the decoding process, in terms of a rectangular region
777+ /// specified in frame coordinates for output.
778+ pub frame_crop_right_offset: u32,
779+ /// Specify the samples of the pictures in the coded video sequence that are
780+ /// output from the decoding process, in terms of a rectangular region
781+ /// specified in frame coordinates for output.
782+ pub frame_crop_top_offset: u32,
783+ /// Specify the samples of the pictures in the coded video sequence that are
784+ /// output from the decoding process, in terms of a rectangular region
785+ /// specified in frame coordinates for output.
786+ pub frame_crop_bottom_offset: u32,
787+
788+ // Calculated
789+ /// Same as ExpectedDeltaPerPicOrderCntCycle, see 7-12 in the specification.
790+ pub expected_delta_per_pic_order_cnt_cycle: i32,
791+
792+ pub vui_parameters_present_flag: bool,
793+ pub vui_parameters: VuiParams,
794+}
795+
796+impl Sps {
797+ /// Returns the coded width of the stream.
798+ ///
799+ /// See 7-13 through 7-17 in the specification.
800+ pub const fn width(&self) -> u32 {
801+ (self.pic_width_in_mbs_minus1 as u32 + 1) * 16
802+ }
803+
804+ /// Returns the coded height of the stream.
805+ ///
806+ /// See 7-13 through 7-17 in the specification.
807+ pub const fn height(&self) -> u32 {
808+ (self.pic_height_in_map_units_minus1 as u32 + 1)
809+ * 16
810+ * (2 - self.frame_mbs_only_flag as u32)
811+ }
812+
813+ /// Returns `ChromaArrayType`, as computed in the specification.
814+ pub const fn chroma_array_type(&self) -> u8 {
815+ match self.separate_colour_plane_flag {
816+ false => self.chroma_format_idc,
817+ true => 0,
818+ }
819+ }
820+
821+ /// Returns `SubWidthC` and `SubHeightC`.
822+ ///
823+ /// See table 6-1 in the specification.
824+ fn sub_width_height_c(&self) -> (u32, u32) {
825+ match (self.chroma_format_idc, self.separate_colour_plane_flag) {
826+ (1, false) => (2, 2),
827+ (2, false) => (2, 1),
828+ (3, false) => (1, 1),
829+ // undefined.
830+ _ => (1, 1),
831+ }
832+ }
833+
834+ /// Returns `CropUnitX` and `CropUnitY`.
835+ ///
836+ /// See 7-19 through 7-22 in the specification.
837+ fn crop_unit_x_y(&self) -> (u32, u32) {
838+ match self.chroma_array_type() {
839+ 0 => (1, 2 - u32::from(self.frame_mbs_only_flag)),
840+ _ => {
841+ let (sub_width_c, sub_height_c) = self.sub_width_height_c();
842+ (sub_width_c, sub_height_c * (2 - u32::from(self.frame_mbs_only_flag)))
843+ }
844+ }
845+ }
846+
847+ /// Same as MaxFrameNum. See 7-10 in the specification.
848+ pub fn max_frame_num(&self) -> u32 {
849+ 1 << (self.log2_max_frame_num_minus4 + 4)
850+ }
851+
852+ pub fn visible_rectangle(&self) -> Rect<u32> {
853+ if !self.frame_cropping_flag {
854+ return Rect {
855+ min: Point { x: 0, y: 0 },
856+ max: Point { x: self.width(), y: self.height() },
857+ };
858+ }
859+
860+ let (crop_unit_x, crop_unit_y) = self.crop_unit_x_y();
861+
862+ let crop_left = crop_unit_x * self.frame_crop_left_offset;
863+ let crop_right = crop_unit_x * self.frame_crop_right_offset;
864+ let crop_top = crop_unit_y * self.frame_crop_top_offset;
865+ let crop_bottom = crop_unit_y * self.frame_crop_bottom_offset;
866+
867+ Rect {
868+ min: Point { x: crop_left, y: crop_top },
869+ max: Point {
870+ x: self.width() - crop_left - crop_right,
871+ y: self.height() - crop_top - crop_bottom,
872+ },
873+ }
874+ }
875+
876+ pub fn max_dpb_frames(&self) -> usize {
877+ let profile = self.profile_idc;
878+ let mut level = self.level_idc;
879+
880+ // A.3.1 and A.3.2: Level 1b for Baseline, Constrained Baseline and Main
881+ // profile if level_idc == 11 and constraint_set3_flag == 1
882+ if matches!(level, Level::L1_1)
883+ && (profile == Profile::Baseline as u8 || profile == Profile::Main as u8)
884+ && self.constraint_set3_flag
885+ {
886+ level = Level::L1B;
887+ };
888+
889+ // Table A.1
890+ let max_dpb_mbs = match level {
891+ Level::L1 => 396,
892+ Level::L1B => 396,
893+ Level::L1_1 => 900,
894+ Level::L1_2 => 2376,
895+ Level::L1_3 => 2376,
896+ Level::L2_0 => 2376,
897+ Level::L2_1 => 4752,
898+ Level::L2_2 => 8100,
899+ Level::L3 => 8100,
900+ Level::L3_1 => 18000,
901+ Level::L3_2 => 20480,
902+ Level::L4 => 32768,
903+ Level::L4_1 => 32768,
904+ Level::L4_2 => 34816,
905+ Level::L5 => 110400,
906+ Level::L5_1 => 184320,
907+ Level::L5_2 => 184320,
908+ Level::L6 => 696320,
909+ Level::L6_1 => 696320,
910+ Level::L6_2 => 696320,
911+ };
912+
913+ let width_mb = self.width() / 16;
914+ let height_mb = self.height() / 16;
915+
916+ let max_dpb_frames =
917+ std::cmp::min(max_dpb_mbs / (width_mb * height_mb), DPB_MAX_SIZE as u32) as usize;
918+
919+ let mut max_dpb_frames = std::cmp::max(max_dpb_frames, self.max_num_ref_frames as usize);
920+
921+ if self.vui_parameters_present_flag && self.vui_parameters.bitstream_restriction_flag {
922+ max_dpb_frames = std::cmp::max(1, self.vui_parameters.max_dec_frame_buffering as usize);
923+ }
924+
925+ max_dpb_frames
926+ }
927+
928+ pub fn max_num_order_frames(&self) -> u32 {
929+ let vui = &self.vui_parameters;
930+ let present = self.vui_parameters_present_flag && vui.bitstream_restriction_flag;
931+
932+ if present {
933+ vui.max_num_reorder_frames
934+ } else {
935+ let profile = self.profile_idc;
936+ if (profile == 44
937+ || profile == 86
938+ || profile == 100
939+ || profile == 110
940+ || profile == 122
941+ || profile == 244)
942+ && self.constraint_set3_flag
943+ {
944+ 0
945+ } else {
946+ self.max_dpb_frames() as u32
947+ }
948+ }
949+ }
950+}
951+
952+// TODO: Replace with builder
953+impl Default for Sps {
954+ fn default() -> Self {
955+ Self {
956+ scaling_lists_4x4: [[0; 16]; 6],
957+ scaling_lists_8x8: [[0; 64]; 6],
958+ offset_for_ref_frame: [0; 255],
959+ seq_parameter_set_id: Default::default(),
960+ profile_idc: Default::default(),
961+ constraint_set0_flag: Default::default(),
962+ constraint_set1_flag: Default::default(),
963+ constraint_set2_flag: Default::default(),
964+ constraint_set3_flag: Default::default(),
965+ constraint_set4_flag: Default::default(),
966+ constraint_set5_flag: Default::default(),
967+ level_idc: Default::default(),
968+ chroma_format_idc: Default::default(),
969+ separate_colour_plane_flag: Default::default(),
970+ bit_depth_luma_minus8: Default::default(),
971+ bit_depth_chroma_minus8: Default::default(),
972+ qpprime_y_zero_transform_bypass_flag: Default::default(),
973+ seq_scaling_matrix_present_flag: Default::default(),
974+ log2_max_frame_num_minus4: Default::default(),
975+ pic_order_cnt_type: Default::default(),
976+ log2_max_pic_order_cnt_lsb_minus4: Default::default(),
977+ delta_pic_order_always_zero_flag: Default::default(),
978+ offset_for_non_ref_pic: Default::default(),
979+ offset_for_top_to_bottom_field: Default::default(),
980+ num_ref_frames_in_pic_order_cnt_cycle: Default::default(),
981+ max_num_ref_frames: Default::default(),
982+ gaps_in_frame_num_value_allowed_flag: Default::default(),
983+ pic_width_in_mbs_minus1: Default::default(),
984+ pic_height_in_map_units_minus1: Default::default(),
985+ frame_mbs_only_flag: Default::default(),
986+ mb_adaptive_frame_field_flag: Default::default(),
987+ direct_8x8_inference_flag: Default::default(),
988+ frame_cropping_flag: Default::default(),
989+ frame_crop_left_offset: Default::default(),
990+ frame_crop_right_offset: Default::default(),
991+ frame_crop_top_offset: Default::default(),
992+ frame_crop_bottom_offset: Default::default(),
993+ expected_delta_per_pic_order_cnt_cycle: Default::default(),
994+ vui_parameters_present_flag: Default::default(),
995+ vui_parameters: Default::default(),
996+ }
997+ }
998+}
999+
1000+#[derive(Default)]
1001+pub struct SpsBuilder(Sps);
1002+
1003+impl SpsBuilder {
1004+ pub fn new() -> Self {
1005+ Default::default()
1006+ }
1007+
1008+ pub fn seq_parameter_set_id(mut self, value: u8) -> Self {
1009+ self.0.seq_parameter_set_id = value;
1010+ self
1011+ }
1012+
1013+ pub fn profile_idc(mut self, value: Profile) -> Self {
1014+ self.0.profile_idc = value as u8;
1015+ self
1016+ }
1017+
1018+ pub fn level_idc(mut self, value: Level) -> Self {
1019+ self.0.level_idc = value;
1020+ self
1021+ }
1022+
1023+ pub fn frame_crop_offsets(mut self, top: u32, bottom: u32, left: u32, right: u32) -> Self {
1024+ self.0.frame_cropping_flag = true;
1025+ self.0.frame_crop_top_offset = top;
1026+ self.0.frame_crop_bottom_offset = bottom;
1027+ self.0.frame_crop_left_offset = left;
1028+ self.0.frame_crop_right_offset = right;
1029+ self
1030+ }
1031+
1032+ pub fn frame_crop(self, top: u32, bottom: u32, left: u32, right: u32) -> Self {
1033+ let sub_width_c = if self.0.chroma_format_idc > 2 { 1 } else { 2 };
1034+ let sub_height_c = if self.0.chroma_format_idc > 1 { 1 } else { 2 };
1035+
1036+ let crop_unit_x = sub_width_c;
1037+ let crop_unit_y = sub_height_c * (if self.0.frame_mbs_only_flag { 1 } else { 2 });
1038+
1039+ self.frame_crop_offsets(
1040+ top / crop_unit_y,
1041+ bottom / crop_unit_y,
1042+ left / crop_unit_x,
1043+ right / crop_unit_x,
1044+ )
1045+ }
1046+
1047+ pub fn resolution(mut self, width: u32, height: u32) -> Self {
1048+ const MB_SIZE: u32 = 16;
1049+
1050+ let mb_width = (width + MB_SIZE - 1) / MB_SIZE;
1051+ let mb_height = (height + MB_SIZE - 1) / MB_SIZE;
1052+
1053+ self.0.pic_width_in_mbs_minus1 = (mb_width - 1) as u16;
1054+ self.0.pic_height_in_map_units_minus1 = (mb_height - 1) as u16;
1055+
1056+ let compressed_width = mb_width * MB_SIZE;
1057+ let compressed_height = mb_height * MB_SIZE;
1058+
1059+ if compressed_width != width || compressed_height != height {
1060+ self = self.frame_crop(0, compressed_height - height, 0, compressed_width - width);
1061+ }
1062+
1063+ self
1064+ }
1065+
1066+ pub fn chroma_format_idc(mut self, value: u8) -> Self {
1067+ self.0.chroma_format_idc = value;
1068+ self
1069+ }
1070+
1071+ pub fn max_num_ref_frames(mut self, value: u8) -> Self {
1072+ self.0.max_num_ref_frames = value;
1073+ self
1074+ }
1075+
1076+ pub fn frame_mbs_only_flag(mut self, value: bool) -> Self {
1077+ self.0.frame_mbs_only_flag = value;
1078+ self
1079+ }
1080+
1081+ pub fn mb_adaptive_frame_field_flag(mut self, value: bool) -> Self {
1082+ self.0.mb_adaptive_frame_field_flag = value;
1083+ self
1084+ }
1085+
1086+ pub fn seq_scaling_matrix_present_flag(mut self, value: bool) -> Self {
1087+ self.0.seq_scaling_matrix_present_flag = value;
1088+ self
1089+ }
1090+
1091+ pub fn direct_8x8_inference_flag(mut self, value: bool) -> Self {
1092+ self.0.direct_8x8_inference_flag = value;
1093+ self
1094+ }
1095+
1096+ pub fn vui_parameters_present(mut self) -> Self {
1097+ if self.0.vui_parameters_present_flag {
1098+ return self;
1099+ }
1100+
1101+ self.0.vui_parameters_present_flag = true;
1102+ // Disable all options at default
1103+ self.0.vui_parameters.aspect_ratio_info_present_flag = false;
1104+ self.0.vui_parameters.overscan_info_present_flag = false;
1105+ self.0.vui_parameters.video_signal_type_present_flag = false;
1106+ self.0.vui_parameters.colour_description_present_flag = false;
1107+ self.0.vui_parameters.chroma_loc_info_present_flag = false;
1108+ self.0.vui_parameters.timing_info_present_flag = false;
1109+ self.0.vui_parameters.nal_hrd_parameters_present_flag = false;
1110+ self.0.vui_parameters.vcl_hrd_parameters_present_flag = false;
1111+ self.0.vui_parameters.pic_struct_present_flag = false;
1112+ self.0.vui_parameters.bitstream_restriction_flag = false;
1113+ self
1114+ }
1115+
1116+ pub fn aspect_ratio_idc(mut self, value: u8) -> Self {
1117+ self = self.vui_parameters_present();
1118+ self.0.vui_parameters.aspect_ratio_info_present_flag = true;
1119+ self.0.vui_parameters.aspect_ratio_idc = value;
1120+ self
1121+ }
1122+
1123+ pub fn sar_resolution(mut self, width: u16, height: u16) -> Self {
1124+ self = self.aspect_ratio_idc(255);
1125+ self.0.vui_parameters.sar_width = width;
1126+ self.0.vui_parameters.sar_height = height;
1127+ self
1128+ }
1129+
1130+ pub fn aspect_ratio(self, width_ratio: u16, height_ratio: u16) -> Self {
1131+ // H.264 Table E-1
1132+ match (width_ratio, height_ratio) {
1133+ (1, 1) => self.aspect_ratio_idc(1),
1134+ (12, 11) => self.aspect_ratio_idc(2),
1135+ (10, 11) => self.aspect_ratio_idc(3),
1136+ (16, 11) => self.aspect_ratio_idc(4),
1137+ (40, 33) => self.aspect_ratio_idc(5),
1138+ (24, 11) => self.aspect_ratio_idc(6),
1139+ (20, 11) => self.aspect_ratio_idc(7),
1140+ (32, 11) => self.aspect_ratio_idc(8),
1141+ (80, 33) => self.aspect_ratio_idc(9),
1142+ (18, 11) => self.aspect_ratio_idc(10),
1143+ (15, 11) => self.aspect_ratio_idc(11),
1144+ (64, 33) => self.aspect_ratio_idc(12),
1145+ (160, 99) => self.aspect_ratio_idc(13),
1146+ (4, 3) => self.aspect_ratio_idc(14),
1147+ (3, 2) => self.aspect_ratio_idc(15),
1148+ (2, 1) => self.aspect_ratio_idc(16),
1149+
1150+ _ => self.sar_resolution(width_ratio, height_ratio),
1151+ }
1152+ }
1153+
1154+ pub fn timing_info(
1155+ mut self,
1156+ num_units_in_tick: u32,
1157+ time_scale: u32,
1158+ fixed_frame_rate_flag: bool,
1159+ ) -> Self {
1160+ self = self.vui_parameters_present();
1161+ self.0.vui_parameters.timing_info_present_flag = true;
1162+ self.0.vui_parameters.num_units_in_tick = num_units_in_tick;
1163+ self.0.vui_parameters.time_scale = time_scale;
1164+ self.0.vui_parameters.fixed_frame_rate_flag = fixed_frame_rate_flag;
1165+ self
1166+ }
1167+
1168+ pub fn log2_max_frame_num_minus4(mut self, value: u8) -> Self {
1169+ self.0.log2_max_frame_num_minus4 = value;
1170+ self
1171+ }
1172+
1173+ pub fn max_frame_num(self, value: u32) -> Self {
1174+ self.log2_max_frame_num_minus4(value.ilog2() as u8 - 4u8)
1175+ }
1176+
1177+ pub fn pic_order_cnt_type(mut self, value: u8) -> Self {
1178+ self.0.pic_order_cnt_type = value;
1179+ self
1180+ }
1181+
1182+ pub fn log2_max_pic_order_cnt_lsb_minus4(mut self, value: u8) -> Self {
1183+ self.0.log2_max_pic_order_cnt_lsb_minus4 = value;
1184+ self
1185+ }
1186+
1187+ pub fn max_pic_order_cnt_lsb(self, value: u32) -> Self {
1188+ self.log2_max_pic_order_cnt_lsb_minus4(value.ilog2() as u8 - 4u8)
1189+ }
1190+
1191+ pub fn delta_pic_order_always_zero_flag(mut self, value: bool) -> Self {
1192+ self.0.delta_pic_order_always_zero_flag = value;
1193+ self
1194+ }
1195+
1196+ pub fn bit_depth_chroma_minus8(mut self, value: u8) -> Self {
1197+ self.0.bit_depth_chroma_minus8 = value;
1198+ self
1199+ }
1200+
1201+ pub fn bit_depth_chroma(self, value: u8) -> Self {
1202+ self.bit_depth_luma_minus8(value - 8u8)
1203+ }
1204+
1205+ pub fn bit_depth_luma_minus8(mut self, value: u8) -> Self {
1206+ self.0.bit_depth_luma_minus8 = value;
1207+ self
1208+ }
1209+
1210+ pub fn bit_depth_luma(self, value: u8) -> Self {
1211+ self.bit_depth_luma_minus8(value - 8u8)
1212+ }
1213+
1214+ pub fn build(self) -> Rc<Sps> {
1215+ Rc::new(self.0)
1216+ }
1217+}
1218+
1219+#[derive(Clone, Debug, Default, PartialEq, Eq)]
1220+pub struct HrdParams {
1221+ /// Plus 1 specifies the number of alternative CPB specifications in the
1222+ /// bitstream. The value of `cpb_cnt_minus1` shall be in the range of 0 to 31,
1223+ /// inclusive
1224+ pub cpb_cnt_minus1: u8,
1225+ /// Together with `bit_rate_value_minus1[ SchedSelIdx ]` specifies the
1226+ /// maximum input bit rate of the `SchedSelIdx`-th CPB.
1227+ pub bit_rate_scale: u8,
1228+ /// Together with `cpb_size_value_minus1[ SchedSelIdx ]` specifies the CPB
1229+ /// size of the SchedSelIdx-th CPB.
1230+ pub cpb_size_scale: u8,
1231+
1232+ /// `[ SchedSelIdx ]` (together with bit_rate_scale) specifies the maximum
1233+ /// input bit rate for the SchedSelIdx-th CPB.
1234+ pub bit_rate_value_minus1: [u32; 32],
1235+ /// `[ SchedSelIdx ]` is used together with cpb_size_scale to specify the
1236+ /// SchedSelIdx-th CPB size.
1237+ pub cpb_size_value_minus1: [u32; 32],
1238+ /// `[ SchedSelIdx ]` equal to 0 specifies that to decode this bitstream by
1239+ /// the HRD using the `SchedSelIdx`-th CPB specification, the hypothetical
1240+ /// stream delivery scheduler (HSS) operates in an intermittent bit rate
1241+ /// mode. `cbr_flag[ SchedSelIdx ]` equal to 1 specifies that the HSS operates
1242+ /// in a constant bit rate (CBR) mode
1243+ pub cbr_flag: [bool; 32],
1244+
1245+ /// Specifies the length in bits of the `initial_cpb_removal_delay[
1246+ /// SchedSelIdx ]` and `initial_cpb_removal_delay_offset[ SchedSelIdx ]` syntax
1247+ /// elements of the buffering period SEI message.
1248+ pub initial_cpb_removal_delay_length_minus1: u8,
1249+ /// Specifies the length in bits of the `cpb_removal_delay` syntax element.
1250+ pub cpb_removal_delay_length_minus1: u8,
1251+ /// Specifies the length in bits of the `dpb_output_delay` syntax element.
1252+ pub dpb_output_delay_length_minus1: u8,
1253+ /// If greater than 0, specifies the length in bits of the `time_offset`
1254+ /// syntax element. `time_offset_length` equal to 0 specifies that the
1255+ /// `time_offset` syntax element is not present
1256+ pub time_offset_length: u8,
1257+}
1258+
1259+#[derive(Clone, Debug, PartialEq, Eq)]
1260+pub struct VuiParams {
1261+ /// Specifies whether `aspect_ratio_idc` is present.
1262+ pub aspect_ratio_info_present_flag: bool,
1263+ /// Specifies the value of the sample aspect ratio of the luma samples.
1264+ /// Table E-1 shows the meaning of the code. When aspect_ratio_idc indicates
1265+ /// Extended_SAR, the sample aspect ratio is represented by sar_width :
1266+ /// sar_height. When the aspect_ratio_idc syntax element is not present,
1267+ /// aspect_ratio_idc value shall be inferred to be equal to 0
1268+ pub aspect_ratio_idc: u8,
1269+
1270+ /* if aspect_ratio_idc == 255 */
1271+ /// Indicates the horizontal size of the sample aspect ratio (in arbitrary
1272+ /// units)
1273+ pub sar_width: u16,
1274+ /// Indicates the vertical size of the sample aspect ratio (in the same
1275+ /// arbitrary units as sar_width).
1276+ pub sar_height: u16,
1277+
1278+ /// If true specifies that the overscan_appropriate_flag is present. Else,
1279+ /// the preferred display method for the video signal is unspecified
1280+ pub overscan_info_present_flag: bool,
1281+ /* if overscan_info_present_flag */
1282+ /// If true, indicates that the cropped decoded pictures output are suitable
1283+ /// for display using overscan. Else, indicates that the cropped decoded
1284+ /// pictures output contain visually important information in the entire
1285+ /// region out to the edges of the cropping rectangle of the picture, such
1286+ /// that the cropped decoded pictures output should not be displayed using
1287+ /// overscan.
1288+ pub overscan_appropriate_flag: bool,
1289+
1290+ /// Specifies that video_format, video_full_range_flag and
1291+ /// colour_description_present_flag are present
1292+ pub video_signal_type_present_flag: bool,
1293+ /// Indicates the representation of the pictures as specified in Table E-2,
1294+ /// before being coded in accordance with this Recommendation |
1295+ /// International Standard. When the video_format syntax element is not
1296+ /// present, video_format value shall be inferred to be equal to 5.
1297+ pub video_format: u8,
1298+ /// Indicates the black level and range of the luma and chroma signals as
1299+ /// derived from E′Y, E′PB, and E′PR or E′ R, E′G, and E′B real-valued
1300+ /// component signals.
1301+ pub video_full_range_flag: bool,
1302+ /// Specifies that colour_primaries, transfer_characteristics and
1303+ /// matrix_coefficients are present.
1304+ pub colour_description_present_flag: bool,
1305+ /// Indicates the chromaticity coordinates of the source primaries as
1306+ /// specified in Table E-3 in terms of the CIE 1931 definition of x and y as
1307+ /// specified by ISO 11664-1.
1308+ pub colour_primaries: u8,
1309+ /// Retains same meaning as in the specification.
1310+ pub transfer_characteristics: u8,
1311+ /// Describes the matrix coefficients used in deriving luma and chroma
1312+ /// signals from the green, blue, and red, or Y, Z, and X primaries, as
1313+ /// specified in Table E-5.
1314+ pub matrix_coefficients: u8,
1315+
1316+ /// Specifies that chroma_sample_loc_type_top_field and
1317+ /// chroma_sample_loc_type_bottom_field are present
1318+ pub chroma_loc_info_present_flag: bool,
1319+ /// Specify the location of chroma samples. See the spec for more details.
1320+ pub chroma_sample_loc_type_top_field: u8,
1321+ /// Specify the location of chroma samples. See the spec for more details.
1322+ pub chroma_sample_loc_type_bottom_field: u8,
1323+
1324+ /// Specifies that num_units_in_tick, time_scale and fixed_frame_rate_flag
1325+ /// are present in the bitstream
1326+ pub timing_info_present_flag: bool,
1327+ /* if timing_info_present_flag */
1328+ /// The number of time units of a clock operating at the frequency
1329+ /// time_scale Hz that corresponds to one increment (called a clock tick) of
1330+ /// a clock tick counter
1331+ pub num_units_in_tick: u32,
1332+ /// The number of time units that pass in one second. For example, a time
1333+ /// coordinate system that measures time using a 27 MHz clock has a
1334+ /// time_scale of 27 000 000. time_scale shall be greater than 0.
1335+ pub time_scale: u32,
1336+ /// Retains the same meaning as the specification.
1337+ pub fixed_frame_rate_flag: bool,
1338+
1339+ /// Specifies that NAL HRD parameters (pertaining to Type II bitstream
1340+ /// conformance) are present.
1341+ pub nal_hrd_parameters_present_flag: bool,
1342+ /* if nal_hrd_parameters_present_flag */
1343+ /// The NAL HDR parameters
1344+ pub nal_hrd_parameters: HrdParams,
1345+ /// Specifies that VCL HRD parameters (pertaining to all bitstream
1346+ /// conformance) are present.
1347+ pub vcl_hrd_parameters_present_flag: bool,
1348+ /* if vcl_hrd_parameters_present_flag */
1349+ /// The VCL HRD parameters
1350+ pub vcl_hrd_parameters: HrdParams,
1351+
1352+ /// Specifies the HRD operational mode as specified in Annex C.
1353+ pub low_delay_hrd_flag: bool,
1354+
1355+ /// Specifies that picture timing SEI messages (clause D.2.3) are present
1356+ /// that include the pic_struct syntax element.
1357+ pub pic_struct_present_flag: bool,
1358+
1359+ /// Specifies that the following coded video sequence bitstream restriction
1360+ /// parameters are present
1361+ pub bitstream_restriction_flag: bool,
1362+ /* if bitstream_restriction_flag */
1363+ /// If false, indicates that no sample outside the picture boundaries and no
1364+ /// sample at a fractional sample position for which the sample value is
1365+ /// derived using one or more samples outside the picture boundaries is used
1366+ /// for inter prediction of any sample. If true, indicates that one or more
1367+ /// samples outside picture boundaries may be used in inter prediction. When
1368+ /// the motion_vectors_over_pic_boundaries_flag syntax element is not
1369+ /// present, motion_vectors_over_pic_boundaries_flag value shall be inferred
1370+ /// to be true.
1371+ pub motion_vectors_over_pic_boundaries_flag: bool,
1372+ /// Indicates a number of bytes not exceeded by the sum of the sizes of the
1373+ /// VCL NAL units associated with any coded picture in the coded video
1374+ /// sequence.
1375+ pub max_bytes_per_pic_denom: u32,
1376+ /// Indicates an upper bound for the number of coded bits of
1377+ /// macroblock_layer( ) data for any macroblock in any picture of the coded
1378+ /// video sequence
1379+ pub max_bits_per_mb_denom: u32,
1380+ /// Retains the same meaning as the specification.
1381+ pub log2_max_mv_length_horizontal: u32,
1382+ /// Retains the same meaning as the specification.
1383+ pub log2_max_mv_length_vertical: u32,
1384+ /// Indicates an upper bound for the number of frames buffers, in the
1385+ /// decoded picture buffer (DPB), that are required for storing frames,
1386+ /// complementary field pairs, and non-paired fields before output. It is a
1387+ /// requirement of bitstream conformance that the maximum number of frames,
1388+ /// complementary field pairs, or non-paired fields that precede any frame,
1389+ /// complementary field pair, or non-paired field in the coded video
1390+ /// sequence in decoding order and follow it in output order shall be less
1391+ /// than or equal to max_num_reorder_frames. The value of
1392+ /// max_num_reorder_frames shall be in the range of 0 to
1393+ /// max_dec_frame_buffering, inclusive.
1394+ ///
1395+ /// When the max_num_reorder_frames syntax element is not present, the value
1396+ /// of max_num_reorder_frames value shall be inferred as follows:
1397+ /// If profile_idc is equal to 44, 86, 100, 110, 122, or 244 and
1398+ /// constraint_set3_flag is equal to 1, the value of max_num_reorder_frames
1399+ /// shall be inferred to be equal to 0.
1400+ ///
1401+ /// Otherwise (profile_idc is not equal to 44, 86, 100, 110, 122, or 244 or
1402+ /// constraint_set3_flag is equal to 0), the value of max_num_reorder_frames
1403+ /// shall be inferred to be equal to MaxDpbFrames.
1404+ pub max_num_reorder_frames: u32,
1405+ /// Specifies the required size of the HRD decoded picture buffer (DPB) in
1406+ /// units of frame buffers. It is a requirement of bitstream conformance
1407+ /// that the coded video sequence shall not require a decoded picture buffer
1408+ /// with size of more than Max( 1, max_dec_frame_buffering ) frame buffers
1409+ /// to enable the output of decoded pictures at the output times specified
1410+ /// by dpb_output_delay of the picture timing SEI messages. The value of
1411+ /// max_dec_frame_buffering shall be greater than or equal to
1412+ /// max_num_ref_frames. An upper bound for the value of
1413+ /// max_dec_frame_buffering is specified by the level limits in clauses
1414+ /// A.3.1, A.3.2, G.10.2.1, and H.10.2.
1415+ ///
1416+ /// When the max_dec_frame_buffering syntax element is not present, the
1417+ /// value of max_dec_frame_buffering shall be inferred as follows:
1418+ ///
1419+ /// If profile_idc is equal to 44, 86, 100, 110, 122, or 244 and
1420+ /// constraint_set3_flag is equal to 1, the value of max_dec_frame_buffering
1421+ /// shall be inferred to be equal to 0.
1422+ ///
1423+ /// Otherwise (profile_idc is not equal to 44, 86, 100, 110, 122, or 244 or
1424+ /// constraint_set3_flag is equal to 0), the value of
1425+ /// max_dec_frame_buffering shall be inferred to be equal to MaxDpbFrames.
1426+ pub max_dec_frame_buffering: u32,
1427+}
1428+
1429+impl Default for VuiParams {
1430+ fn default() -> Self {
1431+ Self {
1432+ aspect_ratio_info_present_flag: Default::default(),
1433+ aspect_ratio_idc: Default::default(),
1434+ sar_width: Default::default(),
1435+ sar_height: Default::default(),
1436+ overscan_info_present_flag: Default::default(),
1437+ overscan_appropriate_flag: Default::default(),
1438+ video_signal_type_present_flag: Default::default(),
1439+ video_format: 5,
1440+ video_full_range_flag: Default::default(),
1441+ colour_description_present_flag: Default::default(),
1442+ colour_primaries: 2,
1443+ transfer_characteristics: 2,
1444+ matrix_coefficients: 2,
1445+ chroma_loc_info_present_flag: Default::default(),
1446+ chroma_sample_loc_type_top_field: Default::default(),
1447+ chroma_sample_loc_type_bottom_field: Default::default(),
1448+ timing_info_present_flag: Default::default(),
1449+ num_units_in_tick: Default::default(),
1450+ time_scale: Default::default(),
1451+ fixed_frame_rate_flag: Default::default(),
1452+ nal_hrd_parameters_present_flag: Default::default(),
1453+ nal_hrd_parameters: Default::default(),
1454+ vcl_hrd_parameters_present_flag: Default::default(),
1455+ vcl_hrd_parameters: Default::default(),
1456+ low_delay_hrd_flag: Default::default(),
1457+ pic_struct_present_flag: Default::default(),
1458+ bitstream_restriction_flag: Default::default(),
1459+ motion_vectors_over_pic_boundaries_flag: Default::default(),
1460+ max_bytes_per_pic_denom: Default::default(),
1461+ max_bits_per_mb_denom: Default::default(),
1462+ log2_max_mv_length_horizontal: Default::default(),
1463+ log2_max_mv_length_vertical: Default::default(),
1464+ max_num_reorder_frames: Default::default(),
1465+ max_dec_frame_buffering: Default::default(),
1466+ }
1467+ }
1468+}
1469+
1470+/// A H264 Picture Parameter Set. A syntax structure containing syntax elements
1471+/// that apply to zero or more entire coded pictures as determined by the
1472+/// `pic_parameter_set_id` syntax element found in each slice header.
1473+#[derive(Debug, PartialEq, Eq)]
1474+pub struct Pps {
1475+ /// Identifies the picture parameter set that is referred to in the slice header.
1476+ pub pic_parameter_set_id: u8,
1477+
1478+ /// Refers to the active sequence parameter set.
1479+ pub seq_parameter_set_id: u8,
1480+
1481+ /// Selects the entropy decoding method to be applied for the syntax
1482+ /// elements for which two descriptors appear in the syntax tables as
1483+ /// follows: If `entropy_coding_mode_flag` is false, the method specified by
1484+ /// the left descriptor in the syntax table is applied (Exp-Golomb coded,
1485+ /// see clause 9.1 or CAVLC, see clause 9.2). Otherwise
1486+ /// (`entropy_coding_mode_flag` is true), the method specified by the right
1487+ /// descriptor in the syntax table is applied (CABAC, see clause 9.3).
1488+ pub entropy_coding_mode_flag: bool,
1489+
1490+ /// If true, specifies that the syntax elements delta_pic_order_cnt_bottom
1491+ /// (when `pic_order_cnt_type` is equal to 0) or `delta_pic_order_cnt[1]`
1492+ /// (when `pic_order_cnt_type` is equal to 1), which are related to picture
1493+ /// order counts for the bottom field of a coded frame, are present in the
1494+ /// slice headers for coded frames as specified in clause 7.3.3. Otherwise,
1495+ /// specifies that the syntax elements `delta_pic_order_cnt_bottom` and
1496+ /// `delta_pic_order_cnt[1]` are not present in the slice headers.
1497+ pub bottom_field_pic_order_in_frame_present_flag: bool,
1498+
1499+ /// Plus 1 specifies the number of slice groups for a picture. When
1500+ /// `num_slice_groups_minus1` is equal to 0, all slices of the picture
1501+ /// belong to the same slice group. The allowed range of
1502+ /// `num_slice_groups_minus1` is specified in Annex A.
1503+ pub num_slice_groups_minus1: u32,
1504+
1505+ /// Specifies how `num_ref_idx_l0_active_minus1` is inferred for P, SP, and
1506+ /// B slices with `num_ref_idx_active_override_flag` not set.
1507+ pub num_ref_idx_l0_default_active_minus1: u8,
1508+
1509+ /// Specifies how `num_ref_idx_l1_active_minus1` is inferred for B slices
1510+ /// with `num_ref_idx_active_override_flag` not set.
1511+ pub num_ref_idx_l1_default_active_minus1: u8,
1512+
1513+ /// If not set, specifies that the default weighted prediction shall be
1514+ /// applied to P and SP slices. If set, specifies that explicit weighted
1515+ /// prediction shall be applied to P and SP slices.
1516+ pub weighted_pred_flag: bool,
1517+
1518+ /// `weighted_bipred_idc` equal to 0 specifies that the default weighted
1519+ /// prediction shall be applied to B slices. `weighted_bipred_idc` equal to
1520+ /// 1 specifies that explicit weighted prediction shall be applied to B
1521+ /// slices. `weighted_bipred_idc` equal to 2 specifies that implicit
1522+ /// weighted prediction shall be applied to B slices
1523+ pub weighted_bipred_idc: u8,
1524+
1525+ /// Specifies the initial value minus 26 of SliceQPY for each slice. The
1526+ /// initial value is modified at the slice layer when a non-zero value of
1527+ /// `slice_qp_delta` is decoded, and is modified further when a non-zero
1528+ /// value of `mb_qp_delta` is decoded at the macroblock layer.
1529+ pub pic_init_qp_minus26: i8,
1530+
1531+ /// Specifies the initial value minus 26 of SliceQSY for all macroblocks in
1532+ /// SP or SI slices. The initial value is modified at the slice layer when a
1533+ /// non-zero value of `slice_qs_delta` is decoded.
1534+ pub pic_init_qs_minus26: i8,
1535+
1536+ /// Specifies the offset that shall be added to QP Y and QSY for addressing
1537+ /// the table of QPC values for the Cb chroma component.
1538+ pub chroma_qp_index_offset: i8,
1539+
1540+ /// If set, specifies that a set of syntax elements controlling the
1541+ /// characteristics of the deblocking filter is present in the slice header.
1542+ /// If not set, specifies that the set of syntax elements controlling the
1543+ /// characteristics of the deblocking filter is not present in the slice
1544+ /// headers and their inferred values are in effect.
1545+ pub deblocking_filter_control_present_flag: bool,
1546+
1547+ /// If not set, specifies that intra prediction allows usage of residual
1548+ /// data and decoded samples of neighbouring macroblocks coded using Inter
1549+ /// macroblock prediction modes for the prediction of macroblocks coded
1550+ /// using Intra macroblock prediction modes. If set, specifies constrained
1551+ /// intra prediction, in which case prediction of macroblocks coded using
1552+ /// Intra macroblock prediction modes only uses residual data and decoded
1553+ /// samples from I or SI macroblock types.
1554+ pub constrained_intra_pred_flag: bool,
1555+
1556+ /// If not set, specifies that the `redundant_pic_cnt` syntax element is not
1557+ /// present in slice headers, coded slice data partition B NAL units, and
1558+ /// coded slice data partition C NAL units that refer (either directly or by
1559+ /// association with a corresponding coded slice data partition A NAL unit)
1560+ /// to the picture parameter set. If set, specifies that the
1561+ /// `redundant_pic_cnt` syntax element is present in all slice headers,
1562+ /// coded slice data partition B NAL units, and coded slice data partition C
1563+ /// NAL units that refer (either directly or by association with a
1564+ /// corresponding coded slice data partition A NAL unit) to the picture
1565+ /// parameter set.
1566+ pub redundant_pic_cnt_present_flag: bool,
1567+
1568+ /// If set, specifies that the 8x8 transform decoding process may be in use
1569+ /// (see clause 8.5). If not set, specifies that the 8x8 transform decoding
1570+ /// process is not in use.
1571+ pub transform_8x8_mode_flag: bool,
1572+
1573+ /// If set, specifies that parameters are present to modify the scaling
1574+ /// lists specified in the sequence parameter set. If not set, specifies
1575+ /// that the scaling lists used for the picture shall be inferred to be
1576+ /// equal to those specified by the sequence parameter set.
1577+ pub pic_scaling_matrix_present_flag: bool,
1578+
1579+ /// 4x4 Scaling list as read with 7.3.2.1.1.1
1580+ pub scaling_lists_4x4: [[u8; 16]; 6],
1581+ /// 8x8 Scaling list as read with 7.3.2.1.1.1
1582+ pub scaling_lists_8x8: [[u8; 64]; 6],
1583+
1584+ /// Specifies the offset that shall be added to QPY and QSY for addressing
1585+ /// the table of QPC values for the Cr chroma component. When
1586+ /// `second_chroma_qp_index_offset` is not present, it shall be inferred to be
1587+ /// equal to `chroma_qp_index_offset`.
1588+ pub second_chroma_qp_index_offset: i8,
1589+
1590+ /// The SPS referenced by this PPS.
1591+ pub sps: Rc<Sps>,
1592+}
1593+
1594+pub struct PpsBuilder(Pps);
1595+
1596+impl PpsBuilder {
1597+ pub fn new(sps: Rc<Sps>) -> Self {
1598+ PpsBuilder(Pps {
1599+ pic_parameter_set_id: 0,
1600+ seq_parameter_set_id: sps.seq_parameter_set_id,
1601+ entropy_coding_mode_flag: false,
1602+ bottom_field_pic_order_in_frame_present_flag: false,
1603+ num_slice_groups_minus1: 0,
1604+ num_ref_idx_l0_default_active_minus1: 0,
1605+ num_ref_idx_l1_default_active_minus1: 0,
1606+ weighted_pred_flag: false,
1607+ weighted_bipred_idc: 0,
1608+ pic_init_qp_minus26: 0,
1609+ pic_init_qs_minus26: 0,
1610+ chroma_qp_index_offset: 0,
1611+ deblocking_filter_control_present_flag: false,
1612+ constrained_intra_pred_flag: false,
1613+ redundant_pic_cnt_present_flag: false,
1614+ transform_8x8_mode_flag: false,
1615+ pic_scaling_matrix_present_flag: false,
1616+ scaling_lists_4x4: [[0; 16]; 6],
1617+ scaling_lists_8x8: [[0; 64]; 6],
1618+ second_chroma_qp_index_offset: 0,
1619+ sps,
1620+ })
1621+ }
1622+
1623+ pub fn pic_parameter_set_id(mut self, value: u8) -> Self {
1624+ self.0.pic_parameter_set_id = value;
1625+ self
1626+ }
1627+
1628+ pub fn pic_init_qp_minus26(mut self, value: i8) -> Self {
1629+ self.0.pic_init_qp_minus26 = value;
1630+ self
1631+ }
1632+
1633+ pub fn pic_init_qp(self, value: u8) -> Self {
1634+ self.pic_init_qp_minus26(value as i8 - 26)
1635+ }
1636+
1637+ pub fn deblocking_filter_control_present_flag(mut self, value: bool) -> Self {
1638+ self.0.deblocking_filter_control_present_flag = value;
1639+ self
1640+ }
1641+
1642+ pub fn num_ref_idx_l0_default_active_minus1(mut self, value: u8) -> Self {
1643+ self.0.num_ref_idx_l0_default_active_minus1 = value;
1644+ self
1645+ }
1646+
1647+ pub fn num_ref_idx_l0_default_active(self, value: u8) -> Self {
1648+ self.num_ref_idx_l0_default_active_minus1(value - 1)
1649+ }
1650+
1651+ pub fn num_ref_idx_l1_default_active_minus1(mut self, value: u8) -> Self {
1652+ self.0.num_ref_idx_l1_default_active_minus1 = value;
1653+ self
1654+ }
1655+
1656+ pub fn num_ref_idx_l1_default_active(self, value: u8) -> Self {
1657+ self.num_ref_idx_l1_default_active_minus1(value - 1)
1658+ }
1659+
1660+ pub fn build(self) -> Rc<Pps> {
1661+ Rc::new(self.0)
1662+ }
1663+}
1664+
1665+#[derive(Debug, Default)]
1666+pub struct Parser {
1667+ active_spses: BTreeMap<u8, Rc<Sps>>,
1668+ active_ppses: BTreeMap<u8, Rc<Pps>>,
1669+}
1670+
1671+impl Parser {
1672+ fn fill_default_scaling_list_4x4(scaling_list4x4: &mut [u8; 16], i: usize) {
1673+ // See table 7.2 in the spec.
1674+ assert!(i < 6);
1675+ if i < 3 {
1676+ *scaling_list4x4 = DEFAULT_4X4_INTRA;
1677+ } else if i < 6 {
1678+ *scaling_list4x4 = DEFAULT_4X4_INTER;
1679+ }
1680+ }
1681+
1682+ fn fill_default_scaling_list_8x8(scaling_list8x8: &mut [u8; 64], i: usize) {
1683+ assert!(i < 6);
1684+ if i % 2 == 0 {
1685+ *scaling_list8x8 = DEFAULT_8X8_INTRA;
1686+ } else {
1687+ *scaling_list8x8 = DEFAULT_8X8_INTER;
1688+ }
1689+ }
1690+
1691+ fn fill_fallback_scaling_list_4x4(
1692+ scaling_list4x4: &mut [[u8; 16]; 6],
1693+ i: usize,
1694+ default_scaling_list_intra: &[u8; 16],
1695+ default_scaling_list_inter: &[u8; 16],
1696+ ) {
1697+ // See table 7.2 in the spec.
1698+ scaling_list4x4[i] = match i {
1699+ 0 => *default_scaling_list_intra,
1700+ 1 => scaling_list4x4[0],
1701+ 2 => scaling_list4x4[1],
1702+ 3 => *default_scaling_list_inter,
1703+ 4 => scaling_list4x4[3],
1704+ 5 => scaling_list4x4[4],
1705+ _ => panic!("Unexpected value {}", i),
1706+ }
1707+ }
1708+
1709+ fn fill_fallback_scaling_list_8x8(
1710+ scaling_list8x8: &mut [[u8; 64]; 6],
1711+ i: usize,
1712+ default_scaling_list_intra: &[u8; 64],
1713+ default_scaling_list_inter: &[u8; 64],
1714+ ) {
1715+ // See table 7.2 in the spec.
1716+ scaling_list8x8[i] = match i {
1717+ 0 => *default_scaling_list_intra,
1718+ 1 => *default_scaling_list_inter,
1719+ 2 => scaling_list8x8[0],
1720+ 3 => scaling_list8x8[1],
1721+ 4 => scaling_list8x8[2],
1722+ 5 => scaling_list8x8[3],
1723+ _ => panic!("Unexpected value {}", i),
1724+ }
1725+ }
1726+
1727+ fn fill_scaling_list_flat(
1728+ scaling_list4x4: &mut [[u8; 16]; 6],
1729+ scaling_list8x8: &mut [[u8; 64]; 6],
1730+ ) {
1731+ // (7-8) in the spec.
1732+ for outer in scaling_list4x4 {
1733+ for inner in outer {
1734+ *inner = 16;
1735+ }
1736+ }
1737+
1738+ // (7-9) in the spec.
1739+ for outer in scaling_list8x8 {
1740+ for inner in outer {
1741+ *inner = 16;
1742+ }
1743+ }
1744+ }
1745+
1746+ fn parse_scaling_list<U: AsMut<[u8]>>(
1747+ r: &mut BitReader,
1748+ scaling_list: &mut U,
1749+ use_default: &mut bool,
1750+ ) -> Result<(), String> {
1751+ // 7.3.2.1.1.1
1752+ let mut last_scale = 8u8;
1753+ let mut next_scale = 8u8;
1754+
1755+ for j in 0..scaling_list.as_mut().len() {
1756+ if next_scale != 0 {
1757+ let delta_scale = r.read_se::<i32>()?;
1758+ next_scale = ((last_scale as i32 + delta_scale + 256) % 256) as u8;
1759+ *use_default = j == 0 && next_scale == 0;
1760+ if *use_default {
1761+ return Ok(());
1762+ }
1763+ }
1764+
1765+ scaling_list.as_mut()[j] = if next_scale == 0 { last_scale } else { next_scale };
1766+
1767+ last_scale = scaling_list.as_mut()[j];
1768+ }
1769+
1770+ Ok(())
1771+ }
1772+
1773+ fn parse_sps_scaling_lists(r: &mut BitReader, sps: &mut Sps) -> Result<(), String> {
1774+ let scaling_lists4x4 = &mut sps.scaling_lists_4x4;
1775+ let scaling_lisst8x8 = &mut sps.scaling_lists_8x8;
1776+
1777+ // Parse scaling_list4x4
1778+ for i in 0..6 {
1779+ let seq_scaling_list_present_flag = r.read_bit()?;
1780+ if seq_scaling_list_present_flag {
1781+ let mut use_default = false;
1782+
1783+ Parser::parse_scaling_list(r, &mut scaling_lists4x4[i], &mut use_default)?;
1784+
1785+ if use_default {
1786+ Parser::fill_default_scaling_list_4x4(&mut scaling_lists4x4[i], i);
1787+ }
1788+ } else {
1789+ Parser::fill_fallback_scaling_list_4x4(
1790+ scaling_lists4x4,
1791+ i,
1792+ &DEFAULT_4X4_INTRA,
1793+ &DEFAULT_4X4_INTER,
1794+ );
1795+ }
1796+ }
1797+
1798+ // Parse scaling_list8x8
1799+ let num_8x8 = if sps.chroma_format_idc != 3 { 2 } else { 6 };
1800+ for i in 0..num_8x8 {
1801+ let seq_scaling_list_present_flag = r.read_bit()?;
1802+ if seq_scaling_list_present_flag {
1803+ let mut use_default = false;
1804+ Parser::parse_scaling_list(r, &mut scaling_lisst8x8[i], &mut use_default)?;
1805+
1806+ if use_default {
1807+ Parser::fill_default_scaling_list_8x8(&mut scaling_lisst8x8[i], i);
1808+ }
1809+ } else {
1810+ Parser::fill_fallback_scaling_list_8x8(
1811+ scaling_lisst8x8,
1812+ i,
1813+ &DEFAULT_8X8_INTRA,
1814+ &DEFAULT_8X8_INTER,
1815+ );
1816+ }
1817+ }
1818+ Ok(())
1819+ }
1820+
1821+ fn parse_pps_scaling_lists(r: &mut BitReader, pps: &mut Pps, sps: &Sps) -> Result<(), String> {
1822+ let scaling_lists4x4 = &mut pps.scaling_lists_4x4;
1823+ let scaling_lists8x8 = &mut pps.scaling_lists_8x8;
1824+
1825+ for i in 0..6 {
1826+ let pic_scaling_list_present_flag = r.read_bit()?;
1827+ if pic_scaling_list_present_flag {
1828+ let mut use_default = false;
1829+
1830+ Parser::parse_scaling_list(r, &mut scaling_lists4x4[i], &mut use_default)?;
1831+
1832+ if use_default {
1833+ Parser::fill_default_scaling_list_4x4(&mut scaling_lists4x4[i], i);
1834+ }
1835+ } else if !sps.seq_scaling_matrix_present_flag {
1836+ // Table 7-2: Fallback rule A
1837+ Parser::fill_fallback_scaling_list_4x4(
1838+ scaling_lists4x4,
1839+ i,
1840+ &DEFAULT_4X4_INTRA,
1841+ &DEFAULT_4X4_INTER,
1842+ );
1843+ } else {
1844+ // Table 7-2: Fallback rule B
1845+ Parser::fill_fallback_scaling_list_4x4(
1846+ scaling_lists4x4,
1847+ i,
1848+ &sps.scaling_lists_4x4[0],
1849+ &sps.scaling_lists_4x4[3],
1850+ );
1851+ }
1852+ }
1853+
1854+ if pps.transform_8x8_mode_flag {
1855+ let num8x8 = if sps.chroma_format_idc != 3 { 2 } else { 6 };
1856+
1857+ for i in 0..num8x8 {
1858+ let pic_scaling_list_present_flag = r.read_bit()?;
1859+ if pic_scaling_list_present_flag {
1860+ let mut use_default = false;
1861+
1862+ Parser::parse_scaling_list(r, &mut scaling_lists8x8[i], &mut use_default)?;
1863+
1864+ if use_default {
1865+ Parser::fill_default_scaling_list_8x8(&mut scaling_lists8x8[i], i);
1866+ }
1867+ } else if !sps.seq_scaling_matrix_present_flag {
1868+ // Table 7-2: Fallback rule A
1869+ Parser::fill_fallback_scaling_list_8x8(
1870+ scaling_lists8x8,
1871+ i,
1872+ &DEFAULT_8X8_INTRA,
1873+ &DEFAULT_8X8_INTER,
1874+ );
1875+ } else {
1876+ // Table 7-2: Fallback rule B
1877+ Parser::fill_fallback_scaling_list_8x8(
1878+ scaling_lists8x8,
1879+ i,
1880+ &sps.scaling_lists_8x8[0],
1881+ &sps.scaling_lists_8x8[1],
1882+ );
1883+ }
1884+ }
1885+ }
1886+
1887+ Ok(())
1888+ }
1889+
1890+ fn parse_hrd(r: &mut BitReader, hrd: &mut HrdParams) -> Result<(), String> {
1891+ hrd.cpb_cnt_minus1 = r.read_ue_max(31)?;
1892+ hrd.bit_rate_scale = r.read_bits(4)?;
1893+ hrd.cpb_size_scale = r.read_bits(4)?;
1894+
1895+ for sched_sel_idx in 0..=usize::from(hrd.cpb_cnt_minus1) {
1896+ hrd.bit_rate_value_minus1[sched_sel_idx] = r.read_ue()?;
1897+ hrd.cpb_size_value_minus1[sched_sel_idx] = r.read_ue()?;
1898+ hrd.cbr_flag[sched_sel_idx] = r.read_bit()?;
1899+ }
1900+
1901+ hrd.initial_cpb_removal_delay_length_minus1 = r.read_bits(5)?;
1902+ hrd.cpb_removal_delay_length_minus1 = r.read_bits(5)?;
1903+ hrd.dpb_output_delay_length_minus1 = r.read_bits(5)?;
1904+ hrd.time_offset_length = r.read_bits(5)?;
1905+ Ok(())
1906+ }
1907+
1908+ fn parse_vui(r: &mut BitReader, sps: &mut Sps) -> Result<(), String> {
1909+ let vui = &mut sps.vui_parameters;
1910+
1911+ vui.aspect_ratio_info_present_flag = r.read_bit()?;
1912+ if vui.aspect_ratio_info_present_flag {
1913+ vui.aspect_ratio_idc = r.read_bits(8)?;
1914+ if vui.aspect_ratio_idc == 255 {
1915+ vui.sar_width = r.read_bits(16)?;
1916+ vui.sar_height = r.read_bits(16)?;
1917+ }
1918+ }
1919+
1920+ vui.overscan_info_present_flag = r.read_bit()?;
1921+ if vui.overscan_info_present_flag {
1922+ vui.overscan_appropriate_flag = r.read_bit()?;
1923+ }
1924+
1925+ vui.video_signal_type_present_flag = r.read_bit()?;
1926+ if vui.video_signal_type_present_flag {
1927+ vui.video_format = r.read_bits(3)?;
1928+ vui.video_full_range_flag = r.read_bit()?;
1929+ vui.colour_description_present_flag = r.read_bit()?;
1930+ if vui.colour_description_present_flag {
1931+ vui.colour_primaries = r.read_bits(8)?;
1932+ vui.transfer_characteristics = r.read_bits(8)?;
1933+ vui.matrix_coefficients = r.read_bits(8)?;
1934+ }
1935+ }
1936+
1937+ vui.chroma_loc_info_present_flag = r.read_bit()?;
1938+ if vui.chroma_loc_info_present_flag {
1939+ vui.chroma_sample_loc_type_top_field = r.read_ue_max(5)?;
1940+ vui.chroma_sample_loc_type_bottom_field = r.read_ue_max(5)?;
1941+ }
1942+
1943+ vui.timing_info_present_flag = r.read_bit()?;
1944+ if vui.timing_info_present_flag {
1945+ vui.num_units_in_tick = r.read_bits::<u32>(31)? << 1;
1946+ vui.num_units_in_tick |= r.read_bit()? as u32;
1947+ if vui.num_units_in_tick == 0 {
1948+ return Err("num_units_in_tick == 0, which is not allowed by E.2.1".into());
1949+ }
1950+
1951+ vui.time_scale = r.read_bits::<u32>(31)? << 1;
1952+ vui.time_scale |= r.read_bit()? as u32;
1953+ if vui.time_scale == 0 {
1954+ return Err("time_scale == 0, which is not allowed by E.2.1".into());
1955+ }
1956+
1957+ vui.fixed_frame_rate_flag = r.read_bit()?;
1958+ }
1959+
1960+ vui.nal_hrd_parameters_present_flag = r.read_bit()?;
1961+ if vui.nal_hrd_parameters_present_flag {
1962+ Parser::parse_hrd(r, &mut vui.nal_hrd_parameters)?;
1963+ }
1964+
1965+ vui.vcl_hrd_parameters_present_flag = r.read_bit()?;
1966+ if vui.vcl_hrd_parameters_present_flag {
1967+ Parser::parse_hrd(r, &mut vui.vcl_hrd_parameters)?;
1968+ }
1969+
1970+ if vui.nal_hrd_parameters_present_flag || vui.vcl_hrd_parameters_present_flag {
1971+ vui.low_delay_hrd_flag = r.read_bit()?;
1972+ }
1973+
1974+ vui.pic_struct_present_flag = r.read_bit()?;
1975+ vui.bitstream_restriction_flag = r.read_bit()?;
1976+
1977+ if vui.bitstream_restriction_flag {
1978+ vui.motion_vectors_over_pic_boundaries_flag = r.read_bit()?;
1979+ vui.max_bytes_per_pic_denom = r.read_ue()?;
1980+ vui.max_bits_per_mb_denom = r.read_ue_max(16)?;
1981+ vui.log2_max_mv_length_horizontal = r.read_ue_max(16)?;
1982+ vui.log2_max_mv_length_vertical = r.read_ue_max(16)?;
1983+ vui.max_num_reorder_frames = r.read_ue()?;
1984+ vui.max_dec_frame_buffering = r.read_ue()?;
1985+ }
1986+
1987+ Ok(())
1988+ }
1989+
1990+ /// Parse a SPS and add it to the list of active SPSes.
1991+ ///
1992+ /// Returns a reference to the new SPS.
1993+ pub fn parse_sps(&mut self, nalu: &Nalu) -> Result<&Rc<Sps>, String> {
1994+ if !matches!(nalu.header.type_, NaluType::Sps) {
1995+ return Err(format!(
1996+ "Invalid NALU type, expected {:?}, got {:?}",
1997+ NaluType::Sps,
1998+ nalu.header.type_
1999+ ));
2000+ }
vendor/cros-codecs/src/codec/h264/picture.rsadded+415 -0
@@ -0,0 +1,415 @@
1+// Copyright 2022 The ChromiumOS Authors
2+// Use of this source code is governed by a BSD-style license that can be
3+// found in the LICENSE file.
4+
5+use std::cell::RefCell;
6+use std::ops::Deref;
7+use std::rc::Rc;
8+use std::rc::Weak;
9+
10+use log::debug;
11+
12+use crate::codec::h264::parser::MaxLongTermFrameIdx;
13+use crate::codec::h264::parser::RefPicMarking;
14+use crate::codec::h264::parser::Slice;
15+use crate::codec::h264::parser::SliceType;
16+use crate::codec::h264::parser::Sps;
17+use crate::Resolution;
18+
19+#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
20+pub enum Field {
21+ #[default]
22+ Frame,
23+ Top,
24+ Bottom,
25+}
26+
27+impl Field {
28+ /// Returns the field of opposite parity.
29+ pub fn opposite(&self) -> Self {
30+ match *self {
31+ Field::Frame => Field::Frame,
32+ Field::Top => Field::Bottom,
33+ Field::Bottom => Field::Top,
34+ }
35+ }
36+}
37+
38+#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
39+pub enum Reference {
40+ #[default]
41+ None,
42+ ShortTerm,
43+ LongTerm,
44+}
45+
46+#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
47+pub enum IsIdr {
48+ #[default]
49+ No,
50+ Yes {
51+ idr_pic_id: u16,
52+ },
53+}
54+
55+/// The rank of a field, i.e. whether it is the first or second one to be parsed from the stream.
56+/// This is unrelated to the `Field` type, as the first field can be either `Top` or `Bottom`.
57+#[derive(Default, Debug)]
58+pub enum FieldRank {
59+ /// Frame has a single field.
60+ #[default]
61+ Single,
62+ /// Frame is interlaced, and this is the first field (with a reference to the second one).
63+ First(Weak<RefCell<PictureData>>),
64+ /// Frame is interlaced, and this is the second field (with a reference to the first one).
65+ Second(Rc<RefCell<PictureData>>),
66+}
67+
68+#[derive(Default)]
69+pub struct PictureData {
70+ pub pic_order_cnt_type: u8,
71+ pub top_field_order_cnt: i32,
72+ pub bottom_field_order_cnt: i32,
73+ pub pic_order_cnt: i32,
74+ pub pic_order_cnt_msb: i32,
75+ pub pic_order_cnt_lsb: i32,
76+ pub delta_pic_order_cnt_bottom: i32,
77+ pub delta_pic_order_cnt0: i32,
78+ pub delta_pic_order_cnt1: i32,
79+
80+ pub pic_num: i32,
81+ pub long_term_pic_num: u32,
82+ pub frame_num: u32,
83+ pub frame_num_offset: u32,
84+ pub frame_num_wrap: i32,
85+ pub long_term_frame_idx: u32,
86+
87+ pub coded_resolution: Resolution,
88+ pub display_resolution: Resolution,
89+
90+ pub type_: SliceType,
91+ pub nal_ref_idc: u8,
92+ pub is_idr: IsIdr,
93+ reference: Reference,
94+ pub ref_pic_list_modification_flag_l0: i32,
95+ pub abs_diff_pic_num_minus1: i32,
96+
97+ // Does memory management op 5 needs to be executed after this
98+ // picture has finished decoding?
99+ pub has_mmco_5: bool,
100+
101+ // Created by the decoding process for gaps in frame_num.
102+ // Not for decode or output.
103+ pub nonexisting: bool,
104+
105+ pub field: Field,
106+
107+ // Values from slice_hdr to be used during reference marking and
108+ // memory management after finishing this picture.
109+ pub ref_pic_marking: RefPicMarking,
110+
111+ field_rank: FieldRank,
112+
113+ pub timestamp: u64,
114+}
115+
116+/// A `PictureData` within a `Rc<RefCell>` which field rank is guaranteed to be correct.
117+///
118+/// The field rank of `PictureData` is only final after both fields have been constructed - namely,
119+/// the first field can only point to the second one after the latter is available as a Rc. Methods
120+/// [`PictureData::into_rc`] and [`PictureData::split_frame`] take care of this, and is this only
121+/// producer of this type, ensuring all instances are correct.
122+#[derive(Default, Debug, Clone)]
123+pub struct RcPictureData {
124+ pic: Rc<RefCell<PictureData>>,
125+}
126+
127+impl Deref for RcPictureData {
128+ type Target = Rc<RefCell<PictureData>>;
129+
130+ fn deref(&self) -> &Self::Target {
131+ &self.pic
132+ }
133+}
134+
135+impl PictureData {
136+ pub fn new_non_existing(frame_num: u32, timestamp: u64) -> Self {
137+ PictureData {
138+ frame_num,
139+ nonexisting: true,
140+ nal_ref_idc: 1,
141+ field: Field::Frame,
142+ pic_num: frame_num as i32,
143+ reference: Reference::ShortTerm,
144+ timestamp,
145+ ..Default::default()
146+ }
147+ }
148+
149+ /// Create a new picture from a `slice`, `sps`, and `timestamp`.
150+ ///
151+ /// `first_field` is set if this picture is the second field of a frame.
152+ pub fn new_from_slice(
153+ slice: &Slice,
154+ sps: &Sps,
155+ timestamp: u64,
156+ first_field: Option<&RcPictureData>,
157+ ) -> Self {
158+ let hdr = &slice.header;
159+ let nalu_hdr = &slice.nalu.header;
160+
161+ let is_idr = if nalu_hdr.idr_pic_flag {
162+ IsIdr::Yes { idr_pic_id: hdr.idr_pic_id }
163+ } else {
164+ IsIdr::No
165+ };
166+
167+ let field = if hdr.field_pic_flag {
168+ if hdr.bottom_field_flag {
169+ Field::Bottom
170+ } else {
171+ Field::Top
172+ }
173+ } else {
174+ Field::Frame
175+ };
176+
177+ let reference = if nalu_hdr.ref_idc != 0 { Reference::ShortTerm } else { Reference::None };
178+
179+ let pic_num = if !hdr.field_pic_flag { hdr.frame_num } else { 2 * hdr.frame_num + 1 };
180+
181+ let (
182+ pic_order_cnt_lsb,
183+ delta_pic_order_cnt_bottom,
184+ delta_pic_order_cnt0,
185+ delta_pic_order_cnt1,
186+ ) = match sps.pic_order_cnt_type {
187+ 0 => (
188+ hdr.pic_order_cnt_lsb,
189+ hdr.delta_pic_order_cnt_bottom,
190+ Default::default(),
191+ Default::default(),
192+ ),
193+ 1 => (
194+ Default::default(),
195+ Default::default(),
196+ hdr.delta_pic_order_cnt[0],
197+ hdr.delta_pic_order_cnt[1],
198+ ),
199+ _ => (Default::default(), Default::default(), Default::default(), Default::default()),
200+ };
201+
202+ let coded_resolution = Resolution::from((sps.width(), sps.height()));
203+
204+ let visible_rect = sps.visible_rectangle();
205+
206+ let display_resolution = Resolution {
207+ width: visible_rect.max.x - visible_rect.min.x,
208+ height: visible_rect.max.y - visible_rect.min.y,
209+ };
210+
211+ let mut pic = PictureData {
212+ pic_order_cnt_type: sps.pic_order_cnt_type,
213+ pic_order_cnt_lsb: i32::from(pic_order_cnt_lsb),
214+ delta_pic_order_cnt_bottom,
215+ delta_pic_order_cnt0,
216+ delta_pic_order_cnt1,
217+ pic_num: i32::from(pic_num),
218+ frame_num: u32::from(hdr.frame_num),
219+ nal_ref_idc: nalu_hdr.ref_idc,
220+ is_idr,
221+ reference,
222+ field,
223+ ref_pic_marking: hdr.dec_ref_pic_marking.clone(),
224+ coded_resolution,
225+ display_resolution,
226+ timestamp,
227+ ..Default::default()
228+ };
229+
230+ if let Some(first_field) = first_field {
231+ pic.set_first_field_to(first_field);
232+ }
233+
234+ pic
235+ }
236+
237+ /// Whether the current picture is a reference, either ShortTerm or LongTerm.
238+ pub fn is_ref(&self) -> bool {
239+ !matches!(self.reference, Reference::None)
240+ }
241+
242+ /// Whether this picture is a second field.
243+ pub fn is_second_field(&self) -> bool {
244+ matches!(self.field_rank, FieldRank::Second(..))
245+ }
246+
247+ /// Returns the field rank of this picture, including a reference to its other field.
248+ pub fn field_rank(&self) -> &FieldRank {
249+ &self.field_rank
250+ }
251+
252+ /// Returns a reference to the picture's Reference
253+ pub fn reference(&self) -> &Reference {
254+ &self.reference
255+ }
256+
257+ /// Mark the picture as a reference picture.
258+ pub fn set_reference(&mut self, reference: Reference, apply_to_other_field: bool) {
259+ log::debug!("Set reference of {:#?} to {:?}", self, reference);
260+ self.reference = reference;
261+
262+ if apply_to_other_field {
263+ if let Some(other_field) = self.other_field() {
264+ log::debug!(
265+ "other_field: Set reference of {:#?} to {:?}",
266+ &other_field.borrow(),
267+ reference
268+ );
269+ other_field.borrow_mut().reference = reference;
270+ }
271+ }
272+ }
273+
274+ /// Get a reference to the picture's other field, if there is any
275+ /// and its reference is still valid.
276+ pub fn other_field(&self) -> Option<Rc<RefCell<PictureData>>> {
277+ match &self.field_rank {
278+ FieldRank::Single => None,
279+ FieldRank::First(other_field) => other_field.upgrade(),
280+ FieldRank::Second(other_field) => Some(other_field.clone()),
281+ }
282+ }
283+
284+ /// Set this picture's second field.
285+ fn set_second_field_to(&mut self, other_field: &Rc<RefCell<Self>>) {
286+ self.field_rank = FieldRank::First(Rc::downgrade(other_field));
287+ }
288+
289+ /// Whether the current picture is the second field of a complementary ref pair.
290+ pub fn is_second_field_of_complementary_ref_pair(&self) -> bool {
291+ self.is_ref()
292+ && matches!(self.field_rank(), FieldRank::Second(first_field) if first_field.borrow().is_ref())
293+ }
294+
295+ /// Set this picture's first field.
296+ fn set_first_field_to(&mut self, other_field: &Rc<RefCell<Self>>) {
297+ self.field_rank = FieldRank::Second(other_field.clone());
298+ }
299+
300+ pub fn pic_num_f(&self, max_pic_num: i32) -> i32 {
301+ if !matches!(self.reference(), Reference::LongTerm) {
302+ self.pic_num
303+ } else {
304+ max_pic_num
305+ }
306+ }
307+
308+ pub fn long_term_pic_num_f(&self, max_long_term_frame_idx: MaxLongTermFrameIdx) -> u32 {
309+ if matches!(self.reference(), Reference::LongTerm) {
310+ self.long_term_pic_num
311+ } else {
312+ 2 * max_long_term_frame_idx.to_value_plus1()
313+ }
314+ }
315+
316+ /// Consume this picture and return a Rc'd version.
317+ ///
318+ /// If the picture was a second field, adjust the field of the first field to point to this
319+ /// one.
320+ pub fn into_rc(self) -> RcPictureData {
321+ let self_rc = Rc::new(RefCell::new(self));
322+
323+ if let FieldRank::Second(first_field) = self_rc.borrow().field_rank() {
324+ first_field.borrow_mut().set_second_field_to(&self_rc);
325+ }
326+
327+ RcPictureData { pic: self_rc }
328+ }
329+
330+ /// Split a frame into two complementary fields that reference one another.
331+ pub fn split_frame(mut self) -> (RcPictureData, RcPictureData) {
332+ assert!(matches!(self.field, Field::Frame));
333+ assert!(matches!(self.field_rank, FieldRank::Single));
334+
335+ debug!(
336+ "Splitting picture (frame_num, POC) ({:?}, {:?})",
337+ self.frame_num, self.pic_order_cnt
338+ );
339+
340+ let second_pic_order_cnt = if self.top_field_order_cnt < self.bottom_field_order_cnt {
341+ self.field = Field::Top;
342+ self.pic_order_cnt = self.top_field_order_cnt;
343+
344+ self.bottom_field_order_cnt
345+ } else {
346+ self.field = Field::Bottom;
347+ self.pic_order_cnt = self.bottom_field_order_cnt;
348+
349+ self.top_field_order_cnt
350+ };
351+
352+ let second_field = PictureData {
353+ top_field_order_cnt: self.top_field_order_cnt,
354+ bottom_field_order_cnt: self.bottom_field_order_cnt,
355+ frame_num: self.frame_num,
356+ reference: self.reference,
357+ nonexisting: self.nonexisting,
358+ pic_order_cnt: second_pic_order_cnt,
359+ field: self.field.opposite(),
360+ ..Default::default()
361+ };
362+
363+ debug!(
364+ "Split into picture (frame_num, POC) ({:?}, {:?}), field: {:?}",
365+ self.frame_num, self.pic_order_cnt, self.field
366+ );
367+ debug!(
368+ "Split into picture (frame_num, POC) ({:?}, {:?}), field {:?}",
369+ second_field.frame_num, second_field.pic_order_cnt, second_field.field
370+ );
371+
372+ let first_field = Rc::new(RefCell::new(self));
373+ let second_field = Rc::new(RefCell::new(second_field));
374+
375+ first_field.borrow_mut().set_second_field_to(&second_field);
376+ second_field.borrow_mut().set_first_field_to(&first_field);
377+
378+ (RcPictureData { pic: first_field }, RcPictureData { pic: second_field })
379+ }
380+}
381+
382+impl std::fmt::Debug for PictureData {
383+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
384+ f.debug_struct("PictureData")
385+ .field("pic_order_cnt_type", &self.pic_order_cnt_type)
386+ .field("top_field_order_cnt", &self.top_field_order_cnt)
387+ .field("bottom_field_order_cnt", &self.bottom_field_order_cnt)
388+ .field("pic_order_cnt", &self.pic_order_cnt)
389+ .field("pic_order_cnt_msb", &self.pic_order_cnt_msb)
390+ .field("pic_order_cnt_lsb", &self.pic_order_cnt_lsb)
391+ .field("delta_pic_order_cnt_bottom", &self.delta_pic_order_cnt_bottom)
392+ .field("delta_pic_order_cnt0", &self.delta_pic_order_cnt0)
393+ .field("delta_pic_order_cnt1", &self.delta_pic_order_cnt1)
394+ .field("pic_num", &self.pic_num)
395+ .field("long_term_pic_num", &self.long_term_pic_num)
396+ .field("frame_num", &self.frame_num)
397+ .field("frame_num_offset", &self.frame_num_offset)
398+ .field("frame_num_wrap", &self.frame_num_wrap)
399+ .field("long_term_frame_idx", &self.long_term_frame_idx)
400+ .field("coded_resolution", &self.coded_resolution)
401+ .field("display_resolution", &self.display_resolution)
402+ .field("type_", &self.type_)
403+ .field("nal_ref_idc", &self.nal_ref_idc)
404+ .field("is_idr", &self.is_idr)
405+ .field("reference", &self.reference)
406+ .field("ref_pic_list_modification_flag_l0", &self.ref_pic_list_modification_flag_l0)
407+ .field("abs_diff_pic_num_minus1", &self.abs_diff_pic_num_minus1)
408+ .field("has_mmco_5", &self.has_mmco_5)
409+ .field("nonexisting", &self.nonexisting)
410+ .field("field", &self.field)
411+ .field("ref_pic_marking", &self.ref_pic_marking)
412+ .field("field_rank", &self.field_rank)
413+ .finish()
414+ }
415+}
vendor/cros-codecs/src/codec/h264/synthesizer.rsadded+582 -0
@@ -0,0 +1,582 @@
1+// Copyright 2024 The ChromiumOS Authors
2+// Use of this source code is governed by a BSD-style license that can be
3+// found in the LICENSE file.
4+use std::fmt;
5+use std::io::Write;
6+
7+use crate::codec::h264::nalu_writer::NaluWriter;
8+use crate::codec::h264::nalu_writer::NaluWriterError;
9+use crate::codec::h264::parser::HrdParams;
10+use crate::codec::h264::parser::NaluType;
11+use crate::codec::h264::parser::Pps;
12+use crate::codec::h264::parser::Sps;
13+use crate::codec::h264::parser::DEFAULT_4X4_INTER;
14+use crate::codec::h264::parser::DEFAULT_4X4_INTRA;
15+use crate::codec::h264::parser::DEFAULT_8X8_INTER;
16+use crate::codec::h264::parser::DEFAULT_8X8_INTRA;
17+
18+mod private {
19+ pub trait NaluStruct {}
20+}
21+
22+impl private::NaluStruct for Sps {}
23+
24+impl private::NaluStruct for Pps {}
25+
26+#[derive(Debug)]
27+pub enum SynthesizerError {
28+ Unsupported,
29+ NaluWriter(NaluWriterError),
30+}
31+
32+impl fmt::Display for SynthesizerError {
33+ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
34+ match self {
35+ SynthesizerError::Unsupported => write!(f, "tried to synthesize unsupported settings"),
36+ SynthesizerError::NaluWriter(x) => write!(f, "{}", x.to_string()),
37+ }
38+ }
39+}
40+
41+impl From<NaluWriterError> for SynthesizerError {
42+ fn from(err: NaluWriterError) -> Self {
43+ SynthesizerError::NaluWriter(err)
44+ }
45+}
46+
47+pub type SynthesizerResult<T> = Result<T, SynthesizerError>;
48+
49+/// A helper to output typed NALUs to [`std::io::Write`] using [`NaluWriter`].
50+pub struct Synthesizer<'n, N: private::NaluStruct, W: Write> {
51+ writer: NaluWriter<W>,
52+ nalu: &'n N,
53+}
54+
55+/// Extended Sample Aspect Ratio - H.264 Table E-1
56+const EXTENDED_SAR: u8 = 255;
57+
58+impl<N: private::NaluStruct, W: Write> Synthesizer<'_, N, W> {
59+ fn u<T: Into<u32>>(&mut self, bits: usize, value: T) -> SynthesizerResult<()> {
60+ self.writer.write_u(bits, value)?;
61+ Ok(())
62+ }
63+
64+ fn f<T: Into<u32>>(&mut self, bits: usize, value: T) -> SynthesizerResult<()> {
65+ self.writer.write_f(bits, value)?;
66+ Ok(())
67+ }
68+
69+ fn ue<T: Into<u32>>(&mut self, value: T) -> SynthesizerResult<()> {
70+ self.writer.write_ue(value)?;
71+ Ok(())
72+ }
73+
74+ fn se<T: Into<i32>>(&mut self, value: T) -> SynthesizerResult<()> {
75+ self.writer.write_se(value)?;
76+ Ok(())
77+ }
78+
79+ fn scaling_list(&mut self, list: &[u8], default: &[u8]) -> SynthesizerResult<()> {
80+ // H.264 7.3.2.1.1.1
81+ if list == default {
82+ self.se(-8)?;
83+ return Ok(());
84+ }
85+
86+ // The number of list values we want to encode.
87+ let mut run = list.len();
88+
89+ // Check how many values at the end of the matrix are the same,
90+ // so we can save on encoding those.
91+ for j in (1..list.len()).rev() {
92+ if list[j - 1] != list[j] {
93+ break;
94+ }
95+ run -= 1;
96+ }
97+
98+ // Encode deltas.
99+ let mut last_scale = 8;
100+ for scale in &list[0..run] {
101+ let delta_scale = *scale as i32 - last_scale;
102+ self.se(delta_scale)?;
103+ last_scale = *scale as i32;
104+ }
105+
106+ // Didn't encode all values, encode -|last_scale| to set decoder's
107+ // |next_scale| (H.264 7.3.2.1.1.1) to zero, i.e. decoder should repeat
108+ // last values in matrix.
109+ if run < list.len() {
110+ self.se(-last_scale)?;
111+ }
112+
113+ Ok(())
114+ }
115+
116+ fn default_scaling_list(i: usize) -> &'static [u8] {
117+ // H.264 Table 7-2
118+ match i {
119+ 0 => &DEFAULT_4X4_INTRA[..],
120+ 1 => &DEFAULT_4X4_INTRA[..],
121+ 2 => &DEFAULT_4X4_INTRA[..],
122+ 3 => &DEFAULT_4X4_INTER[..],
123+ 4 => &DEFAULT_4X4_INTER[..],
124+ 5 => &DEFAULT_4X4_INTER[..],
125+ 6 => &DEFAULT_8X8_INTRA[..],
126+ 7 => &DEFAULT_8X8_INTER[..],
127+ 8 => &DEFAULT_8X8_INTRA[..],
128+ 9 => &DEFAULT_8X8_INTER[..],
129+ 10 => &DEFAULT_8X8_INTRA[..],
130+ 11 => &DEFAULT_8X8_INTER[..],
131+ _ => unreachable!(),
132+ }
133+ }
134+
135+ fn rbsp_trailing_bits(&mut self) -> SynthesizerResult<()> {
136+ self.f(1, 1u32)?;
137+
138+ while !self.writer.aligned() {
139+ self.f(1, 0u32)?;
140+ }
141+
142+ Ok(())
143+ }
144+}
145+
146+impl<'n, W: Write> Synthesizer<'n, Sps, W> {
147+ pub fn synthesize(
148+ ref_idc: u8,
149+ sps: &'n Sps,
150+ writer: W,
151+ ep_enabled: bool,
152+ ) -> SynthesizerResult<()> {
153+ let mut s = Self { writer: NaluWriter::<W>::new(writer, ep_enabled), nalu: sps };
154+
155+ s.writer.write_header(ref_idc, NaluType::Sps as u8)?;
156+ s.seq_parameter_set_data()?;
157+ s.rbsp_trailing_bits()
158+ }
159+
160+ fn hrd_parameters(&mut self, hrd_params: &HrdParams) -> SynthesizerResult<()> {
161+ self.ue(hrd_params.cpb_cnt_minus1)?;
162+ self.u(4, hrd_params.bit_rate_scale)?;
163+ self.u(4, hrd_params.cpb_size_scale)?;
164+
165+ for i in 0..=(hrd_params.cpb_cnt_minus1 as usize) {
166+ self.ue(hrd_params.bit_rate_value_minus1[i])?;
167+ self.ue(hrd_params.cpb_size_value_minus1[i])?;
168+ self.u(1, hrd_params.cbr_flag[i])?;
169+ }
170+
171+ self.u(5, hrd_params.initial_cpb_removal_delay_length_minus1)?;
172+ self.u(5, hrd_params.cpb_removal_delay_length_minus1)?;
173+ self.u(5, hrd_params.dpb_output_delay_length_minus1)?;
174+ self.u(5, hrd_params.time_offset_length)?;
175+
176+ Ok(())
177+ }
178+
179+ fn vui_parameters(&mut self) -> SynthesizerResult<()> {
180+ // H.264 E.1.1
181+ let vui_params = &self.nalu.vui_parameters;
182+
183+ self.u(1, vui_params.aspect_ratio_info_present_flag)?;
184+ if vui_params.aspect_ratio_info_present_flag {
185+ self.u(8, vui_params.aspect_ratio_idc)?;
186+ if vui_params.aspect_ratio_idc == EXTENDED_SAR {
187+ self.u(16, vui_params.sar_width)?;
188+ self.u(16, vui_params.sar_height)?;
189+ }
190+ }
191+
192+ self.u(1, vui_params.overscan_info_present_flag)?;
193+ if vui_params.overscan_info_present_flag {
194+ self.u(1, vui_params.overscan_appropriate_flag)?;
195+ }
196+
197+ self.u(1, vui_params.video_signal_type_present_flag)?;
198+ if vui_params.video_signal_type_present_flag {
199+ self.u(3, vui_params.video_format)?;
200+ self.u(1, vui_params.video_full_range_flag)?;
201+
202+ self.u(1, vui_params.colour_description_present_flag)?;
203+ if vui_params.colour_description_present_flag {
204+ self.u(8, vui_params.colour_primaries)?;
205+ self.u(8, vui_params.transfer_characteristics)?;
206+ self.u(8, vui_params.matrix_coefficients)?;
207+ }
208+ }
209+
210+ self.u(1, vui_params.chroma_loc_info_present_flag)?;
211+ if vui_params.chroma_loc_info_present_flag {
212+ self.ue(vui_params.chroma_sample_loc_type_top_field)?;
213+ self.ue(self.nalu.vui_parameters.chroma_sample_loc_type_bottom_field)?;
214+ }
215+
216+ self.u(1, vui_params.timing_info_present_flag)?;
217+ if vui_params.timing_info_present_flag {
218+ self.u(32, vui_params.num_units_in_tick)?;
219+ self.u(32, vui_params.time_scale)?;
220+ self.u(1, vui_params.fixed_frame_rate_flag)?;
221+ }
222+
223+ self.u(1, vui_params.nal_hrd_parameters_present_flag)?;
224+ if vui_params.nal_hrd_parameters_present_flag {
225+ self.hrd_parameters(&vui_params.nal_hrd_parameters)?;
226+ }
227+ self.u(1, vui_params.vcl_hrd_parameters_present_flag)?;
228+ if vui_params.vcl_hrd_parameters_present_flag {
229+ self.hrd_parameters(&vui_params.vcl_hrd_parameters)?;
230+ }
231+
232+ if vui_params.nal_hrd_parameters_present_flag || vui_params.vcl_hrd_parameters_present_flag
233+ {
234+ self.u(1, vui_params.low_delay_hrd_flag)?;
235+ }
236+
237+ self.u(1, vui_params.pic_struct_present_flag)?;
238+
239+ self.u(1, vui_params.bitstream_restriction_flag)?;
240+ if vui_params.bitstream_restriction_flag {
241+ self.u(1, vui_params.motion_vectors_over_pic_boundaries_flag)?;
242+ self.ue(vui_params.max_bytes_per_pic_denom)?;
243+ self.ue(vui_params.max_bits_per_mb_denom)?;
244+ self.ue(vui_params.log2_max_mv_length_horizontal)?;
245+ self.ue(vui_params.log2_max_mv_length_vertical)?;
246+ self.ue(vui_params.max_num_reorder_frames)?;
247+ self.ue(vui_params.max_dec_frame_buffering)?;
248+ }
249+
250+ Ok(())
251+ }
252+
253+ fn seq_parameter_set_data(&mut self) -> SynthesizerResult<()> {
254+ // H.264 7.3.2.1.1
255+ self.u(8, self.nalu.profile_idc)?;
256+ self.u(1, self.nalu.constraint_set0_flag)?;
257+ self.u(1, self.nalu.constraint_set1_flag)?;
258+ self.u(1, self.nalu.constraint_set2_flag)?;
259+ self.u(1, self.nalu.constraint_set3_flag)?;
260+ self.u(1, self.nalu.constraint_set4_flag)?;
261+ self.u(1, self.nalu.constraint_set5_flag)?;
262+ self.u(2, /* reserved_zero_2bits */ 0u32)?;
263+ self.u(8, self.nalu.level_idc as u32)?;
264+ self.ue(self.nalu.seq_parameter_set_id)?;
265+
266+ if self.nalu.profile_idc == 100
267+ || self.nalu.profile_idc == 110
268+ || self.nalu.profile_idc == 122
269+ || self.nalu.profile_idc == 244
270+ || self.nalu.profile_idc == 44
271+ || self.nalu.profile_idc == 83
272+ || self.nalu.profile_idc == 86
273+ || self.nalu.profile_idc == 118
274+ || self.nalu.profile_idc == 128
275+ || self.nalu.profile_idc == 138
276+ || self.nalu.profile_idc == 139
277+ || self.nalu.profile_idc == 134
278+ || self.nalu.profile_idc == 135
279+ {
280+ self.ue(self.nalu.chroma_format_idc)?;
281+
282+ if self.nalu.chroma_format_idc == 3 {
283+ self.u(1, self.nalu.separate_colour_plane_flag)?;
284+ }
285+
286+ self.ue(self.nalu.bit_depth_luma_minus8)?;
287+ self.ue(self.nalu.bit_depth_chroma_minus8)?;
288+ self.u(1, self.nalu.qpprime_y_zero_transform_bypass_flag)?;
289+ self.u(1, self.nalu.seq_scaling_matrix_present_flag)?;
290+
291+ if self.nalu.seq_scaling_matrix_present_flag {
292+ let scaling_list_count = if self.nalu.chroma_format_idc != 3 { 8 } else { 12 };
293+
294+ for i in 0..scaling_list_count {
295+ // Assume if scaling lists are zeroed that they are not present.
296+ if i < 6 {
297+ if self.nalu.scaling_lists_4x4[i] == [0; 16] {
298+ self.u(1, /* seq_scaling_list_present_flag */ false)?;
299+ } else {
300+ self.u(1, /* seq_scaling_list_present_flag */ true)?;
301+ self.scaling_list(
302+ &self.nalu.scaling_lists_4x4[i],
303+ Self::default_scaling_list(i),
304+ )?;
305+ }
306+ } else if self.nalu.scaling_lists_8x8[i - 6] == [0; 64] {
307+ self.u(1, /* seq_scaling_list_present_flag */ false)?;
308+ } else {
309+ self.u(1, /* seq_scaling_list_present_flag */ true)?;
310+ self.scaling_list(
311+ &self.nalu.scaling_lists_8x8[i - 6],
312+ Self::default_scaling_list(i),
313+ )?;
314+ }
315+ }
316+ }
317+ }
318+
319+ self.ue(self.nalu.log2_max_frame_num_minus4)?;
320+ self.ue(self.nalu.pic_order_cnt_type)?;
321+
322+ if self.nalu.pic_order_cnt_type == 0 {
323+ self.ue(self.nalu.log2_max_pic_order_cnt_lsb_minus4)?;
324+ } else if self.nalu.pic_order_cnt_type == 1 {
325+ self.u(1, self.nalu.delta_pic_order_always_zero_flag)?;
326+ self.se(self.nalu.offset_for_non_ref_pic)?;
327+ self.se(self.nalu.offset_for_top_to_bottom_field)?;
328+ self.ue(self.nalu.num_ref_frames_in_pic_order_cnt_cycle)?;
329+
330+ for offset_for_ref_frame in &self.nalu.offset_for_ref_frame {
331+ self.se(*offset_for_ref_frame)?;
332+ }
333+ }
334+
335+ self.ue(self.nalu.max_num_ref_frames)?;
336+ self.u(1, self.nalu.gaps_in_frame_num_value_allowed_flag)?;
337+ self.ue(self.nalu.pic_width_in_mbs_minus1)?;
338+ self.ue(self.nalu.pic_height_in_map_units_minus1)?;
339+ self.u(1, self.nalu.frame_mbs_only_flag)?;
340+ if !self.nalu.frame_mbs_only_flag {
341+ self.u(1, self.nalu.mb_adaptive_frame_field_flag)?;
342+ }
343+ self.u(1, self.nalu.direct_8x8_inference_flag)?;
344+
345+ self.u(1, self.nalu.frame_cropping_flag)?;
346+ if self.nalu.frame_cropping_flag {
347+ self.ue(self.nalu.frame_crop_left_offset)?;
348+ self.ue(self.nalu.frame_crop_right_offset)?;
349+ self.ue(self.nalu.frame_crop_top_offset)?;
350+ self.ue(self.nalu.frame_crop_bottom_offset)?;
351+ }
352+
353+ self.u(1, self.nalu.vui_parameters_present_flag)?;
354+ if self.nalu.vui_parameters_present_flag {
355+ self.vui_parameters()?;
356+ }
357+
358+ Ok(())
359+ }
360+}
361+
362+impl<'n, W: Write> Synthesizer<'n, Pps, W> {
363+ pub fn synthesize(
364+ ref_idc: u8,
365+ pps: &'n Pps,
366+ writer: W,
367+ ep_enabled: bool,
368+ ) -> SynthesizerResult<()> {
369+ let mut s = Self { writer: NaluWriter::<W>::new(writer, ep_enabled), nalu: pps };
370+
371+ s.writer.write_header(ref_idc, NaluType::Pps as u8)?;
372+ s.pic_parameter_set_rbsp()?;
373+ s.rbsp_trailing_bits()
374+ }
375+
376+ fn pic_parameter_set_rbsp(&mut self) -> SynthesizerResult<()> {
377+ self.ue(self.nalu.pic_parameter_set_id)?;
378+ self.ue(self.nalu.seq_parameter_set_id)?;
379+ self.u(1, self.nalu.entropy_coding_mode_flag)?;
380+ self.u(1, self.nalu.bottom_field_pic_order_in_frame_present_flag)?;
381+
382+ self.ue(self.nalu.num_slice_groups_minus1)?;
383+ if self.nalu.num_slice_groups_minus1 > 0 {
384+ return Err(SynthesizerError::Unsupported);
385+ }
386+
387+ self.ue(self.nalu.num_ref_idx_l0_default_active_minus1)?;
388+ self.ue(self.nalu.num_ref_idx_l1_default_active_minus1)?;
389+ self.u(1, self.nalu.weighted_pred_flag)?;
390+ self.u(2, self.nalu.weighted_bipred_idc)?;
391+ self.se(self.nalu.pic_init_qp_minus26)?;
392+ self.se(self.nalu.pic_init_qs_minus26)?;
393+ self.se(self.nalu.chroma_qp_index_offset)?;
394+ self.u(1, self.nalu.deblocking_filter_control_present_flag)?;
395+ self.u(1, self.nalu.constrained_intra_pred_flag)?;
396+ self.u(1, self.nalu.redundant_pic_cnt_present_flag)?;
397+
398+ if !(self.nalu.transform_8x8_mode_flag
399+ || self.nalu.pic_scaling_matrix_present_flag
400+ || self.nalu.second_chroma_qp_index_offset != 0)
401+ {
402+ return Ok(());
403+ }
404+
405+ self.u(1, self.nalu.transform_8x8_mode_flag)?;
406+ self.u(1, self.nalu.pic_scaling_matrix_present_flag)?;
407+
408+ if self.nalu.pic_scaling_matrix_present_flag {
409+ let mut scaling_list_count = 6;
410+ if self.nalu.transform_8x8_mode_flag {
411+ if self.nalu.sps.chroma_format_idc != 3 {
412+ scaling_list_count += 2;
413+ } else {
414+ scaling_list_count += 6;
415+ }
416+ }
417+
418+ for i in 0..scaling_list_count {
419+ // Assume if scaling lists are zeroed that they are not present.
420+ if i < 6 {
421+ if self.nalu.scaling_lists_4x4[i] == [0; 16] {
422+ self.u(1, /* seq_scaling_list_present_flag */ false)?;
423+ } else {
424+ self.u(1, /* seq_scaling_list_present_flag */ true)?;
425+ self.scaling_list(
426+ &self.nalu.scaling_lists_4x4[i],
427+ Self::default_scaling_list(i),
428+ )?;
429+ }
430+ } else if self.nalu.scaling_lists_8x8[i - 6] == [0; 64] {
431+ self.u(1, /* seq_scaling_list_present_flag */ false)?;
432+ } else {
433+ self.u(1, /* seq_scaling_list_present_flag */ true)?;
434+ self.scaling_list(
435+ &self.nalu.scaling_lists_8x8[i - 6],
436+ Self::default_scaling_list(i),
437+ )?;
438+ }
439+ }
440+ }
441+
442+ self.se(self.nalu.second_chroma_qp_index_offset)?;
443+
444+ Ok(())
445+ }
446+}
447+
448+#[cfg(test)]
449+mod tests {
450+ use std::io::Cursor;
451+
452+ use super::*;
453+ use crate::codec::h264::parser::Nalu;
454+ use crate::codec::h264::parser::NaluType;
455+ use crate::codec::h264::parser::Parser;
456+ use crate::codec::h264::parser::Profile;
457+
458+ #[test]
459+ fn synthesize_sps() {
460+ let raw_sps_buf = [0x00, 0x00, 0x00, 0x01, 0x07, 0x00, 0x00, 0x0a, 0xfb, 0x88];
461+ let mut raw_sps = Cursor::new(&raw_sps_buf[..]);
462+
463+ let nalu = Nalu::next(&mut raw_sps).unwrap();
464+ assert_eq!(nalu.header.type_, NaluType::Sps);
465+
466+ let mut parser = Parser::default();
467+ let sps = parser.parse_sps(&nalu).unwrap();
468+
469+ let mut buf = Vec::<u8>::new();
470+ Synthesizer::<'_, Sps, _>::synthesize(0, sps, &mut buf, false).unwrap();
471+
472+ assert_eq!(buf, raw_sps_buf);
473+
474+ let write_to_file = std::option_env!("CROS_CODECS_TEST_WRITE_TO_FILE") == Some("true");
475+ if write_to_file {
476+ let mut out = std::fs::File::create("sps.h264").unwrap();
477+ out.write_all(&buf).unwrap();
478+ out.flush().unwrap();
479+ }
480+
481+ let mut cursor = Cursor::new(&buf[..]);
482+ let nalu = Nalu::next(&mut cursor).unwrap();
483+
484+ let mut parser = Parser::default();
485+
486+ let sps2 = parser.parse_sps(&nalu).unwrap();
487+
488+ assert_eq!(sps, sps2);
489+ }
490+
491+ #[test]
492+ fn synthesize_sps_scaling_lists() {
493+ let sps = Sps {
494+ profile_idc: Profile::High as u8,
495+ seq_scaling_matrix_present_flag: true,
496+ scaling_lists_4x4: [[11, 20, 10, 20, 10, 22, 10, 20, 10, 20, 13, 20, 10, 20, 10, 24];
497+ 6],
498+ scaling_lists_8x8: [
499+ [
500+ 33, 20, 10, 21, 33, 20, 12, 20, 33, 23, 10, 20, 33, 20, 10, 20, 33, 24, 10, 20,
501+ 33, 20, 15, 20, 33, 20, 10, 26, 33, 20, 17, 20, 33, 28, 10, 20, 33, 20, 10, 20,
502+ 33, 29, 10, 20, 33, 20, 11, 20, 33, 20, 10, 20, 33, 20, 10, 20, 33, 20, 10, 20,
503+ 33, 20, 10, 20,
504+ ],
505+ [
506+ 10, 77, 11, 20, 10, 77, 12, 20, 10, 77, 13, 20, 10, 77, 14, 20, 10, 77, 15, 20,
507+ 10, 77, 16, 20, 10, 77, 17, 20, 10, 77, 18, 20, 10, 77, 19, 20, 10, 77, 10, 20,
508+ 10, 77, 10, 21, 10, 77, 10, 22, 10, 77, 10, 23, 10, 77, 10, 24, 10, 77, 10, 26,
509+ 10, 77, 10, 28,
510+ ],
511+ [0; 64],
512+ [0; 64],
513+ [0; 64],
514+ [0; 64],
515+ ],
516+ frame_mbs_only_flag: true,
517+ ..Default::default()
518+ };
519+
520+ let mut buf = Vec::<u8>::new();
521+ Synthesizer::<'_, Sps, _>::synthesize(0, &sps, &mut buf, false).unwrap();
522+
523+ let write_to_file = std::option_env!("CROS_CODECS_TEST_WRITE_TO_FILE") == Some("true");
524+ if write_to_file {
525+ let mut out = std::fs::File::create("sps.h264").unwrap();
526+ out.write_all(&buf).unwrap();
527+ out.flush().unwrap();
528+ }
529+
530+ let mut cursor = Cursor::new(&buf[..]);
531+ let nalu = Nalu::next(&mut cursor).unwrap();
532+
533+ let mut parser = Parser::default();
534+
535+ let sps2 = parser.parse_sps(&nalu).unwrap();
536+
537+ assert_eq!(sps.scaling_lists_4x4, sps2.scaling_lists_4x4);
538+ assert_eq!(sps.scaling_lists_8x8, sps2.scaling_lists_8x8);
539+ }
540+
541+ #[test]
542+ fn synthesize_pps() {
543+ let raw_sps_pps = [
544+ 0x00, 0x00, 0x00, 0x01, 0x07, 0x4d, 0x40, 0x0d, 0xa9, 0x18, 0x28, 0x3e, 0x60, 0x0d,
545+ 0x41, 0x80, 0x41, 0xad, 0xb0, 0xad, 0x7b, 0xdf, 0x01, 0x00, 0x00, 0x00, 0x01, 0x08,
546+ 0xde, 0x09, 0x88,
547+ ];
548+
549+ let mut buf = Vec::<u8>::new();
550+ let mut out = Cursor::new(&mut buf);
551+
552+ let mut cursor = Cursor::new(&raw_sps_pps[..]);
553+ let mut parser: Parser = Default::default();
554+
555+ while let Ok(nalu) = Nalu::next(&mut cursor) {
556+ match nalu.header.type_ {
557+ NaluType::Sps => {
558+ let sps = parser.parse_sps(&nalu).unwrap();
559+ Synthesizer::<'_, Sps, _>::synthesize(0, sps, &mut out, false).unwrap();
560+ }
561+ NaluType::Pps => {
562+ let pps = parser.parse_pps(&nalu).unwrap();
563+ Synthesizer::<'_, Pps, _>::synthesize(0, pps, &mut out, false).unwrap();
564+ }
565+ _ => panic!(),
566+ }
567+ }
568+
569+ let write_to_file = std::option_env!("CROS_CODECS_TEST_WRITE_TO_FILE") == Some("true");
570+ if write_to_file {
571+ let mut out = std::fs::File::create("sps_pps.h264").unwrap();
572+ out.write_all(&buf).unwrap();
573+ out.flush().unwrap();
574+
575+ let mut out = std::fs::File::create("sps_pps_ref.h264").unwrap();
576+ out.write_all(&raw_sps_pps).unwrap();
577+ out.flush().unwrap();
578+ }
579+
580+ assert_eq!(buf, raw_sps_pps);
581+ }
582+}
vendor/cros-codecs/src/codec/h265.rsadded+7 -0
@@ -0,0 +1,7 @@
1+// Copyright 2023 The ChromiumOS Authors
2+// Use of this source code is governed by a BSD-style license that can be
3+// found in the LICENSE file.
4+
5+pub mod dpb;
6+pub mod parser;
7+pub mod picture;
vendor/cros-codecs/src/codec/h265/dpb.rsadded+276 -0
@@ -0,0 +1,276 @@
1+// Copyright 2023 The ChromiumOS Authors
2+// Use of this source code is governed by a BSD-style license that can be
3+// found in the LICENSE file.
4+
5+use std::cell::Ref;
6+use std::cell::RefCell;
7+use std::cell::RefMut;
8+use std::rc::Rc;
9+
10+use crate::codec::h265::parser::Sps;
11+use crate::codec::h265::picture::PictureData;
12+use crate::codec::h265::picture::Reference;
13+
14+// Shortcut to refer to a DPB entry.
15+//
16+// The first member of the tuple is the `PictureData` for the frame.
17+//
18+// The second member is the backend handle of the frame.
19+#[derive(Clone, Debug)]
20+pub struct DpbEntry<T>(pub Rc<RefCell<PictureData>>, pub T);
21+
22+pub struct Dpb<T> {
23+ /// List of `PictureData` and backend handles to decoded pictures.
24+ entries: Vec<DpbEntry<T>>,
25+ /// The maximum number of pictures that can be stored.
26+ max_num_pics: usize,
27+}
28+
29+impl<T: Clone> Dpb<T> {
30+ /// Returns an iterator over the underlying H265 pictures stored in the
31+ /// DPB.
32+ pub fn pictures(&self) -> impl Iterator<Item = Ref<'_, PictureData>> {
33+ self.entries.iter().map(|h| h.0.borrow())
34+ }
35+
36+ /// Returns a mutable iterator over the underlying H265 pictures stored in
37+ /// the DPB.
38+ pub fn pictures_mut(&mut self) -> impl Iterator<Item = RefMut<'_, PictureData>> {
39+ self.entries.iter().map(|h| h.0.borrow_mut())
40+ }
41+
42+ /// Returns the length of the DPB.
43+ pub fn len(&self) -> usize {
44+ self.entries.len()
45+ }
46+
47+ pub fn is_empty(&self) -> bool {
48+ self.len() == 0
49+ }
50+
51+ /// Get a reference to the whole DPB entries.
52+ pub fn entries(&self) -> &Vec<DpbEntry<T>> {
53+ &self.entries
54+ }
55+
56+ /// Set the dpb's max num pics.
57+ pub fn set_max_num_pics(&mut self, max_num_pics: usize) {
58+ self.max_num_pics = max_num_pics;
59+ }
60+
61+ /// Get a reference to the dpb's max num pics.
62+ pub fn max_num_pics(&self) -> usize {
63+ self.max_num_pics
64+ }
65+
66+ /// Mark all pictures in the DPB as unused for reference.
67+ pub fn mark_all_as_unused_for_ref(&mut self) {
68+ for mut picture in self.pictures_mut() {
69+ picture.set_reference(Reference::None);
70+ }
71+ }
72+
73+ /// Gets the position of `needle` in the DPB, if any.
74+ fn get_position(&self, needle: &Rc<RefCell<PictureData>>) -> Option<usize> {
75+ self.entries.iter().position(|handle| Rc::ptr_eq(&handle.0, needle))
76+ }
77+
78+ /// Finds a reference picture in the DPB using `poc`.
79+ pub fn find_ref_by_poc(&self, poc: i32) -> Option<DpbEntry<T>> {
80+ let position = self.pictures().position(|p| p.is_ref() && p.pic_order_cnt_val == poc);
81+
82+ log::debug!("find_ref_by_poc: {}, found position {:?}", poc, position);
83+ Some(self.entries[position?].clone())
84+ }
85+
86+ /// Finds a reference picture in the DPB using `poc` and `mask`.
87+ pub fn find_ref_by_poc_masked(&self, poc: i32, mask: i32) -> Option<DpbEntry<T>> {
88+ let position =
89+ self.pictures().position(|p| p.is_ref() && p.pic_order_cnt_val & mask == poc);
90+
91+ log::debug!("find_ref_by_poc: {}, found position {:?}", poc, position);
92+ Some(self.entries[position?].clone())
93+ }
94+
95+ /// Finds a short term reference picture in the DPB using `poc`.
96+ pub fn find_short_term_ref_by_poc(&self, poc: i32) -> Option<DpbEntry<T>> {
97+ let position = self.pictures().position(|p| {
98+ matches!(p.reference(), Reference::ShortTerm) && p.pic_order_cnt_val == poc
99+ });
100+
101+ log::debug!("find_short_term_ref_by_poc: {}, found position {:?}", poc, position);
102+ Some(self.entries[position?].clone())
103+ }
104+
105+ /// Drains the DPB by continuously invoking the bumping process.
106+ pub fn drain(&mut self) -> Vec<DpbEntry<T>> {
107+ log::debug!("Draining the DPB.");
108+
109+ let mut pics = vec![];
110+ while let Some(pic) = self.bump(true) {
111+ pics.push(pic);
112+ }
113+
114+ pics
115+ }
116+
117+ /// Whether the DPB needs bumping. See C.5.2.2.
118+ pub fn needs_bumping(&mut self, sps: &Sps) -> bool {
119+ let num_needed_for_output = self.pictures().filter(|pic| pic.needed_for_output).count();
120+
121+ let highest_tid = sps.max_sub_layers_minus1;
122+ let max_num_reorder_pics = sps.max_num_reorder_pics[usize::from(highest_tid)];
123+ let max_latency_increase_plus1 = sps.max_latency_increase_plus1[usize::from(highest_tid)];
124+ let pic_over_max_latency = self.pictures().find(|pic| {
125+ pic.needed_for_output && pic.pic_latency_cnt >= i32::from(max_latency_increase_plus1)
126+ });
127+ let max_dec_pic_buffering =
128+ usize::from(sps.max_dec_pic_buffering_minus1[usize::from(highest_tid)]) + 1;
129+
130+ num_needed_for_output > max_num_reorder_pics.into()
131+ || (max_latency_increase_plus1 != 0 && pic_over_max_latency.is_some())
132+ || self.entries().len() >= max_dec_pic_buffering
133+ }
134+
135+ /// Find the lowest POC in the DPB that can be bumped.
136+ fn find_lowest_poc_for_bumping(&self) -> Option<DpbEntry<T>> {
137+ let lowest = self
138+ .pictures()
139+ .filter(|pic| pic.needed_for_output)
140+ .min_by_key(|pic| pic.pic_order_cnt_val)?;
141+
142+ let position = self
143+ .entries
144+ .iter()
145+ .position(|handle| handle.0.borrow().pic_order_cnt_val == lowest.pic_order_cnt_val)
146+ .unwrap();
147+
148+ Some(self.entries[position].clone())
149+ }
150+
151+ /// See C.5.2.4 "Bumping process".
152+ pub fn bump(&mut self, flush: bool) -> Option<DpbEntry<T>> {
153+ let handle = self.find_lowest_poc_for_bumping()?;
154+ let mut pic = handle.0.borrow_mut();
155+
156+ pic.needed_for_output = false;
157+ log::debug!("Bumping POC {} from the dpb", pic.pic_order_cnt_val);
158+ log::trace!("{:#?}", pic);
159+
160+ if !pic.is_ref() || flush {
161+ let index = self.get_position(&handle.0).unwrap();
162+
163+ log::debug!(
164+ "Removed POC {} from the dpb: reference: {}, flush: {}",
165+ pic.pic_order_cnt_val,
166+ pic.is_ref(),
167+ flush
168+ );
169+ log::trace!("{:#?}", pic);
170+
171+ self.entries.remove(index);
172+ }
173+
174+ Some(handle.clone())
175+ }
176+
177+ /// See C.5.2.3. Happens when we are done decoding the picture.
178+ pub fn needs_additional_bumping(&mut self, sps: &Sps) -> bool {
179+ let num_needed_for_output = self.pictures().filter(|pic| pic.needed_for_output).count();
180+ let highest_tid = sps.max_sub_layers_minus1;
181+
182+ let max_num_reorder_pics = sps.max_num_reorder_pics[usize::from(highest_tid)];
183+ let max_latency_increase_plus1 = sps.max_latency_increase_plus1[usize::from(highest_tid)];
184+
185+ let pic_over_max_latency = self.pictures().find(|pic| {
186+ pic.needed_for_output && pic.pic_latency_cnt >= i32::from(max_latency_increase_plus1)
187+ });
188+
189+ num_needed_for_output > max_num_reorder_pics.into()
190+ || (max_latency_increase_plus1 != 0 && pic_over_max_latency.is_some())
191+ }
192+
193+ /// Clears the DPB, dropping all the pictures.
194+ pub fn clear(&mut self) {
195+ log::debug!("Clearing the DPB");
196+
197+ let max_num_pics = self.max_num_pics;
198+
199+ *self = Default::default();
200+ self.max_num_pics = max_num_pics;
201+ }
202+
203+ /// Removes all pictures which are marked as "not needed for output" and
204+ /// "unused for reference". See C.5.2.2
205+ pub fn remove_unused(&mut self) {
206+ log::debug!("Removing unused pictures from DPB.");
207+ self.entries.retain(|e| {
208+ let pic = e.0.borrow();
209+ let retain = pic.needed_for_output || pic.is_ref();
210+ log::debug!("Retaining pic POC: {}: {}", pic.pic_order_cnt_val, retain);
211+ retain
212+ })
213+ }
214+
215+ /// Store a picture and its backend handle in the DPB.
216+ pub fn store_picture(
217+ &mut self,
218+ picture: Rc<RefCell<PictureData>>,
219+ handle: T,
220+ ) -> Result<(), String> {
221+ if self.entries.len() >= self.max_num_pics {
222+ return Err("Can't add a picture to the DPB: DPB is full.".into());
223+ }
224+
225+ let mut pic = picture.borrow_mut();
226+ log::debug!(
227+ "Stored picture POC {:?}, the DPB length is {:?}",
228+ pic.pic_order_cnt_val,
229+ self.entries.len()
230+ );
231+
232+ if pic.pic_output_flag {
233+ pic.needed_for_output = true;
234+ pic.pic_latency_cnt = 0;
235+ } else {
236+ pic.needed_for_output = false;
237+ }
238+
239+ // C.3.4.
240+ // After all the slices of the current picture have been decoded, this
241+ // picture is marked as "used for short-term reference".
242+ pic.set_reference(Reference::ShortTerm);
243+ drop(pic);
244+
245+ for mut pic in self.pictures_mut() {
246+ pic.pic_latency_cnt += 1;
247+ }
248+
249+ self.entries.push(DpbEntry(picture, handle));
250+
251+ Ok(())
252+ }
253+
254+ /// Returns all the references in the DPB.
255+ pub fn get_all_references(&self) -> Vec<DpbEntry<T>> {
256+ self.entries.iter().filter(|e| e.0.borrow().is_ref()).cloned().collect()
257+ }
258+}
259+
260+impl<T: Clone> Default for Dpb<T> {
261+ fn default() -> Self {
262+ // See https://github.com/rust-lang/rust/issues/26925 on why this can't
263+ // be derived.
264+ Self { entries: Default::default(), max_num_pics: Default::default() }
265+ }
266+}
267+
268+impl<T: Clone> std::fmt::Debug for Dpb<T> {
269+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
270+ let pics = self.entries.iter().map(|h| &h.0).enumerate().collect::<Vec<_>>();
271+ f.debug_struct("Dpb")
272+ .field("pictures", &pics)
273+ .field("max_num_pics", &self.max_num_pics)
274+ .finish()
275+ }
276+}
vendor/cros-codecs/src/codec/h265/parser.rsadded+4784 -0

Diff too large; view file

@@ -0,0 +1,4784 @@
1+// Copyright 2023 The ChromiumOS Authors
2+// Use of this source code is governed by a BSD-style license that can be
3+// found in the LICENSE file.
4+
5+//! An Annex B h.265 parser.
6+//!
7+//! Parses VPSs, SPSs, PPSs and Slices from NALUs.
8+
9+use std::collections::BTreeMap;
10+use std::io::Read;
11+use std::io::Seek;
12+use std::io::SeekFrom;
13+use std::rc::Rc;
14+
15+use crate::bitstream_utils::BitReader;
16+use crate::codec::h264::nalu;
17+use crate::codec::h264::nalu::Header;
18+use crate::codec::h264::parser::Point;
19+use crate::codec::h264::parser::Rect;
20+
21+// Given the max VPS id.
22+const MAX_VPS_COUNT: usize = 16;
23+// Given the max SPS id.
24+const MAX_SPS_COUNT: usize = 16;
25+// Given the max PPS id.
26+const MAX_PPS_COUNT: usize = 64;
27+// 7.4.7.1
28+const MAX_REF_IDX_ACTIVE: u32 = 15;
29+
30+// 7.4.3.2.1:
31+// num_short_term_ref_pic_sets specifies the number of st_ref_pic_set( ) syntax
32+// structures included in the SPS. The value of num_short_term_ref_pic_sets
33+// shall be in the range of 0 to 64, inclusive.
34+// NOTE 5 – A decoder should allocate memory for a total number of
35+// num_short_term_ref_pic_sets + 1 st_ref_pic_set( ) syntax structures since
36+// there may be a st_ref_pic_set( ) syntax structure directly signalled in the
37+// slice headers of a current picture. A st_ref_pic_set( ) syntax structure
38+// directly signalled in the slice headers of a current picture has an index
39+// equal to num_short_term_ref_pic_sets.
40+const MAX_SHORT_TERM_REF_PIC_SETS: usize = 65;
41+
42+// 7.4.3.2.1:
43+const MAX_LONG_TERM_REF_PIC_SETS: usize = 32;
44+
45+// From table 7-5.
46+const DEFAULT_SCALING_LIST_0: [u8; 16] = [16; 16];
47+
48+// From Table 7-6.
49+const DEFAULT_SCALING_LIST_1: [u8; 64] = [
50+ 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 17, 16, 17, 16, 17, 18, 17, 18, 18, 17, 18, 21, 19, 20,
51+ 21, 20, 19, 21, 24, 22, 22, 24, 24, 22, 22, 24, 25, 25, 27, 30, 27, 25, 25, 29, 31, 35, 35, 31,
52+ 29, 36, 41, 44, 41, 36, 47, 54, 54, 47, 65, 70, 65, 88, 88, 115,
53+];
54+
55+// From Table 7-6.
56+const DEFAULT_SCALING_LIST_2: [u8; 64] = [
57+ 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 17, 18, 18, 18, 18, 18, 18, 20, 20, 20,
58+ 20, 20, 20, 20, 24, 24, 24, 24, 24, 24, 24, 24, 25, 25, 25, 25, 25, 25, 25, 28, 28, 28, 28, 28,
59+ 28, 33, 33, 33, 33, 33, 41, 41, 41, 41, 54, 54, 54, 71, 71, 91,
60+];
61+
62+/// Table 7-1 – NAL unit type codes and NAL unit type classes
63+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord)]
64+pub enum NaluType {
65+ #[default]
66+ TrailN = 0,
67+ TrailR = 1,
68+ TsaN = 2,
69+ TsaR = 3,
70+ StsaN = 4,
71+ StsaR = 5,
72+ RadlN = 6,
73+ RadlR = 7,
74+ RaslN = 8,
75+ RaslR = 9,
76+ RsvVclN10 = 10,
77+ RsvVclR11 = 11,
78+ RsvVclN12 = 12,
79+ RsvVclR13 = 13,
80+ RsvVclN14 = 14,
81+ RsvVclR15 = 15,
82+ BlaWLp = 16,
83+ BlaWRadl = 17,
84+ BlaNLp = 18,
85+ IdrWRadl = 19,
86+ IdrNLp = 20,
87+ CraNut = 21,
88+ RsvIrapVcl22 = 22,
89+ RsvIrapVcl23 = 23,
90+ RsvVcl24 = 24,
91+ RsvVcl25 = 25,
92+ RsvVcl26 = 26,
93+ RsvVcl27 = 27,
94+ RsvVcl28 = 28,
95+ RsvVcl29 = 29,
96+ RsvVcl30 = 30,
97+ RsvVcl31 = 31,
98+ VpsNut = 32,
99+ SpsNut = 33,
100+ PpsNut = 34,
101+ AudNut = 35,
102+ EosNut = 36,
103+ EobNut = 37,
104+ FdNut = 38,
105+ PrefixSeiNut = 39,
106+ SuffixSeiNut = 40,
107+ RsvNvcl41 = 41,
108+ RsvNvcl42 = 42,
109+ RsvNvcl43 = 43,
110+ RsvNvcl44 = 44,
111+ RsvNvcl45 = 45,
112+ RsvNvcl46 = 46,
113+ RsvNvcl47 = 47,
114+}
115+
116+impl TryFrom<u32> for NaluType {
117+ type Error = String;
118+
119+ fn try_from(value: u32) -> Result<Self, Self::Error> {
120+ match value {
121+ 0 => Ok(NaluType::TrailN),
122+ 1 => Ok(NaluType::TrailR),
123+ 2 => Ok(NaluType::TsaN),
124+ 3 => Ok(NaluType::TsaR),
125+ 4 => Ok(NaluType::StsaN),
126+ 5 => Ok(NaluType::StsaR),
127+ 6 => Ok(NaluType::RadlN),
128+ 7 => Ok(NaluType::RadlR),
129+ 8 => Ok(NaluType::RaslN),
130+ 9 => Ok(NaluType::RaslR),
131+ 10 => Ok(NaluType::RsvVclN10),
132+ 11 => Ok(NaluType::RsvVclR11),
133+ 12 => Ok(NaluType::RsvVclN12),
134+ 13 => Ok(NaluType::RsvVclR13),
135+ 14 => Ok(NaluType::RsvVclN14),
136+ 15 => Ok(NaluType::RsvVclR15),
137+ 16 => Ok(NaluType::BlaWLp),
138+ 17 => Ok(NaluType::BlaWRadl),
139+ 18 => Ok(NaluType::BlaNLp),
140+ 19 => Ok(NaluType::IdrWRadl),
141+ 20 => Ok(NaluType::IdrNLp),
142+ 21 => Ok(NaluType::CraNut),
143+ 22 => Ok(NaluType::RsvIrapVcl22),
144+ 23 => Ok(NaluType::RsvIrapVcl23),
145+ 24 => Ok(NaluType::RsvVcl24),
146+ 25 => Ok(NaluType::RsvVcl25),
147+ 26 => Ok(NaluType::RsvVcl26),
148+ 27 => Ok(NaluType::RsvVcl27),
149+ 28 => Ok(NaluType::RsvVcl28),
150+ 29 => Ok(NaluType::RsvVcl29),
151+ 30 => Ok(NaluType::RsvVcl30),
152+ 31 => Ok(NaluType::RsvVcl31),
153+ 32 => Ok(NaluType::VpsNut),
154+ 33 => Ok(NaluType::SpsNut),
155+ 34 => Ok(NaluType::PpsNut),
156+ 35 => Ok(NaluType::AudNut),
157+ 36 => Ok(NaluType::EosNut),
158+ 37 => Ok(NaluType::EobNut),
159+ 38 => Ok(NaluType::FdNut),
160+ 39 => Ok(NaluType::PrefixSeiNut),
161+ 40 => Ok(NaluType::SuffixSeiNut),
162+ 41 => Ok(NaluType::RsvNvcl41),
163+ 42 => Ok(NaluType::RsvNvcl42),
164+ 43 => Ok(NaluType::RsvNvcl43),
165+ 44 => Ok(NaluType::RsvNvcl44),
166+ 45 => Ok(NaluType::RsvNvcl45),
167+ 46 => Ok(NaluType::RsvNvcl46),
168+ 47 => Ok(NaluType::RsvNvcl47),
169+ _ => Err(format!("Invalid NaluType {}", value)),
170+ }
171+ }
172+}
173+
174+impl NaluType {
175+ /// Whether this is an IDR NALU.
176+ pub fn is_idr(&self) -> bool {
177+ matches!(self, Self::IdrWRadl | Self::IdrNLp)
178+ }
179+
180+ /// Whether this is an IRAP NALU.
181+ pub fn is_irap(&self) -> bool {
182+ let type_ = *self as u32;
183+ type_ >= Self::BlaWLp as u32 && type_ <= Self::RsvIrapVcl23 as u32
184+ }
185+
186+ /// Whether this is a BLA NALU.
187+ pub fn is_bla(&self) -> bool {
188+ let type_ = *self as u32;
189+ type_ >= Self::BlaWLp as u32 && type_ <= Self::BlaNLp as u32
190+ }
191+
192+ /// Whether this is a CRA NALU.
193+ pub fn is_cra(&self) -> bool {
194+ matches!(self, Self::CraNut)
195+ }
196+
197+ /// Whether this is a RADL NALU.
198+ pub fn is_radl(&self) -> bool {
199+ matches!(self, Self::RadlN | Self::RadlR)
200+ }
201+
202+ /// Whether this is a RASL NALU.
203+ pub fn is_rasl(&self) -> bool {
204+ matches!(self, Self::RaslN | Self::RaslR)
205+ }
206+
207+ //// Whether this is a SLNR NALU.
208+ pub fn is_slnr(&self) -> bool {
209+ // From the specification:
210+ // If a picture has nal_unit_type equal to TRAIL_N, TSA_N, STSA_N,
211+ // RADL_N, RASL_N, RSV_VCL_N10, RSV_VCL_N12 or RSV_VCL_N14, the picture
212+ // is an SLNR picture. Otherwise, the picture is a sub-layer reference
213+ // picture.
214+ matches!(
215+ self,
216+ Self::TrailN
217+ | Self::TsaN
218+ | Self::StsaN
219+ | Self::RadlN
220+ | Self::RaslN
221+ | Self::RsvVclN10
222+ | Self::RsvVclN12
223+ | Self::RsvVclN14
224+ )
225+ }
226+}
227+
228+#[derive(Clone, Debug, Default, PartialEq, Eq)]
229+pub struct NaluHeader {
230+ /// The NALU type.
231+ pub type_: NaluType,
232+ /// Specifies the identifier of the layer to which a VCL NAL unit belongs or
233+ /// the identifier of a layer to which a non-VCL NAL unit applies.
234+ pub nuh_layer_id: u8,
235+ /// Minus 1 specifies a temporal identifier for the NAL unit. The value of
236+ /// nuh_temporal_id_plus1 shall not be equal to 0.
237+ pub nuh_temporal_id_plus1: u8,
238+}
239+
240+impl NaluHeader {
241+ pub fn nuh_temporal_id(&self) -> u8 {
242+ self.nuh_temporal_id_plus1.saturating_sub(1)
243+ }
244+}
245+
246+impl Header for NaluHeader {
247+ fn parse<T: AsRef<[u8]>>(cursor: &mut std::io::Cursor<T>) -> Result<Self, String> {
248+ let mut data = [0u8; 2];
249+ cursor.read_exact(&mut data).map_err(|_| String::from("Broken Data"))?;
250+ let mut r = BitReader::new(&data, false);
251+ let _ = cursor.seek(SeekFrom::Current(-1 * data.len() as i64));
252+
253+ // Skip forbidden_zero_bit
254+ r.skip_bits(1)?;
255+
256+ Ok(Self {
257+ type_: NaluType::try_from(r.read_bits::<u32>(6)?)?,
258+ nuh_layer_id: r.read_bits::<u8>(6)?,
259+ nuh_temporal_id_plus1: r.read_bits::<u8>(3)?,
260+ })
261+ }
262+
263+ fn is_end(&self) -> bool {
264+ matches!(self.type_, NaluType::EosNut | NaluType::EobNut)
265+ }
266+
267+ fn len(&self) -> usize {
268+ // 7.3.1.2
269+ 2
270+ }
271+}
272+
273+pub type Nalu<'a> = nalu::Nalu<'a, NaluHeader>;
274+
275+/// H265 levels as defined by table A.8.
276+/// `general_level_idc` and `sub_layer_level_idc[ OpTid ]` shall be set equal to a
277+/// value of 30 times the level number specified in Table A.8
278+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord)]
279+pub enum Level {
280+ #[default]
281+ L1 = 30,
282+ L2 = 60,
283+ L2_1 = 63,
284+ L3 = 90,
285+ L3_1 = 93,
286+ L4 = 120,
287+ L4_1 = 123,
288+ L5 = 150,
289+ L5_1 = 153,
290+ L5_2 = 156,
291+ L6 = 180,
292+ L6_1 = 183,
293+ L6_2 = 186,
294+}
295+
296+impl TryFrom<u8> for Level {
297+ type Error = String;
298+
299+ fn try_from(value: u8) -> Result<Self, Self::Error> {
300+ match value {
301+ 30 => Ok(Level::L1),
302+ 60 => Ok(Level::L2),
303+ 63 => Ok(Level::L2_1),
304+ 90 => Ok(Level::L3),
305+ 93 => Ok(Level::L3_1),
306+ 120 => Ok(Level::L4),
307+ 123 => Ok(Level::L4_1),
308+ 150 => Ok(Level::L5),
309+ 153 => Ok(Level::L5_1),
310+ 156 => Ok(Level::L5_2),
311+ 180 => Ok(Level::L6),
312+ 183 => Ok(Level::L6_1),
313+ 186 => Ok(Level::L6_2),
314+ _ => Err(format!("Invalid Level {}", value)),
315+ }
316+ }
317+}
318+
319+/// H265 profiles. See A.3.
320+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord)]
321+pub enum Profile {
322+ #[default]
323+ Main = 1,
324+ Main10 = 2,
325+ MainStill = 3,
326+ RangeExtensions = 4,
327+ HighThroughput = 5,
328+ MultiviewMain = 6,
329+ ScalableMain = 7,
330+ ThreeDMain = 8,
331+ ScreenContentCoding = 9,
332+ ScalableRangeExtensions = 10,
333+ HighThroughputScreenContentCoding = 11,
334+}
335+
336+impl TryFrom<u8> for Profile {
337+ type Error = String;
338+
339+ fn try_from(value: u8) -> Result<Self, Self::Error> {
340+ match value {
341+ 1 => Ok(Profile::Main),
342+ 2 => Ok(Profile::Main10),
343+ 3 => Ok(Profile::MainStill),
344+ 4 => Ok(Profile::RangeExtensions),
345+ 5 => Ok(Profile::HighThroughput),
346+ 6 => Ok(Profile::MultiviewMain),
347+ 7 => Ok(Profile::ScalableMain),
348+ 8 => Ok(Profile::ThreeDMain),
349+ 9 => Ok(Profile::ScreenContentCoding),
350+ 10 => Ok(Profile::ScalableRangeExtensions),
351+ 11 => Ok(Profile::HighThroughputScreenContentCoding),
352+ _ => Err(format!("Invalid Profile {}", value)),
353+ }
354+ }
355+}
356+
357+/// A H.265 Video Parameter Set.
358+#[derive(Clone, Debug, PartialEq, Eq)]
359+pub struct Vps {
360+ /// Identifies the VPS for reference by other syntax elements.
361+ pub video_parameter_set_id: u8,
362+ /// If vps_base_layer_internal_flag is equal to 1 and
363+ /// vps_base_layer_available_flag is equal to 1, the base layer is present
364+ /// in the bitstream.
365+ pub base_layer_internal_flag: bool,
366+ /// See `base_layer_internal_flag`.
367+ pub base_layer_available_flag: bool,
368+ /// Plus 1 specifies the maximum allowed number of layers in each CVS
369+ /// referring to the VPS.
370+ pub max_layers_minus1: u8,
371+ /// Plus 1 specifies the maximum number of temporal sub-layers that may be
372+ /// present in each CVS referring to the VPS.
373+ pub max_sub_layers_minus1: u8,
374+ /// When vps_max_sub_layers_minus1 is greater than 0, specifies whether
375+ /// inter prediction is additionally restricted for CVSs referring to the
376+ /// VPS.
377+ pub temporal_id_nesting_flag: bool,
378+ /// ProfileTierLevel() data.
379+ pub profile_tier_level: ProfileTierLevel,
380+ /// When true, specifies that `vps_max_dec_pic_buffering_minus1[ i ]`,
381+ /// `vps_max_num_reorder_pics[ i ]` and `vps_max_latency_increase_plus1[ i ]`
382+ /// are present for vps_max_sub_layers_ minus1 + 1 sub-layers.
383+ /// vps_sub_layer_ordering_info_present_flag equal to 0 specifies that the
384+ /// values of `vps_max_dec_pic_buffering_minus1[ vps_max_sub_layers_minus1 ]`,
385+ /// vps_max_num_reorder_pics[ vps_max_sub_ layers_minus1 ] and
386+ /// `vps_max_latency_increase_plus1[ vps_max_sub_layers_minus1 ]` apply to all
387+ /// sub-layers
388+ pub sub_layer_ordering_info_present_flag: bool,
389+ /// `max_dec_pic_buffering_minus1[i]` plus 1 specifies the maximum required
390+ /// size of the decoded picture buffer for the CVS in units of picture
391+ /// storage buffers when HighestTid is equal to i.
392+ pub max_dec_pic_buffering_minus1: [u32; 7],
393+ /// Indicates the maximum allowed number of pictures with PicOutputFlag
394+ /// equal to 1 that can precede any picture with PicOutputFlag equal to 1 in
395+ /// the CVS in decoding order and follow that picture with PicOutputFlag
396+ /// equal to 1 in output order when HighestTid is equal to i.
397+ pub max_num_reorder_pics: [u32; 7],
398+ /// When true, `max_latency_increase_plus1[i]` is used to compute the value of
399+ /// `VpsMaxLatencyPictures[ i ]`, which specifies the maximum number of
400+ /// pictures with PicOutputFlag equal to 1 that can precede any picture with
401+ /// PicOutputFlag equal to 1 in the CVS in output order and follow that
402+ /// picture with PicOutputFlag equal to 1 in decoding order when HighestTid
403+ /// is equal to i.
404+ pub max_latency_increase_plus1: [u32; 7],
405+ /// Specifies the maximum allowed value of nuh_layer_id of all NAL units in
406+ /// each CVS referring to the VPS.
407+ pub max_layer_id: u8,
408+ /// num_layer_sets_minus1 plus 1 specifies the number of layer sets that are
409+ /// specified by the VPS.
410+ pub num_layer_sets_minus1: u32,
411+ /// When true, specifies that num_units_in_tick, time_scale,
412+ /// poc_proportional_to_timing_flag and num_hrd_parameters are present in
413+ /// the VPS.
414+ pub timing_info_present_flag: bool,
415+ /// The number of time units of a clock operating at the frequency
416+ /// vps_time_scale Hz that corresponds to one increment (called a clock
417+ /// tick) of a clock tick counter. The value of vps_num_units_in_tick shall
418+ /// be greater than 0. A clock tick, in units of seconds, is equal to the
419+ /// quotient of vps_num_units_in_tick divided by vps_time_scale. For
420+ /// example, when the picture rate of a video signal is 25 Hz,
421+ /// vps_time_scale may be equal to 27 000 000 and vps_num_units_in_tick may
422+ /// be equal to 1 080 000, and consequently a clock tick may be 0.04
423+ /// seconds.
424+ pub num_units_in_tick: u32,
425+ /// The number of time units that pass in one second. For example, a time
426+ /// coordinate system that measures time using a 27 MHz clock has a
427+ /// vps_time_scale of 27 000 000.
428+ pub time_scale: u32,
429+ /// When true, indicates that the picture order count value for each picture
430+ /// in the CVS that is not the first picture in the CVS, in decoding order,
431+ /// is proportional to the output time of the picture relative to the output
432+ /// time of the first picture in the CVS. When false, indicates that the
433+ /// picture order count value for each picture in the CVS that is not the
434+ /// first picture in the CVS, in decoding order, may or may not be
435+ /// proportional to the output time of the picture relative to the output
436+ /// time of the first picture in the CVS.
437+ pub poc_proportional_to_timing_flag: bool,
438+ /// num_ticks_poc_diff_one_minus1 plus 1 specifies the number of clock ticks
439+ /// corresponding to a difference of picture order count values equal to 1.
440+ pub num_ticks_poc_diff_one_minus1: u32,
441+ /// Specifies the number of hrd_parameters( ) syntax structures present in
442+ /// the VPS RBSP before the vps_extension_flag syntax element.
443+ pub num_hrd_parameters: u32,
444+ /// `hrd_layer_set_idx[ i ]` specifies the index, into the list of layer sets
445+ /// specified by the VPS, of the layer set to which the i-th hrd_parameters(
446+ /// ) syntax structure in the VPS applies.
447+ pub hrd_layer_set_idx: Vec<u16>,
448+ /// `cprms_present_flag[ i ]` equal to true specifies that the HRD parameters
449+ /// that are common for all sub-layers are present in the i-th
450+ /// hrd_parameters( ) syntax structure in the VPS. `cprms_present_flag[ i ]`
451+ /// equal to false specifies that the HRD parameters that are common for all
452+ /// sub-layers are not present in the i-th hrd_parameters( ) syntax
453+ /// structure in the VPS and are derived to be the same as the ( i − 1 )-th
454+ /// hrd_parameters( ) syntax structure in the VPS. `cprms_present_flag[ 0 ]`
455+ /// is inferred to be equal to true.
456+ pub cprms_present_flag: Vec<bool>,
457+ /// The hrd_parameters() data.
458+ pub hrd_parameters: Vec<HrdParams>,
459+ /// When false, specifies that no vps_extension_data_flag syntax elements
460+ /// are present in the VPS RBSP syntax structure. When true, specifies that
461+ /// there are vps_extension_data_flag syntax elements present in the VPS
462+ /// RBSP syntax structure. Decoders conforming to a profile specified in
463+ /// Annex A but not supporting the INBLD capability specified in Annex F
464+ /// shall ignore all data that follow the value 1 for vps_extension_flag in
465+ /// a VPS NAL unit.
466+ pub extension_flag: bool,
467+}
468+
469+impl Default for Vps {
470+ fn default() -> Self {
471+ Self {
472+ video_parameter_set_id: Default::default(),
473+ base_layer_internal_flag: Default::default(),
474+ base_layer_available_flag: Default::default(),
475+ max_layers_minus1: Default::default(),
476+ max_sub_layers_minus1: Default::default(),
477+ temporal_id_nesting_flag: Default::default(),
478+ profile_tier_level: Default::default(),
479+ sub_layer_ordering_info_present_flag: Default::default(),
480+ max_dec_pic_buffering_minus1: Default::default(),
481+ max_num_reorder_pics: Default::default(),
482+ max_latency_increase_plus1: Default::default(),
483+ max_layer_id: Default::default(),
484+ num_layer_sets_minus1: Default::default(),
485+ timing_info_present_flag: Default::default(),
486+ num_units_in_tick: Default::default(),
487+ time_scale: Default::default(),
488+ poc_proportional_to_timing_flag: Default::default(),
489+ num_ticks_poc_diff_one_minus1: Default::default(),
490+ num_hrd_parameters: Default::default(),
491+ hrd_layer_set_idx: Default::default(),
492+ cprms_present_flag: vec![true],
493+ hrd_parameters: Default::default(),
494+ extension_flag: Default::default(),
495+ }
496+ }
497+}
498+
499+#[derive(Clone, Debug, Default, PartialEq, Eq)]
500+pub struct ProfileTierLevel {
501+ /// Specifies the context for the interpretation of general_profile_idc and
502+ /// `general_profile_compatibility_flag[ j ]` for all values of j in the range
503+ /// of 0 to 31, inclusive.
504+ pub general_profile_space: u8,
505+ /// Specifies the tier context for the interpretation of general_level_idc
506+ /// as specified in Annex A.
507+ pub general_tier_flag: bool,
508+ /// When general_profile_space is equal to 0, indicates a profile to which
509+ /// the CVS conforms as specified in Annex A. Bitstreams shall not contain
510+ /// values of general_profile_idc other than those specified in Annex A.
511+ /// Other values of general_profile_idc are reserved for future use by ITU-T
512+ /// | ISO/IEC.
513+ pub general_profile_idc: u8,
514+ /// `general_profile_compatibility_flag[ j ]` equal to true, when
515+ /// general_profile_space is false, indicates that the CVS conforms to the
516+ /// profile indicated by general_profile_idc equal to j as specified in
517+ /// Annex A.
518+ pub general_profile_compatibility_flag: [bool; 32],
519+ /// general_progressive_source_flag and general_interlaced_source_flag are
520+ /// interpreted as follows:
521+ ///
522+ /// –If general_progressive_source_flag is true and
523+ /// general_interlaced_source_flag is false, the source scan type of the
524+ /// pictures in the CVS should be interpreted as progressive only.
525+ ///
526+ /// –Otherwise, if general_progressive_source_flag is false and
527+ /// general_interlaced_source_flag is true, the source scan type of the
528+ /// pictures in the CVS should be interpreted as interlaced only.
529+ ///
530+ /// –Otherwise, if general_progressive_source_flag is false and
531+ /// general_interlaced_source_flag is false, the source scan type of the
532+ /// pictures in the CVS should be interpreted as unknown or unspecified.
533+ ///
534+ /// –Otherwise (general_progressive_source_flag is true and
535+ /// general_interlaced_source_flag is true), the source scan type of each
536+ /// picture in the CVS is indicated at the picture level using the syntax
537+ /// element source_scan_type in a picture timing SEI message.
538+ pub general_progressive_source_flag: bool,
539+ /// See `general_progressive_source_flag`.
540+ pub general_interlaced_source_flag: bool,
541+ /// If true, specifies that there are no frame packing arrangement SEI
542+ /// messages, segmented rectangular frame packing arrangement SEI messages,
543+ /// equirectangular projection SEI messages, or cubemap projection SEI
544+ /// messages present in the CVS. If false, indicates that there may or may
545+ /// not be one or more frame packing arrangement SEI messages, segmented
546+ /// rectangular frame packing arrangement SEI messages, equirectangular
547+ /// projection SEI messages, or cubemap projection SEI messages present in
548+ /// the CVS.
549+ pub general_non_packed_constraint_flag: bool,
550+ /// When true, specifies that field_seq_flag is false. When false, indicates
551+ /// that field_seq_flag may or may not be false.
552+ pub general_frame_only_constraint_flag: bool,
553+ /// See Annex A.
554+ pub general_max_12bit_constraint_flag: bool,
555+ /// See Annex A.
556+ pub general_max_10bit_constraint_flag: bool,
557+ /// See Annex A.
558+ pub general_max_8bit_constraint_flag: bool,
559+ /// See Annex A.
560+ pub general_max_422chroma_constraint_flag: bool,
561+ /// See Annex A.
562+ pub general_max_420chroma_constraint_flag: bool,
563+ /// See Annex A.
564+ pub general_max_monochrome_constraint_flag: bool,
565+ /// See Annex A.
566+ pub general_intra_constraint_flag: bool,
567+ /// See Annex A.
568+ pub general_lower_bit_rate_constraint_flag: bool,
569+ /// See Annex A.
570+ pub general_max_14bit_constraint_flag: bool,
571+ /// See Annex A.
572+ pub general_one_picture_only_constraint_flag: bool,
573+ /// When true, specifies that the INBLD capability as specified in Annex F
574+ /// is required for decoding of the layer to which the profile_tier_level( )
575+ /// syntax structure applies. When false, specifies that the INBLD
576+ /// capability as specified in Annex F is not required for decoding of the
577+ /// layer to which the profile_tier_level( ) syntax structure applies.
578+ pub general_inbld_flag: bool,
579+ /// Indicates a level to which the CVS conforms as specified in Annex A.
580+ pub general_level_idc: Level,
581+ /// Sub-layer syntax element.
582+ pub sub_layer_profile_present_flag: [bool; 6],
583+ /// Sub-layer syntax element.
584+ pub sub_layer_level_present_flag: [bool; 6],
585+ /// Sub-layer syntax element.
586+ pub sub_layer_profile_space: [u8; 6],
587+ /// Sub-layer syntax element.
588+ pub sub_layer_tier_flag: [bool; 6],
589+ /// Sub-layer syntax element.
590+ pub sub_layer_profile_idc: [u8; 6],
591+ /// Sub-layer syntax element.
592+ pub sub_layer_profile_compatibility_flag: [[bool; 32]; 6],
593+ /// Sub-layer syntax element.
594+ pub sub_layer_progressive_source_flag: [bool; 6],
595+ /// Sub-layer syntax element.
596+ pub sub_layer_interlaced_source_flag: [bool; 6],
597+ /// Sub-layer syntax element.
598+ pub sub_layer_non_packed_constraint_flag: [bool; 6],
599+ /// Sub-layer syntax element.
600+ pub sub_layer_frame_only_constraint_flag: [bool; 6],
601+ /// Sub-layer syntax element.
602+ pub sub_layer_max_12bit_constraint_flag: [bool; 6],
603+ /// Sub-layer syntax element.
604+ pub sub_layer_max_10bit_constraint_flag: [bool; 6],
605+ /// Sub-layer syntax element.
606+ pub sub_layer_max_8bit_constraint_flag: [bool; 6],
607+ /// Sub-layer syntax element.
608+ pub sub_layer_max_422chroma_constraint_flag: [bool; 6],
609+ /// Sub-layer syntax element.
610+ pub sub_layer_max_420chroma_constraint_flag: [bool; 6],
611+ /// Sub-layer syntax element.
612+ pub sub_layer_max_monochrome_constraint_flag: [bool; 6],
613+ /// Sub-layer syntax element.
614+ pub sub_layer_intra_constraint_flag: [bool; 6],
615+ /// Sub-layer syntax element.
616+ pub sub_layer_one_picture_only_constraint_flag: [bool; 6],
617+ /// Sub-layer syntax element.
618+ pub sub_layer_lower_bit_rate_constraint_flag: [bool; 6],
619+ /// Sub-layer syntax element.
620+ pub sub_layer_max_14bit_constraint_flag: [bool; 6],
vendor/cros-codecs/src/codec/h265/picture.rsadded+154 -0

Diff too large; view file

vendor/cros-codecs/src/codec/vp8.rsadded+11 -0

Diff too large; view file

vendor/cros-codecs/src/codec/vp8/bool_decoder.rsadded+309 -0

Diff too large; view file

vendor/cros-codecs/src/codec/vp8/parser.rsadded+811 -0

Diff too large; view file

vendor/cros-codecs/src/codec/vp8/probs.rsadded+365 -0

Diff too large; view file

vendor/cros-codecs/src/codec/vp9.rsadded+10 -0

Diff too large; view file

vendor/cros-codecs/src/codec/vp9/lookups.rsadded+116 -0

Diff too large; view file

vendor/cros-codecs/src/codec/vp9/parser.rsadded+1478 -0

Diff too large; view file

vendor/cros-codecs/src/decoder.rsadded+266 -0

Diff too large; view file

vendor/cros-codecs/src/decoder/stateless.rsadded+495 -0

Diff too large; view file

vendor/cros-codecs/src/decoder/stateless/av1.rsadded+565 -0

Diff too large; view file

vendor/cros-codecs/src/decoder/stateless/av1/dummy.rsadded+69 -0

Diff too large; view file

vendor/cros-codecs/src/decoder/stateless/av1/v4l2.rsadded+169 -0

Diff too large; view file

vendor/cros-codecs/src/decoder/stateless/av1/vaapi.rsadded+625 -0

Diff too large; view file

vendor/cros-codecs/src/decoder/stateless/h264.rsadded+1501 -0

Diff too large; view file

vendor/cros-codecs/src/decoder/stateless/h264/dummy.rsadded+75 -0

Diff too large; view file

vendor/cros-codecs/src/decoder/stateless/h264/v4l2.rsadded+180 -0

Diff too large; view file

vendor/cros-codecs/src/decoder/stateless/h264/vaapi.rsadded+733 -0

Diff too large; view file

vendor/cros-codecs/src/decoder/stateless/h265.rsadded+1365 -0

Diff too large; view file

vendor/cros-codecs/src/decoder/stateless/h265/dummy.rsadded+74 -0

Diff too large; view file

vendor/cros-codecs/src/decoder/stateless/h265/vaapi.rsadded+980 -0

Diff too large; view file

vendor/cros-codecs/src/decoder/stateless/vp8.rsadded+364 -0

Diff too large; view file

vendor/cros-codecs/src/decoder/stateless/vp8/dummy.rsadded+53 -0

Diff too large; view file

vendor/cros-codecs/src/decoder/stateless/vp8/v4l2.rsadded+151 -0

Diff too large; view file

vendor/cros-codecs/src/decoder/stateless/vp8/vaapi.rsadded+707 -0

Diff too large; view file

vendor/cros-codecs/src/decoder/stateless/vp9.rsadded+461 -0

Diff too large; view file

vendor/cros-codecs/src/decoder/stateless/vp9/dummy.rsadded+51 -0

Diff too large; view file

vendor/cros-codecs/src/decoder/stateless/vp9/v4l2.rsadded+154 -0

Diff too large; view file

vendor/cros-codecs/src/decoder/stateless/vp9/vaapi.rsadded+651 -0

Diff too large; view file

vendor/cros-codecs/src/device.rsadded+6 -0

Diff too large; view file

vendor/cros-codecs/src/device/v4l2.rsadded+6 -0

Diff too large; view file

vendor/cros-codecs/src/device/v4l2/stateless.rsadded+8 -0

Diff too large; view file

vendor/cros-codecs/src/device/v4l2/stateless/controls.rsadded+8 -0

Diff too large; view file

vendor/cros-codecs/src/device/v4l2/stateless/controls/av1.rsadded+689 -0

Diff too large; view file

vendor/cros-codecs/src/device/v4l2/stateless/controls/h264.rsadded+294 -0

Diff too large; view file

vendor/cros-codecs/src/device/v4l2/stateless/controls/vp8.rsadded+183 -0

Diff too large; view file

vendor/cros-codecs/src/device/v4l2/stateless/controls/vp9.rsadded+212 -0

Diff too large; view file

vendor/cros-codecs/src/device/v4l2/stateless/device.rsadded+227 -0

Diff too large; view file

vendor/cros-codecs/src/device/v4l2/stateless/queue.rsadded+447 -0

Diff too large; view file

vendor/cros-codecs/src/device/v4l2/stateless/request.rsadded+249 -0

Diff too large; view file

vendor/cros-codecs/src/device/v4l2/utils.rsadded+130 -0

Diff too large; view file

vendor/cros-codecs/src/encoder.rsadded+418 -0

Diff too large; view file

vendor/cros-codecs/src/encoder/av1.rsadded+34 -0

Diff too large; view file

vendor/cros-codecs/src/encoder/h264.rsadded+34 -0

Diff too large; view file

vendor/cros-codecs/src/encoder/h265.rsadded+30 -0

Diff too large; view file

vendor/cros-codecs/src/encoder/stateful.rsadded+257 -0

Diff too large; view file

vendor/cros-codecs/src/encoder/stateful/h264.rsadded+6 -0

Diff too large; view file

vendor/cros-codecs/src/encoder/stateful/h264/v4l2.rsadded+313 -0

Diff too large; view file

vendor/cros-codecs/src/encoder/stateful/h265.rsadded+6 -0

Diff too large; view file

vendor/cros-codecs/src/encoder/stateful/h265/v4l2.rsadded+305 -0

Diff too large; view file

vendor/cros-codecs/src/encoder/stateful/vp8.rsadded+6 -0

Diff too large; view file

vendor/cros-codecs/src/encoder/stateful/vp8/v4l2.rsadded+332 -0

Diff too large; view file

vendor/cros-codecs/src/encoder/stateful/vp9.rsadded+6 -0

Diff too large; view file

vendor/cros-codecs/src/encoder/stateful/vp9/v4l2.rsadded+337 -0

Diff too large; view file

vendor/cros-codecs/src/encoder/stateless.rsadded+398 -0

Diff too large; view file

vendor/cros-codecs/src/encoder/stateless/av1.rsadded+133 -0

Diff too large; view file

vendor/cros-codecs/src/encoder/stateless/av1/predictor.rsadded+326 -0

Diff too large; view file

vendor/cros-codecs/src/encoder/stateless/av1/vaapi.rsadded+1009 -0

Diff too large; view file

vendor/cros-codecs/src/encoder/stateless/h264.rsadded+197 -0

Diff too large; view file

vendor/cros-codecs/src/encoder/stateless/h264/predictor.rsadded+269 -0

Diff too large; view file

vendor/cros-codecs/src/encoder/stateless/h264/vaapi.rsadded+695 -0

Diff too large; view file

vendor/cros-codecs/src/encoder/stateless/predictor.rsadded+346 -0

Diff too large; view file

vendor/cros-codecs/src/encoder/stateless/vp9.rsadded+122 -0

Diff too large; view file

vendor/cros-codecs/src/encoder/stateless/vp9/predictor.rsadded+138 -0

Diff too large; view file

vendor/cros-codecs/src/encoder/stateless/vp9/vaapi.rsadded+602 -0

Diff too large; view file

vendor/cros-codecs/src/encoder/vp8.rsadded+24 -0

Diff too large; view file

vendor/cros-codecs/src/encoder/vp9.rsadded+31 -0

Diff too large; view file

vendor/cros-codecs/src/image_processing.rsadded+551 -0

Diff too large; view file

vendor/cros-codecs/src/lib.rsadded+463 -0

Diff too large; view file

vendor/cros-codecs/src/utils.rsadded+117 -0

Diff too large; view file

vendor/cros-codecs/src/video_frame.rsadded+311 -0

Diff too large; view file

vendor/cros-codecs/src/video_frame/frame_pool.rsadded+115 -0

Diff too large; view file

vendor/cros-codecs/src/video_frame/gbm_video_frame.rsadded+784 -0

Diff too large; view file

vendor/cros-codecs/src/video_frame/generic_dma_video_frame.rsadded+548 -0

Diff too large; view file

vendor/cros-codecs/src/video_frame/v4l2_mmap_video_frame.rsadded+158 -0

Diff too large; view file

vendor/cros-libva/.cargo_vcs_info.jsonadded+6 -0

Diff too large; view file

vendor/cros-libva/Android.bpadded+76 -0

Diff too large; view file

vendor/cros-libva/Cargo.tomladded+42 -0

Diff too large; view file

vendor/cros-libva/README.mdadded+83 -0

Diff too large; view file

vendor/cros-libva/bindgen_gen.rsadded+18 -0

Diff too large; view file

vendor/cros-libva/build.rsadded+141 -0

Diff too large; view file

vendor/cros-libva/libva-wrapper.hadded+7 -0

Diff too large; view file

vendor/cros-libva/src/bindings.rsadded+15 -0

Diff too large; view file

vendor/cros-libva/src/buffer.rsadded+553 -0

Diff too large; view file

vendor/cros-libva/src/buffer/av1.rsadded+1156 -0

Diff too large; view file

vendor/cros-libva/src/buffer/enc_misc.rsadded+337 -0

Diff too large; view file

vendor/cros-libva/src/buffer/h264.rsadded+807 -0

Diff too large; view file

vendor/cros-libva/src/buffer/hevc.rsadded+1154 -0

Diff too large; view file

vendor/cros-libva/src/buffer/mpeg2.rsadded+172 -0

Diff too large; view file

vendor/cros-libva/src/buffer/vp8.rsadded+397 -0

Diff too large; view file

vendor/cros-libva/src/buffer/vp9.rsadded+448 -0

Diff too large; view file

vendor/cros-libva/src/config.rsadded+137 -0

Diff too large; view file

vendor/cros-libva/src/context.rsadded+102 -0

Diff too large; view file

vendor/cros-libva/src/display.rsadded+362 -0

Diff too large; view file

vendor/cros-libva/src/generic_value.rsadded+50 -0

Diff too large; view file

vendor/cros-libva/src/image.rsadded+235 -0

Diff too large; view file

vendor/cros-libva/src/lib.rsadded+540 -0

Diff too large; view file

vendor/cros-libva/src/picture.rsadded+307 -0

Diff too large; view file

vendor/cros-libva/src/surface.rsadded+452 -0

Diff too large; view file

vendor/cros-libva/src/test_frame.nv12added+0 -0

Binary file changed

vendor/cros-libva/src/usage_hint.rsadded+26 -0

Diff too large; view file