vpstream 0.8.2__tar.gz → 0.8.4__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (80) hide show
  1. {vpstream-0.8.2 → vpstream-0.8.4}/CHANGELOG.md +18 -0
  2. vpstream-0.8.4/PKG-INFO +108 -0
  3. vpstream-0.8.4/README.md +88 -0
  4. {vpstream-0.8.2 → vpstream-0.8.4}/pyproject.toml +1 -1
  5. {vpstream-0.8.2 → vpstream-0.8.4}/src/vpstream/assets/dashboard.js +3 -1
  6. {vpstream-0.8.2 → vpstream-0.8.4}/src/vpstream/caddy.py +23 -9
  7. {vpstream-0.8.2 → vpstream-0.8.4}/src/vpstream/cli.py +16 -2
  8. {vpstream-0.8.2 → vpstream-0.8.4}/src/vpstream/control.py +89 -9
  9. {vpstream-0.8.2 → vpstream-0.8.4}/src/vpstream/daemon.py +3 -1
  10. {vpstream-0.8.2 → vpstream-0.8.4}/src/vpstream/doctor.py +1 -1
  11. vpstream-0.8.4/src/vpstream/mkv.py +175 -0
  12. {vpstream-0.8.2 → vpstream-0.8.4}/src/vpstream/public.py +7 -0
  13. vpstream-0.8.4/src/vpstream/reindex.py +113 -0
  14. {vpstream-0.8.2 → vpstream-0.8.4}/src/vpstream/stream.py +37 -3
  15. {vpstream-0.8.2 → vpstream-0.8.4}/src/vpstream/tests/fakes.py +67 -1
  16. vpstream-0.8.4/src/vpstream/tests/mkvdata.py +84 -0
  17. {vpstream-0.8.2 → vpstream-0.8.4}/src/vpstream/tests/test_caddy.py +14 -13
  18. {vpstream-0.8.2 → vpstream-0.8.4}/src/vpstream/tests/test_control.py +121 -2
  19. {vpstream-0.8.2 → vpstream-0.8.4}/src/vpstream/tests/test_daemon.py +30 -0
  20. vpstream-0.8.4/src/vpstream/tests/test_mkv.py +116 -0
  21. {vpstream-0.8.2 → vpstream-0.8.4}/src/vpstream/tests/test_public.py +16 -0
  22. vpstream-0.8.4/src/vpstream/tests/test_reindex.py +110 -0
  23. {vpstream-0.8.2 → vpstream-0.8.4}/src/vpstream/tests/test_stream.py +36 -0
  24. {vpstream-0.8.2 → vpstream-0.8.4}/src/vpstream/tests/test_stream_integration.py +87 -2
  25. vpstream-0.8.4/src/vpstream/tests/test_traffic.py +162 -0
  26. {vpstream-0.8.2 → vpstream-0.8.4}/src/vpstream/tools.py +12 -0
  27. vpstream-0.8.4/src/vpstream/traffic.py +116 -0
  28. vpstream-0.8.2/PKG-INFO +0 -270
  29. vpstream-0.8.2/README.md +0 -250
  30. {vpstream-0.8.2 → vpstream-0.8.4}/.gitignore +0 -0
  31. {vpstream-0.8.2 → vpstream-0.8.4}/LICENSE +0 -0
  32. {vpstream-0.8.2 → vpstream-0.8.4}/src/vpstream/__init__.py +0 -0
  33. {vpstream-0.8.2 → vpstream-0.8.4}/src/vpstream/__main__.py +0 -0
  34. {vpstream-0.8.2 → vpstream-0.8.4}/src/vpstream/access.py +0 -0
  35. {vpstream-0.8.2 → vpstream-0.8.4}/src/vpstream/api.py +0 -0
  36. {vpstream-0.8.2 → vpstream-0.8.4}/src/vpstream/assets/__init__.py +0 -0
  37. {vpstream-0.8.2 → vpstream-0.8.4}/src/vpstream/assets/caps.html +0 -0
  38. {vpstream-0.8.2 → vpstream-0.8.4}/src/vpstream/assets/caps.js +0 -0
  39. {vpstream-0.8.2 → vpstream-0.8.4}/src/vpstream/assets/dashboard.html +0 -0
  40. {vpstream-0.8.2 → vpstream-0.8.4}/src/vpstream/assets/hls.js.LICENSE +0 -0
  41. {vpstream-0.8.2 → vpstream-0.8.4}/src/vpstream/assets/hls.js.version +0 -0
  42. {vpstream-0.8.2 → vpstream-0.8.4}/src/vpstream/assets/hls.min.js +0 -0
  43. {vpstream-0.8.2 → vpstream-0.8.4}/src/vpstream/bench.py +0 -0
  44. {vpstream-0.8.2 → vpstream-0.8.4}/src/vpstream/caps/__init__.py +0 -0
  45. {vpstream-0.8.2 → vpstream-0.8.4}/src/vpstream/caps/clips.py +0 -0
  46. {vpstream-0.8.2 → vpstream-0.8.4}/src/vpstream/caps/server.py +0 -0
  47. {vpstream-0.8.2 → vpstream-0.8.4}/src/vpstream/client.py +0 -0
  48. {vpstream-0.8.2 → vpstream-0.8.4}/src/vpstream/config.py +0 -0
  49. {vpstream-0.8.2 → vpstream-0.8.4}/src/vpstream/ffargs.py +0 -0
  50. {vpstream-0.8.2 → vpstream-0.8.4}/src/vpstream/ffmpeg_install.py +0 -0
  51. {vpstream-0.8.2 → vpstream-0.8.4}/src/vpstream/files.py +0 -0
  52. {vpstream-0.8.2 → vpstream-0.8.4}/src/vpstream/firewall.py +0 -0
  53. {vpstream-0.8.2 → vpstream-0.8.4}/src/vpstream/gate.py +0 -0
  54. {vpstream-0.8.2 → vpstream-0.8.4}/src/vpstream/media.py +0 -0
  55. {vpstream-0.8.2 → vpstream-0.8.4}/src/vpstream/net.py +0 -0
  56. {vpstream-0.8.2 → vpstream-0.8.4}/src/vpstream/probe.py +0 -0
  57. {vpstream-0.8.2 → vpstream-0.8.4}/src/vpstream/selftest.py +0 -0
  58. {vpstream-0.8.2 → vpstream-0.8.4}/src/vpstream/service.py +0 -0
  59. {vpstream-0.8.2 → vpstream-0.8.4}/src/vpstream/state.py +0 -0
  60. {vpstream-0.8.2 → vpstream-0.8.4}/src/vpstream/subtitles.py +0 -0
  61. {vpstream-0.8.2 → vpstream-0.8.4}/src/vpstream/tailscale.py +0 -0
  62. {vpstream-0.8.2 → vpstream-0.8.4}/src/vpstream/tests/__init__.py +0 -0
  63. {vpstream-0.8.2 → vpstream-0.8.4}/src/vpstream/tests/conftest.py +0 -0
  64. {vpstream-0.8.2 → vpstream-0.8.4}/src/vpstream/tests/data/three-cues.sup +0 -0
  65. {vpstream-0.8.2 → vpstream-0.8.4}/src/vpstream/tests/test_access.py +0 -0
  66. {vpstream-0.8.2 → vpstream-0.8.4}/src/vpstream/tests/test_assets.py +0 -0
  67. {vpstream-0.8.2 → vpstream-0.8.4}/src/vpstream/tests/test_bench.py +0 -0
  68. {vpstream-0.8.2 → vpstream-0.8.4}/src/vpstream/tests/test_caps.py +0 -0
  69. {vpstream-0.8.2 → vpstream-0.8.4}/src/vpstream/tests/test_cli.py +0 -0
  70. {vpstream-0.8.2 → vpstream-0.8.4}/src/vpstream/tests/test_config.py +0 -0
  71. {vpstream-0.8.2 → vpstream-0.8.4}/src/vpstream/tests/test_doctor.py +0 -0
  72. {vpstream-0.8.2 → vpstream-0.8.4}/src/vpstream/tests/test_ffargs.py +0 -0
  73. {vpstream-0.8.2 → vpstream-0.8.4}/src/vpstream/tests/test_ffmpeg_install.py +0 -0
  74. {vpstream-0.8.2 → vpstream-0.8.4}/src/vpstream/tests/test_firewall.py +0 -0
  75. {vpstream-0.8.2 → vpstream-0.8.4}/src/vpstream/tests/test_gate.py +0 -0
  76. {vpstream-0.8.2 → vpstream-0.8.4}/src/vpstream/tests/test_host_integration.py +0 -0
  77. {vpstream-0.8.2 → vpstream-0.8.4}/src/vpstream/tests/test_integration.py +0 -0
  78. {vpstream-0.8.2 → vpstream-0.8.4}/src/vpstream/tests/test_probe.py +0 -0
  79. {vpstream-0.8.2 → vpstream-0.8.4}/src/vpstream/tests/test_service.py +0 -0
  80. {vpstream-0.8.2 → vpstream-0.8.4}/src/vpstream/tests/test_subtitles.py +0 -0
