#!/usr/bin/env python3 """``hhs-mjpeg-read`` -- read a real MJPEG stream, and optionally keep watching. What `checks/vm-stream.nix` uses as the *person with a phone*. Two jobs, and the second is the one that matters: 1. Read N frames off ``multipart/x-mixed-replace`` and report their sizes, so "the stream works" is a statement about bytes a client actually received rather than about a 200. 2. **Hold the connection open** for a while afterwards. The broker counts connected viewers and treats one as activity, so proving that needs a viewer that is still there a minute later -- a client that read three frames and exited would make the sweep correct and untested. Standard library only, and a hand-rolled multipart reader rather than anything that understands HTTP for us: the framing is this repository's own (`hhstream_live.server`), and a parser that shared code with it could not tell you the boundary was wrong. """ from __future__ import annotations import argparse import json import socket import sys import time import urllib.parse SOI = b"\xff\xd8" EOI = b"\xff\xd9" def connect(url: str, timeout: float) -> socket.socket: parsed = urllib.parse.urlsplit(url) host = parsed.hostname or "127.0.0.1" port = parsed.port or 80 path = parsed.path or "/" sock = socket.create_connection((host, port), timeout=timeout) request = ( f"GET {path} HTTP/1.1\r\n" f"Host: {host}:{port}\r\n" "Accept: */*\r\n" "Connection: close\r\n\r\n" ) sock.sendall(request.encode("ascii")) return sock def read_headers(sock: socket.socket) -> tuple[int, dict[str, str], bytes]: buffer = b"" while b"\r\n\r\n" not in buffer: chunk = sock.recv(4096) if not chunk: raise SystemExit("the server closed the connection before any headers") buffer += chunk head, rest = buffer.split(b"\r\n\r\n", 1) lines = head.decode("latin-1").split("\r\n") status = int(lines[0].split()[1]) headers = {} for line in lines[1:]: if ":" in line: name, _, value = line.partition(":") headers[name.strip().lower()] = value.strip() return status, headers, rest def frames(sock: socket.socket, rest: bytes, wanted: int, deadline: float) -> list[int]: """Sizes of the JPEGs read off the multipart body, by SOI/EOI. Framed on the markers rather than on ``Content-Length``: a stream that sent the right lengths and the wrong bytes would pass a length-based reader, and what the check is about is whether a browser would paint this. """ sizes: list[int] = [] buffer = rest while len(sizes) < wanted: if time.monotonic() > deadline: raise SystemExit( f"only {len(sizes)} of {wanted} frames arrived before the deadline" ) start = buffer.find(SOI) end = buffer.find(EOI, start + 2) if start != -1 else -1 if start != -1 and end != -1: sizes.append(end + 2 - start) buffer = buffer[end + 2 :] continue try: chunk = sock.recv(65536) except TimeoutError: raise SystemExit("the stream went quiet") from None if not chunk: raise SystemExit("the stream ended before enough frames arrived") buffer += chunk return sizes def main(argv: list[str] | None = None) -> int: parser = argparse.ArgumentParser(prog="hhs-mjpeg-read", description=__doc__) parser.add_argument("url", help="the stream.mjpg URL") parser.add_argument("--frames", type=int, default=2, help="how many to read") parser.add_argument( "--hold", type=float, default=0.0, metavar="SECONDS", help="keep the connection open this long after reading, so the broker " "counts a viewer for that whole time", ) parser.add_argument("--timeout", type=float, default=30.0) args = parser.parse_args(argv) sock = connect(args.url, args.timeout) sock.settimeout(args.timeout) try: status, headers, rest = read_headers(sock) content_type = headers.get("content-type", "") if status != 200: print(json.dumps({"status": status}), flush=True) raise SystemExit(f"the stream answered {status}, not 200") if "multipart/x-mixed-replace" not in content_type: raise SystemExit(f"content-type is {content_type!r}, not multipart") sizes = frames(sock, rest, args.frames, time.monotonic() + args.timeout) print( json.dumps( {"status": status, "content_type": content_type, "frames": sizes} ), flush=True, ) if args.hold > 0: # Still connected, and still reading: a viewer that stopped reading # would have its socket buffer fill and the server would see it go. deadline = time.monotonic() + args.hold while time.monotonic() < deadline: try: if not sock.recv(65536): break except TimeoutError: continue print(json.dumps({"held_for_s": args.hold}), flush=True) finally: sock.close() return 0 if __name__ == "__main__": sys.exit(main())