Debian Codegraph @

av/video/reformatter.py

raw
1 from enum import IntEnum
2
3 import cython
4 import cython.cimports.libav as lib
5 from cython.cimports.av.error import err_check
6 from cython.cimports.av.video.format import VideoFormat, get_pix_fmt
7 from cython.cimports.av.video.frame import alloc_video_frame
8
9
10 class Interpolation(IntEnum):
11 FAST_BILINEAR: "Fast bilinear" = SWS_FAST_BILINEAR
12 BILINEAR: "Bilinear" = SWS_BILINEAR
13 BICUBIC: "2-tap cubic B-spline" = SWS_BICUBIC
14 X: "Experimental" = SWS_X
15 POINT: "Nearest neighbor / point" = SWS_POINT
16 AREA: "Area averaging" = SWS_AREA
17 BICUBLIN: "Bicubic luma / Bilinear chroma" = SWS_BICUBLIN
18 GAUSS: "Gaussian approximation" = SWS_GAUSS
19 SINC: "Unwindowed Sinc" = SWS_SINC
20 LANCZOS: "3-tap sinc/sinc" = SWS_LANCZOS
21 SPLINE: "Unwindowed natural cubic spline" = SWS_SPLINE
22
23
24 class Colorspace(IntEnum):
25 ITU709 = SWS_CS_ITU709
26 FCC = SWS_CS_FCC
27 ITU601 = SWS_CS_ITU601
28 ITU624 = SWS_CS_ITU624
29 SMPTE170M = SWS_CS_SMPTE170M
30 SMPTE240M = SWS_CS_SMPTE240M
31 DEFAULT = SWS_CS_DEFAULT
32 # Lowercase for b/c.
33 itu709 = SWS_CS_ITU709
34 fcc = SWS_CS_FCC
35 itu601 = SWS_CS_ITU601
36 itu624 = SWS_CS_ITU624
37 smpte170m = SWS_CS_SMPTE170M
38 smpte240m = SWS_CS_SMPTE240M
39 default = SWS_CS_DEFAULT
40
41
42 class ColorRange(IntEnum):
43 UNSPECIFIED: "Unspecified" = lib.AVCOL_RANGE_UNSPECIFIED
44 MPEG: "MPEG (limited) YUV range, 219*2^(n-8)" = lib.AVCOL_RANGE_MPEG
45 JPEG: "JPEG (full) YUV range, 2^n-1" = lib.AVCOL_RANGE_JPEG
46 NB: "Not part of ABI" = lib.AVCOL_RANGE_NB
47
48
49 class ColorTrc(IntEnum):
50 """Transfer characteristic (gamma curve) of a video frame.
51
52 Maps to FFmpeg's ``AVColorTransferCharacteristic``.
53 """
54
55 BT709: "BT.709" = lib.AVCOL_TRC_BT709
56 UNSPECIFIED: "Unspecified" = lib.AVCOL_TRC_UNSPECIFIED
57 GAMMA22: "Gamma 2.2 (BT.470M)" = lib.AVCOL_TRC_GAMMA22
58 GAMMA28: "Gamma 2.8 (BT.470BG)" = lib.AVCOL_TRC_GAMMA28
59 SMPTE170M: "SMPTE 170M" = lib.AVCOL_TRC_SMPTE170M
60 SMPTE240M: "SMPTE 240M" = lib.AVCOL_TRC_SMPTE240M
61 LINEAR: "Linear" = lib.AVCOL_TRC_LINEAR
62 LOG: "Logarithmic (100:1 range)" = lib.AVCOL_TRC_LOG
63 LOG_SQRT: "Logarithmic (100*sqrt(10):1 range)" = lib.AVCOL_TRC_LOG_SQRT
64 IEC61966_2_4: "IEC 61966-2-4 (sRGB)" = lib.AVCOL_TRC_IEC61966_2_4
65 BT1361_ECG: "BT.1361 extended colour gamut" = lib.AVCOL_TRC_BT1361_ECG
66 IEC61966_2_1: "IEC 61966-2-1 (sYCC)" = lib.AVCOL_TRC_IEC61966_2_1
67 BT2020_10: "BT.2020 10-bit" = lib.AVCOL_TRC_BT2020_10
68 BT2020_12: "BT.2020 12-bit" = lib.AVCOL_TRC_BT2020_12
69 SMPTE2084: "SMPTE 2084 (PQ, HDR10)" = lib.AVCOL_TRC_SMPTE2084
70 SMPTE428: "SMPTE 428-1" = lib.AVCOL_TRC_SMPTE428
71 ARIB_STD_B67: "ARIB STD-B67 (HLG)" = lib.AVCOL_TRC_ARIB_STD_B67
72
73
74 class ColorPrimaries(IntEnum):
75 """Color primaries of a video frame.
76
77 Maps to FFmpeg's ``AVColorPrimaries``.
78 """
79
80 BT709: "BT.709 / sRGB / sYCC" = lib.AVCOL_PRI_BT709
81 UNSPECIFIED: "Unspecified" = lib.AVCOL_PRI_UNSPECIFIED
82 BT470M: "BT.470M" = lib.AVCOL_PRI_BT470M
83 BT470BG: "BT.470BG / BT.601-6 625" = lib.AVCOL_PRI_BT470BG
84 SMPTE170M: "SMPTE 170M / BT.601-6 525" = lib.AVCOL_PRI_SMPTE170M
85 SMPTE240M: "SMPTE 240M" = lib.AVCOL_PRI_SMPTE240M
86 FILM: "Generic film (Illuminant C)" = lib.AVCOL_PRI_FILM
87 BT2020: "BT.2020 / BT.2100" = lib.AVCOL_PRI_BT2020
88 SMPTE428: "SMPTE 428-1 / XYZ" = lib.AVCOL_PRI_SMPTE428
89 SMPTE431: "SMPTE 431-2 (DCI-P3)" = lib.AVCOL_PRI_SMPTE431
90 SMPTE432: "SMPTE 432-1 (Display P3)" = lib.AVCOL_PRI_SMPTE432
91 EBU3213: "EBU 3213-E / JEDEC P22" = lib.AVCOL_PRI_EBU3213
92
93
94 @cython.cfunc
95 @cython.inline
96 def _resolve_enum_value(
97 value: object, enum_class: object, default: cython.int
98 ) -> cython.int:
99 # Helper function to resolve enum values from different input types.
100 if value is None:
101 return default
102 if isinstance(value, enum_class):
103 return value.value
104 if isinstance(value, int):
105 return value
106 if isinstance(value, str):
107 return enum_class[value].value
108 raise ValueError(f"Cannot convert {value} to {enum_class.__name__}")
109
110
111 @cython.cfunc
112 @cython.inline
113 def _resolve_format(format: object, default: lib.AVPixelFormat) -> lib.AVPixelFormat:
114 if format is None:
115 return default
116 if isinstance(format, VideoFormat):
117 return cython.cast(VideoFormat, format).pix_fmt
118 return get_pix_fmt(format)
119
120
121 @cython.cfunc
122 def _set_frame_colorspace(
123 frame: cython.pointer(lib.AVFrame),
124 colorspace: cython.int,
125 color_range: cython.int,
126 ):
127 """Set AVFrame colorspace/range from SWS_CS_* and AVColorRange values."""
128 if color_range != lib.AVCOL_RANGE_UNSPECIFIED:
129 frame.color_range = cython.cast(lib.AVColorRange, color_range)
130 # Mapping from SWS_CS_* (swscale colorspace) to AVColorSpace (frame metadata).
131 # Note: SWS_CS_ITU601, SWS_CS_ITU624, SWS_CS_SMPTE170M, and SWS_CS_DEFAULT all have
132 # the same value (5), so we map 5 -> AVCOL_SPC_SMPTE170M as the most common case.
133 # SWS_CS_DEFAULT is handled specially by not setting frame metadata.
134 if colorspace == SWS_CS_ITU709:
135 frame.colorspace = lib.AVCOL_SPC_BT709
136 elif colorspace == SWS_CS_FCC:
137 frame.colorspace = lib.AVCOL_SPC_FCC
138 elif colorspace == SWS_CS_ITU601:
139 frame.colorspace = lib.AVCOL_SPC_SMPTE170M
140 elif colorspace == SWS_CS_SMPTE240M:
141 frame.colorspace = lib.AVCOL_SPC_SMPTE240M
142
143
144 @cython.final
145 @cython.cclass
146 class VideoReformatter:
147 """An object for reformatting size and pixel format of :class:`.VideoFrame`.
148
149 It is most efficient to have a reformatter object for each set of parameters
150 you will use as calling :meth:`reformat` will reconfigure the internal object.
151
152 """
153
154 def __dealloc__(self):
155 with cython.nogil:
156 sws_free_context(cython.address(self.ptr))
157
158 def reformat(
159 self,
160 frame: VideoFrame,
161 width=None,
162 height=None,
163 format=None,
164 src_colorspace=None,
165 dst_colorspace=None,
166 interpolation=None,
167 src_color_range=None,
168 dst_color_range=None,
169 dst_color_trc=None,
170 dst_color_primaries=None,
171 threads=None,
172 ):
173 """Create a new :class:`VideoFrame` with the given width/height/format/colorspace.
174
175 Returns the same frame untouched if nothing needs to be done to it.
176
177 :param int width: New width, or ``None`` for the same width.
178 :param int height: New height, or ``None`` for the same height.
179 :param format: New format, or ``None`` for the same format.
180 :type format: :class:`.VideoFormat` or ``str``
181 :param src_colorspace: Current colorspace, or ``None`` for the frame colorspace.
182 :type src_colorspace: :class:`Colorspace` or ``str``
183 :param dst_colorspace: Desired colorspace, or ``None`` for the frame colorspace.
184 :type dst_colorspace: :class:`Colorspace` or ``str``
185 :param interpolation: The interpolation method to use, or ``None`` for ``BILINEAR``.
186 :type interpolation: :class:`Interpolation` or ``str``
187 :param src_color_range: Current color range, or ``None`` for the ``UNSPECIFIED``.
188 :type src_color_range: :class:`ColorRange` or ``str``
189 :param dst_color_range: Desired color range, or ``None`` for the ``UNSPECIFIED``.
190 :type dst_color_range: :class:`ColorRange` or ``str``
191 :param dst_color_trc: Desired transfer characteristic to tag on the output frame,
192 or ``None`` to preserve the source frame's value. This sets frame metadata only;
193 it does not perform a pixel-level transfer function conversion.
194 :type dst_color_trc: :class:`ColorTrc` or ``int``
195 :param dst_color_primaries: Desired color primaries to tag on the output frame,
196 or ``None`` to preserve the source frame's value.
197 :type dst_color_primaries: :class:`ColorPrimaries` or ``int``
198 :param int threads: How many threads to use for scaling, or ``0`` for automatic
199 selection based on the number of available CPUs. Defaults to ``0`` (auto).
200
201 """
202 c_dst_format = _resolve_format(format, frame.format.pix_fmt)
203 c_src_colorspace = _resolve_enum_value(
204 src_colorspace, Colorspace, frame.ptr.colorspace
205 )
206 c_dst_colorspace = _resolve_enum_value(
207 dst_colorspace, Colorspace, frame.ptr.colorspace
208 )
209 c_interpolation = _resolve_enum_value(
210 interpolation, Interpolation, SWS_BILINEAR
211 )
212 c_src_color_range = _resolve_enum_value(src_color_range, ColorRange, 0)
213 c_dst_color_range = _resolve_enum_value(dst_color_range, ColorRange, 0)
214 c_dst_color_trc = _resolve_enum_value(dst_color_trc, ColorTrc, 0)
215 c_dst_color_primaries = _resolve_enum_value(
216 dst_color_primaries, ColorPrimaries, 0
217 )
218 c_threads: cython.int = threads if threads is not None else 0
219 c_width: cython.int = width if width is not None else frame.ptr.width
220 c_height: cython.int = height if height is not None else frame.ptr.height
221
222 # Track whether user explicitly specified destination metadata
223 set_dst_color_trc: cython.bint = dst_color_trc is not None
224 set_dst_color_primaries: cython.bint = dst_color_primaries is not None
225
226 return self._reformat(
227 frame,
228 c_width,
229 c_height,
230 c_dst_format,
231 c_src_colorspace,
232 c_dst_colorspace,
233 c_interpolation,
234 c_src_color_range,
235 c_dst_color_range,
236 c_dst_color_trc,
237 c_dst_color_primaries,
238 set_dst_color_trc,
239 set_dst_color_primaries,
240 c_threads,
241 )
242
243 @cython.cfunc
244 def _reformat(
245 self,
246 frame: VideoFrame,
247 width: cython.int,
248 height: cython.int,
249 dst_format: lib.AVPixelFormat,
250 src_colorspace: cython.int,
251 dst_colorspace: cython.int,
252 interpolation: cython.int,
253 src_color_range: cython.int,
254 dst_color_range: cython.int,
255 dst_color_trc: cython.int,
256 dst_color_primaries: cython.int,
257 set_dst_color_trc: cython.bint,
258 set_dst_color_primaries: cython.bint,
259 threads: cython.int,
260 ):
261 if frame.ptr.format < 0:
262 raise ValueError("Frame does not have format set.")
263
264 src_format = cython.cast(lib.AVPixelFormat, frame.ptr.format)
265
266 # Shortcut!
267 if (
268 dst_format == src_format
269 and width == frame.ptr.width
270 and height == frame.ptr.height
271 and dst_colorspace == src_colorspace
272 and src_color_range == dst_color_range
273 and not set_dst_color_trc
274 and not set_dst_color_primaries
275 ):
276 return frame
277
278 if frame.ptr.hw_frames_ctx:
279 frame_sw = alloc_video_frame()
280 err_check(lib.av_hwframe_transfer_data(frame_sw.ptr, frame.ptr, 0))
281 frame_sw.pts = frame.pts
282 frame_sw._init_user_attributes()
283 frame = frame_sw
284 src_format = cython.cast(lib.AVPixelFormat, frame.ptr.format)
285
286 if self.ptr == cython.NULL:
287 self.ptr = sws_alloc_context()
288 if self.ptr == cython.NULL:
289 raise MemoryError("Could not allocate SwsContext")
290 self.ptr.threads = threads
291 self.ptr.flags = cython.cast(cython.uint, interpolation)
292
293 new_frame: VideoFrame = alloc_video_frame()
294 new_frame._copy_internal_attributes(frame)
295 new_frame._init(dst_format, width, height)
296
297 # Set source frame colorspace/range so sws_scale_frame can read it
298 frame_src_colorspace: lib.AVColorSpace = frame.ptr.colorspace
299 frame_src_color_range: lib.AVColorRange = frame.ptr.color_range
300 _set_frame_colorspace(frame.ptr, src_colorspace, src_color_range)
301 _set_frame_colorspace(new_frame.ptr, dst_colorspace, dst_color_range)
302
303 with cython.nogil:
304 ret = sws_scale_frame(self.ptr, new_frame.ptr, frame.ptr)
305
306 # Restore source frame colorspace/range to avoid side effects
307 frame.ptr.colorspace = frame_src_colorspace
308 frame.ptr.color_range = frame_src_color_range
309
310 err_check(ret)
311
312 # Set metadata-only properties on the output frame if explicitly specified
313 if set_dst_color_trc:
314 new_frame.ptr.color_trc = cython.cast(
315 lib.AVColorTransferCharacteristic, dst_color_trc
316 )
317 if set_dst_color_primaries:
318 new_frame.ptr.color_primaries = cython.cast(
319 lib.AVColorPrimaries, dst_color_primaries
320 )
321
322 return new_frame