feat(live): one port, a router, and a phrase per session (stage 1)
The session-stream web app: a single HTTP listener (9988) that serves a page
per enabled session, keyed by a spoken phrase. Off by default, so a stream
exists only for the sessions it was enabled on.
src/hhstream_live/phrase.py four EFF-large words + a 5-char base-36 tail
(~77.5 bits); the phrase is the password
src/hhstream_live/publisher.py one capture thread + one frame slot per
output; one slot/no queue; capture paused at
zero viewers
src/hhstream_live/server.py the router: /, /<phrase>/, /stream.mjpg,
/frame.jpg, /status.json; unknown phrase is
an empty 404, rate-limited
src/hhstream_live/pages.py the built-in dark pages (no CDN, no build)
src/hhstream_live/__main__.py hhstream-live serve|phrase, standalone
The root page is a form, never a list: the phrase is known only by whoever
enabled the stream. Transport is MJPEG (multipart/x-mixed-replace), reusing
the JPEG grim already produces. Not yet wired to the broker -- that is
stage 2. Tests: tests/live (51).
This commit is contained in:
1 parent
4b5cb5197a
commit
9744d35945
18 files changed
+9611
No files matched your search
@@ -0,0 +1,139 @@
|
||||
"""``hhstream-live`` -- run the session-stream web app.
|
||||
|
||||
Stage 1 runs it **standalone**: the streams are named on the command line as
|
||||
``--stream <phrase>=<output>``, which is enough to watch a real container and to
|
||||
drive the unit tests. Stage 2 adds the broker's control socket
|
||||
(``/run/hhstream/live.sock``), at which point ``--stream`` becomes the way a
|
||||
human debugs it rather than the way the broker configures it.
|
||||
|
||||
hhstream-live serve --stream four-words-and-a-tail=hh-demo
|
||||
hhstream-live phrase
|
||||
|
||||
The capture command is one list of words; the output is aimed by inserting
|
||||
``-o <output>`` before the trailing ``-``, which is grim's "write to stdout".
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import logging
|
||||
import sys
|
||||
|
||||
from . import phrase as phrase_mod
|
||||
from .publisher import DEFAULT_FPS, FPS_CAP, StreamRegistry, StreamSpec
|
||||
from .server import DEFAULT_HOST, DEFAULT_PORT, LiveServer
|
||||
|
||||
#: The session's own capture command, JPEG for the same reason the host config
|
||||
#: spells it out: a 1280x720 JPEG q80 is ~46 ms and the point is a video, not a
|
||||
#: slideshow. `-c` asks grim to include the cursor.
|
||||
DEFAULT_CAPTURE = ["grim", "-c", "-t", "jpeg", "-q", "80", "-"]
|
||||
|
||||
|
||||
def capture_argv(base: list[str], output: str) -> list[str]:
|
||||
"""Aim the base capture command at one output.
|
||||
|
||||
``grim`` writes to stdout when its last argument is ``-``; the output
|
||||
selector goes just before it so the shape holds for any tool that keeps that
|
||||
convention, and a base without a trailing ``-`` simply gets ``-o`` appended.
|
||||
"""
|
||||
base = list(base)
|
||||
if base and base[-1] == "-":
|
||||
return base[:-1] + ["-o", output, "-"]
|
||||
return base + ["-o", output]
|
||||
|
||||
|
||||
def parse_stream(arg: str) -> tuple[str, str]:
|
||||
"""``<phrase>=<output>`` -> the pair, each side checked non-empty."""
|
||||
phrase, sep, output = arg.partition("=")
|
||||
if not sep or not phrase.strip() or not output.strip():
|
||||
raise argparse.ArgumentTypeError(f"expected PHRASE=OUTPUT, got {arg!r}")
|
||||
try:
|
||||
return phrase_mod.validate(phrase), output.strip()
|
||||
except ValueError as exc:
|
||||
raise argparse.ArgumentTypeError(str(exc)) from exc
|
||||
|
||||
|
||||
def build_parser() -> argparse.ArgumentParser:
|
||||
parser = argparse.ArgumentParser(prog="hhstream-live", description=__doc__)
|
||||
parser.add_argument("--log-level", default="info",
|
||||
choices=["debug", "info", "warning", "error"])
|
||||
subs = parser.add_subparsers(dest="command")
|
||||
|
||||
serve = subs.add_parser("serve", help="run the web app (default)")
|
||||
serve.add_argument("--port", type=int, default=DEFAULT_PORT,
|
||||
help=f"the one port every stream shares (default {DEFAULT_PORT})")
|
||||
serve.add_argument("--bind", default=DEFAULT_HOST,
|
||||
help=f"address to bind (default {DEFAULT_HOST}, loopback)")
|
||||
serve.add_argument("--fps", type=int, default=DEFAULT_FPS,
|
||||
help=f"capture rate for streams that do not set one "
|
||||
f"(default {DEFAULT_FPS}, cap {FPS_CAP})")
|
||||
serve.add_argument("--stream", action="append", default=[], type=parse_stream,
|
||||
metavar="PHRASE=OUTPUT",
|
||||
help="enable a stream on this output; repeatable")
|
||||
serve.add_argument("--capture-command", action="append", default=None,
|
||||
metavar="WORD",
|
||||
help="capture argv word; repeat (a repeated flag is the "
|
||||
"only shape that survives words starting with '-')")
|
||||
|
||||
gen = subs.add_parser("phrase", help="print a fresh phrase and exit")
|
||||
gen.add_argument("--count", type=int, default=1)
|
||||
|
||||
return parser
|
||||
|
||||
|
||||
def make_registry(streams: list[tuple[str, str]], capture_base: list[str],
|
||||
fps: int) -> StreamRegistry:
|
||||
from hhstream.capture import CommandCapture
|
||||
|
||||
registry = StreamRegistry()
|
||||
for phrase, output in streams:
|
||||
spec = StreamSpec(phrase=phrase, output=output, fps=fps, label=output)
|
||||
registry.add(spec, CommandCapture(capture_argv(capture_base, output)))
|
||||
return registry
|
||||
|
||||
|
||||
def cmd_serve(args: argparse.Namespace) -> int:
|
||||
capture_base = args.capture_command or DEFAULT_CAPTURE
|
||||
registry = make_registry(args.stream, capture_base, args.fps)
|
||||
server = LiveServer(registry, host=args.bind, port=args.port)
|
||||
|
||||
print(f"landing page: http://{server.address}:{args.port}/", file=sys.stderr)
|
||||
if not args.stream:
|
||||
print("no --stream given; only the landing page will answer", file=sys.stderr)
|
||||
server.start() # raises OSError loudly if the port is taken
|
||||
for phrase in registry.phrases():
|
||||
print(server.url_for(phrase))
|
||||
sys.stdout.flush()
|
||||
|
||||
try:
|
||||
import time
|
||||
|
||||
while True:
|
||||
time.sleep(3600)
|
||||
except KeyboardInterrupt:
|
||||
print("stopping", file=sys.stderr)
|
||||
finally:
|
||||
server.stop()
|
||||
return 0
|
||||
|
||||
|
||||
def main(argv: list[str] | None = None) -> int:
|
||||
parser = build_parser()
|
||||
args = parser.parse_args(argv)
|
||||
logging.basicConfig(
|
||||
level=getattr(logging, (args.log_level or "info").upper()),
|
||||
format="%(asctime)s %(levelname)s %(name)s: %(message)s",
|
||||
)
|
||||
command = args.command or "serve"
|
||||
if command == "phrase":
|
||||
for _ in range(args.count):
|
||||
print(phrase_mod.generate())
|
||||
return 0
|
||||
if command == "serve":
|
||||
return cmd_serve(args)
|
||||
parser.error(f"unknown command {command!r}") # pragma: no cover
|
||||
return 2
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
Reference in new issue
Block a user