screenstream-client 0.2.0__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.
- screenstream_client-0.2.0/PKG-INFO +86 -0
- screenstream_client-0.2.0/README.md +67 -0
- screenstream_client-0.2.0/pyproject.toml +40 -0
- screenstream_client-0.2.0/screenstream_client/__init__.py +80 -0
- screenstream_client-0.2.0/screenstream_client/cli.py +133 -0
- screenstream_client-0.2.0/screenstream_client/control.py +168 -0
- screenstream_client-0.2.0/screenstream_client/fmp4.py +101 -0
- screenstream_client-0.2.0/screenstream_client/wire.py +312 -0
- screenstream_client-0.2.0/screenstream_client.egg-info/PKG-INFO +86 -0
- screenstream_client-0.2.0/screenstream_client.egg-info/SOURCES.txt +12 -0
- screenstream_client-0.2.0/screenstream_client.egg-info/dependency_links.txt +1 -0
- screenstream_client-0.2.0/screenstream_client.egg-info/entry_points.txt +3 -0
- screenstream_client-0.2.0/screenstream_client.egg-info/top_level.txt +1 -0
- screenstream_client-0.2.0/setup.cfg +4 -0
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: screenstream-client
|
|
3
|
+
Version: 0.2.0
|
|
4
|
+
Summary: Read the screenstream app's raw RGBA frames and encoded fragmented MP4.
|
|
5
|
+
Author: MBanucu
|
|
6
|
+
License-Expression: GPL-3.0-or-later
|
|
7
|
+
Project-URL: Homepage, https://github.com/MBanucu/screenstream
|
|
8
|
+
Project-URL: Documentation, https://github.com/MBanucu/screenstream#readme
|
|
9
|
+
Project-URL: Issues, https://github.com/MBanucu/screenstream/issues
|
|
10
|
+
Keywords: screen,android,streaming,rgba,fmp4,testing
|
|
11
|
+
Classifier: Development Status :: 4 - Beta
|
|
12
|
+
Classifier: Environment :: Console
|
|
13
|
+
Classifier: Intended Audience :: Developers
|
|
14
|
+
Classifier: Operating System :: OS Independent
|
|
15
|
+
Classifier: Programming Language :: Python :: 3
|
|
16
|
+
Classifier: Topic :: Software Development :: Testing
|
|
17
|
+
Requires-Python: >=3.9
|
|
18
|
+
Description-Content-Type: text/markdown
|
|
19
|
+
|
|
20
|
+
# screenstream-client
|
|
21
|
+
|
|
22
|
+
The Python client for [screenstream](https://github.com/MBanucu/screenstream):
|
|
23
|
+
the phone's screen as raw RGBA frames on a local port, and the same capture as
|
|
24
|
+
H.264 in a fragmented MP4 on a second one. No Android, no device, no runtime
|
|
25
|
+
dependency beyond the standard library (ffmpeg is used only when a PNG is
|
|
26
|
+
wanted).
|
|
27
|
+
|
|
28
|
+
```bash
|
|
29
|
+
pip install screenstream-client
|
|
30
|
+
# or install it in an isolated environment:
|
|
31
|
+
pipx install screenstream-client
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
The commands keep the flags of the scripts they replace, so an existing
|
|
35
|
+
`python3 client/stream.py --port 7200 --seconds 5 --png out/stream` becomes:
|
|
36
|
+
|
|
37
|
+
```bash
|
|
38
|
+
screenstream-stream --port 7200 --seconds 5 --frames-dir out/stream
|
|
39
|
+
screenstream-fmp4 --seconds 10 --out out/live.mp4
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
As a library:
|
|
43
|
+
|
|
44
|
+
```python
|
|
45
|
+
from screenstream_client import connect, read_fmp4, save_png
|
|
46
|
+
|
|
47
|
+
with connect("127.0.0.1", 7100) as link:
|
|
48
|
+
frame = link.wait_for_change(timeout=5) # None on a still screen
|
|
49
|
+
print(frame.number, frame.timestamp_ns, frame.size)
|
|
50
|
+
save_png(frame, "out/frame.png")
|
|
51
|
+
|
|
52
|
+
for number, timestamp_ns, size, pixels in link.frames():
|
|
53
|
+
...
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
`read_fmp4` parses an init segment, a saved file, or bytes. `base_ns` gives the
|
|
57
|
+
device clock's reading for the track's zero from the `udta`/`uuid` box, so a
|
|
58
|
+
frame's device time is `base_ns + pts * 1000`.
|
|
59
|
+
|
|
60
|
+
## Protocol version
|
|
61
|
+
|
|
62
|
+
This client speaks screenstream protocol **2.x**. A stream whose major version
|
|
63
|
+
is different is refused with a sentence that names both versions, not read as
|
|
64
|
+
if the fields still meant the same thing. Protocol 1 (magic `RAW1`, the
|
|
65
|
+
unversioned 36-byte header) is still accepted for an app installed before the
|
|
66
|
+
version existed.
|
|
67
|
+
|
|
68
|
+
The distribution and the AAR share the version in `pyproject.toml`; it must
|
|
69
|
+
equal `build.gradle.kts` and `build.sh`, and the test suite checks that.
|
|
70
|
+
|
|
71
|
+
## The control surface
|
|
72
|
+
|
|
73
|
+
`screenstream_client.control` is the shared parser for the `content call` wire
|
|
74
|
+
format: `parse_call` for a command, `parse_result` for the
|
|
75
|
+
`Result: Bundle[{code=..., data=...}]` reply, `parse_fields` for the
|
|
76
|
+
`key=value` body and `parse_extra` for `name:type:value`. Its
|
|
77
|
+
`SCHEMA_VERSION` must equal the Java library's
|
|
78
|
+
`ControlContract.SCHEMA_VERSION`; `test/test_control.py` reads both and the
|
|
79
|
+
shared fixture, so the Java and Python grammars cannot drift silently.
|
|
80
|
+
`client/control.py` is the adb command-line wrapper over it.
|
|
81
|
+
|
|
82
|
+
The contract is `docs/control-surface.md` in the repository.
|
|
83
|
+
|
|
84
|
+
## License
|
|
85
|
+
|
|
86
|
+
GPL-3.0-or-later, as the rest of screenstream.
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
# screenstream-client
|
|
2
|
+
|
|
3
|
+
The Python client for [screenstream](https://github.com/MBanucu/screenstream):
|
|
4
|
+
the phone's screen as raw RGBA frames on a local port, and the same capture as
|
|
5
|
+
H.264 in a fragmented MP4 on a second one. No Android, no device, no runtime
|
|
6
|
+
dependency beyond the standard library (ffmpeg is used only when a PNG is
|
|
7
|
+
wanted).
|
|
8
|
+
|
|
9
|
+
```bash
|
|
10
|
+
pip install screenstream-client
|
|
11
|
+
# or install it in an isolated environment:
|
|
12
|
+
pipx install screenstream-client
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
The commands keep the flags of the scripts they replace, so an existing
|
|
16
|
+
`python3 client/stream.py --port 7200 --seconds 5 --png out/stream` becomes:
|
|
17
|
+
|
|
18
|
+
```bash
|
|
19
|
+
screenstream-stream --port 7200 --seconds 5 --frames-dir out/stream
|
|
20
|
+
screenstream-fmp4 --seconds 10 --out out/live.mp4
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
As a library:
|
|
24
|
+
|
|
25
|
+
```python
|
|
26
|
+
from screenstream_client import connect, read_fmp4, save_png
|
|
27
|
+
|
|
28
|
+
with connect("127.0.0.1", 7100) as link:
|
|
29
|
+
frame = link.wait_for_change(timeout=5) # None on a still screen
|
|
30
|
+
print(frame.number, frame.timestamp_ns, frame.size)
|
|
31
|
+
save_png(frame, "out/frame.png")
|
|
32
|
+
|
|
33
|
+
for number, timestamp_ns, size, pixels in link.frames():
|
|
34
|
+
...
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
`read_fmp4` parses an init segment, a saved file, or bytes. `base_ns` gives the
|
|
38
|
+
device clock's reading for the track's zero from the `udta`/`uuid` box, so a
|
|
39
|
+
frame's device time is `base_ns + pts * 1000`.
|
|
40
|
+
|
|
41
|
+
## Protocol version
|
|
42
|
+
|
|
43
|
+
This client speaks screenstream protocol **2.x**. A stream whose major version
|
|
44
|
+
is different is refused with a sentence that names both versions, not read as
|
|
45
|
+
if the fields still meant the same thing. Protocol 1 (magic `RAW1`, the
|
|
46
|
+
unversioned 36-byte header) is still accepted for an app installed before the
|
|
47
|
+
version existed.
|
|
48
|
+
|
|
49
|
+
The distribution and the AAR share the version in `pyproject.toml`; it must
|
|
50
|
+
equal `build.gradle.kts` and `build.sh`, and the test suite checks that.
|
|
51
|
+
|
|
52
|
+
## The control surface
|
|
53
|
+
|
|
54
|
+
`screenstream_client.control` is the shared parser for the `content call` wire
|
|
55
|
+
format: `parse_call` for a command, `parse_result` for the
|
|
56
|
+
`Result: Bundle[{code=..., data=...}]` reply, `parse_fields` for the
|
|
57
|
+
`key=value` body and `parse_extra` for `name:type:value`. Its
|
|
58
|
+
`SCHEMA_VERSION` must equal the Java library's
|
|
59
|
+
`ControlContract.SCHEMA_VERSION`; `test/test_control.py` reads both and the
|
|
60
|
+
shared fixture, so the Java and Python grammars cannot drift silently.
|
|
61
|
+
`client/control.py` is the adb command-line wrapper over it.
|
|
62
|
+
|
|
63
|
+
The contract is `docs/control-surface.md` in the repository.
|
|
64
|
+
|
|
65
|
+
## License
|
|
66
|
+
|
|
67
|
+
GPL-3.0-or-later, as the rest of screenstream.
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
# screenstream-client: install the Python client for screenstream.
|
|
2
|
+
#
|
|
3
|
+
# The version is the AAR's version: build.gradle.kts and build.sh carry the same
|
|
4
|
+
# number, and test/test_client.py fails if they ever disagree. A release tag is
|
|
5
|
+
# checked against this file before publishing, so there is one version per
|
|
6
|
+
# release and not a PyPI version beside a Maven version.
|
|
7
|
+
|
|
8
|
+
[build-system]
|
|
9
|
+
requires = ["setuptools>=77"]
|
|
10
|
+
build-backend = "setuptools.build_meta"
|
|
11
|
+
|
|
12
|
+
[project]
|
|
13
|
+
name = "screenstream-client"
|
|
14
|
+
version = "0.2.0"
|
|
15
|
+
description = "Read the screenstream app's raw RGBA frames and encoded fragmented MP4."
|
|
16
|
+
readme = "README.md"
|
|
17
|
+
requires-python = ">=3.9"
|
|
18
|
+
license = "GPL-3.0-or-later"
|
|
19
|
+
authors = [{ name = "MBanucu" }]
|
|
20
|
+
keywords = ["screen", "android", "streaming", "rgba", "fmp4", "testing"]
|
|
21
|
+
classifiers = [
|
|
22
|
+
"Development Status :: 4 - Beta",
|
|
23
|
+
"Environment :: Console",
|
|
24
|
+
"Intended Audience :: Developers",
|
|
25
|
+
"Operating System :: OS Independent",
|
|
26
|
+
"Programming Language :: Python :: 3",
|
|
27
|
+
"Topic :: Software Development :: Testing",
|
|
28
|
+
]
|
|
29
|
+
|
|
30
|
+
[project.urls]
|
|
31
|
+
Homepage = "https://github.com/MBanucu/screenstream"
|
|
32
|
+
Documentation = "https://github.com/MBanucu/screenstream#readme"
|
|
33
|
+
Issues = "https://github.com/MBanucu/screenstream/issues"
|
|
34
|
+
|
|
35
|
+
[project.scripts]
|
|
36
|
+
screenstream-stream = "screenstream_client.cli:stream_main"
|
|
37
|
+
screenstream-fmp4 = "screenstream_client.cli:fmp4_main"
|
|
38
|
+
|
|
39
|
+
[tool.setuptools]
|
|
40
|
+
packages = ["screenstream_client"]
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
"""A client for screenstream: the phone's screen as frames on a local port.
|
|
2
|
+
|
|
3
|
+
The app serves one TCP port; this package reads it without Android and without
|
|
4
|
+
a device, so a test can build frames in memory or connect over an adb forward:
|
|
5
|
+
|
|
6
|
+
from screenstream_client import connect
|
|
7
|
+
|
|
8
|
+
with connect("127.0.0.1", 7100) as link:
|
|
9
|
+
frame = link.wait_for_change(5)
|
|
10
|
+
print(frame.number, frame.timestamp_ns, frame.size)
|
|
11
|
+
|
|
12
|
+
The command-line clients are thin wrappers over the same functions:
|
|
13
|
+
``screenstream-stream`` reads the raw frames and ``screenstream-fmp4`` saves
|
|
14
|
+
the encoded stream as a fragmented MP4.
|
|
15
|
+
|
|
16
|
+
Protocol compatibility is a major-version rule: this client speaks 2.x, and a
|
|
17
|
+
stream that announces another major version is refused with a sentence instead
|
|
18
|
+
of being read as if the fields still meant what they did. Protocol 1 (magic
|
|
19
|
+
``RAW1``) is still accepted for apps installed before the version existed.
|
|
20
|
+
"""
|
|
21
|
+
|
|
22
|
+
from .fmp4 import BASE_UUID, Box, base_ns, boxes, read_fmp4
|
|
23
|
+
from .wire import (
|
|
24
|
+
BYTES_PER_PIXEL,
|
|
25
|
+
HEADER,
|
|
26
|
+
LEGACY_HEADER,
|
|
27
|
+
LEGACY_MAGIC,
|
|
28
|
+
MAGIC,
|
|
29
|
+
MAX_FRAME_BYTES,
|
|
30
|
+
PROTOCOL_MAJOR,
|
|
31
|
+
PROTOCOL_MINOR,
|
|
32
|
+
PROTOCOL_VERSION,
|
|
33
|
+
RGBA_8888,
|
|
34
|
+
Connection,
|
|
35
|
+
ConnectionClosed,
|
|
36
|
+
Frame,
|
|
37
|
+
ProtocolError,
|
|
38
|
+
SaveError,
|
|
39
|
+
ScreenstreamError,
|
|
40
|
+
connect,
|
|
41
|
+
save_png,
|
|
42
|
+
)
|
|
43
|
+
|
|
44
|
+
__all__ = [
|
|
45
|
+
"BASE_UUID",
|
|
46
|
+
"BYTES_PER_PIXEL",
|
|
47
|
+
"Box",
|
|
48
|
+
"Connection",
|
|
49
|
+
"ConnectionClosed",
|
|
50
|
+
"Frame",
|
|
51
|
+
"HEADER",
|
|
52
|
+
"LEGACY_HEADER",
|
|
53
|
+
"LEGACY_MAGIC",
|
|
54
|
+
"MAGIC",
|
|
55
|
+
"MAX_FRAME_BYTES",
|
|
56
|
+
"PROTOCOL_MAJOR",
|
|
57
|
+
"PROTOCOL_MINOR",
|
|
58
|
+
"PROTOCOL_VERSION",
|
|
59
|
+
"ProtocolError",
|
|
60
|
+
"RGBA_8888",
|
|
61
|
+
"SaveError",
|
|
62
|
+
"ScreenstreamError",
|
|
63
|
+
"base_ns",
|
|
64
|
+
"boxes",
|
|
65
|
+
"connect",
|
|
66
|
+
"frames",
|
|
67
|
+
"read_fmp4",
|
|
68
|
+
"save_png",
|
|
69
|
+
"wait_for_change",
|
|
70
|
+
]
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def frames(connection, timeout=None):
|
|
74
|
+
"""The frames of an already-connected stream; see :meth:`Connection.frames`."""
|
|
75
|
+
return connection.frames(timeout)
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def wait_for_change(connection, timeout, since=None):
|
|
79
|
+
"""The next changed frame; see :meth:`Connection.wait_for_change`."""
|
|
80
|
+
return connection.wait_for_change(timeout, since)
|
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
"""The two command-line clients: raw frames, and the encoded stream to a file."""
|
|
2
|
+
|
|
3
|
+
import argparse
|
|
4
|
+
import socket
|
|
5
|
+
import sys
|
|
6
|
+
import time
|
|
7
|
+
|
|
8
|
+
from .fmp4 import base_ns
|
|
9
|
+
from .wire import (
|
|
10
|
+
ConnectionClosed,
|
|
11
|
+
ProtocolError,
|
|
12
|
+
SaveError,
|
|
13
|
+
ScreenstreamError,
|
|
14
|
+
connect,
|
|
15
|
+
save_png,
|
|
16
|
+
)
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def stream_main(argv=None) -> int:
|
|
20
|
+
"""Reads the phone's raw screen stream and prints its shape."""
|
|
21
|
+
parser = argparse.ArgumentParser(
|
|
22
|
+
description="Read frames from the phone's raw screen stream.")
|
|
23
|
+
parser.add_argument("--host", default="127.0.0.1")
|
|
24
|
+
parser.add_argument("--port", type=int, default=7100)
|
|
25
|
+
parser.add_argument("--frames", type=int, default=0, help="stop after this many frames")
|
|
26
|
+
parser.add_argument("--seconds", type=float, default=5.0,
|
|
27
|
+
help="stop after this long (0 waits for --frames)")
|
|
28
|
+
parser.add_argument("--frames-dir", "--png", dest="png", default="",
|
|
29
|
+
help="write frames here, as .png")
|
|
30
|
+
parser.add_argument("--quiet", action="store_true")
|
|
31
|
+
args = parser.parse_args(argv)
|
|
32
|
+
|
|
33
|
+
started = time.monotonic()
|
|
34
|
+
limit = None if args.seconds <= 0 else started + args.seconds
|
|
35
|
+
try:
|
|
36
|
+
link = connect(args.host, args.port, 10 if limit is None else args.seconds)
|
|
37
|
+
except (ScreenstreamError, OSError) as failed:
|
|
38
|
+
print("stream: %s" % failed, file=sys.stderr)
|
|
39
|
+
return 1
|
|
40
|
+
if not args.quiet:
|
|
41
|
+
print("stream: attached to %s:%d" % (args.host, args.port))
|
|
42
|
+
|
|
43
|
+
count = 0
|
|
44
|
+
numbers = []
|
|
45
|
+
stamps = []
|
|
46
|
+
written = []
|
|
47
|
+
try:
|
|
48
|
+
while True:
|
|
49
|
+
if limit is not None and time.monotonic() > limit:
|
|
50
|
+
break
|
|
51
|
+
if args.frames and count >= args.frames:
|
|
52
|
+
break
|
|
53
|
+
timeout = 0.5 if limit is None else max(0.05, limit - time.monotonic())
|
|
54
|
+
frame = link.read_frame(timeout)
|
|
55
|
+
if frame is None:
|
|
56
|
+
continue
|
|
57
|
+
gap = (frame.timestamp_ns - stamps[-1]) / 1e6 if stamps else 0.0
|
|
58
|
+
if not args.quiet:
|
|
59
|
+
print("frame %6d %dx%d stride %d %6.1f MB ts %d ns (+%.1f ms)"
|
|
60
|
+
% (frame.number, frame.width, frame.height, frame.stride,
|
|
61
|
+
frame.size / 1e6, frame.timestamp_ns, gap))
|
|
62
|
+
numbers.append(frame.number)
|
|
63
|
+
stamps.append(frame.timestamp_ns)
|
|
64
|
+
count += 1
|
|
65
|
+
if args.png:
|
|
66
|
+
path = "%s/frame-%05d-%d.png" % (args.png, frame.number,
|
|
67
|
+
frame.timestamp_ns)
|
|
68
|
+
written.append(save_png(frame, path))
|
|
69
|
+
except ConnectionClosed:
|
|
70
|
+
pass
|
|
71
|
+
except (ProtocolError, SaveError) as failed:
|
|
72
|
+
print("stream: %s" % failed, file=sys.stderr)
|
|
73
|
+
return 1
|
|
74
|
+
finally:
|
|
75
|
+
link.close()
|
|
76
|
+
|
|
77
|
+
if not count:
|
|
78
|
+
print("stream: no frames in that window (a still screen sends none)")
|
|
79
|
+
return 0
|
|
80
|
+
spent = (stamps[-1] - stamps[0]) / 1e9 if count > 1 else 0.0
|
|
81
|
+
gaps = [(b - a) / 1e6 for a, b in zip(stamps, stamps[1:])]
|
|
82
|
+
print("stream: %d frame(s) over %.1f s of screen time, numbers %d..%d, "
|
|
83
|
+
"gaps %.1f..%.1f ms" % (count, spent, numbers[0], numbers[-1],
|
|
84
|
+
min(gaps) if gaps else 0.0, max(gaps) if gaps else 0.0))
|
|
85
|
+
for png in written:
|
|
86
|
+
print(" %s" % png)
|
|
87
|
+
return 0
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def fmp4_main(argv=None) -> int:
|
|
91
|
+
"""Attaches to the encoded stream and saves what it sends."""
|
|
92
|
+
parser = argparse.ArgumentParser(
|
|
93
|
+
description="Attach to the encoded stream and save what it sends.")
|
|
94
|
+
parser.add_argument("--host", default="127.0.0.1")
|
|
95
|
+
parser.add_argument("--port", type=int, default=7101)
|
|
96
|
+
parser.add_argument("--seconds", type=float, default=10.0,
|
|
97
|
+
help="how long to listen (0 runs until killed)")
|
|
98
|
+
parser.add_argument("--out", default="live.mp4",
|
|
99
|
+
help="where to write the fragmented MP4")
|
|
100
|
+
args = parser.parse_args(argv)
|
|
101
|
+
|
|
102
|
+
started = time.monotonic()
|
|
103
|
+
deadline = started + args.seconds if args.seconds > 0 else None
|
|
104
|
+
total = 0
|
|
105
|
+
head = b""
|
|
106
|
+
reported = False
|
|
107
|
+
try:
|
|
108
|
+
with socket.create_connection((args.host, args.port), timeout=5) as link, \
|
|
109
|
+
open(args.out, "wb") as out:
|
|
110
|
+
link.settimeout(1.0)
|
|
111
|
+
while deadline is None or time.monotonic() < deadline:
|
|
112
|
+
try:
|
|
113
|
+
chunk = link.recv(1 << 16)
|
|
114
|
+
except socket.timeout:
|
|
115
|
+
continue
|
|
116
|
+
if not chunk:
|
|
117
|
+
break
|
|
118
|
+
out.write(chunk)
|
|
119
|
+
total += len(chunk)
|
|
120
|
+
if not reported and len(head) < (1 << 16):
|
|
121
|
+
head += chunk
|
|
122
|
+
found = base_ns(head)
|
|
123
|
+
if found is not None:
|
|
124
|
+
print("base_ns=%d (device clock, ns)" % found)
|
|
125
|
+
reported = True
|
|
126
|
+
except OSError as failed:
|
|
127
|
+
print("could not read the stream: %s" % failed, file=sys.stderr)
|
|
128
|
+
return 1
|
|
129
|
+
span = time.monotonic() - started
|
|
130
|
+
if not reported:
|
|
131
|
+
print("base_ns=unknown (no udta in the init segment)")
|
|
132
|
+
print("%s: %d bytes in %.1fs (%.0f KiB/s)" % (args.out, total, span, total / 1024 / span))
|
|
133
|
+
return 0 if total else 1
|
|
@@ -0,0 +1,168 @@
|
|
|
1
|
+
"""The ``content call`` wire format, shared by every consumer of the surface.
|
|
2
|
+
|
|
3
|
+
The Java library ``android-control-surface`` implements the same two shapes and
|
|
4
|
+
is tested against the same fixture (``control-call-fixtures.properties``), so a
|
|
5
|
+
change to the grammar has to be made in both places deliberately.
|
|
6
|
+
|
|
7
|
+
A call is::
|
|
8
|
+
|
|
9
|
+
adb [-s SERIAL] shell content call --uri URI --method METHOD \\
|
|
10
|
+
[--extra name:type:value]...
|
|
11
|
+
|
|
12
|
+
The reply is a Bundle printed as::
|
|
13
|
+
|
|
14
|
+
Result: Bundle[{code=0, data=key=value
|
|
15
|
+
key=value
|
|
16
|
+
}]
|
|
17
|
+
|
|
18
|
+
``code`` is 0 for success, 400 for a call that was understood but could not be
|
|
19
|
+
done, and 403 for a caller that is not allowed. ``data`` is one ``key=value``
|
|
20
|
+
line per field, split on the first ``=``; a value never contains a newline.
|
|
21
|
+
"""
|
|
22
|
+
|
|
23
|
+
from __future__ import annotations
|
|
24
|
+
|
|
25
|
+
import re
|
|
26
|
+
import shlex
|
|
27
|
+
from dataclasses import dataclass
|
|
28
|
+
from typing import Iterable, Mapping
|
|
29
|
+
|
|
30
|
+
#: The version of the reply/extras grammar. Java's ControlContract.SCHEMA_VERSION
|
|
31
|
+
#: must match; test/test_control.py reads that constant from the Java source.
|
|
32
|
+
SCHEMA_VERSION = 1
|
|
33
|
+
|
|
34
|
+
TYPES = "silfdz"
|
|
35
|
+
|
|
36
|
+
# `content call` prints `Result: Bundle[{code=0, data=...}]`; the data's newlines
|
|
37
|
+
# are literal, so the match has to span them.
|
|
38
|
+
_RESULT = re.compile(r"Result: Bundle\[\{code=(-?\d+), data=(.*)\}\]\s*$", re.S)
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
class ControlError(Exception):
|
|
42
|
+
"""The command failed before it produced a provider reply."""
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
@dataclass(frozen=True)
|
|
46
|
+
class Extra:
|
|
47
|
+
"""One ``--extra name:type:value`` with the platform's type letter."""
|
|
48
|
+
|
|
49
|
+
name: str
|
|
50
|
+
type: str
|
|
51
|
+
value: str
|
|
52
|
+
|
|
53
|
+
@classmethod
|
|
54
|
+
def parse(cls, text: str) -> "Extra":
|
|
55
|
+
name, sep, rest = text.partition(":")
|
|
56
|
+
type_, sep2, value = rest.partition(":")
|
|
57
|
+
if not sep or not sep2 or not name:
|
|
58
|
+
raise ValueError("extra %r is not name:type:value" % text)
|
|
59
|
+
if len(type_) != 1 or type_ not in TYPES:
|
|
60
|
+
raise ValueError("unknown extra type %r; use s, i, l, f, d or z"
|
|
61
|
+
% type_)
|
|
62
|
+
return cls(name, type_, value)
|
|
63
|
+
|
|
64
|
+
def typed(self):
|
|
65
|
+
"""The value as its type names it, or None when it does not parse."""
|
|
66
|
+
text = self.value.strip()
|
|
67
|
+
try:
|
|
68
|
+
if self.type == "i" or self.type == "l":
|
|
69
|
+
return int(text)
|
|
70
|
+
if self.type in ("f", "d"):
|
|
71
|
+
return float(text)
|
|
72
|
+
if self.type == "z":
|
|
73
|
+
return text.lower() == "true"
|
|
74
|
+
except ValueError:
|
|
75
|
+
return None
|
|
76
|
+
return self.value
|
|
77
|
+
|
|
78
|
+
def __str__(self) -> str:
|
|
79
|
+
return "%s:%s:%s" % (self.name, self.type, self.value)
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
@dataclass(frozen=True)
|
|
83
|
+
class Call:
|
|
84
|
+
"""A parsed call: where it goes, what it asks for, and its extras."""
|
|
85
|
+
|
|
86
|
+
uri: str | None
|
|
87
|
+
method: str
|
|
88
|
+
extras: tuple[Extra, ...]
|
|
89
|
+
|
|
90
|
+
def args(self) -> dict[str, object]:
|
|
91
|
+
out: dict[str, object] = {}
|
|
92
|
+
for extra in self.extras:
|
|
93
|
+
typed = extra.typed()
|
|
94
|
+
out[extra.name] = extra.value if typed is None else typed
|
|
95
|
+
return out
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def parse_extra(text: str) -> Extra:
|
|
99
|
+
"""Parses ``name:type:value``; a value may itself contain ``:``."""
|
|
100
|
+
return Extra.parse(text)
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def parse_call(command: str | Iterable[str]) -> Call:
|
|
104
|
+
"""Parses a short or full ``adb ... shell content call ...`` command."""
|
|
105
|
+
tokens = shlex.split(command) if isinstance(command, str) else list(command)
|
|
106
|
+
uri = None
|
|
107
|
+
method = None
|
|
108
|
+
extras: list[Extra] = []
|
|
109
|
+
index = 0
|
|
110
|
+
while index < len(tokens):
|
|
111
|
+
token = tokens[index]
|
|
112
|
+
if token == "--uri" and index + 1 < len(tokens):
|
|
113
|
+
index += 1
|
|
114
|
+
uri = tokens[index]
|
|
115
|
+
elif token == "--method" and index + 1 < len(tokens):
|
|
116
|
+
index += 1
|
|
117
|
+
method = tokens[index]
|
|
118
|
+
elif token == "--extra" and index + 1 < len(tokens):
|
|
119
|
+
index += 1
|
|
120
|
+
extras.append(Extra.parse(tokens[index]))
|
|
121
|
+
index += 1
|
|
122
|
+
if method is None:
|
|
123
|
+
raise ValueError("no --method in %r" % command)
|
|
124
|
+
return Call(uri, method, tuple(extras))
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
class Reply:
|
|
128
|
+
def __init__(self, code: int, data: str):
|
|
129
|
+
self.code = code
|
|
130
|
+
self.data = data
|
|
131
|
+
|
|
132
|
+
@property
|
|
133
|
+
def fields(self) -> dict[str, str]:
|
|
134
|
+
return parse_fields(self.data)
|
|
135
|
+
|
|
136
|
+
def __getitem__(self, key: str) -> str:
|
|
137
|
+
return self.fields[key]
|
|
138
|
+
|
|
139
|
+
def __repr__(self) -> str:
|
|
140
|
+
return "Reply(code=%r, data=%r)" % (self.code, self.data)
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
def parse_fields(data: str) -> dict[str, str]:
|
|
144
|
+
"""Splits ``key=value`` lines; a value may itself contain ``=`` or ``:``."""
|
|
145
|
+
fields: dict[str, str] = {}
|
|
146
|
+
for line in data.splitlines():
|
|
147
|
+
if "=" not in line:
|
|
148
|
+
continue
|
|
149
|
+
key, value = line.split("=", 1)
|
|
150
|
+
key = key.strip()
|
|
151
|
+
if key:
|
|
152
|
+
# The last occurrence wins, like a shell reading the file.
|
|
153
|
+
fields[key] = value.strip()
|
|
154
|
+
return fields
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
def parse_result(text: str) -> Reply:
|
|
158
|
+
"""Parses the `content call` output, tolerating lines before the Result."""
|
|
159
|
+
match = _RESULT.search(text)
|
|
160
|
+
if not match:
|
|
161
|
+
raise ControlError("no Result: Bundle in %r" % text.strip()[:500])
|
|
162
|
+
return Reply(int(match.group(1)), match.group(2))
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
def fields_match(mapping: Mapping[str, object]) -> str:
|
|
166
|
+
"""Renders fields the way a provider does; useful for tests and fixtures."""
|
|
167
|
+
return "\n".join("%s=%s" % (key, str(value).replace("\n", " ").replace("\r", " "))
|
|
168
|
+
for key, value in mapping.items())
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
"""The encoded stream's container: boxes, the init segment, and ``base_ns``.
|
|
2
|
+
|
|
3
|
+
A fragmented MP4 is a sequence of length-prefixed boxes. The init segment
|
|
4
|
+
(``ftyp`` + ``moov``) describes the track and carries the device clock's reading
|
|
5
|
+
for the track's zero in a private ``udta``/``uuid`` box; every fragment after it
|
|
6
|
+
is a ``moof`` and an ``mdat`` that can be played as it arrives.
|
|
7
|
+
|
|
8
|
+
:func:`read_fmp4` is the offline parser: hand it bytes or a binary file and it
|
|
9
|
+
yields every complete top-level box. A *truncated* box at the end is not
|
|
10
|
+
yielded and is not an error - a live stream can stop in the middle of one - so a
|
|
11
|
+
caller can tell what is whole from what is not.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
import os
|
|
15
|
+
import struct
|
|
16
|
+
from typing import Iterator, NamedTuple, Optional
|
|
17
|
+
|
|
18
|
+
# The udta/uuid box's identifier: a private extension, skipped by size by every
|
|
19
|
+
# reader that does not know it.
|
|
20
|
+
BASE_UUID = bytes.fromhex("6d42414e7563750073747265616d0001")
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class Box(NamedTuple):
|
|
24
|
+
"""One complete top-level box: its type, offset, total size and body."""
|
|
25
|
+
|
|
26
|
+
kind: bytes
|
|
27
|
+
offset: int
|
|
28
|
+
size: int
|
|
29
|
+
body: bytes
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def _walk(data, start: int = 0, end: Optional[int] = None):
|
|
33
|
+
"""Every complete box in data[start:end], as (kind, start, body, size, total)."""
|
|
34
|
+
if end is None:
|
|
35
|
+
end = len(data)
|
|
36
|
+
end = min(end, len(data))
|
|
37
|
+
position = start
|
|
38
|
+
while position + 8 <= end:
|
|
39
|
+
size, kind = struct.unpack(">I4s", data[position:position + 8])
|
|
40
|
+
header = 8
|
|
41
|
+
if size == 1:
|
|
42
|
+
# A 64-bit size is legal MP4, even though this writer never needs it.
|
|
43
|
+
if position + 16 > end:
|
|
44
|
+
return
|
|
45
|
+
size = struct.unpack(">Q", data[position + 8:position + 16])[0]
|
|
46
|
+
header = 16
|
|
47
|
+
if size < header or position + size > end:
|
|
48
|
+
# Truncated, or smaller than its own header: the rest is not a box.
|
|
49
|
+
return
|
|
50
|
+
yield kind, position, position + header, size - header, size
|
|
51
|
+
position += size
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def boxes(data, start: int = 0, end: Optional[int] = None):
|
|
55
|
+
"""Every complete box in data[start:end], as (type, body offset, body size)."""
|
|
56
|
+
for kind, _offset, body, size, _total in _walk(data, start, end):
|
|
57
|
+
yield kind, body, size
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def base_ns(init) -> Optional[int]:
|
|
61
|
+
"""The device time of the track's zero from the init segment, or None."""
|
|
62
|
+
for kind, body, size in boxes(init, 0, len(init)):
|
|
63
|
+
if kind != b"moov":
|
|
64
|
+
continue
|
|
65
|
+
for kind2, body2, size2 in boxes(init, body, body + size):
|
|
66
|
+
if kind2 != b"udta":
|
|
67
|
+
continue
|
|
68
|
+
for kind3, body3, size3 in boxes(init, body2, body2 + size2):
|
|
69
|
+
if kind3 != b"uuid" or size3 < 32 or init[body3:body3 + 16] != BASE_UUID:
|
|
70
|
+
continue
|
|
71
|
+
version = struct.unpack(">I", init[body3 + 16:body3 + 20])[0]
|
|
72
|
+
if version != 1:
|
|
73
|
+
continue
|
|
74
|
+
return struct.unpack(">Q", init[body3 + 24:body3 + 32])[0]
|
|
75
|
+
return None
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def _read_all(source) -> bytes:
|
|
79
|
+
if isinstance(source, (bytes, bytearray, memoryview)):
|
|
80
|
+
return bytes(source)
|
|
81
|
+
if isinstance(source, (str, os.PathLike)):
|
|
82
|
+
with open(source, "rb") as handle:
|
|
83
|
+
return handle.read()
|
|
84
|
+
read = getattr(source, "read", None)
|
|
85
|
+
if read is not None:
|
|
86
|
+
return read()
|
|
87
|
+
return b"".join(source)
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def read_fmp4(source) -> Iterator[Box]:
|
|
91
|
+
"""Every complete top-level box in an init segment, a file, or a byte string.
|
|
92
|
+
|
|
93
|
+
``source`` may be ``bytes``, a path, a binary file-like object, or an
|
|
94
|
+
iterable of byte chunks. The parser reads it to the end, so a live socket is
|
|
95
|
+
better fed to the client's streaming command; this is for an init segment, a
|
|
96
|
+
saved file, or an in-memory test vector. Incomplete boxes at the end are
|
|
97
|
+
dropped, which is what makes a truncated fragment safe to parse.
|
|
98
|
+
"""
|
|
99
|
+
data = _read_all(source)
|
|
100
|
+
for kind, offset, body, size, total in _walk(data):
|
|
101
|
+
yield Box(kind, offset, total, bytes(data[body:body + size]))
|
|
@@ -0,0 +1,312 @@
|
|
|
1
|
+
"""The raw frame protocol: a versioned header, then RGBA_8888 pixels.
|
|
2
|
+
|
|
3
|
+
The protocol is deliberately small enough to re-implement in another language:
|
|
4
|
+
|
|
5
|
+
magic "RAW2" 4 bytes
|
|
6
|
+
major u16 protocol major version, 2 today
|
|
7
|
+
minor u16 protocol minor version
|
|
8
|
+
width u32
|
|
9
|
+
height u32
|
|
10
|
+
row stride u32 bytes per row in the payload, padding included
|
|
11
|
+
format u32 1 = RGBA_8888, 4 bytes per pixel
|
|
12
|
+
frame number u64 changed frames since the capture began
|
|
13
|
+
timestamp u64 nanoseconds, the device's elapsed clock
|
|
14
|
+
|
|
15
|
+
A client reads the magic first, then the version, and refuses a major version it
|
|
16
|
+
does not know before it reads the rest of the header. The sentence is the whole
|
|
17
|
+
point: an unknown stream is a compatibility problem, not a struct error.
|
|
18
|
+
|
|
19
|
+
Magic ``RAW1`` is protocol 1, the 36-byte header older apps served. It is still
|
|
20
|
+
accepted, with no version fields, so a client keeps working against an app that
|
|
21
|
+
was installed before the version existed. New streams are always ``RAW2``.
|
|
22
|
+
"""
|
|
23
|
+
|
|
24
|
+
import os
|
|
25
|
+
import socket
|
|
26
|
+
import struct
|
|
27
|
+
import subprocess
|
|
28
|
+
import time
|
|
29
|
+
from dataclasses import dataclass
|
|
30
|
+
from typing import Iterator, Optional, Tuple
|
|
31
|
+
|
|
32
|
+
MAGIC = b"RAW2"
|
|
33
|
+
LEGACY_MAGIC = b"RAW1"
|
|
34
|
+
|
|
35
|
+
PROTOCOL_MAJOR = 2
|
|
36
|
+
PROTOCOL_MINOR = 0
|
|
37
|
+
PROTOCOL_VERSION = "%d.%d" % (PROTOCOL_MAJOR, PROTOCOL_MINOR)
|
|
38
|
+
|
|
39
|
+
# magic, major, minor, width, height, stride, format, number, ts_ns
|
|
40
|
+
HEADER = struct.Struct(">4sHHIIIIQQ")
|
|
41
|
+
# Protocol 1: magic, width, height, stride, format, number, ts_ns
|
|
42
|
+
LEGACY_HEADER = struct.Struct(">4sIIIIQQ")
|
|
43
|
+
|
|
44
|
+
MAX_FRAME_BYTES = 64 * 1024 * 1024
|
|
45
|
+
RGBA_8888 = 1
|
|
46
|
+
BYTES_PER_PIXEL = 4
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
class ScreenstreamError(Exception):
|
|
50
|
+
"""The stream could not be read, or was not a screenstream stream."""
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
class ProtocolError(ScreenstreamError):
|
|
54
|
+
"""The stream speaks a version or a shape this client does not understand."""
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
class ConnectionClosed(ScreenstreamError):
|
|
58
|
+
"""The source closed, or a frame ended before its payload did."""
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
class SaveError(ScreenstreamError):
|
|
62
|
+
"""A frame could not be written as a picture."""
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
@dataclass(frozen=True)
|
|
66
|
+
class Frame:
|
|
67
|
+
"""One changed frame.
|
|
68
|
+
|
|
69
|
+
The first four fields are the portable tuple: ``number, timestamp_ns, size,
|
|
70
|
+
pixels``. The rest describes the payload, which is needed to write it out.
|
|
71
|
+
``pixels`` includes row padding; use :attr:`body` for width * height * 4.
|
|
72
|
+
"""
|
|
73
|
+
|
|
74
|
+
number: int
|
|
75
|
+
timestamp_ns: int
|
|
76
|
+
size: int
|
|
77
|
+
pixels: bytes
|
|
78
|
+
width: int
|
|
79
|
+
height: int
|
|
80
|
+
stride: int
|
|
81
|
+
pixel_format: int
|
|
82
|
+
protocol_version: Tuple[int, int]
|
|
83
|
+
|
|
84
|
+
def __iter__(self):
|
|
85
|
+
return iter((self.number, self.timestamp_ns, self.size, self.pixels))
|
|
86
|
+
|
|
87
|
+
@property
|
|
88
|
+
def body(self) -> bytes:
|
|
89
|
+
"""The pixels with the row padding removed: what a picture wants."""
|
|
90
|
+
row = self.width * BYTES_PER_PIXEL
|
|
91
|
+
if self.stride == row:
|
|
92
|
+
return bytes(self.pixels)
|
|
93
|
+
return b"".join(
|
|
94
|
+
bytes(self.pixels[y * self.stride:y * self.stride + row])
|
|
95
|
+
for y in range(self.height)
|
|
96
|
+
)
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
class _ReadTimeout(Exception):
|
|
100
|
+
"""A socket read passed its deadline; ``got`` bytes of the part arrived."""
|
|
101
|
+
|
|
102
|
+
def __init__(self, got: int):
|
|
103
|
+
super().__init__(got)
|
|
104
|
+
self.got = got
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def _header_progress(got: int, total: int) -> str:
|
|
108
|
+
return ("%d of %d bytes of a frame header" % (got, total)) if got else "a frame header"
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
class Connection:
|
|
112
|
+
"""One attached consumer of the raw stream.
|
|
113
|
+
|
|
114
|
+
Use :func:`connect` to get one. A socket-like object can be passed directly
|
|
115
|
+
(that is what the offline tests do), as long as it has ``recv_into`` and
|
|
116
|
+
``settimeout``.
|
|
117
|
+
"""
|
|
118
|
+
|
|
119
|
+
def __init__(self, sock):
|
|
120
|
+
self.sock = sock
|
|
121
|
+
# Set once the first frame's header has been read.
|
|
122
|
+
self.protocol_version: Optional[Tuple[int, int]] = None
|
|
123
|
+
|
|
124
|
+
def close(self) -> None:
|
|
125
|
+
try:
|
|
126
|
+
self.sock.close()
|
|
127
|
+
except OSError:
|
|
128
|
+
pass
|
|
129
|
+
|
|
130
|
+
def __enter__(self) -> "Connection":
|
|
131
|
+
return self
|
|
132
|
+
|
|
133
|
+
def __exit__(self, *exc_info) -> None:
|
|
134
|
+
self.close()
|
|
135
|
+
|
|
136
|
+
def _set_timeout(self, timeout: Optional[float]) -> None:
|
|
137
|
+
try:
|
|
138
|
+
self.sock.settimeout(timeout)
|
|
139
|
+
except (AttributeError, OSError):
|
|
140
|
+
# A test double, or a socket that refuses it: the caller's deadline
|
|
141
|
+
# still applies to whole frames, not to each read.
|
|
142
|
+
pass
|
|
143
|
+
|
|
144
|
+
def _read_exactly(self, size: int, what: str) -> bytes:
|
|
145
|
+
data = bytearray(size)
|
|
146
|
+
view = memoryview(data)
|
|
147
|
+
got = 0
|
|
148
|
+
while got < size:
|
|
149
|
+
try:
|
|
150
|
+
chunk = self.sock.recv_into(view[got:], size - got)
|
|
151
|
+
except socket.timeout:
|
|
152
|
+
raise _ReadTimeout(got)
|
|
153
|
+
if chunk <= 0:
|
|
154
|
+
raise ConnectionClosed(
|
|
155
|
+
"screenstream: the source closed after %d of %d bytes of %s."
|
|
156
|
+
% (got, size, what))
|
|
157
|
+
got += chunk
|
|
158
|
+
return bytes(data)
|
|
159
|
+
|
|
160
|
+
def _read_header_part(self, size: int, total: int) -> bytes:
|
|
161
|
+
try:
|
|
162
|
+
return self._read_exactly(size, "a frame header")
|
|
163
|
+
except _ReadTimeout as stalled:
|
|
164
|
+
raise ProtocolError(
|
|
165
|
+
"screenstream: the stream stopped in the middle of a frame header "
|
|
166
|
+
"(%s)." % _header_progress(stalled.got, total))
|
|
167
|
+
|
|
168
|
+
def read_frame(self, timeout: Optional[float] = None) -> Optional[Frame]:
|
|
169
|
+
"""Reads one frame, or returns None if no header arrived before ``timeout``.
|
|
170
|
+
|
|
171
|
+
A timeout is only a quiet screen when it happens before the first byte of
|
|
172
|
+
a header. A partial header or payload is a malformed stream, and raises
|
|
173
|
+
:class:`ProtocolError` with a sentence rather than a decode error.
|
|
174
|
+
"""
|
|
175
|
+
self._set_timeout(timeout)
|
|
176
|
+
try:
|
|
177
|
+
magic = self._read_exactly(4, "a frame header")
|
|
178
|
+
except _ReadTimeout as stalled:
|
|
179
|
+
if stalled.got == 0:
|
|
180
|
+
return None
|
|
181
|
+
raise ProtocolError(
|
|
182
|
+
"screenstream: the stream stopped in the middle of a frame header "
|
|
183
|
+
"(%s)." % _header_progress(stalled.got, HEADER.size))
|
|
184
|
+
|
|
185
|
+
if magic == LEGACY_MAGIC:
|
|
186
|
+
major, minor = 1, 0
|
|
187
|
+
rest = self._read_header_part(LEGACY_HEADER.size - 4, LEGACY_HEADER.size)
|
|
188
|
+
width, height, stride, pixel_format, number, ts_ns = struct.unpack(
|
|
189
|
+
">IIIIQQ", rest)
|
|
190
|
+
elif magic == MAGIC:
|
|
191
|
+
version = self._read_header_part(4, HEADER.size)
|
|
192
|
+
major, minor = struct.unpack(">HH", version)
|
|
193
|
+
if major != PROTOCOL_MAJOR:
|
|
194
|
+
raise ProtocolError(
|
|
195
|
+
"screenstream: the stream speaks protocol %d.%d, and this "
|
|
196
|
+
"client understands %d.x; upgrade the client or the app."
|
|
197
|
+
% (major, minor, PROTOCOL_MAJOR))
|
|
198
|
+
rest = self._read_header_part(HEADER.size - 8, HEADER.size)
|
|
199
|
+
width, height, stride, pixel_format, number, ts_ns = struct.unpack(
|
|
200
|
+
">IIIIQQ", rest)
|
|
201
|
+
else:
|
|
202
|
+
raise ProtocolError(
|
|
203
|
+
"screenstream: not a frame header (magic %r); expected %r or %r."
|
|
204
|
+
% (magic, MAGIC, LEGACY_MAGIC))
|
|
205
|
+
|
|
206
|
+
self.protocol_version = (major, minor)
|
|
207
|
+
if width <= 0 or height <= 0 or stride < width * BYTES_PER_PIXEL:
|
|
208
|
+
raise ProtocolError(
|
|
209
|
+
"screenstream: impossible frame geometry %dx%d with stride %d."
|
|
210
|
+
% (width, height, stride))
|
|
211
|
+
if pixel_format != RGBA_8888:
|
|
212
|
+
raise ProtocolError(
|
|
213
|
+
"screenstream: unknown pixel format %d; this client reads "
|
|
214
|
+
"RGBA_8888 (format 1)." % pixel_format)
|
|
215
|
+
size = stride * height
|
|
216
|
+
if size <= 0 or size > MAX_FRAME_BYTES:
|
|
217
|
+
raise ProtocolError(
|
|
218
|
+
"screenstream: refusing a %d-byte frame (%dx%d, stride %d)."
|
|
219
|
+
% (size, width, height, stride))
|
|
220
|
+
|
|
221
|
+
try:
|
|
222
|
+
pixels = self._read_exactly(size, "a frame")
|
|
223
|
+
except _ReadTimeout as stalled:
|
|
224
|
+
raise ProtocolError(
|
|
225
|
+
"screenstream: the stream stopped in the middle of a frame "
|
|
226
|
+
"(%d of %d pixel bytes)." % (stalled.got, size))
|
|
227
|
+
return Frame(number, ts_ns, size, pixels, width, height, stride,
|
|
228
|
+
pixel_format, (major, minor))
|
|
229
|
+
|
|
230
|
+
def frames(self, timeout: Optional[float] = None) -> Iterator[Frame]:
|
|
231
|
+
"""Every frame until the source closes; a quiet timeout just keeps waiting."""
|
|
232
|
+
while True:
|
|
233
|
+
try:
|
|
234
|
+
frame = self.read_frame(timeout)
|
|
235
|
+
except ConnectionClosed:
|
|
236
|
+
return
|
|
237
|
+
if frame is not None:
|
|
238
|
+
yield frame
|
|
239
|
+
|
|
240
|
+
def wait_for_change(self, timeout: float,
|
|
241
|
+
since: Optional[int] = None) -> Optional[Frame]:
|
|
242
|
+
"""Waits up to ``timeout`` for a frame newer than ``since``.
|
|
243
|
+
|
|
244
|
+
``since`` is a frame number, normally the last one seen. A still screen
|
|
245
|
+
sends nothing, so this returns None when the timeout passes. A closed
|
|
246
|
+
connection raises :class:`ConnectionClosed`.
|
|
247
|
+
"""
|
|
248
|
+
deadline = time.monotonic() + max(0.0, timeout)
|
|
249
|
+
while True:
|
|
250
|
+
remaining = deadline - time.monotonic()
|
|
251
|
+
if remaining <= 0:
|
|
252
|
+
return None
|
|
253
|
+
frame = self.read_frame(remaining)
|
|
254
|
+
if frame is None:
|
|
255
|
+
return None
|
|
256
|
+
if since is None or frame.number > since:
|
|
257
|
+
return frame
|
|
258
|
+
|
|
259
|
+
|
|
260
|
+
def connect(host, port, timeout: float = 10.0) -> Connection:
|
|
261
|
+
"""Connects to a stream, retrying while the capture is still starting.
|
|
262
|
+
|
|
263
|
+
``timeout`` is how long to keep trying, not a socket timeout: a connection
|
|
264
|
+
that succeeds has no read timeout, so :meth:`Connection.wait_for_change`
|
|
265
|
+
decides how long a still screen may stay quiet.
|
|
266
|
+
"""
|
|
267
|
+
deadline = time.monotonic() + max(0.0, timeout)
|
|
268
|
+
last_error = None
|
|
269
|
+
while True:
|
|
270
|
+
remaining = deadline - time.monotonic()
|
|
271
|
+
try:
|
|
272
|
+
sock = socket.create_connection(
|
|
273
|
+
(host, int(port)), timeout=max(0.1, min(5.0, remaining)))
|
|
274
|
+
except OSError as failed:
|
|
275
|
+
last_error = failed
|
|
276
|
+
if time.monotonic() >= deadline:
|
|
277
|
+
raise ConnectionError(
|
|
278
|
+
"screenstream: cannot reach %s:%d (%s)."
|
|
279
|
+
% (host, int(port), last_error))
|
|
280
|
+
time.sleep(0.2)
|
|
281
|
+
continue
|
|
282
|
+
sock.settimeout(None)
|
|
283
|
+
return Connection(sock)
|
|
284
|
+
|
|
285
|
+
|
|
286
|
+
def save_png(frame: Frame, path) -> str:
|
|
287
|
+
"""Writes one frame as a PNG through ffmpeg.
|
|
288
|
+
|
|
289
|
+
No image library is a dependency; ffmpeg is expected where pictures are
|
|
290
|
+
wanted, exactly as the command-line clients already expected it. Raises
|
|
291
|
+
:class:`SaveError` with a sentence when it is missing or refuses the frame.
|
|
292
|
+
"""
|
|
293
|
+
path = os.fspath(path)
|
|
294
|
+
directory = os.path.dirname(os.path.abspath(path))
|
|
295
|
+
os.makedirs(directory, exist_ok=True)
|
|
296
|
+
argv = [
|
|
297
|
+
"ffmpeg", "-hide_banner", "-loglevel", "error", "-y",
|
|
298
|
+
"-f", "rawvideo", "-pixel_format", "rgba",
|
|
299
|
+
"-video_size", "%dx%d" % (frame.width, frame.height),
|
|
300
|
+
"-i", "pipe:0", "-frames:v", "1", path,
|
|
301
|
+
]
|
|
302
|
+
try:
|
|
303
|
+
result = subprocess.run(argv, input=frame.body,
|
|
304
|
+
capture_output=True, text=True)
|
|
305
|
+
except FileNotFoundError:
|
|
306
|
+
raise SaveError(
|
|
307
|
+
"screenstream: ffmpeg is not installed, so %s was not written." % path)
|
|
308
|
+
if result.returncode != 0:
|
|
309
|
+
raise SaveError(
|
|
310
|
+
"screenstream: ffmpeg could not write %s: %s"
|
|
311
|
+
% (path, (result.stderr or "").strip()))
|
|
312
|
+
return path
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: screenstream-client
|
|
3
|
+
Version: 0.2.0
|
|
4
|
+
Summary: Read the screenstream app's raw RGBA frames and encoded fragmented MP4.
|
|
5
|
+
Author: MBanucu
|
|
6
|
+
License-Expression: GPL-3.0-or-later
|
|
7
|
+
Project-URL: Homepage, https://github.com/MBanucu/screenstream
|
|
8
|
+
Project-URL: Documentation, https://github.com/MBanucu/screenstream#readme
|
|
9
|
+
Project-URL: Issues, https://github.com/MBanucu/screenstream/issues
|
|
10
|
+
Keywords: screen,android,streaming,rgba,fmp4,testing
|
|
11
|
+
Classifier: Development Status :: 4 - Beta
|
|
12
|
+
Classifier: Environment :: Console
|
|
13
|
+
Classifier: Intended Audience :: Developers
|
|
14
|
+
Classifier: Operating System :: OS Independent
|
|
15
|
+
Classifier: Programming Language :: Python :: 3
|
|
16
|
+
Classifier: Topic :: Software Development :: Testing
|
|
17
|
+
Requires-Python: >=3.9
|
|
18
|
+
Description-Content-Type: text/markdown
|
|
19
|
+
|
|
20
|
+
# screenstream-client
|
|
21
|
+
|
|
22
|
+
The Python client for [screenstream](https://github.com/MBanucu/screenstream):
|
|
23
|
+
the phone's screen as raw RGBA frames on a local port, and the same capture as
|
|
24
|
+
H.264 in a fragmented MP4 on a second one. No Android, no device, no runtime
|
|
25
|
+
dependency beyond the standard library (ffmpeg is used only when a PNG is
|
|
26
|
+
wanted).
|
|
27
|
+
|
|
28
|
+
```bash
|
|
29
|
+
pip install screenstream-client
|
|
30
|
+
# or install it in an isolated environment:
|
|
31
|
+
pipx install screenstream-client
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
The commands keep the flags of the scripts they replace, so an existing
|
|
35
|
+
`python3 client/stream.py --port 7200 --seconds 5 --png out/stream` becomes:
|
|
36
|
+
|
|
37
|
+
```bash
|
|
38
|
+
screenstream-stream --port 7200 --seconds 5 --frames-dir out/stream
|
|
39
|
+
screenstream-fmp4 --seconds 10 --out out/live.mp4
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
As a library:
|
|
43
|
+
|
|
44
|
+
```python
|
|
45
|
+
from screenstream_client import connect, read_fmp4, save_png
|
|
46
|
+
|
|
47
|
+
with connect("127.0.0.1", 7100) as link:
|
|
48
|
+
frame = link.wait_for_change(timeout=5) # None on a still screen
|
|
49
|
+
print(frame.number, frame.timestamp_ns, frame.size)
|
|
50
|
+
save_png(frame, "out/frame.png")
|
|
51
|
+
|
|
52
|
+
for number, timestamp_ns, size, pixels in link.frames():
|
|
53
|
+
...
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
`read_fmp4` parses an init segment, a saved file, or bytes. `base_ns` gives the
|
|
57
|
+
device clock's reading for the track's zero from the `udta`/`uuid` box, so a
|
|
58
|
+
frame's device time is `base_ns + pts * 1000`.
|
|
59
|
+
|
|
60
|
+
## Protocol version
|
|
61
|
+
|
|
62
|
+
This client speaks screenstream protocol **2.x**. A stream whose major version
|
|
63
|
+
is different is refused with a sentence that names both versions, not read as
|
|
64
|
+
if the fields still meant the same thing. Protocol 1 (magic `RAW1`, the
|
|
65
|
+
unversioned 36-byte header) is still accepted for an app installed before the
|
|
66
|
+
version existed.
|
|
67
|
+
|
|
68
|
+
The distribution and the AAR share the version in `pyproject.toml`; it must
|
|
69
|
+
equal `build.gradle.kts` and `build.sh`, and the test suite checks that.
|
|
70
|
+
|
|
71
|
+
## The control surface
|
|
72
|
+
|
|
73
|
+
`screenstream_client.control` is the shared parser for the `content call` wire
|
|
74
|
+
format: `parse_call` for a command, `parse_result` for the
|
|
75
|
+
`Result: Bundle[{code=..., data=...}]` reply, `parse_fields` for the
|
|
76
|
+
`key=value` body and `parse_extra` for `name:type:value`. Its
|
|
77
|
+
`SCHEMA_VERSION` must equal the Java library's
|
|
78
|
+
`ControlContract.SCHEMA_VERSION`; `test/test_control.py` reads both and the
|
|
79
|
+
shared fixture, so the Java and Python grammars cannot drift silently.
|
|
80
|
+
`client/control.py` is the adb command-line wrapper over it.
|
|
81
|
+
|
|
82
|
+
The contract is `docs/control-surface.md` in the repository.
|
|
83
|
+
|
|
84
|
+
## License
|
|
85
|
+
|
|
86
|
+
GPL-3.0-or-later, as the rest of screenstream.
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
README.md
|
|
2
|
+
pyproject.toml
|
|
3
|
+
screenstream_client/__init__.py
|
|
4
|
+
screenstream_client/cli.py
|
|
5
|
+
screenstream_client/control.py
|
|
6
|
+
screenstream_client/fmp4.py
|
|
7
|
+
screenstream_client/wire.py
|
|
8
|
+
screenstream_client.egg-info/PKG-INFO
|
|
9
|
+
screenstream_client.egg-info/SOURCES.txt
|
|
10
|
+
screenstream_client.egg-info/dependency_links.txt
|
|
11
|
+
screenstream_client.egg-info/entry_points.txt
|
|
12
|
+
screenstream_client.egg-info/top_level.txt
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
screenstream_client
|