"""Capture cards on Linux: the picture through V4L2, the sound through ALSA (framegen/capture.py is the shared part; its Windows side is DirectShow). - Devices: every /dev/video* whose driver says it captures video (VIDIOC_QUERYCAP; a UVC card's second node is metadata and is left out), by the name its driver gives ("Live Gamer MINI"). Sound devices: the ALSA cards with a capture PCM (/proc/asound), by their name, opened as hw:CARD=. A card's sound device usually has the card's own name, so capture.pick_audio() finds it as it does on Windows. - Formats: VIDIOC_ENUM_FMT / ENUM_FRAMESIZES / ENUM_FRAMEINTERVALS, as capture.Mode, so capture.pick_mode() chooses the same way on both systems. - Opening: FFmpeg's video4linux2 and alsa inputs through PyAV. The PyAV wheel from PyPI is built without them; build it against the system's FFmpeg instead (`uv pip install --no-binary av av`), which on Arch has both, plus NVDEC/NVENC. - The picture and the sound are two inputs (on Windows, one DirectShow graph), each read on a thread of its own; FFmpeg times both by the wall clock, so CardSource.sound_late_s() still compares them. """ from __future__ import annotations import ctypes import fcntl import os import re from pathlib import Path from .capture import Device, Mode # PyAV's wheels bundle their own libasound, built to look for its config under /tmp/vendor, where nothing is: every # ALSA device then reads as "Unknown PCM". Point it at the system's config (it reads this when it first loads it). if "ALSA_CONFIG_PATH" not in os.environ: for _conf in ("/usr/share/alsa/alsa.conf", "/etc/alsa/alsa.conf"): if os.path.exists(_conf): os.environ["ALSA_CONFIG_PATH"] = _conf break VIDIOC_QUERYCAP = 0x80685600 VIDIOC_ENUM_FMT = 0xC0405602 VIDIOC_ENUM_FRAMESIZES = 0xC02C564A VIDIOC_ENUM_FRAMEINTERVALS = 0xC034564B CAP_VIDEO_CAPTURE, CAP_DEVICE_CAPS = 0x1, 0x80000000 BUF_TYPE_VIDEO_CAPTURE = 1 DISCRETE = 1 # V4L2_FRMSIZE_TYPE_DISCRETE == V4L2_FRMIVAL_TYPE_DISCRETE # V4L2 fourcc -> (FFmpeg's name for it: a pixel format or a codec, raw) FOURCC = {"MJPG": ("mjpeg", False), "JPEG": ("mjpeg", False), "H264": ("h264", False), "HEVC": ("hevc", False), "YUYV": ("yuyv422", True), "UYVY": ("uyvy422", True), "NV12": ("nv12", True), "YU12": ("yuv420p", True), "BGR3": ("bgr24", True), "RGB3": ("rgb24", True), "P010": ("p010", True)} u32 = ctypes.c_uint32 class _Cap(ctypes.Structure): _fields_ = [("driver", ctypes.c_char * 16), ("card", ctypes.c_char * 32), ("bus_info", ctypes.c_char * 32), ("version", u32), ("capabilities", u32), ("device_caps", u32), ("reserved", u32 * 3)] class _FmtDesc(ctypes.Structure): _fields_ = [("index", u32), ("type", u32), ("flags", u32), ("description", ctypes.c_char * 32), ("pixelformat", u32), ("mbus_code", u32), ("reserved", u32 * 3)] class _FrmSize(ctypes.Structure): _fields_ = [("index", u32), ("pixel_format", u32), ("type", u32), ("u", u32 * 6), ("reserved", u32 * 2)] class _FrmIval(ctypes.Structure): _fields_ = [("index", u32), ("pixel_format", u32), ("width", u32), ("height", u32), ("type", u32), ("u", u32 * 6), ("reserved", u32 * 2)] def _ioctl(fd: int, request: int, arg) -> bool: try: fcntl.ioctl(fd, request, arg) return True except OSError: return False def fourcc_name(v: int) -> str: return bytes((v >> s) & 0xFF for s in (0, 8, 16, 24)).decode("ascii", "replace").strip() # ---- devices --------------------------------------------------------------------------------------------------- def video_devices() -> list[Device]: """The video capture devices, in /dev/videoN order: Device(name, "video", alt=/dev/videoN). Two devices with one name (two of the same webcam) get " (2)" and so on after the second.""" out: list[Device] = [] seen: dict[str, int] = {} nodes = sorted(Path("/sys/class/video4linux").glob("video*"), key=lambda p: int(re.sub(r"\D", "", p.name) or 0)) for node in nodes: path = f"/dev/{node.name}" try: fd = os.open(path, os.O_RDWR | os.O_NONBLOCK) except OSError: continue # no permission (not in the video group) or gone try: cap = _Cap() if not _ioctl(fd, VIDIOC_QUERYCAP, cap): continue caps = cap.device_caps if cap.capabilities & CAP_DEVICE_CAPS else cap.capabilities if not caps & CAP_VIDEO_CAPTURE: continue # e.g. a UVC device's metadata node name = cap.card.decode("utf-8", "replace").strip() or node.name finally: os.close(fd) seen[name] = seen.get(name, 0) + 1 out.append(Device(name if seen[name] == 1 else f"{name} ({seen[name]})", "video", alt=path)) return out _CARD = re.compile(r"^\s*(\d+)\s+\[(\S+)\s*\]:\s+(.+?)\s+-\s+(.+?)\s*$") def parse_asound_cards(text: str) -> list[tuple[int, str, str]]: """(number, id, name) for each card in /proc/asound/cards: the line ` 5 [MINI ]: USB-Audio - Live Gamer MINI` is (5, "MINI", "Live Gamer MINI").""" out = [] for line in text.splitlines(): m = _CARD.match(line) if m: out.append((int(m.group(1)), m.group(2), m.group(4))) return out def audio_devices(root: Path = Path("/proc/asound")) -> list[Device]: """ALSA cards that can record: Device(name, "audio", alt="hw:CARD=").""" try: cards = parse_asound_cards((root / "cards").read_text()) except OSError: return [] return [Device(name, "audio", alt=f"hw:CARD={cid}") for n, cid, name in cards if any((root / f"card{n}").glob("pcm*c"))] def list_devices() -> list[Device]: return video_devices() + audio_devices() def resolve_video(name: str) -> str: """/dev/videoN for a device name (or the path itself).""" if name.startswith("/dev/"): return name for d in video_devices(): if d.name == name: return d.alt raise RuntimeError(f"no capture device named {name!r} (see run.py --list-devices); is the card plugged in?") def resolve_audio(name: str) -> str | None: """The ALSA device for a sound device's name (or an ALSA name itself), None if there's no such device.""" if re.match(r"^(plug)?hw:|^default$|^sysdefault", name): return name for d in audio_devices(): if d.name == name: return d.alt return None # ---- formats --------------------------------------------------------------------------------------------------- def enumerate_formats(fd: int) -> list[tuple[str, int, int, list[float]]]: """(fourcc, width, height, frame rates) for everything the device offers. A stepwise size or rate range is given by its ends.""" out = [] i = 0 while True: f = _FmtDesc(index=i, type=BUF_TYPE_VIDEO_CAPTURE) if not _ioctl(fd, VIDIOC_ENUM_FMT, f): break i += 1 j = 0 while True: s = _FrmSize(index=j, pixel_format=f.pixelformat) if not _ioctl(fd, VIDIOC_ENUM_FRAMESIZES, s): break j += 1 sizes = [(s.u[0], s.u[1])] if s.type == DISCRETE else [(s.u[1], s.u[3])] # stepwise: its largest for w, h in sizes: rates = [] k = 0 while True: v = _FrmIval(index=k, pixel_format=f.pixelformat, width=w, height=h) if not _ioctl(fd, VIDIOC_ENUM_FRAMEINTERVALS, v): break k += 1 fracs = [(v.u[0], v.u[1])] if v.type == DISCRETE else [(v.u[0], v.u[1]), (v.u[2], v.u[3])] rates += [den / num for num, den in fracs if num] if v.type != DISCRETE: break out.append((fourcc_name(f.pixelformat), w, h, rates)) if s.type != DISCRETE: break return out def modes_from(entries) -> list[Mode]: """capture.Mode for each (fourcc, w, h, rates) a device listed, in the formats SmoovPlay knows of.""" modes = [] for fourcc, w, h, rates in entries: if fourcc not in FOURCC or not rates: continue fmt, raw = FOURCC[fourcc] mode = Mode(fmt, raw, w, h, round(min(rates), 3), round(max(rates), 3)) if mode not in modes: modes.append(mode) return modes def list_modes(path: str) -> list[Mode]: fd = os.open(path, os.O_RDWR | os.O_NONBLOCK) try: return modes_from(enumerate_formats(fd)) finally: os.close(fd) def open_options(mode: Mode, fps: float = 60.0) -> dict: rate = min(fps, mode.fps_max) if mode.fps_max >= fps - 0.5 else mode.fps_max return {"input_format": mode.fmt, "video_size": f"{mode.w}x{mode.h}", "framerate": f"{rate:g}"} # ---- opening --------------------------------------------------------------------------------------------------- def holders(path: str) -> list[str]: """The programs (of this user) that have `path` open: who to close when the card is busy.""" names = [] real = os.path.realpath(path) for proc in Path("/proc").glob("[0-9]*"): try: if proc.name == str(os.getpid()): continue for fd in (proc / "fd").iterdir(): if os.readlink(fd) == real: comm = (proc / "comm").read_text().strip() if comm not in names: names.append(comm) break except OSError: continue return names def open_video(path: str, opts: dict, name: str): """av.open of the card's picture, with a plain-words reason when it fails.""" import av try: return av.open(path, format="video4linux2", options=opts) except av.error.OSError as e: if e.errno == 16: # EBUSY who = holders(path) raise RuntimeError(f"{name} is in use by " + (", ".join(who) if who else "another app") + ": close it there (a video call, OBS, a camera app), then press Play again. A card works " "with one app at a time") from e if e.errno == 13: # EACCES raise RuntimeError(f"no permission to open {path}: add yourself to the video group " "(sudo usermod -aG video $USER), then log out and in again") from e raise except ValueError as e: # a PyAV built without the video4linux2 input if "video4linux2" in str(e): raise RuntimeError("this PyAV has no video4linux2 input: reinstall it built against the system's FFmpeg " "(uv pip install --no-binary av av)") from e raise def open_audio(alsa: str): """av.open of the card's sound (16-bit stereo at 48 kHz, what HDMI cards send); plughw: if hw: won't take it.""" import av opts = {"sample_rate": "48000", "channels": "2"} try: return av.open(alsa, format="alsa", options=opts) except av.error.OSError: if alsa.startswith("hw:"): return av.open("plug" + alsa, format="alsa", options=opts) raise