Repository navigation
Expand file tree
/
Copy pathupstream.py
More file actions
296 lines (248 loc) · 14.2 KB
/
Copy pathupstream.py
File metadata and controls
296 lines (248 loc) · 14.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
#!/usr/bin/env python3
"""Make the series for FFmpeg's own tree from this repository, one commit per change.
upstream.py FFMPEG_TREE [fftools|protocol|all]
There are two series, to be sent apart (UPSTREAMING.md, The Series): fftools, how ffmpeg and ffprobe
end when an input's reads fail, for every input; and protocol, fdproxy itself. Each applies to
FFmpeg alone; all makes both, fftools first.
FFMPEG_TREE is a clean checkout of FFmpeg (tools/upstream.sh checks out the commit UPSTREAM_COMMIT
names). Each change is made by inserting lines at an anchor in FFmpeg's file, so the series follows
FFmpeg as it moves, and fails, naming the anchor, when one is gone. The code comes from src/ and the
documentation from upstream/, the same files the jellyfin patches carry, so the two cannot drift.
The commits carry no Signed-off-by: `git format-patch -s` adds the sender's."""
import os, re, shutil, subprocess, sys
HERE = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
def insert(tree, path, anchor, lines, before=False):
"""Inserts lines after (or before) the one place anchor appears in tree's file path."""
file = os.path.join(tree, path)
with open(file, encoding="utf-8") as f:
text = f.read()
if text.count(anchor) != 1:
raise SystemExit(f"{path}: the anchor appears {text.count(anchor)} times, not once:\n{anchor}")
at = text.index(anchor) + (0 if before else len(anchor))
with open(file, "w", encoding="utf-8") as f:
f.write(text[:at] + lines + text[at:])
def replace(tree, path, old, new):
"""Replaces the one place old appears in tree's file path with new."""
file = os.path.join(tree, path)
with open(file, encoding="utf-8") as f:
text = f.read()
if text.count(old) != 1:
raise SystemExit(f"{path}: the anchor appears {text.count(old)} times, not once:\n{old}")
with open(file, "w", encoding="utf-8") as f:
f.write(text.replace(old, new))
def copy(tree, source, path):
"""Copies source into the tree, without what is between the markers "ffmpeg-fdproxy only:" and
"ffmpeg-fdproxy only: end.", which serves only this repository's users."""
os.makedirs(os.path.dirname(os.path.join(tree, path)), exist_ok=True)
kept, skipping = [], False
for line in read(source).splitlines(keepends=True):
if "ffmpeg-fdproxy only:" in line:
skipping = not line.rstrip().endswith("end. */")
continue
if not skipping:
kept.append(line)
with open(os.path.join(tree, path), "w", encoding="utf-8") as f:
f.write("".join(kept))
def read(path):
with open(os.path.join(HERE, path), encoding="utf-8") as f:
return f.read()
def protocol(tree):
copy(tree, "src/libavformat/fdproxy.c", "libavformat/fdproxy.c")
insert(tree, "libavformat/protocols.c", "extern const URLProtocol ff_fd_protocol;\n",
"extern const URLProtocol ff_fdproxy_protocol;\n")
insert(tree, "libavformat/Makefile", "OBJS-$(CONFIG_FD_PROTOCOL) += file.o\n",
"OBJS-$(CONFIG_FDPROXY_PROTOCOL) += fdproxy.o\n")
insert(tree, "configure", 'ffrtmpcrypt_protocol_conflict="librtmp_protocol"\n',
'fdproxy_protocol_deps="poll_h"\n', before=True)
insert(tree, "doc/protocols.texi", "@section file\n", read("upstream/protocols.texi"), before=True)
insert(tree, "Changelog", "version <next>:\n", "- fdproxy protocol\n")
version = os.path.join(tree, "libavformat/version.h")
with open(version, encoding="utf-8") as f:
text = f.read()
minor = re.search(r"#define LIBAVFORMAT_VERSION_MINOR +(\d+)", text)
micro = re.search(r"#define LIBAVFORMAT_VERSION_MICRO +(\d+)", text)
if not minor or not micro:
raise SystemExit("libavformat/version.h: no LIBAVFORMAT_VERSION_MINOR or _MICRO")
text = text.replace(minor.group(0), minor.group(0)[:-len(minor.group(1))] + str(int(minor.group(1)) + 1))
text = text.replace(micro.group(0), micro.group(0)[:-len(micro.group(1))] + "100")
with open(version, "w", encoding="utf-8") as f:
f.write(text)
def fate(tree):
copy(tree, "src/libavformat/tests/fdproxy.c", "libavformat/tests/fdproxy.c")
copy(tree, "src/tests/ref/fate/fdproxy", "tests/ref/fate/fdproxy")
insert(tree, "libavformat/Makefile", "TESTPROGS-$(CONFIG_FFRTMPCRYPT_PROTOCOL) += rtmpdh\n",
"TESTPROGS-$(CONFIG_FDPROXY_PROTOCOL) += fdproxy\n", before=True)
insert(tree, "tests/fate/libavformat.mak", "FATE_LIBAVFORMAT-$(CONFIG_FFRTMPCRYPT_PROTOCOL) += fate-rtmpdh\n",
"FATE_LIBAVFORMAT-$(CONFIG_FDPROXY_PROTOCOL) += fate-fdproxy\n"
"fate-fdproxy: libavformat/tests/fdproxy$(EXESUF)\n"
"fate-fdproxy: CMD = run libavformat/tests/fdproxy$(EXESUF)\n\n", before=True)
def seek(tree):
replace(tree, "libavformat/seek.c",
' if (proto && !(strcmp(proto, "file") && strcmp(proto, "pipe") && strcmp(proto, "cache")))\n',
" /* fdproxy is local too: its parent serves any offset, so a seek\n"
" * costs nothing, and reading forward in place of one would read\n"
" * megabytes it never needed. */\n"
' if (proto && !(strcmp(proto, "file") && strcmp(proto, "pipe") &&\n'
' strcmp(proto, "cache") && strcmp(proto, "fdproxy")))\n')
def demux(tree):
replace(tree, "fftools/ffmpeg_demux.c",
" if (d->loop) {\n",
" /* An input whose reads failed is not looped: it would fail\n"
" * again at once, for ever. */\n"
" if (d->loop && !(f->ctx->pb && f->ctx->pb->error < 0 &&\n"
" f->ctx->pb->error != AVERROR(EAGAIN))) {\n")
insert(tree, "fftools/ffmpeg_demux.c",
" // EOF/EXIT is normal termination\n if (ret == AVERROR_EOF || ret == AVERROR_EXIT)\n",
" /* An input whose reads failed fails the run, where it would otherwise\n"
" * end as if the input had simply ended. */\n"
" if ((ret >= 0 || ret == AVERROR_EOF || ret == AVERROR_EXIT) &&\n"
" f->ctx->pb && f->ctx->pb->error < 0 &&\n"
" f->ctx->pb->error != AVERROR(EAGAIN)) {\n"
" ret = f->ctx->pb->error == AVERROR_EXIT ? AVERROR(EINTR)\n"
" : f->ctx->pb->error;\n"
' av_log(d, AV_LOG_ERROR, "Reading the input failed: %s\\n",\n'
" av_err2str(ret));\n"
" }\n\n", before=True)
insert(tree, "fftools/ffmpeg_demux.c",
" if (ic->nb_streams == 0)\n return ret;\n }\n",
" /* A read that failed while probing is not the input ending. */\n"
" if (ic->pb && ic->pb->error < 0 &&\n"
" ic->pb->error != AVERROR(EAGAIN)) {\n"
" ret = ic->pb->error == AVERROR_EXIT ? AVERROR(EINTR)\n"
" : ic->pb->error;\n"
" av_log(d, AV_LOG_FATAL,\n"
' "Reading the input failed while probing it: %s\\n",\n'
" av_err2str(ret));\n"
" return ret;\n"
" }\n")
def signal_exit(tree):
replace(tree, "fftools/ffmpeg.c",
"finish:\n if (ret == AVERROR_EXIT)\n ret = 0;\n",
"finish:\n"
" /* An interrupt during the opening of an input never reaches\n"
" * transcode(); a signal must still exit non-zero. */\n"
" if (ret == AVERROR_EXIT)\n"
" ret = received_nb_signals ? 255 : 0;\n")
def probe(tree):
insert(tree, "fftools/ffprobe.c", "#include <math.h>\n", "#include <signal.h>\n")
insert(tree, "fftools/ffprobe.c", " init_dynload();\n\n",
"#ifdef SIGPIPE\n"
" signal(SIGPIPE, SIG_IGN); /* a write to a closed pipe fails, as in ffmpeg */\n"
"#endif\n\n")
replace(tree, "fftools/ffprobe.c",
"end:\n if (ifile.fmt_ctx)\n close_input_file(&ifile);\n",
"end:\n"
" /* A read that failed is not the input ending. */\n"
" if (ret >= 0 && ifile.fmt_ctx && ifile.fmt_ctx->pb &&\n"
" ifile.fmt_ctx->pb->error < 0 &&\n"
" ifile.fmt_ctx->pb->error != AVERROR(EAGAIN)) {\n"
" ret = ifile.fmt_ctx->pb->error;\n"
" if (ret == AVERROR_EXIT)\n"
" ret = AVERROR(EINTR);\n"
' av_log(NULL, AV_LOG_ERROR, "Reading the input failed: %s\\n",\n'
" av_err2str(ret));\n"
" }\n"
" if (ifile.fmt_ctx)\n close_input_file(&ifile);\n")
# Each commit: what it changes, and its message in FFmpeg's form.
PROTOCOL = [
(protocol, """avformat/fdproxy: add the fdproxy protocol
fdproxy reads an input whose every byte a parent process serves, by
offset, over two pipes the parent hands down. FFmpeg confined by a
sandbox (Landlock, seccomp, a container) can then read its input with
no path to the file, no socket and no other way to reach the storage.
The parent decides every read, and can schedule, pace or refuse it.
Storage that stops answering, such as a network share that has gone
away, holds a thread of the parent, which can always end the run,
rather than FFmpeg waiting in the kernel where it cannot be killed.
The protocol has six messages of fixed form, each bounded and checked
before use; FFmpeg's side trusts the parent, and the parent trusts
nothing FFmpeg sends. Its specification:
https://github.com/kstenerud/ffmpeg-fdproxy
Like fd:, it works on duplicates of the descriptors it is given and
never closes or changes the caller's. It starts no thread and touches no
signal: a parent that has gone raises SIGPIPE, as for any pipe FFmpeg
writes, which the program ignores. Its default whitelist is itself, so a
demuxer's nested open cannot name the channel's descriptors through
pipe: or fd:. It needs only poll().
"""),
(fate, """fate/libavformat: add a test of the fdproxy protocol
A thread serves as the parent over two pipes: a file read through and
by seeks, a parent that leaves mid-session, terms the protocol refuses,
and a second session on a pipe that is open already.
"""),
(seek, """avformat/seek: treat fdproxy as a local protocol
Its parent serves any offset, so a seek costs no more than reading on,
and reading forward in place of a seek read megabytes the demuxer never
needed.
"""),
]
FFTOOLS = [
(demux, """fftools/ffmpeg_demux: fail when reading an input failed
Without -xerror, an error while demuxing is logged and the input ends
with status 0, so a run whose input could not be read through exits 0
with a truncated output. That suits a stream that may break; it does
not suit a file read for a measurement or an encode, which the caller
must not take as whole. -xerror is no way out, since it also ends the
run on a decode error that would have been concealed.
A read error left in the input's AVIOContext, an I/O failure rather
than a damaged stream, now fails the run, after the input ends and
while its streams are probed. An input whose reads failed is not
looped by -stream_loop either: it seeked back and failed again at
once, for ever, with -xerror or without.
"""),
(signal_exit, """fftools/ffmpeg: exit non-zero when a signal interrupts opening an input
A signal while an input was opening ended ffmpeg with AVERROR_EXIT,
which never reached transcode() and was turned into exit status 0, so a
killed run looked like a successful one.
"""),
(probe, """fftools/ffprobe: fail when reading the input failed
As in ffmpeg: a read error left in the input's AVIOContext was taken as
the input ending, and ffprobe printed partial results and exited 0.
It also ignores SIGPIPE, as ffmpeg does, so a write to a pipe whose
reader has gone fails with EPIPE rather than killing the process.
"""),
]
def git(tree, *args):
subprocess.run(["git", "-C", tree, *args], check=True)
def added_lines(diff, paths):
"""The lines a diff adds to the files in paths, in order, per file."""
added, current = {}, None
for line in diff.split("\n"):
if line.startswith("+++ "):
current = line[len("+++ b/"):] if line[len("+++ b/"):] in paths else None
elif current and line.startswith("+"):
added.setdefault(current, []).append(line[1:])
return added
SERIES = {"fftools": FFTOOLS, "protocol": PROTOCOL, "all": FFTOOLS + PROTOCOL}
# The files each series changes that patches/ changes too, for jellyfin.
CHECKED = {"fftools": ["fftools/ffmpeg_demux.c", "fftools/ffmpeg.c", "fftools/ffprobe.c"],
"protocol": ["libavformat/seek.c"]}
CHECKED["all"] = CHECKED["fftools"] + CHECKED["protocol"]
def check_against_patches(tree, base, paths):
"""The fftools and seek.c changes are written twice, in patches/ for jellyfin and here for
FFmpeg; fails when what they add differs."""
ours = added_lines(subprocess.run(["git", "-C", tree, "diff", base, "HEAD", "--", *paths],
capture_output=True, text=True, check=True).stdout, paths)
jellyfin = {}
for name in ("9000-fdproxy-protocol.patch", "9001-fftools-input-errors.patch"):
jellyfin.update(added_lines(read(os.path.join("patches", name)), paths))
for path in paths:
if ours.get(path) != jellyfin.get(path):
raise SystemExit(f"{path}: the series adds other lines than patches/ do; change both")
def main(argv):
if len(argv) not in (1, 2) or (len(argv) == 2 and argv[1] not in SERIES):
print(__doc__, file=sys.stderr)
return 2
tree = argv[0]
name = argv[1] if len(argv) == 2 else "all"
base = subprocess.run(["git", "-C", tree, "rev-parse", "HEAD"], capture_output=True, text=True,
check=True).stdout.strip()
for change, message in SERIES[name]:
change(tree)
git(tree, "add", "-A")
git(tree, "commit", "--quiet", "-m", message)
check_against_patches(tree, base, CHECKED[name])
print(f"the {name} series: {len(SERIES[name])} commits in {tree}, adding what patches/ add")
return 0
if __name__ == "__main__":
sys.exit(main(sys.argv[1:]))