Files
Triforce-Source/tests/test_video_decode_ahead.py
ruckus7382sfgsgdf b527e29adb Triforce v0.8.5
A Randomizer page in the launcher, a new title screen with Mods and Save Select tabs, scaling changes applied in game, the Jabu-Jabu bars fixed, renderer frame-time work and the brightness-flash fix, and fixes from the 0.8.4 reports.
2026-11-28 10:54:41 -06:00

494 lines
30 KiB
Python

"""A movie's pictures are decoded ahead of the game by a host thread of the decoder's (host/nn_video.c; no game, no decoder).
The pictures were decoded in the game's Acquire...DecoderOutputBuffer call: 3-13 ms each for the title screen's 1080p AV1
movie, single ones 80-200 ms, several in a row when the movie was behind its clock (728 ms in one call), and the movie
stuttered wherever a scene loads over it. Each decoder now has a host thread that decodes the submissions ahead and keeps
a few pictures queued. Checked here, in three parts:
1. the rules, cut out of nn_video.c unchanged and run: how many pictures are kept ahead (HOS_VIDEO_DECODE_AHEAD: unset
or 1 six, 0 none, 2 and more that many, two places of the queue left over), when the worker decodes the next
submission (the stream's end at once, a picture only below the count: never into a queue that has it), and when a
picture is behind the movie's clock (the catch-up's 25 ms);
2. the wiring, read: the worker lets the decoder's lock go before it decodes and takes it after; the decoding functions
touch neither the lock's fields nor guest memory; mf_av1_decode and avcodec_send_packet are called nowhere else; the
worker waits for room in a full queue instead of dropping; a flush takes the decoder from the worker first (counts
the flush, holds new decodes off, waits for the one in flight) and the close ends the worker before anything is
freed; with a worker the acquire decodes nothing, the catch-up included, and wakes the worker for the room it made;
the switch, the pictures-taken line and the development guide;
3. the threads, run (Windows: SRW locks and condition variables as the runtime uses them): the worker, the wait of an
acquire, the flush and the close are cut out of nn_video.c unchanged and driven by a stand-in decoder (random time,
frames held back, several pictures from one submission) and a stand-in game that submits, takes, flushes and closes
as dec_submit, dec_acquire, dec_flush and dec_finalize do. Every picture must come out once, in order, the
last one with the last flag, none of a flushed stream after its flush, never two threads in the decoder, nothing
leaked, and the run must end (a deadlock is a failure after two minutes). Run with 2, 6 and 14 pictures ahead.
python -I -B tests/test_video_decode_ahead.py [--cc gcc]
"""
import argparse
import os
import re
import subprocess
import tempfile
from pathlib import Path
RUN_ALL_ARGS = ["--cc", "gcc"]
ROOT = Path(__file__).resolve().parents[1]
RULES_MAIN = r'''
#define CHECK(x) do { if (!(x)) { fprintf(stderr, "FAIL:%d %s\n", __LINE__, #x); return 1; } } while (0)
int main(void) {
/* (the count: unset and 1 are the default, 0 and no number are off, the queue keeps two places) */
CHECK(VIDEO_AHEAD_PICTURES == 12 && VIDEO_AHEAD_PICTURES <= MAX_QUEUE - 2);
CHECK(video_ahead_count(NULL, MAX_QUEUE) == 12 && video_ahead_count("1", MAX_QUEUE) == 12);
CHECK(video_ahead_count("0", MAX_QUEUE) == 0 && video_ahead_count("", MAX_QUEUE) == 0);
CHECK(video_ahead_count("off", MAX_QUEUE) == 0 && video_ahead_count("-3", MAX_QUEUE) == 0);
CHECK(video_ahead_count("2", MAX_QUEUE) == 2 && video_ahead_count("12", MAX_QUEUE) == 12);
CHECK(video_ahead_count("14", 16) == 14 && video_ahead_count("15", 16) == 14 && video_ahead_count("999", 16) == 14);
CHECK(video_ahead_count(NULL, 8) == 6 && video_ahead_count(NULL, 6) == 4 && video_ahead_count(NULL, 3) == 1);
CHECK(video_ahead_count(NULL, 2) == 0 && video_ahead_count("5", 0) == 0);
/* (the worker: the end at once, a picture below the count only, nothing without a submission) */
for (int ahead = 1; ahead <= MAX_QUEUE - 2; ahead++)
for (int q = 0; q <= MAX_QUEUE; q++) {
CHECK(video_ahead_decode(1, 0, q, ahead) == (q < ahead));
CHECK(video_ahead_decode(1, 1, q, ahead) == 1);
CHECK(video_ahead_decode(0, 0, q, ahead) == 0 && video_ahead_decode(0, 1, q, ahead) == 0);
}
/* (late: the picture at 1.000 s was due at 5.000 s; at 5.100 s the picture of 1.100 s is due) */
const int64_t ms = 1000000, cp = 1000 * ms, cn = 5000 * ms, now = 5100 * ms;
CHECK(VIDEO_LATE_NS == 25 * ms);
CHECK(!video_picture_late(1100 * ms, cp, cn, now, VIDEO_LATE_NS));
CHECK(!video_picture_late(1075 * ms, cp, cn, now, VIDEO_LATE_NS)); /* 25 ms behind: not yet */
CHECK(video_picture_late(1075 * ms - 1, cp, cn, now, VIDEO_LATE_NS));
CHECK(video_picture_late(1000 * ms, cp, cn, now, VIDEO_LATE_NS));
CHECK(!video_picture_late(1200 * ms, cp, cn, now, VIDEO_LATE_NS)); /* decoded ahead: never late */
CHECK(!video_picture_late(cp, cp, cn, cn, VIDEO_LATE_NS)); /* the clock's own picture, at its time */
return 0;
}
'''
# (the stand-ins of the threads' fixture, before the parts cut out of nn_video.c)
STRESS_HEAD = r'''
#include <windows.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_SLOTS 16
#define CHECK(x) do { if (!(x)) { fprintf(stderr, "FAIL:%d %s\n", __LINE__, #x); fflush(stderr); ExitProcess(1); } } while (0)
static volatile LONG live; /* allocations not freed yet */
static void *t_calloc(size_t a, size_t b) { void *p = calloc(a, b); CHECK(p); InterlockedIncrement(&live); return p; }
static void *t_realloc(void *p, size_t n) { if (!p) InterlockedIncrement(&live); p = realloc(p, n); CHECK(p); return p; }
static void t_free(void *p) { if (p) InterlockedDecrement(&live); free(p); }
#define calloc t_calloc
#define realloc t_realloc
#define free t_free
typedef struct AVCodecContext AVCodecContext;
typedef struct AVFrame AVFrame;
typedef struct AVPacket { int64_t pts; int size; } AVPacket; /* (size: the stream the packet is of) */
static void av_packet_free(AVPacket **p) { free(*p); *p = NULL; }
static int64_t hos_now_ns(void) {
LARGE_INTEGER f, c;
QueryPerformanceFrequency(&f), QueryPerformanceCounter(&c);
return (int64_t)(c.QuadPart / f.QuadPart * 1000000000LL + c.QuadPart % f.QuadPart * 1000000000LL / f.QuadPart);
}
/* (as the runtime's with virtual cores, host/hos_thread.c: after the wait the lock is let go while a core is taken again) */
static int hos_cv_sleep(void *cv, void *lk, unsigned ms) {
const BOOL r = SleepConditionVariableSRW((PCONDITION_VARIABLE)cv, (PSRWLOCK)lk, ms, 0);
ReleaseSRWLockExclusive((PSRWLOCK)lk);
SwitchToThread();
AcquireSRWLockExclusive((PSRWLOCK)lk);
return r;
}
static int hos_vcore_away(void) { return 0; }
static void hos_vcore_back(void) {}
static void hos_host_thread_register_self(const char *name) { (void)name; }
static void hos_thread_pin(void *h, const char *name) { (void)h, (void)name; }
static void hos_log(const char *fmt, ...) { (void)fmt; }
static void spin_us(int us) {
const int64_t until = hos_now_ns() + (int64_t)us * 1000;
while (hos_now_ns() < until) YieldProcessor();
}
static unsigned rnd(unsigned *s) { return (*s = *s * 1664525u + 1013904223u) >> 8; }
'''
# (the stand-in decoder and game, after them)
STRESS_MAIN = r'''
/* the stand-in decoder: one thread in it at a time (in_decoder), a random time for each submission, the frames of a
stream held back by (stream % 5) submissions, so one submission gives none, one or, at the end, several pictures */
static volatile LONG in_decoder;
static struct { int64_t pts; int stream; } held[8];
static int nheld;
static unsigned dec_rnd = 7;
static void emit(Dec *d) {
Picture p;
memset(&p, 0, sizeof p);
p.nv12 = (uint8_t *)calloc(1, 16);
p.w = held[0].stream, p.h = 1, p.pts = held[0].pts;
memmove(held, held + 1, (size_t)--nheld * sizeof held[0]);
CHECK(out_push(d, &p));
}
static void decode_one(Dec *d, Pending *n) {
CHECK(InterlockedExchange(&in_decoder, 1) == 0);
spin_us((int)(rnd(&dec_rnd) % 120));
if (n->pkt) {
held[nheld].pts = n->pkt->pts, held[nheld].stream = n->pkt->size, nheld++;
while (nheld > n->pkt->size % 5) emit(d);
} else {
while (nheld) emit(d);
}
av_packet_free(&n->pkt);
free(n);
CHECK(InterlockedExchange(&in_decoder, 0) == 1);
}
static void avcodec_flush_buffers(AVCodecContext *c) { (void)c; CHECK(0); }
static void mf_av1_flush(void *m) { /* (the flush has the decoder: the worker is not in it) */
(void)m;
CHECK(InterlockedExchange(&in_decoder, 1) == 0);
nheld = 0;
CHECK(InterlockedExchange(&in_decoder, 0) == 1);
}
''' + "__CUT_AFTER_DECODER__" + r'''
/* the stand-in game, as dec_submit, dec_acquire, dec_flush and dec_finalize use the parts above */
static void submit(Dec *d, int stream, int64_t pts, int last) {
AcquireSRWLockExclusive(&d->lock);
AVPacket *pkt = (AVPacket *)calloc(1, sizeof *pkt);
pkt->pts = pts, pkt->size = stream;
pending_push(d, pkt);
if (last) pending_push(d, NULL);
if (d->worker) WakeAllConditionVariable(&d->work);
ReleaseSRWLockExclusive(&d->lock);
}
static int64_t longest_wait;
static int take(Dec *d, Picture *got) { /* 1: the oldest picture; 0: none (the end, or nothing submitted) */
AcquireSRWLockExclusive(&d->lock);
const int64_t waited = ahead_wait(d);
if (waited > longest_wait) longest_wait = waited;
CHECK(d->qn >= 0 && d->qn <= MAX_QUEUE);
if (!d->qn) {
CHECK(!d->phead && !d->decoding && !d->uncommitted); /* (none is on its way) */
ReleaseSRWLockExclusive(&d->lock);
return 0;
}
CHECK(d->qn > 1 || !tail_unsettled(d));
*got = d->queue[d->qhead];
memset(&d->queue[d->qhead], 0, sizeof d->queue[0]);
d->qhead = (d->qhead + 1) % MAX_QUEUE, d->qn--;
if (d->worker) WakeAllConditionVariable(&d->work);
ReleaseSRWLockExclusive(&d->lock);
return 1;
}
static void flush(Dec *d) {
AcquireSRWLockExclusive(&d->lock);
flush_locked(d);
CHECK(!d->qn && !d->phead && !d->eos && !d->hold);
ReleaseSRWLockExclusive(&d->lock);
}
static void finalize(Dec *d) {
ahead_close(d);
CHECK(!d->worker && !d->nout && !d->decoding);
pending_free(d);
for (int i = 0; i < d->qn; i++) picture_free(&d->queue[(d->qhead + i) % MAX_QUEUE]);
free(d->out);
free(d);
}
int main(int argc, char **argv) {
const int want_ahead = argc > 1 ? atoi(argv[1]) : 12;
unsigned s = 12345u + (unsigned)want_ahead;
int stream = 0;
long pictures = 0, flushes = 0, ends = 0;
for (int dec = 0; dec < 4; dec++) {
Dec *d = (Dec *)calloc(1, sizeof *d);
InitializeSRWLock(&d->lock);
d->mf = d; /* (any address: the stand-in decoder is the one above) */
ahead_start(d);
CHECK(d->worker && d->ahead == want_ahead);
for (int round = 0; round < 120; round++) {
stream++;
const int n = 1 + (int)(rnd(&s) % 150), delay = stream % 5;
const int flush_at = rnd(&s) % 4 == 0 ? (int)(rnd(&s) % (unsigned)(n + 1)) : -1;
const int slow = rnd(&s) % 3 == 0; /* (a game that takes slower than the worker decodes: the queue at its count) */
int submitted = 0, taken = 0, flushed = 0;
while (taken < n && !flushed) {
for (int k = 1 + (int)(rnd(&s) % (rnd(&s) % 2 ? 60u : 400u)); k > 0 && submitted < n; k--, submitted++)
submit(d, stream, submitted, submitted == n - 1);
/* (only pictures that will come: one more would wait 100 ms for a submission, as an acquire does) */
const int avail = submitted == n ? n : submitted > delay ? submitted - delay : 0;
int upto = taken + 1 + (int)(rnd(&s) % 30);
if (upto > avail) upto = avail;
while (taken < upto && !flushed) {
if (taken == flush_at) {
flush(d), flushed = 1, flushes++;
break;
}
Picture p;
CHECK(take(d, &p));
CHECK(p.w == stream); /* (no picture of a stream flushed or ended before) */
CHECK(p.pts == taken); /* (none dropped, none out of order, none twice) */
CHECK(p.last == (taken == n - 1)); /* (the last one, and only it, with its flag) */
CHECK(p.nv12 && !p.rgba);
picture_free(&p);
taken++, pictures++;
if (slow) spin_us((int)(rnd(&s) % 200));
}
}
if (!flushed) { /* (after the last picture: the end, at once) */
Picture p;
const int64_t t0 = hos_now_ns();
CHECK(!take(d, &p));
CHECK(hos_now_ns() - t0 < 50000000);
AcquireSRWLockExclusive(&d->lock);
CHECK(d->eos);
ReleaseSRWLockExclusive(&d->lock);
ends++;
}
}
stream++;
if (dec < 2) { /* (the close with the worker at work: a stream submitted and not taken) */
for (int i = 0; i < 40 + dec * 30; i++) submit(d, stream, i, 0);
if (dec & 1) spin_us(2000);
} else {
/* (a full queue: with the most pictures ahead, a stream whose 4 held frames come out at its end finds room
for 2 of them. The worker waits with the other 2 and drops nothing: they are queued as the game takes
(dec 2), and a close that finds the worker waiting ends it (dec 3)) */
const int n = MAX_QUEUE + 2;
while (stream % 5 != 4) stream++;
for (int i = 0; i < n; i++) submit(d, stream, i, i == n - 1);
if (want_ahead == MAX_QUEUE - 2)
for (int tries = 0;; tries++) {
AcquireSRWLockExclusive(&d->lock);
const int there = d->qn == MAX_QUEUE && d->uncommitted == 2 && d->eos && !d->decoding;
ReleaseSRWLockExclusive(&d->lock);
if (there) break;
CHECK(tries < 10000);
Sleep(1);
}
for (int i = 0; dec == 2 && i <= n; i++) {
Picture p;
if (i == n) {
CHECK(!take(d, &p));
break;
}
CHECK(take(d, &p) && p.w == stream && p.pts == i && p.last == (i == n - 1));
picture_free(&p);
}
}
finalize(d);
CHECK(nheld <= 4);
nheld = 0; /* (the stand-in decoder's frames of the closed stream: it kept no memory for them) */
}
CHECK(live == 0);
CHECK(pictures > 10000 && flushes > 50 && ends > 200 && !video_picture_late(0, 0, 0, 0, VIDEO_LATE_NS));
printf("%ld pictures, %ld flushes, %ld ends, longest wait %.1f ms\n", pictures, flushes, ends, (double)longest_wait / 1e6);
return 0;
}
'''
def check(cond, what):
if not cond:
raise SystemExit("FAIL: " + what)
def block(source, marker):
start = source.find(marker)
check(start >= 0, "%s is missing" % marker)
end = source.index("{", start) + 1
depth = 1
while depth:
depth += (source[end] == "{") - (source[end] == "}")
end += 1
return source[start:end]
def line_of(source, pattern):
found = re.search(pattern, source, re.M)
check(found is not None, "%s is missing" % pattern)
return found.group(0)
def build_and_run(cc, tmp, name, source, flags, runs):
src, exe = Path(tmp) / (name + ".c"), Path(tmp) / (name + ".exe")
src.write_text(source, encoding="utf-8")
built = subprocess.run([cc, *flags, "-o", str(exe), str(src)], capture_output=True, text=True)
check(built.returncode == 0, "%s does not compile:\n%s" % (name, built.stderr))
out = []
for args, env in runs:
try:
ran = subprocess.run([str(exe), *args], capture_output=True, text=True, timeout=120, env=env)
except subprocess.TimeoutExpired:
raise SystemExit("FAIL: %s %s did not end in 120 s: the worker and the game's calls wait for each other"
% (name, " ".join(args))) from None
check(ran.returncode == 0, "%s %s: %s" % (name, " ".join(args), ran.stderr.strip() or "exit %d" % ran.returncode))
out.append(ran.stdout.strip())
return out
def main():
parser = argparse.ArgumentParser()
parser.add_argument("--cc", default=os.environ.get("CC", "gcc"))
args = parser.parse_args()
video = (ROOT / "host/nn_video.c").read_text(encoding="utf-8")
# ---- 1. the rules
max_queue = line_of(video, r"^#define MAX_QUEUE \d+")
check(int(max_queue.split()[2]) >= 8, "the queue is shorter than the count's default needs")
rules = "\n".join([line_of(video, r"^enum \{ VIDEO_AHEAD_PICTURES = 12, VIDEO_LATE_NS = 25000000 \};"),
block(video, "static inline int video_ahead_count("), block(video, "static inline int video_ahead_decode("),
block(video, "static inline int video_picture_late(")])
with tempfile.TemporaryDirectory() as tmp:
build_and_run(args.cc, tmp, "video_ahead_rules",
"\n".join(["#include <stdint.h>", "#include <stdio.h>", "#include <stdlib.h>", max_queue, rules, RULES_MAIN]),
["-std=c11", "-Wall", "-Werror"], [([], None)])
# ---- 2. the wiring
worker = block(video, "static DWORD WINAPI decode_ahead_main(LPVOID arg) {")
order = [worker.find(part) for part in (
"if (d->hold || !video_ahead_decode(d->phead != NULL, d->phead && !d->phead->pkt, d->qn, d->ahead)) {",
"Pending *n = pending_pop(d);", "const uint32_t gen = d->gen;", "d->decoding = 1, d->ending = end;",
"ReleaseSRWLockExclusive(&d->lock);", "decode_one(d, n);", "AcquireSRWLockExclusive(&d->lock);\n decode_done(",
"d->decoding = d->ending = 0;", "d->uncommitted = d->nout;", "WakeAllConditionVariable(&d->idle);",
"while (i < d->nout && gen == d->gen && !d->closing) {", "if (d->qn == MAX_QUEUE) {",
"SleepConditionVariableSRW(&d->work, &d->lock, INFINITE, 0);\n continue;", "queue_push(d, &d->out[i++]);",
"for (; i < d->nout; i++) picture_free(&d->out[i]);", "d->nout = d->uncommitted = 0;")]
check(all(i >= 0 for i in order), "the worker's steps changed (step %d)" % (order.index(-1) + 1 if -1 in order else 0))
check(order == sorted(order), "the worker's steps are out of order: the lock let go, the decode, the lock, the queue")
between = worker[worker.index("d->decoding = 1, d->ending = end;"):worker.index("decode_done(")]
check(between.count("ReleaseSRWLockExclusive(&d->lock);") == 1 and between.count("AcquireSRWLockExclusive(&d->lock);") == 1
and between.index("ReleaseSRWLockExclusive") < between.index("decode_one(d, n);") < between.index("AcquireSRWLockExclusive"),
"the worker holds the decoder's lock across the decode")
check("decode_done(d, end && gen == d->gen, ns, gen == d->gen);" in worker, "a flushed stream's end still ends the stream after it")
check(worker.count("picture_free(") == 1, "the worker frees a picture somewhere else than after a flush or the close")
check("while (!d->closing) {" in worker and worker.rstrip().endswith("return 0;\n}"), "the worker does not end at the close")
guest = ("GP(", "G64(", "G32(", "ARG(", "hos_guest_range", "HOS_WRITTEN", "hos_vcore", "hos_cv_sleep", "hos_sleep_ns")
check(not any(g in worker for g in guest), "the worker touches guest memory or a virtual core")
one = block(video, "static void decode_one(Dec *d, Pending *n) {")
check(one.count("mf_av1_decode(") == 2 and video.count("mf_av1_decode(") == 3, "mf_av1_decode is called outside decode_one")
check(one.count("avcodec_send_packet(") == video.count("avcodec_send_packet(") == 3, "avcodec_send_packet is called outside decode_one")
check(video.count("avcodec_receive_frame(") == 1 and "avcodec_receive_frame(" in block(video, "static void drain(Dec *d) {"),
"avcodec_receive_frame is called outside drain")
shared = ("d->lock", "d->queue", "d->qn", "d->qhead", "d->phead", "d->ptail", "d->eos", "d->st_", "d->slot", "d->busy", "d->clock",
"d->decoding", "d->gen", "d->hold", "d->uncommitted")
for name in ("static void decode_one(Dec *d, Pending *n) {", "static void queue_frame(Dec *d, const AVFrame *f) {",
"static void mf_picture(", "static void drain(Dec *d) {", "static int out_push(Dec *d, Picture *p) {"):
part = block(video, name)
check(not any(f in part for f in shared), "%s reads or writes what the decoder's lock guards" % name.split("(")[0])
check(not any(g in part for g in guest), "%s touches guest memory or a virtual core" % name.split("(")[0])
check("out_push(d, &p)" in block(video, "static void queue_frame(Dec *d, const AVFrame *f) {"),
"a decoded frame does not go to the decoding thread's own list")
check(video.count("decode_one(") == 3, "decode_one is called from elsewhere (definition, decode_next, the worker expected)")
check(video.count("queue_push(") == 3, "queue_push is called from elsewhere (definition, decode_next, the worker expected)")
stop, go = block(video, "static void ahead_stop(Dec *d) {"), block(video, "static void ahead_go(Dec *d) {")
check(stop.index("d->gen++, d->hold++;") < stop.index("WakeAllConditionVariable(&d->work);")
< stop.index("while (d->decoding) hos_cv_sleep(&d->idle, &d->lock, 20);"),
"a flush does not count itself, hold new decodes off and wait for the decode in flight")
check(go.index("d->hold--;") < go.index("WakeAllConditionVariable(&d->work);"), "the worker is not let on after a flush")
flush = block(video, "static void flush_locked(Dec *d) {")
steps = [flush.find(part) for part in ("ahead_stop(d);", "if (d->ctx) avcodec_flush_buffers(d->ctx);", "else mf_av1_flush(d->mf);",
"pending_free(d);", "picture_free(&d->queue[", "d->qhead = d->qn = 0;", "ahead_go(d);")]
check(all(i >= 0 for i in steps) and steps == sorted(steps), "the flush touches the decoder or the queue before it has the decoder")
check(not any(w in flush for w in ("ReleaseSRWLock", "hos_cv_sleep", "hos_sleep_ns")),
"the flush lets the lock go between taking the decoder and giving it back")
check(video.count("avcodec_flush_buffers(") == 2 and video.count("mf_av1_flush(") == 2,
"the decoder is flushed outside flush_locked and decode_one")
outer = block(video, "static void dec_flush(Ctx *c, const char *what) {")
check(outer.index("AcquireSRWLockExclusive(&d->lock);") < outer.index("flush_locked(d);") < outer.index("ReleaseSRWLockExclusive(&d->lock);"),
"dec_flush does not flush under the decoder's lock")
close = block(video, "static void ahead_close(Dec *d) {")
check(close.index("d->closing = 1;") < close.index("WakeAllConditionVariable(&d->work);") < close.index("ReleaseSRWLockExclusive(&d->lock);")
< close.index("WaitForSingleObject(d->worker, INFINITE);") < close.index("CloseHandle(d->worker);"),
"the close does not end the worker and wait for it, with the lock let go")
final = block(video, "static void dec_finalize(Ctx *c) {")
steps = [final.find(part) for part in ("set_host(ARG(0), DEC_MAGIC, NULL);", "ahead_close(d);", "pending_free(d);", "free(d->out);",
"avcodec_free_context(&d->ctx);", "mf_av1_close(d->mf);", "\n free(d);")]
check(all(i >= 0 for i in steps) and steps == sorted(steps), "the decoder is freed before its worker has ended")
start = block(video, "static void ahead_start(Dec *d) {")
check(start.index("d->ahead = decode_ahead();") < start.index("if (!d->ahead) return;")
< start.index("d->worker = CreateThread(NULL, 0, decode_ahead_main, d, 0, NULL);"), "the switch does not keep the worker from starting")
check("SetThreadPriority" not in video, "the worker's priority is changed (normal is the rule)")
switch = block(video, "static int decode_ahead(void) {")
check('video_ahead_count(getenv("HOS_VIDEO_DECODE_AHEAD"), MAX_QUEUE)' in switch, "HOS_VIDEO_DECODE_AHEAD is not read")
init = block(video, "static void dec_init_sized(Ctx *c, enum AVCodecID id, const char *what, int w, int h) {")
check(init.index("d->frame = av_frame_alloc();") < init.index("if (d->ctx || d->mf) ahead_start(d);") < init.index("set_host(ARG(0), DEC_MAGIC, d);"),
"the worker starts after the game can find the decoder, or before the decoder is whole")
check(video.count("d->worker = ") == 2, "d->worker changes after the start (the start and the close expected)")
wait = block(video, "static int64_t ahead_wait(Dec *d) {")
check("if (d->qn > 1 || (d->qn == 1 && !tail_unsettled(d))) break;" in wait, "an acquire may take a picture whose last flag is not settled")
check("const int coming = d->qn || d->phead || d->decoding || d->uncommitted;" in wait and
"if (!coming && (d->eos || d->stopped || t0 >= idle_until)) break;" in wait, "an acquire gives up on a picture that is on its way, or waits at the end")
check("hos_cv_sleep(&d->idle, &d->lock, 2);" in wait and "decode_next" not in wait and "decode_pending" not in wait and "decode_one" not in wait,
"the wait decodes, or does not let the lock go")
tail = block(video, "static int tail_unsettled(const Dec *d) {")
check("return d->ending || (!d->decoding && !d->uncommitted && d->phead && !d->phead->pkt);" in tail, "the unsettled-tail rule changed")
body = block(video, "static void dec_acquire(Ctx *c) {")
check(body.index("if (d->worker) {") < body.index("waited_ns = ahead_wait(d);") < body.index("} else {") < body.index("decode_pending(d);"),
"with a worker the acquire still decodes")
catch = body[body.index("for (int guard = 0;"):body.index("d->st_skipped += skipped;")]
check(catch.index("if (d->worker || !d->phead) break;") < catch.index("decode_next(d);"), "the catch-up decodes in the call with a worker")
check(body.count("decode_next(d);") == 1 and body.count("decode_pending(d);") == 2, "the acquire decodes somewhere else")
check("if (!video_picture_late(d->queue[d->qhead].pts, d->clock_pts, d->clock_ns, now, late)) break;" in catch,
"the catch-up's rule is not the one tested")
check(catch.index("if (d->worker && d->qn == 2 && tail_unsettled(d)) break;") < catch.index("picture_free(&d->queue[d->qhead]);"),
"the catch-up may leave a picture whose last flag is not settled as the one to go out")
check("const int idle = !d->eos && !d->phead && !d->decoding && !d->uncommitted;" in body,
"a buffer is called idle while the worker has a picture on its way")
check(body.index("picture_free(p);") < body.index("if (d->worker) WakeAllConditionVariable(&d->work);") < body.rindex("ReleaseSRWLockExclusive(&d->lock);"),
"the acquire does not wake the worker for the room it made")
check("const int64_t call_ns = d->worker ? waited_ns : d->st_ns - call_ns0;" in body and "if (call_ns > 0) d->st_waited++;" in body
and "else d->st_ready++;" in body, "the acquires are not counted as ready or waited")
line = body[body.index("if (d->st_taken >= 600"):]
for part in ('d->worker ? "decoded ahead by a host thread (HOS_VIDEO_DECODE_AHEAD)" : "in the game\'s call"', "found their picture ready",
"waited for it", "(long long)d->st_ready, (long long)d->st_waited", "d->st_ready = d->st_waited = 0;"):
check(part in line[:1800], "the pictures-taken line lost: " + part)
submit = block(video, "static void dec_submit(Ctx *c) {")
check(submit.index("pending_push(d, NULL);") < submit.index("if (d->worker) WakeAllConditionVariable(&d->work);")
< submit.rindex("ReleaseSRWLockExclusive(&d->lock);"), "a submission does not wake the worker")
check(submit.index("memcpy(pkt->data, data, (size_t)ARG(3));") < submit.index("pending_push(d, pkt);"),
"a submission's data is not copied before the worker can have it")
guide = (ROOT / "docs/development.md").read_text(encoding="utf-8")
check("| `HOS_VIDEO_DECODE_AHEAD=0`" in guide and "tests/test_video_decode_ahead.py" in guide, "docs/development.md does not name HOS_VIDEO_DECODE_AHEAD")
# ---- 3. the threads
if os.name != "nt":
print("ok (the threads' fixture was not run: it is written for Windows' SRW locks)")
return
dec = block(video, "typedef struct {\n /* ((Triforce) The decoder:")
check(video[video.index(dec) + len(dec):].startswith(" Dec;"), "the decoder's struct is not cut whole")
dec += " Dec;"
types = [line_of(video, r"^typedef struct \{ uint8_t \*rgba, \*nv12; .*\} Picture;"),
line_of(video, r"^typedef struct Pending \{ .*\} Pending;"), max_queue, rules, dec]
before = [block(video, f) for f in ("static void picture_free(Picture *p) {", "static void pending_free(Dec *d) {",
"static int out_push(Dec *d, Picture *p) {", "static void queue_push(Dec *d, const Picture *p) {",
"static Pending *pending_pop(Dec *d) {", "static void decode_done(Dec *d, int end, int64_t ns, int live) {",
"static void pending_push(Dec *d, AVPacket *pkt) {")]
after = [block(video, f) for f in ("static int decode_ahead(void) {", "static int tail_unsettled(const Dec *d) {",
"static DWORD WINAPI decode_ahead_main(LPVOID arg) {", "static void ahead_start(Dec *d) {",
"static void ahead_close(Dec *d) {", "static void ahead_stop(Dec *d) {", "static void ahead_go(Dec *d) {",
"static void flush_locked(Dec *d) {", "static int64_t ahead_wait(Dec *d) {")]
# ((Triforce, 11-22, on v0.7.0) the decoder's record keeps v0.7.0's movie counts, pace and input limit too: their
# headers before the fixture's own calloc and free, and the ready event's room (input_room) as nothing: no game here
head = "".join('#include "%s"\n' % (ROOT / "host" / h).as_posix()
for h in ("video_movie.h", "video_catchup.h", "video_input.h")) + STRESS_HEAD
types.append("static void input_room(Dec *d) { (void)d; }")
source = "\n".join([head, *types, *before, STRESS_MAIN.replace("__CUT_AFTER_DECODER__", "\n".join(after))])
with tempfile.TemporaryDirectory() as tmp:
runs = []
for count in ("2", "12", "14"):
env = dict(os.environ)
env["HOS_VIDEO_DECODE_AHEAD"] = "1" if count == "12" else count
runs.append(([count], env))
for out in build_and_run(args.cc, tmp, "video_ahead_threads", source, ["-std=gnu11", "-O1", "-Wall", "-Werror"], runs):
print(" " + out)
print("ok")
if __name__ == "__main__":
main()