Debian Codegraph @

av/error.py

raw
1 import errno
2 import os
3 import sys
4 import traceback
5 from threading import local
6
7 import cython
8 from cython.cimports import libav as lib
9 from cython.cimports.av.logging import get_last_error
10 from cython.cimports.libc.stdio import fprintf, stderr
11 from cython.cimports.libc.stdlib import free, malloc
12
13 # Will get extended with all the exceptions.
14 __all__ = [
15 "ErrorType",
16 "FFmpegError",
17 "LookupError",
18 "HTTPError",
19 "HTTPClientError",
20 "UndefinedError",
21 ]
22 sentinel = cython.declare(object, object())
23
24
25 @cython.ccall
26 def code_to_tag(code: cython.int) -> bytes:
27 """Convert an integer error code into 4-byte tag.
28
29 >>> code_to_tag(1953719668)
30 b'test'
31
32 """
33 return bytes(
34 (
35 code & 0xFF,
36 (code >> 8) & 0xFF,
37 (code >> 16) & 0xFF,
38 (code >> 24) & 0xFF,
39 )
40 )
41
42
43 @cython.ccall
44 def tag_to_code(tag: bytes) -> cython.int:
45 """Convert a 4-byte error tag into an integer code.
46
47 >>> tag_to_code(b'test')
48 1953719668
49
50 """
51 if len(tag) != 4:
52 raise ValueError("Error tags are 4 bytes.")
53 return (tag[0]) + (tag[1] << 8) + (tag[2] << 16) + (tag[3] << 24)
54
55
56 class FFmpegError(Exception):
57 """Exception class for errors from within FFmpeg.
58
59 .. attribute:: errno
60
61 FFmpeg's integer error code.
62
63 .. attribute:: strerror
64
65 FFmpeg's error message.
66
67 .. attribute:: filename
68
69 The filename that was being operated on (if available).
70
71 .. attribute:: log
72
73 The tuple from :func:`av.logging.get_last_log`, or ``None``.
74
75 """
76
77 def __init__(self, code, message, filename=None, log=None):
78 args = [code, message]
79 if filename or log:
80 args.append(filename)
81 if log:
82 args.append(log)
83 super().__init__(*args)
84
85 self.errno = code
86 self.strerror = message
87 self.args = tuple(args)
88
89 @property
90 def filename(self):
91 try:
92 return self.args[2]
93 except IndexError:
94 pass
95
96 @property
97 def log(self):
98 try:
99 return self.args[3]
100 except IndexError:
101 pass
102
103 def __str__(self):
104 msg = ""
105 if self.errno is not None:
106 msg = f"{msg}[Errno {self.errno}] "
107 if self.strerror is not None:
108 msg = f"{msg}{self.strerror}"
109 if self.filename:
110 msg = f"{msg}: {self.filename!r}"
111 if self.log:
112 msg = (
113 f"{msg}; last error log: [{self.log[1].strip()}] {self.log[2].strip()}"
114 )
115
116 return msg
117
118
119 # Our custom error, used in callbacks.
120 c_PYAV_STASHED_ERROR = cython.declare(cython.int, tag_to_code(b"PyAV"))
121 PYAV_STASHED_ERROR_message = cython.declare(str, "Error in PyAV callback")
122
123
124 # Bases for the FFmpeg-based exceptions.
125 class LookupError(FFmpegError, LookupError):
126 pass
127
128
129 class HTTPError(FFmpegError):
130 pass
131
132
133 class HTTPClientError(FFmpegError):
134 pass
135
136
137 # Tuples of (enum_name, enum_value, exc_name, exc_base).
138 # tuple[str, int, str | None, Exception | none]
139 # fmt: off
140 _ffmpeg_specs = (
141 ("BSF_NOT_FOUND", -lib.AVERROR_BSF_NOT_FOUND, "BSFNotFoundError", LookupError),
142 ("BUG", -lib.AVERROR_BUG, None, RuntimeError),
143 ("BUFFER_TOO_SMALL", -lib.AVERROR_BUFFER_TOO_SMALL, None, ValueError),
144 ("DECODER_NOT_FOUND", -lib.AVERROR_DECODER_NOT_FOUND, None, LookupError),
145 ("DEMUXER_NOT_FOUND", -lib.AVERROR_DEMUXER_NOT_FOUND, None, LookupError),
146 ("ENCODER_NOT_FOUND", -lib.AVERROR_ENCODER_NOT_FOUND, None, LookupError),
147 ("EOF", -lib.AVERROR_EOF, "EOFError", EOFError),
148 ("EXIT", -lib.AVERROR_EXIT, None, None),
149 ("EXTERNAL", -lib.AVERROR_EXTERNAL, None, None),
150 ("FILTER_NOT_FOUND", -lib.AVERROR_FILTER_NOT_FOUND, None, LookupError),
151 ("INVALIDDATA", -lib.AVERROR_INVALIDDATA, "InvalidDataError", ValueError),
152 ("MUXER_NOT_FOUND", -lib.AVERROR_MUXER_NOT_FOUND, None, LookupError),
153 ("OPTION_NOT_FOUND", -lib.AVERROR_OPTION_NOT_FOUND, None, LookupError),
154 ("PATCHWELCOME", -lib.AVERROR_PATCHWELCOME, "PatchWelcomeError", None),
155 ("PROTOCOL_NOT_FOUND", -lib.AVERROR_PROTOCOL_NOT_FOUND, None, LookupError),
156 ("UNKNOWN", -lib.AVERROR_UNKNOWN, None, None),
157 ("EXPERIMENTAL", -lib.AVERROR_EXPERIMENTAL, None, None),
158 ("INPUT_CHANGED", -lib.AVERROR_INPUT_CHANGED, None, None),
159 ("OUTPUT_CHANGED", -lib.AVERROR_OUTPUT_CHANGED, None, None),
160 ("HTTP_BAD_REQUEST", -lib.AVERROR_HTTP_BAD_REQUEST, "HTTPBadRequestError", HTTPClientError),
161 ("HTTP_UNAUTHORIZED", -lib.AVERROR_HTTP_UNAUTHORIZED, "HTTPUnauthorizedError", HTTPClientError),
162 ("HTTP_FORBIDDEN", -lib.AVERROR_HTTP_FORBIDDEN, "HTTPForbiddenError", HTTPClientError),
163 ("HTTP_NOT_FOUND", -lib.AVERROR_HTTP_NOT_FOUND, "HTTPNotFoundError", HTTPClientError),
164 ("HTTP_TOO_MANY_REQUESTS", -lib.AVERROR_HTTP_TOO_MANY_REQUESTS, "HTTPTooManyRequestsError", HTTPClientError),
165 ("HTTP_OTHER_4XX", -lib.AVERROR_HTTP_OTHER_4XX, "HTTPOtherClientError", HTTPClientError),
166 ("HTTP_SERVER_ERROR", -lib.AVERROR_HTTP_SERVER_ERROR, "HTTPServerError", HTTPError),
167 ("PYAV_CALLBACK", c_PYAV_STASHED_ERROR, "PyAVCallbackError", RuntimeError),
168 )
169 # fmt: on
170
171
172 class EnumType(type):
173 def __new__(mcl, name, bases, attrs, *args):
174 # Just adapting the method signature.
175 return super().__new__(mcl, name, bases, attrs)
176
177 def __init__(self, name, bases, attrs, items):
178 self._by_name = {}
179 self._by_value = {}
180 self._all = []
181
182 for spec in items:
183 self._create(*spec)
184
185 def _create(self, name, value, doc=None, by_value_only=False):
186 # We only have one instance per value.
187 try:
188 item = self._by_value[value]
189 except KeyError:
190 item = self(sentinel, name, value, doc)
191 self._by_value[value] = item
192
193 return item
194
195 def __len__(self):
196 return len(self._all)
197
198 def __iter__(self):
199 return iter(self._all)
200
201
202 @cython.cclass
203 class EnumItem:
204 """An enumeration of FFmpeg's error types.
205
206 .. attribute:: tag
207
208 The FFmpeg byte tag for the error.
209
210 .. attribute:: strerror
211
212 The error message that would be returned.
213 """
214
215 name = cython.declare(str, visibility="readonly")
216 value = cython.declare(cython.int, visibility="readonly")
217
218 def __cinit__(self, sentinel_, name: str, value: cython.int, doc=None):
219 if sentinel_ is not sentinel:
220 raise RuntimeError(f"Cannot instantiate {self.__class__.__name__}.")
221
222 self.name = name
223 self.value = value
224 self.__doc__ = doc
225
226 def __repr__(self):
227 return f"<{self.__class__.__module__}.{self.__class__.__name__}:{self.name}(0x{self.value:x})>"
228
229 def __str__(self):
230 return self.name
231
232 def __int__(self):
233 return self.value
234
235 @property
236 def tag(self):
237 return code_to_tag(self.value)
238
239
240 ErrorType = EnumType(
241 "ErrorType", (EnumItem,), {"__module__": __name__}, [x[:2] for x in _ffmpeg_specs]
242 )
243
244
245 for enum in ErrorType:
246 # Mimick the errno module.
247 globals()[enum.name] = enum
248 if enum.value == c_PYAV_STASHED_ERROR:
249 enum.strerror = PYAV_STASHED_ERROR_message
250 else:
251 enum.strerror = lib.av_err2str(-enum.value)
252
253 classes: dict = {}
254
255
256 def _extend_builtin(name, codes):
257 base = getattr(__builtins__, name, OSError)
258 cls = type(name, (FFmpegError, base), {"__module__": __name__})
259
260 # Register in builder.
261 for code in codes:
262 classes[code] = cls
263
264 # Register in module.
265 globals()[name] = cls
266 __all__.append(name)
267
268 return cls
269
270
271 _extend_builtin("PermissionError", (errno.EACCES, errno.EPERM))
272 _extend_builtin(
273 "BlockingIOError",
274 (errno.EAGAIN, errno.EALREADY, errno.EINPROGRESS, errno.EWOULDBLOCK),
275 )
276 _extend_builtin("ChildProcessError", (errno.ECHILD,))
277 _extend_builtin("ConnectionAbortedError", (errno.ECONNABORTED,))
278 _extend_builtin("ConnectionRefusedError", (errno.ECONNREFUSED,))
279 _extend_builtin("ConnectionResetError", (errno.ECONNRESET,))
280 _extend_builtin("FileExistsError", (errno.EEXIST,))
281 _extend_builtin("InterruptedError", (errno.EINTR,))
282 _extend_builtin("IsADirectoryError", (errno.EISDIR,))
283 _extend_builtin("FileNotFoundError", (errno.ENOENT,))
284 _extend_builtin("NotADirectoryError", (errno.ENOTDIR,))
285 _extend_builtin("BrokenPipeError", (errno.EPIPE, errno.ESHUTDOWN))
286 _extend_builtin("ProcessLookupError", (errno.ESRCH,))
287 _extend_builtin("TimeoutError", (errno.ETIMEDOUT,))
288 _extend_builtin("MemoryError", (errno.ENOMEM,))
289 _extend_builtin("NotImplementedError", (errno.ENOSYS,))
290 _extend_builtin("OverflowError", (errno.ERANGE,))
291 _extend_builtin("OSError", [code for code in errno.errorcode if code not in classes])
292
293
294 class ArgumentError(FFmpegError, ValueError):
295 def __str__(self):
296 msg = ""
297 if self.strerror is not None:
298 msg = f"{msg}{self.strerror}"
299 if self.filename:
300 msg = f"{msg}: {self.filename!r}"
301 if self.errno is not None:
302 msg = f"{msg} returned {self.errno}"
303 if self.log:
304 msg = (
305 f"{msg}; last error log: [{self.log[1].strip()}] {self.log[2].strip()}"
306 )
307
308 return msg
309
310
311 class UndefinedError(FFmpegError):
312 """Fallback exception type in case FFmpeg returns an error we don't know about."""
313
314 pass
315
316
317 classes[errno.EINVAL] = ArgumentError
318 globals()["ArgumentError"] = ArgumentError
319 __all__.append("ArgumentError")
320
321
322 # Classes for the FFmpeg errors.
323 for enum_name, code, name, base in _ffmpeg_specs:
324 name = name or enum_name.title().replace("_", "") + "Error"
325
326 if base is None:
327 bases = (FFmpegError,)
328 elif issubclass(base, FFmpegError):
329 bases = (base,)
330 else:
331 bases = (FFmpegError, base)
332
333 cls = type(name, bases, {"__module__": __name__})
334
335 # Register in builder.
336 classes[code] = cls
337
338 # Register in module.
339 globals()[name] = cls
340 __all__.append(name)
341
342 del _ffmpeg_specs
343
344
345 # Storage for stashing.
346 _local = cython.declare(object, local())
347 _err_count = cython.declare(cython.int, 0)
348 _last_log_count = cython.declare(cython.int, 0)
349
350
351 @cython.cfunc
352 def stash_exception(exc_info=None) -> cython.int:
353 global _err_count
354
355 existing = getattr(_local, "exc_info", None)
356 if existing is not None:
357 fprintf(stderr, "PyAV library exception being dropped:\n")
358 traceback.print_exception(*existing)
359 _err_count -= 1 # Balance out the +=1 that is coming.
360
361 exc_info = exc_info or sys.exc_info()
362 _local.exc_info = exc_info
363 if exc_info:
364 _err_count += 1
365
366 return -c_PYAV_STASHED_ERROR
367
368
369 @cython.ccall
370 @cython.exceptval(-1, check=False)
371 def err_check(res: cython.int, filename=None) -> cython.int:
372 """Raise appropriate exceptions from library return code."""
373
374 global _err_count
375 global _last_log_count
376
377 # Check for stashed exceptions.
378 if _err_count:
379 exc_info = getattr(_local, "exc_info", None)
380 if exc_info is not None:
381 _err_count -= 1
382 _local.exc_info = None
383 raise exc_info[1].with_traceback(exc_info[2])
384
385 if res >= 0:
386 return res
387
388 # Grab details from the last log.
389 log_count, last_log = get_last_error()
390 if log_count > _last_log_count:
391 _last_log_count = log_count
392 log = last_log
393 else:
394 log = None
395
396 code: cython.int = -res
397 error_buffer: cython.p_char = cython.cast(
398 cython.p_char, malloc(lib.AV_ERROR_MAX_STRING_SIZE * cython.sizeof(char))
399 )
400 if error_buffer == cython.NULL:
401 raise MemoryError()
402
403 try:
404 if code == c_PYAV_STASHED_ERROR:
405 message = PYAV_STASHED_ERROR_message
406 else:
407 lib.av_strerror(res, error_buffer, lib.AV_ERROR_MAX_STRING_SIZE)
408 # Fallback to OS error string if no message
409 message = error_buffer or os.strerror(code)
410
411 cls = classes.get(code, UndefinedError)
412 raise cls(code, message, filename, log)
413 finally:
414 free(error_buffer)