Debian Codegraph @

av/logging.py

raw
1 # type: ignore
2 """
3 FFmpeg has a logging system that it uses extensively. It's very noisy, so PyAV turns it
4 off by default. This unfortunately has the effect of making raised errors have less
5 detailed messages. It's therefore recommended to use VERBOSE when developing.
6
7 .. _enable_logging:
8
9 Enabling Logging
10 ~~~~~~~~~~~~~~~~~
11
12 You can hook into the logging system with Python by setting the log level::
13
14 import av
15
16 av.logging.set_level(av.logging.VERBOSE)
17
18
19 PyAV hooks into that system to translate FFmpeg logs into Python's
20 `logging system <https://docs.python.org/3/library/logging.html#logging.basicConfig>`_.
21
22 If you are not already using Python's logging system, you can initialize it
23 quickly with::
24
25 import logging
26 logging.basicConfig()
27
28
29 Note that handling logs with Python sometimes doesn't play nicely with multi-threaded workflows.
30 An alternative is :func:`restore_default_callback`.
31
32 This restores FFmpeg's default logging system, which prints to the terminal.
33 Like with setting the log level to ``None``, this may also result in raised errors
34 having less detailed messages.
35
36
37 API Reference
38 ~~~~~~~~~~~~~
39
40 """
41
42 import logging
43 import sys
44 from threading import Lock, get_ident
45
46 import cython
47 from cython.cimports.libc.stdio import fprintf, stderr
48 from cython.cimports.libc.stdlib import free, malloc
49
50 # Library levels.
51 PANIC = lib.AV_LOG_PANIC # 0
52 FATAL = lib.AV_LOG_FATAL # 8
53 ERROR = lib.AV_LOG_ERROR
54 WARNING = lib.AV_LOG_WARNING
55 INFO = lib.AV_LOG_INFO
56 VERBOSE = lib.AV_LOG_VERBOSE
57 DEBUG = lib.AV_LOG_DEBUG
58 TRACE = lib.AV_LOG_TRACE
59
60 # Mimicking stdlib.
61 CRITICAL = FATAL
62
63
64 @cython.ccall
65 def adapt_level(level: cython.int):
66 """Convert a library log level to a Python log level."""
67 if level <= lib.AV_LOG_FATAL: # Includes PANIC
68 return 50 # logging.CRITICAL
69 elif level <= lib.AV_LOG_ERROR:
70 return 40 # logging.ERROR
71 elif level <= lib.AV_LOG_WARNING:
72 return 30 # logging.WARNING
73 elif level <= lib.AV_LOG_INFO:
74 return 20 # logging.INFO
75 elif level <= lib.AV_LOG_VERBOSE:
76 return 10 # logging.DEBUG
77 elif level <= lib.AV_LOG_DEBUG:
78 return 5 # Lower than any logging constant.
79 else: # lib.AV_LOG_TRACE
80 return 1
81
82
83 level_threshold = cython.declare(object, None)
84 c_level_threshold = cython.declare(cython.int, lib.AV_LOG_QUIET)
85
86 # ... but lets limit ourselves to WARNING (assuming nobody already did this).
87 if "libav" not in logging.Logger.manager.loggerDict:
88 logging.getLogger("libav").setLevel(logging.WARNING)
89
90
91 def get_level():
92 """Returns the current log level. See :func:`set_level`."""
93 return level_threshold
94
95
96 def set_level(level):
97 """set_level(level)
98
99 Sets PyAV's log level. It can be set to constants available in this
100 module: ``PANIC``, ``FATAL``, ``ERROR``, ``WARNING``, ``INFO``,
101 ``VERBOSE``, ``DEBUG``, or ``None`` (the default).
102
103 PyAV defaults to totally ignoring all ffmpeg logs. This has the side effect of
104 making certain Exceptions have no messages. It's therefore recommended to use:
105
106 av.logging.set_level(av.logging.VERBOSE)
107
108 When developing your application.
109 """
110 global level_threshold
111 global c_level_threshold
112
113 if level is None:
114 level_threshold = level
115 lib.av_log_set_callback(nolog_callback)
116 elif type(level) is int:
117 level_threshold = level
118 c_level_threshold = level
119 lib.av_log_set_callback(log_callback)
120 else:
121 raise ValueError("level must be: int | None")
122
123
124 def set_libav_level(level):
125 """Set libav's log level. It can be set to constants available in this
126 module: ``PANIC``, ``FATAL``, ``ERROR``, ``WARNING``, ``INFO``,
127 ``VERBOSE``, ``DEBUG``.
128
129 When PyAV logging is disabled, setting this will change the level of
130 the logs printed to the terminal.
131 """
132 lib.av_log_set_level(level)
133
134
135 def restore_default_callback():
136 """Revert back to FFmpeg's log callback, which prints to the terminal."""
137 lib.av_log_set_callback(lib.av_log_default_callback)
138
139
140 skip_repeated = cython.declare(cython.bint, True)
141 skip_lock = cython.declare(object, Lock())
142 last_log = cython.declare(object, None)
143 skip_count = cython.declare(cython.int, 0)
144
145
146 def get_skip_repeated():
147 """Will identical logs be emitted?"""
148 return skip_repeated
149
150
151 def set_skip_repeated(v):
152 """Set if identical logs will be emitted"""
153 global skip_repeated
154 skip_repeated = bool(v)
155
156
157 # For error reporting.
158 last_error = cython.declare(object, None)
159 error_count = cython.declare(cython.int, 0)
160
161
162 @cython.ccall
163 def get_last_error():
164 """Get the last log that was at least ``ERROR``."""
165 if error_count:
166 with skip_lock:
167 return error_count, last_error
168 else:
169 return 0, None
170
171
172 global_captures = cython.declare(list, [])
173 thread_captures = cython.declare(dict, {})
174
175
176 @cython.final
177 @cython.cclass
178 class Capture:
179 """A context manager for capturing logs.
180
181 :param bool local: Should logs from all threads be captured, or just one
182 this object is constructed in?
183
184 e.g.::
185
186 with Capture() as logs:
187 # Do something.
188 for log in logs:
189 print(log.message)
190
191 """
192
193 logs = cython.declare(list, visibility="readonly")
194 captures = cython.declare(list, visibility="private")
195
196 def __init__(self, local: cython.bint = True):
197 self.logs = []
198 if local:
199 self.captures = thread_captures.setdefault(get_ident(), [])
200 else:
201 self.captures = global_captures
202
203 def __enter__(self):
204 self.captures.append(self.logs)
205 return self.logs
206
207 def __exit__(self, type_, value, traceback):
208 self.captures.pop()
209
210
211 log_context = cython.struct(
212 class_=cython.pointer[lib.AVClass],
213 name=cython.p_char,
214 )
215
216 item_name_func = cython.typedef("const char *(*item_name_func)(void *) noexcept nogil")
217
218
219 @cython.cfunc
220 @cython.nogil
221 @cython.exceptval(check=False)
222 def log_context_name(ptr: cython.p_void) -> cython.p_char:
223 obj: cython.pointer[log_context] = cython.cast(cython.pointer[log_context], ptr)
224 return obj.name
225
226
227 log_class = cython.declare(lib.AVClass)
228 log_class.item_name = cython.cast(item_name_func, log_context_name)
229
230
231 @cython.ccall
232 def log(level: cython.int, name: str, message: str):
233 """Send a log through the library logging system.
234
235 This is mostly for testing.
236 """
237 obj: cython.pointer[log_context] = cython.cast(
238 cython.pointer[log_context], malloc(cython.sizeof(log_context))
239 )
240 obj.class_ = cython.address(log_class)
241 obj.name = name
242 message_bytes: bytes = message.encode("utf-8")
243
244 lib.av_log(
245 cython.cast(cython.p_void, obj),
246 level,
247 "%s",
248 cython.cast(cython.p_char, message_bytes),
249 )
250 free(obj)
251
252
253 @cython.cfunc
254 def log_callback_gil(
255 level: cython.int, c_name: cython.p_const_char, c_message: cython.p_char
256 ):
257 global error_count
258 global skip_count
259 global last_log
260 global last_error
261
262 name = cython.cast(str, c_name) if c_name is not cython.NULL else ""
263 message = cython.cast(bytes, c_message).decode("utf8", "backslashreplace")
264 log = (level, name, message)
265
266 # We have to filter it ourselves, but we will still process it in general so
267 # it is available to our error handling.
268 # Note that FFmpeg's levels are backwards from Python's.
269 is_interesting: cython.bint = level <= level_threshold
270
271 # Skip messages which are identical to the previous.
272 # TODO: Be smarter about threads.
273 is_repeated: cython.bint = False
274 repeat_log: object = None
275
276 with skip_lock:
277 if is_interesting:
278 is_repeated = skip_repeated and last_log == log
279
280 if is_repeated:
281 skip_count += 1
282
283 elif skip_count:
284 # Now that we have hit the end of the repeat cycle, tally up how many.
285 if skip_count == 1:
286 repeat_log = last_log
287 else:
288 repeat_log = (
289 last_log[0],
290 last_log[1],
291 "%s (repeated %d more times)" % (last_log[2], skip_count),
292 )
293 skip_count = 0
294
295 last_log = log
296
297 # Hold onto errors for err_check.
298 if level == lib.AV_LOG_ERROR:
299 error_count += 1
300 last_error = log
301
302 if repeat_log is not None:
303 log_callback_emit(repeat_log)
304
305 if is_interesting and not is_repeated:
306 log_callback_emit(log)
307
308
309 @cython.cfunc
310 def log_callback_emit(log):
311 lib_level, name, message = log
312
313 captures = thread_captures.get(get_ident()) or global_captures
314 if captures:
315 captures[-1].append(log)
316 return
317
318 py_level = adapt_level(lib_level)
319
320 logger_name = "libav." + name if name else "libav.generic"
321 logger = logging.getLogger(logger_name)
322 logger.log(py_level, message.strip())
323
324
325 @cython.cfunc
326 @cython.nogil
327 @cython.exceptval(check=False)
328 def log_callback(
329 ptr: cython.p_void,
330 level: cython.int,
331 format: cython.p_const_char,
332 args: lib.va_list,
333 ) -> cython.void:
334 inited: cython.bint = Py_IsInitialized()
335 if not inited:
336 return
337 if level > c_level_threshold and level != lib.AV_LOG_ERROR:
338 return
339
340 # Format the message.
341 message: cython.char[1024]
342 vsnprintf(message, 1023, format, args)
343
344 # Get the name.
345 name: cython.p_const_char = cython.NULL
346 cls: cython.pointer[lib.AVClass] = (
347 cython.cast(cython.pointer[cython.pointer[lib.AVClass]], ptr)[0]
348 if ptr
349 else cython.NULL
350 )
351 if cls and cls.item_name:
352 name = cls.item_name(ptr)
353
354 with cython.gil:
355 try:
356 log_callback_gil(level, name, message)
357 except Exception:
358 fprintf(
359 stderr,
360 "av.logging: exception while handling %s[%d]: %s\n",
361 name,
362 level,
363 message,
364 )
365 # For some reason PyErr_PrintEx(0) won't work.
366 exc, type_, tb = sys.exc_info()
367 PyErr_Display(exc, type_, tb)
368
369
370 @cython.cfunc
371 @cython.nogil
372 @cython.exceptval(check=False)
373 def nolog_callback(
374 ptr: cython.p_void,
375 level: cython.int,
376 format: cython.p_const_char,
377 args: lib.va_list,
378 ) -> cython.void:
379 pass
380
381
382 lib.av_log_set_callback(nolog_callback)