Debian Codegraph @

tests/test_display_matrix.py

raw
1 from __future__ import annotations
2
3 import io
4 import struct
5 from typing import cast
6
7 import numpy as np
8 import pytest
9
10 import av
11 from av.sidedata.sidedata import SideData
12 from av.video.stream import VideoStream
13
14 WIDTH = 320
15 HEIGHT = 240
16 DURATION = 10
17
18 # The 8 EXIF orientations as 3x3 transformation matrices, built the same way as
19 # the application code: a 90 deg rotation generator (R) and a horizontal-flip
20 # generator (F). Orientations 2, 4, 5, 7 are reflections, which a scalar
21 # rotation cannot represent -- so these are verified by comparing the full
22 # matrix that round-trips through the container.
23 _R = np.asarray([[0, -1, 0], [1, 0, 0], [0, 0, 1]], dtype=float) # exif 8
24 _F = np.asarray([[-1, 0, 0], [0, 1, 0], [0, 0, 1]], dtype=float) # exif 2
25
26 EXIF_MATRICES = {
27 1: np.eye(3),
28 2: _F,
29 3: _R @ _R,
30 4: _F @ _R @ _R,
31 5: _F @ _R @ _R @ _R,
32 6: _R @ _R @ _R,
33 7: _F @ _R,
34 8: _R,
35 }
36
37 # Pure-rotation orientations also have a well-defined scalar rotation, reported
38 # by av_display_rotation_get() (counter-clockwise, range [-180, 180]).
39 EXPECTED_ROTATION = {1: 0, 3: 180, 6: -90, 8: 90}
40
41 # Each EXIF orientation expressed through the convenience API as
42 # (degrees_ccw, hflip, vflip). Verified to reproduce EXIF_MATRICES exactly.
43 EXIF_VIA_ROTATION = {
44 1: (0, False, False),
45 2: (0, True, False),
46 3: (0, True, True),
47 4: (0, False, True),
48 5: (90, True, False),
49 6: (90, True, True),
50 7: (90, False, True),
51 8: (90, False, False),
52 }
53
54 # One encoder per codec family we care about, plus the near-universal mpeg4
55 # baseline. Unavailable encoders are skipped at runtime so the suite stays
56 # portable across FFmpeg builds.
57 CODECS = ["mpeg4", "libx264", "libopenh264", "libx265", "libsvtav1", "libaom-av1"]
58
59
60 def matrix_to_ints(matrix: np.ndarray) -> list[int]:
61 """Convert a 3x3 matrix to FFmpeg's AV_PKT_DATA_DISPLAYMATRIX integers.
62
63 Layout (a, b, u, c, d, v, x, y, w): 16.16 fixed point everywhere except
64 u, v, w (indices 2, 5, 8) which are 2.30.
65 """
66 flat = [float(v) for v in matrix.reshape(-1)]
67 return [
68 int(round(v * (1 << 30))) if i in (2, 5, 8) else int(round(v * (1 << 16)))
69 for i, v in enumerate(flat)
70 ]
71
72
73 def _has_encoder(name: str) -> bool:
74 try:
75 av.codec.Codec(name, "w")
76 except Exception:
77 return False
78 return True
79
80
81 def _encode(codec_name: str, matrix: list[int] | None) -> io.BytesIO:
82 buf = io.BytesIO()
83 container = av.open(buf, "w", format="mp4")
84 stream = cast(VideoStream, container.add_stream(codec_name, rate=24))
85 stream.width = WIDTH
86 stream.height = HEIGHT
87 stream.pix_fmt = "yuv420p"
88
89 if matrix is not None:
90 stream.set_display_matrix(matrix)
91
92 for i in range(DURATION):
93 img = np.full((HEIGHT, WIDTH, 3), (i * 8) % 256, dtype=np.uint8)
94 frame = av.VideoFrame.from_ndarray(img, format="rgb24")
95 for packet in stream.encode(frame):
96 container.mux(packet)
97 for packet in stream.encode():
98 container.mux(packet)
99 container.close()
100
101 buf.seek(0)
102 return buf
103
104
105 def _read_frame(buf: io.BytesIO) -> av.VideoFrame:
106 with av.open(buf, "r", format="mp4") as container:
107 return next(container.decode(video=0))
108
109
110 def _read_matrix(frame: av.VideoFrame) -> list[int] | None:
111 sd = frame.side_data.get("DISPLAYMATRIX")
112 if sd is None:
113 return None
114 return list(struct.unpack("=9i", bytes(cast(SideData, sd))))
115
116
117 @pytest.mark.parametrize("codec_name", CODECS)
118 @pytest.mark.parametrize("orientation", sorted(EXIF_MATRICES))
119 def test_exif_orientation_roundtrip(codec_name: str, orientation: int) -> None:
120 if not _has_encoder(codec_name):
121 pytest.skip(f"encoder {codec_name} not available")
122
123 expected = matrix_to_ints(EXIF_MATRICES[orientation])
124 frame = _read_frame(_encode(codec_name, expected))
125 got = _read_matrix(frame)
126
127 identity = matrix_to_ints(np.eye(3))
128 if expected == identity:
129 # Identity is the container default; demuxers emit no side data for it.
130 assert got is None
131 assert frame.rotation == 0
132 else:
133 assert got == expected, f"exif {orientation}: wrote {expected}, read {got}"
134
135 if orientation in EXPECTED_ROTATION:
136 rotation = frame.rotation
137 # 180 may come back negated; rotations are exact otherwise.
138 if abs(EXPECTED_ROTATION[orientation]) == 180:
139 assert abs(rotation) == 180
140 else:
141 assert rotation == EXPECTED_ROTATION[orientation]
142
143
144 @pytest.mark.parametrize("degrees,expected", [(0, 0), (90, 90), (180, 180), (270, -90)])
145 def test_set_display_rotation_roundtrip(degrees: int, expected: int) -> None:
146 # The public angle is counter-clockwise, matching VideoFrame.rotation.
147 buf = io.BytesIO()
148 container = av.open(buf, "w", format="mp4")
149 stream = container.add_stream("mpeg4", rate=24)
150 stream.width = WIDTH
151 stream.height = HEIGHT
152 stream.pix_fmt = "yuv420p"
153 stream.set_display_rotation(degrees)
154 for i in range(DURATION):
155 frame = av.VideoFrame.from_ndarray(
156 np.zeros((HEIGHT, WIDTH, 3), dtype=np.uint8), format="rgb24"
157 )
158 for packet in stream.encode(frame):
159 container.mux(packet)
160 for packet in stream.encode():
161 container.mux(packet)
162 container.close()
163
164 buf.seek(0)
165 rotation = _read_frame(buf).rotation
166 if abs(expected) == 180:
167 assert abs(rotation) == 180
168 else:
169 assert rotation == expected
170
171
172 @pytest.mark.parametrize("orientation", sorted(EXIF_VIA_ROTATION))
173 def test_convenience_reaches_all_exif_orientations(orientation: int) -> None:
174 # set_display_rotation(degrees, hflip, vflip) must reproduce the exact same
175 # matrix as the explicit EXIF table for every one of the 8 orientations.
176 degrees, hflip, vflip = EXIF_VIA_ROTATION[orientation]
177 expected = matrix_to_ints(EXIF_MATRICES[orientation])
178
179 buf = io.BytesIO()
180 container = av.open(buf, "w", format="mp4")
181 stream = container.add_stream("mpeg4", rate=24)
182 stream.width = WIDTH
183 stream.height = HEIGHT
184 stream.pix_fmt = "yuv420p"
185 stream.set_display_rotation(degrees, hflip=hflip, vflip=vflip)
186 for i in range(DURATION):
187 frame = av.VideoFrame.from_ndarray(
188 np.zeros((HEIGHT, WIDTH, 3), dtype=np.uint8), format="rgb24"
189 )
190 for packet in stream.encode(frame):
191 container.mux(packet)
192 for packet in stream.encode():
193 container.mux(packet)
194 container.close()
195
196 buf.seek(0)
197 got = _read_matrix(_read_frame(buf))
198 if expected == matrix_to_ints(np.eye(3)):
199 assert got is None # identity emits no side data
200 else:
201 assert got == expected, f"exif {orientation}: wrote {expected}, read {got}"
202
203
204 def test_matrix_and_rotation_setters_are_mutually_exclusive() -> None:
205 # Setting one path must clear the other so they don't both apply.
206 buf = io.BytesIO()
207 with av.open(buf, "w", format="mp4") as container:
208 stream = container.add_stream("mpeg4", rate=24)
209 stream.width = WIDTH
210 stream.height = HEIGHT
211 stream.pix_fmt = "yuv420p"
212 stream.set_display_rotation(90)
213 stream.set_display_matrix(None) # clears both paths
214 frame = av.VideoFrame.from_ndarray(
215 np.zeros((HEIGHT, WIDTH, 3), dtype=np.uint8), format="rgb24"
216 )
217 for packet in stream.encode(frame):
218 container.mux(packet)
219 for packet in stream.encode():
220 container.mux(packet)
221
222 buf.seek(0)
223 assert _read_matrix(_read_frame(buf)) is None
224
225
226 def test_set_display_matrix_validates_length() -> None:
227 buf = io.BytesIO()
228 with av.open(buf, "w", format="mp4") as container:
229 stream = container.add_stream("mpeg4", rate=24)
230 with pytest.raises(ValueError):
231 stream.set_display_matrix([0, 1, 2])
232
233
234 def test_set_display_matrix_none_clears() -> None:
235 buf = io.BytesIO()
236 with av.open(buf, "w", format="mp4") as container:
237 stream = container.add_stream("mpeg4", rate=24)
238 stream.set_display_matrix(matrix_to_ints(EXIF_MATRICES[6]))
239 stream.set_display_matrix(None) # clear before encoding
240 stream.width = WIDTH
241 stream.height = HEIGHT
242 stream.pix_fmt = "yuv420p"
243 frame = av.VideoFrame.from_ndarray(
244 np.zeros((HEIGHT, WIDTH, 3), dtype=np.uint8), format="rgb24"
245 )
246 for packet in stream.encode(frame):
247 container.mux(packet)
248 for packet in stream.encode():
249 container.mux(packet)
250
251 buf.seek(0)
252 assert _read_matrix(_read_frame(buf)) is None