@@ -2,6 +2,24 @@
2
2
 
3
3
  <!-- version list -->
4
4
 
5
+ ## v0.8.4 (2026-11-11)
6
+
7
+ ### Bug Fixes
8
+
9
+ - Serve MKV files with a full seek index, so VLC resumes them quickly
10
+ ([#15](https://github.com/skj-skj/vpstream/pull/15),
11
+ [`3749019`](https://github.com/skj-skj/vpstream/commit/3749019b7316f31b0a596ed7a4b81f39e1894183))
12
+
13
+
14
+ ## v0.8.3 (2026-11-11)
15
+
16
+ ### Bug Fixes
17
+
18
+ - Count the bytes each viewer got from the kernel, not only from Caddy's log
19
+ ([#14](https://github.com/skj-skj/vpstream/pull/14),
20
+ [`8605f3c`](https://github.com/skj-skj/vpstream/commit/8605f3c8e7383fed5fa60e1e2fdab41c467295c3))
21
+
22
+
5
23
  ## v0.8.2 (2026-11-11)
6
24
 
7
25
  ### Bug Fixes
@@ -0,0 +1,108 @@
1
+ Metadata-Version: 2.5
2
+ Name: vpstream
3
+ Version: 0.8.4
4
+ Summary: On-demand video streaming from a VPS, controlled over SSH or a private dashboard
5
+ License-Expression: MIT
6
+ License-File: LICENSE
7
+ License-File: src/vpstream/assets/hls.js.LICENSE
8
+ Classifier: Environment :: Console
9
+ Classifier: Operating System :: POSIX :: Linux
10
+ Classifier: Programming Language :: Python :: 3
11
+ Classifier: Programming Language :: Python :: 3.12
12
+ Classifier: Programming Language :: Python :: 3.13
13
+ Classifier: Programming Language :: Python :: 3.14
14
+ Classifier: Topic :: Multimedia :: Video
15
+ Requires-Python: >=3.12
16
+ Requires-Dist: flask>=3.0
17
+ Provides-Extra: dev
18
+ Requires-Dist: pytest>=8; extra == 'dev'
19
+ Description-Content-Type: text/markdown
20
+
21
+ # vpstream
22
+
23
+ On-demand video streaming from a VPS. The public port is open only while a stream runs, and
24
+ everything is controlled over SSH or a dashboard on your tailnet.
25
+
26
+ Status: early development. Streams a file or a folder as it is, for players such as VLC and
27
+ mpv (direct mode). Playing in a TV browser comes next.
28
+
29
+ ## Install
30
+
31
+ Needs Linux, Python 3.12+, Caddy, ufw, Tailscale (with HTTPS certificates) and systemd.
32
+ ffmpeg is used by `bench` and `caps`; mkvtoolnix and the `acl` package are optional (see
33
+ below). `vpstream doctor` checks all of it and prints the fix for anything missing.
34
+
35
+ ```text
36
+ sudo PIPX_HOME=/opt/pipx PIPX_BIN_DIR=/usr/local/bin pipx install "vpstream[dev]"
37
+ vpstream doctor
38
+ sudo vpstream init
39
+ ```
40
+
41
+ The install must be system-wide (the service runs as its own user). Upgrade with the same
42
+ prefix and `pipx upgrade vpstream`, then `sudo vpstream init` again.
43
+
44
+ ## Commands
45
+
46
+ | Command | What it does |
47
+ | --- | --- |
48
+ | `vpstream start --file F` / `--dir D` | Starts a stream of one video, or of a folder's videos |
49
+ | `vpstream stop` / `status` | Stops the stream, or shows its addresses and state |
50
+ | `vpstream devices [enable\|disable ADDRESS \| lock \| unlock]` | Who asked for the stream, and who gets in |
51
+ | `vpstream alias NAME` | Changes the short name in the address |
52
+ | `vpstream revoke` | Takes back file access a stream that ended by itself left behind |
53
+ | `vpstream doctor` | Checks this host |
54
+ | `sudo vpstream init` / `uninstall` | Sets the service up, or removes it (`--purge` also the cache) |
55
+ | `vpstream bench FILE` | Measures how fast this host copies, transcodes and burns in subtitles |
56
+ | `vpstream caps` | Serves a page that tests what a TV browser can play |
57
+ | `vpstream install ffmpeg` / `update ffmpeg` | Installs or updates a current static ffmpeg build |
58
+ | `vpstream selftest [--integration]` | Runs the tests shipped with the package |
59
+
60
+ ## Streaming
61
+
62
+ ```text
63
+ vpstream start --file /srv/media/film.mkv # http://<ip>:1337/abc
64
+ vpstream start --dir /srv/media/show --alias show # /show (index or playlist), /show/1, /show/2 ...
65
+ vpstream stop
66
+ ```
67
+
68
+ - **Addresses:** `/ALIAS` plays a `--file` stream. For `--dir` it is an episode list in a
69
+ browser and an M3U playlist in a player; videos are numbered in natural order of their names.
70
+ - **Who gets in:** `--policy open` (default; disable single addresses), `approval` (only those
71
+ you approve; others wait, marked WL) or `locked` (only enabled ones). Change it live with
72
+ `vpstream devices` or the dashboard. An address that tries 20 wrong paths is shut out.
73
+ - **Time limit:** `--ttl MINUTES`, default 180, 0 for none.
74
+ - **Your files:** the service reads videos as its own user. If it cannot, `start` gives it
75
+ read access with an ACL entry for that user alone (needs the `acl` package and you owning
76
+ the files); `stop` takes it back.
77
+ - **Seeking:** MKV files whose seek index has no audio entries (most of them) make VLC for
78
+ Android resume by reading from the start. vpstream serves such a file from a copy with a full
79
+ index, made once with mkvmerge (no re-encoding, about a minute per GB) and kept in
80
+ `/var/cache/vpstream/index`; until it is ready the address says to try again. Without
81
+ mkvtoolnix the file is served as it is.
82
+ - **Safety:** Caddy runs only while a stream does and asks the daemon about every request.
83
+ Stop, the time limit and stopping the service close the port; after a crash the stream is
84
+ taken up again, never after a reboot. The stream is plain HTTP.
85
+
86
+ ## Configuration
87
+
88
+ `/etc/vpstream/config.toml`: `port` (1337) and `host` (the address shown in URLs) under
89
+ `[stream]`, `port` (1338) under `[dashboard]`. Restart the service after a change.
90
+
91
+ The dashboard listens on `127.0.0.1` and `init` publishes it with `tailscale serve` at
92
+ `https://<tailnet name>:1338/`. The stream port is opened and closed by a small root helper,
93
+ `vpstream-fw`, which only runs `ufw allow` / `ufw delete allow` for that one port.
94
+
95
+ ## Development
96
+
97
+ ```text
98
+ python -m venv .venv && .venv/bin/pip install -e ".[dev]"
99
+ .venv/bin/pytest [--integration]
100
+ git config core.hooksPath .githooks
101
+ ```
102
+
103
+ Pull request titles are Conventional Commits; releases are made from `main` by
104
+ python-semantic-release. hls.js (Apache-2.0) is bundled; `scripts/update-hlsjs.py` updates it.
105
+
106
+ ## License
107
+
108
+ MIT
@@ -0,0 +1,88 @@
1
+ # vpstream
2
+
3
+ On-demand video streaming from a VPS. The public port is open only while a stream runs, and
4
+ everything is controlled over SSH or a dashboard on your tailnet.
5
+
6
+ Status: early development. Streams a file or a folder as it is, for players such as VLC and
7
+ mpv (direct mode). Playing in a TV browser comes next.
8
+
9
+ ## Install
10
+
11
+ Needs Linux, Python 3.12+, Caddy, ufw, Tailscale (with HTTPS certificates) and systemd.
12
+ ffmpeg is used by `bench` and `caps`; mkvtoolnix and the `acl` package are optional (see
13
+ below). `vpstream doctor` checks all of it and prints the fix for anything missing.
14
+
15
+ ```text
16
+ sudo PIPX_HOME=/opt/pipx PIPX_BIN_DIR=/usr/local/bin pipx install "vpstream[dev]"
17
+ vpstream doctor
18
+ sudo vpstream init
19
+ ```
20
+
21
+ The install must be system-wide (the service runs as its own user). Upgrade with the same
22
+ prefix and `pipx upgrade vpstream`, then `sudo vpstream init` again.
23
+
24
+ ## Commands
25
+
26
+ | Command | What it does |
27
+ | --- | --- |
28
+ | `vpstream start --file F` / `--dir D` | Starts a stream of one video, or of a folder's videos |
29
+ | `vpstream stop` / `status` | Stops the stream, or shows its addresses and state |
30
+ | `vpstream devices [enable\|disable ADDRESS \| lock \| unlock]` | Who asked for the stream, and who gets in |
31
+ | `vpstream alias NAME` | Changes the short name in the address |
32
+ | `vpstream revoke` | Takes back file access a stream that ended by itself left behind |
33
+ | `vpstream doctor` | Checks this host |
34
+ | `sudo vpstream init` / `uninstall` | Sets the service up, or removes it (`--purge` also the cache) |
35
+ | `vpstream bench FILE` | Measures how fast this host copies, transcodes and burns in subtitles |
36
+ | `vpstream caps` | Serves a page that tests what a TV browser can play |
37
+ | `vpstream install ffmpeg` / `update ffmpeg` | Installs or updates a current static ffmpeg build |
38
+ | `vpstream selftest [--integration]` | Runs the tests shipped with the package |
39
+
40
+ ## Streaming
41
+
42
+ ```text
43
+ vpstream start --file /srv/media/film.mkv # http://<ip>:1337/abc
44
+ vpstream start --dir /srv/media/show --alias show # /show (index or playlist), /show/1, /show/2 ...
45
+ vpstream stop
46
+ ```
47
+
48
+ - **Addresses:** `/ALIAS` plays a `--file` stream. For `--dir` it is an episode list in a
49
+ browser and an M3U playlist in a player; videos are numbered in natural order of their names.
50
+ - **Who gets in:** `--policy open` (default; disable single addresses), `approval` (only those
51
+ you approve; others wait, marked WL) or `locked` (only enabled ones). Change it live with
52
+ `vpstream devices` or the dashboard. An address that tries 20 wrong paths is shut out.
53
+ - **Time limit:** `--ttl MINUTES`, default 180, 0 for none.
54
+ - **Your files:** the service reads videos as its own user. If it cannot, `start` gives it
55
+ read access with an ACL entry for that user alone (needs the `acl` package and you owning
56
+ the files); `stop` takes it back.
57
+ - **Seeking:** MKV files whose seek index has no audio entries (most of them) make VLC for
58
+ Android resume by reading from the start. vpstream serves such a file from a copy with a full
59
+ index, made once with mkvmerge (no re-encoding, about a minute per GB) and kept in
60
+ `/var/cache/vpstream/index`; until it is ready the address says to try again. Without
61
+ mkvtoolnix the file is served as it is.
62
+ - **Safety:** Caddy runs only while a stream does and asks the daemon about every request.
63
+ Stop, the time limit and stopping the service close the port; after a crash the stream is
64
+ taken up again, never after a reboot. The stream is plain HTTP.
65
+
66
+ ## Configuration
67
+
68
+ `/etc/vpstream/config.toml`: `port` (1337) and `host` (the address shown in URLs) under
69
+ `[stream]`, `port` (1338) under `[dashboard]`. Restart the service after a change.
70
+
71
+ The dashboard listens on `127.0.0.1` and `init` publishes it with `tailscale serve` at
72
+ `https://<tailnet name>:1338/`. The stream port is opened and closed by a small root helper,
73
+ `vpstream-fw`, which only runs `ufw allow` / `ufw delete allow` for that one port.
74
+
75
+ ## Development
76
+
77
+ ```text
78
+ python -m venv .venv && .venv/bin/pip install -e ".[dev]"
79
+ .venv/bin/pytest [--integration]
80
+ git config core.hooksPath .githooks
81
+ ```
82
+
83
+ Pull request titles are Conventional Commits; releases are made from `main` by
84
+ python-semantic-release. hls.js (Apache-2.0) is bundled; `scripts/update-hlsjs.py` updates it.
85
+
86
+ ## License
87
+
88
+ MIT
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "vpstream"
7
- version = "0.8.2"
7
+ version = "0.8.4"
8
8
  description = "On-demand video streaming from a VPS, controlled over SSH or a private dashboard"
9
9
  readme = "README.md"
10
10
  license = "MIT"
@@ -95,7 +95,9 @@
95
95
  }
96
96
  stream.videos.forEach(function (video) {
97
97
  var url = stream.kind === "dir" ? video.url : stream.url;
98
- rows.push(row([stream.kind === "dir" ? video.number : "", el("td", url, "url"), video.name]));
98
+ var name = video.name + (video.preparing ? " (preparing a seek index)" : "") +
99
+ (video.note ? " (" + video.note + ")" : "");
100
+ rows.push(row([stream.kind === "dir" ? video.number : "", el("td", url, "url"), name]));
99
101
  });
100
102
  fill($("videos"), rows);
101
103
  }
@@ -23,6 +23,7 @@ from typing import Any, Protocol
23
23
 
24
24
  from vpstream.config import Paths
25
25
  from vpstream.files import write_atomic
26
+ from vpstream.net import normal_ip
26
27
  from vpstream.tools import Runner, require
27
28
 
28
29
  # Set by Caddy on the way in, whatever the viewer sent: the address the request came from.
@@ -41,12 +42,22 @@ class CaddyError(RuntimeError):
41
42
  pass
42
43
 
43
44
 
44
- def link_videos(folder: Path, videos: Sequence[str]) -> None:
45
- """Fill `folder` with one link per video, named 1, 2, 3 and so on. What was there goes."""
45
+ def link_videos(folder: Path, videos: Sequence[str | None]) -> None:
46
+ """Fill `folder` with one link per video, named 1, 2, 3 and so on; None leaves a number
47
+ without one for now. What was there goes."""
46
48
  unlink_videos(folder)
47
49
  folder.mkdir(mode=0o750, parents=True)
48
50
  for number, video in enumerate(videos, 1):
49
- (folder / str(number)).symlink_to(video)
51
+ if video is not None:
52
+ (folder / str(number)).symlink_to(video)
53
+
54
+
55
+ def link_video(folder: Path, number: int, video: str) -> None:
56
+ """Point one number at `video`, in one step: a request sees the old link or the new."""
57
+ part = folder / f".{number}.new"
58
+ part.unlink(missing_ok=True)
59
+ part.symlink_to(video)
60
+ os.replace(part, folder / str(number))
50
61
 
51
62
 
52
63
  def unlink_videos(folder: Path) -> None:
@@ -118,18 +129,21 @@ def config(port: int, gate_socket: Path, access_log: Path, videos_dir: Path) ->
118
129
  # --- the access log
119
130
 
120
131
 
121
- def log_entry(line: str) -> tuple[str, int] | None:
122
- """The viewer's address and the bytes sent, from one line of the access log."""
132
+ def log_entry(line: str) -> tuple[str, str, int] | None:
133
+ """The viewer's address and port, and the bytes sent, from one line of the access log.
134
+ Caddy 2.6.2 logs about 512 bytes for a transfer the viewer cut off (see `traffic`)."""
123
135
  try:
124
136
  data = json.loads(line)
125
137
  request = data["request"]
126
- ip = request.get("remote_ip") or request["remote_addr"].rsplit(":", 1)[0].strip("[]")
138
+ host, _, port = str(request.get("remote_addr") or "").rpartition(":")
139
+ ip = normal_ip(request.get("remote_ip") or host.strip("[]"))
140
+ port = str(request.get("remote_port") or port)
127
141
  size = data["size"]
128
142
  except (ValueError, KeyError, TypeError, AttributeError):
129
143
  return None
130
- if not isinstance(ip, str) or isinstance(size, bool) or not isinstance(size, int):
144
+ if ip is None or isinstance(size, bool) or not isinstance(size, int):
131
145
  return None
132
- return ip, size
146
+ return ip, port, size
133
147
 
134
148
 
135
149
  class LogTail:
@@ -141,7 +155,7 @@ class LogTail:
141
155
  self._offset = 0
142
156
  self._rest = b""
143
157
 
144
- def read(self) -> Iterator[tuple[str, int]]:
158
+ def read(self) -> Iterator[tuple[str, str, int]]:
145
159
  try:
146
160
  with self.path.open("rb") as fh:
147
161
  st = os.fstat(fh.fileno())
@@ -221,12 +221,26 @@ def format_stream(stream: dict[str, Any]) -> str:
221
221
  f"Address: {stream.get('url')} (index for browsers, playlist for players)"
222
222
  )
223
223
  width = len(str(len(videos)))
224
- lines += [f" {v['number']:>{width}} {v['url']} {v['name']}" for v in videos]
224
+ lines += [
225
+ f" {v['number']:>{width}} {v['url']} {v['name']}{_video_state(v)}" for v in videos
226
+ ]
225
227
  else:
226
- lines.append(f"Address: {stream.get('url')}")
228
+ lines.append(f"Address: {stream.get('url')}{''.join(map(_video_state, videos[:1]))}")
229
+ preparing = sum(bool(v.get("preparing")) for v in videos)
230
+ if preparing:
231
+ lines.append(
232
+ f"Preparing: {preparing} MKV {'file gets' if preparing == 1 else 'files get'} a "
233
+ "full seek index (no re-encoding, about a minute per GB); until then its address "
234
+ "says to try again"
235
+ )
236
+ lines += [f"note: video {v['number']}: {v['note']}" for v in videos if v.get("note")]
227
237
  return "\n".join(lines)
228
238
 
229
239
 
240
+ def _video_state(video: dict[str, Any]) -> str:
241
+ return " [preparing]" if video.get("preparing") else ""
242
+
243
+
230
244
  def format_status(info: dict[str, Any], cli_version: str) -> str:
231
245
  """The daemon's status as text for `vpstream status`."""
232
246
  dash = info.get("dashboard") or {}
@@ -10,12 +10,13 @@ from dataclasses import dataclass, field
10
10
  from pathlib import Path
11
11
  from typing import Any
12
12
 
13
- from vpstream import net, state
14
- from vpstream.caddy import CaddyError, LogTail, Server, link_videos, unlink_videos
13
+ from vpstream import mkv, net, reindex, state
14
+ from vpstream.caddy import CaddyError, Server, link_video, link_videos, unlink_videos
15
15
  from vpstream.config import Config, Paths
16
16
  from vpstream.firewall import Firewall, FirewallError
17
17
  from vpstream.stream import MISSING, Answer, Stream, StreamError, check_alias
18
- from vpstream.tools import ToolMissing
18
+ from vpstream.tools import NO_PROGRAMS, Runner, ToolMissing
19
+ from vpstream.traffic import Traffic
19
20
 
20
21
  BOOT_ID = "/proc/sys/kernel/random/boot_id"
21
22
 
@@ -50,7 +51,10 @@ class Control:
50
51
  # stream record is read or changed.
51
52
  _op: threading.RLock = field(default_factory=threading.RLock)
52
53
  _lock: threading.RLock = field(default_factory=threading.RLock)
53
- _tail: LogTail | None = None
54
+ runner: Runner | None = None # for `ss`; without one, the access log alone counts bytes
55
+ _traffic: Traffic | None = None
56
+ _indexer: threading.Thread | None = None
57
+ _cancel: threading.Event = field(default_factory=threading.Event)
54
58
  _host: str = ""
55
59
 
56
60
  # --- the pieces
@@ -92,7 +96,10 @@ class Control:
92
96
  if self.server is None:
93
97
  raise ControlError("this daemon has no public server to start")
94
98
  try:
95
- link_videos(self.paths.videos_dir, stream.videos)
99
+ link_videos(
100
+ self.paths.videos_dir,
101
+ [None if n in stream.indexing else v for n, v in enumerate(stream.served, 1)],
102
+ )
96
103
  self.server.start()
97
104
  except (CaddyError, ToolMissing, OSError) as exc:
98
105
  unlink_videos(self.paths.videos_dir)
@@ -101,7 +108,9 @@ class Control:
101
108
  self._port("open")
102
109
  with self._lock:
103
110
  self.stream = stream
104
- self._tail = LogTail(self.paths.access_log)
111
+ self._traffic = Traffic(
112
+ self.runner or NO_PROGRAMS, self.config.stream_port, self.paths.access_log
113
+ )
105
114
  self._save()
106
115
  except (FirewallError, OSError) as exc:
107
116
  # A helper that was cut off may have opened the port all the same.
@@ -111,7 +120,7 @@ class Control:
111
120
  def _undo(self) -> None:
112
121
  """Take back whatever a start or a stop left: nothing of it may fail the caller."""
113
122
  with self._lock:
114
- self.stream = self._tail = None
123
+ self.stream = self._traffic = None
115
124
  steps: tuple[tuple[str, Callable[[], None]], ...] = (
116
125
  ("closing the stream port", lambda: self._port("close")),
117
126
  ("stopping Caddy", self._stop_server),
@@ -140,6 +149,7 @@ class Control:
140
149
  def _end(self, why: str) -> None:
141
150
  """Forget the stream and its approvals, so the gate refuses at once; then close the
142
151
  port and stop Caddy. Called with `_op` held."""
152
+ self._stop_indexing()
143
153
  self._undo()
144
154
  port = self.config.stream_port
145
155
  if self.firewall_problem:
@@ -148,6 +158,72 @@ class Control:
148
158
  port_now = "is closed" if self.firewall else "was not opened (no firewall helper)"
149
159
  self.log(f"the stream is stopped ({why}); stream port {port} {port_now}")
150
160
 
161
+ # --- the seek index of MKV files (see `mkv`)
162
+
163
+ def _plan_index(self, stream: Stream, numbers: Any) -> None:
164
+ """Serve a copy with a proper index for each of these videos that lacks one: the
165
+ copy made before, or one made now (`indexing`). Without mkvmerge, the video itself."""
166
+ can_fix = bool(self.runner and self.runner.which(reindex.TOOL))
167
+ for n in numbers:
168
+ source = stream.videos[n - 1]
169
+ stream.indexing.discard(n)
170
+ problem = mkv.index_problem(source)
171
+ if problem is None:
172
+ continue
173
+ copy = reindex.ready(self.paths.cache_dir, source)
174
+ if copy is not None:
175
+ stream.served[n - 1] = str(copy.resolve())
176
+ elif can_fix:
177
+ stream.indexing.add(n)
178
+ self.log(f"video {n}: {problem}; making a copy with a full index")
179
+ else:
180
+ stream.notes[n] = f"{problem}, so VLC resumes it slowly (install mkvtoolnix)"
181
+
182
+ def _start_indexing(self, stream: Stream) -> None:
183
+ if not stream.indexing or self.runner is None:
184
+ return
185
+ self._cancel = threading.Event()
186
+ self._indexer = threading.Thread(
187
+ target=self._index, args=(stream, self.runner, self._cancel), daemon=True
188
+ )
189
+ self._indexer.start()
190
+
191
+ def _stop_indexing(self) -> None:
192
+ self._cancel.set()
193
+ if self._indexer is not None:
194
+ self._indexer.join(timeout=15)
195
+ self._indexer = None
196
+
197
+ def _index(self, stream: Stream, runner: Runner, cancel: threading.Event) -> None:
198
+ """Make the copies one after the other. Each is served as soon as it is ready."""
199
+ for n in sorted(stream.indexing):
200
+ source = stream.videos[n - 1]
201
+ started = time.monotonic()
202
+ note = None
203
+ try:
204
+ out = reindex.copy_path(self.paths.cache_dir, source)
205
+ if not out.is_file(): # the same file may be in the folder twice
206
+ reindex.make(runner, source, out, cancel)
207
+ served = str(out.resolve())
208
+ except reindex.Cancelled:
209
+ return
210
+ except (reindex.ReindexError, ToolMissing, OSError) as exc:
211
+ served, note = source, f"VLC resumes it slowly: the copy failed: {exc}"
212
+ with self._lock:
213
+ if self.stream is not stream or cancel.is_set():
214
+ return
215
+ stream.served[n - 1] = served
216
+ stream.indexing.discard(n)
217
+ if note:
218
+ stream.notes[n] = note
219
+ try:
220
+ link_video(self.paths.videos_dir, n, served)
221
+ self._save()
222
+ except OSError as exc:
223
+ self.log(f"WARNING: video {n}: {exc}")
224
+ took = time.monotonic() - started
225
+ self.log(f"video {n}: {note or f'copy with a full index ready ({took:.0f} s)'}")
226
+
151
227
  # --- when the daemon starts and stops
152
228
 
153
229
  def reconcile(self) -> None:
@@ -188,11 +264,13 @@ class Control:
188
264
  if stream.expires is not None and stream.expires <= self.clock():
189
265
  self.log("the recorded stream's time limit is over; it is not started again")
190
266
  return False
267
+ self._plan_index(stream, sorted(stream.indexing))
191
268
  try:
192
269
  self._serve(stream)
193
270
  except ControlError as exc:
194
271
  self.log(f"WARNING: the recorded stream could not be started again: {exc}")
195
272
  return False
273
+ self._start_indexing(stream)
196
274
  self.log(f"the stream /{stream.alias} is running again after a restart of the daemon")
197
275
  return True
198
276
 
@@ -209,8 +287,8 @@ class Control:
209
287
  stream = self.stream
210
288
  if stream is None:
211
289
  return
212
- if self._tail is not None:
213
- for ip, size in self._tail.read():
290
+ if self._traffic is not None:
291
+ for ip, size in self._traffic.read():
214
292
  stream.devices.add_bytes(ip, size)
215
293
  # The wall clock, because the time limit must hold across a restart of the
216
294
  # daemon; a clock that is set while a stream runs moves its end with it.
@@ -233,8 +311,10 @@ class Control:
233
311
  f"a stream is already running (/{self.stream.alias}); stop it first"
234
312
  )
235
313
  stream = Stream.create(options, self.clock())
314
+ self._plan_index(stream, range(1, len(stream.videos) + 1))
236
315
  self._serve(stream)
237
316
  self.log(f"stream /{stream.alias} started: {stream.source} ({stream.policy})")
317
+ self._start_indexing(stream)
238
318
  return self.status()
239
319
 
240
320
  def stop(self) -> dict[str, Any]:
@@ -124,7 +124,9 @@ class Daemon:
124
124
  _published: tuple[float, str | None, str | None] | None = None
125
125
 
126
126
  def __post_init__(self) -> None:
127
- self.control = Control(self.config, self.paths, self.firewall, self.server, self.log)
127
+ self.control = Control(
128
+ self.config, self.paths, self.firewall, self.server, self.log, runner=self.runner
129
+ )
128
130
 
129
131
  def published(self) -> tuple[str | None, str | None]:
130
132
  """The dashboard's tailnet URL, or why it has none. Asked from Tailscale, then
@@ -48,7 +48,7 @@ TOOLS = (
48
48
  Tool("sudo", "the firewall helper", "as root: apt install sudo"),
49
49
  Tool("setfacl", "letting `vpstream start` give the service access to your videos", "", False),
50
50
  Tool("mkvextract", "WebVTT subtitles stored by mkvmerge", "", required=False),
51
- Tool("mkvmerge", "WebVTT subtitles stored by mkvmerge", "", required=False),
51
+ Tool("mkvmerge", "a full seek index in MKV files, so VLC resumes them quickly", "", False),
52
52
  )
53
53
 
54
54
  # Burned-in subtitles fall back to these when a file does not carry its font.