fix(remote-play): the decoder reports a changed stream size, so fullscreen streams are not cropped to a corner (#3095)

* fix(remote-play): the decoder reports a changed stream size, so fullscreen streams are not cropped to a corner

* fix(remote-play): capture buffers are sized for large streams up front and a size change reopens only the app decoder

* fix(remote-play): reject out-of-range scaling deltas and an SPS that ends before its frame flag
This commit is contained in:
Kurt Himebauch authored and GitHub committed 2026-11-23 17:31:13 -05:00
1 parent b0a8c0898e
commit 15b1e196af
3 files changed
+338 -11

No files matched your search

+192 -5
View File
@@ -29,6 +29,8 @@
#define VDEC_BITSTREAM_SIZE (4u << 20)
#define VDEC_PADDING 64
#define VDEC_DUMB 64
#define VDEC_CAP_MIN_WIDTH 4096u
#define VDEC_CAP_MIN_HEIGHT 2304u
struct vd_dma_heap_alloc {
uint64_t len;
@@ -135,6 +137,8 @@ struct vdec {
uint32_t n_cap_done;
int out_on, cap_on;
int sock, hw, hw_failed;
int resizing;
uint32_t stream_w, stream_h;
int64_t pts;
void *ctx, *packet, *frame;
uint8_t *packet_data;
@@ -318,7 +322,8 @@ static int vd_open_hardware(struct vdec *v) {
if (sock < 0) return -1;
struct vdec_config c = {
.type = VDEC_CONFIG, .codec = v->fourcc == V4L2_PIX_FMT_HEVC ? VENC_HEVC : VENC_H264,
.width = v->width ? v->width : v->cap_width, .height = v->height ? v->height : v->cap_height,
.width = v->stream_w ? v->stream_w : v->width ? v->width : v->cap_width,
.height = v->stream_h ? v->stream_h : v->height ? v->height : v->cap_height,
.stride = v->bpl, .rows = v->cap_height, .bitstreams = v->out_count, .bitstream_size = VDEC_BITSTREAM_SIZE,
};
struct vdec_result r;
@@ -563,8 +568,12 @@ static int vd_set_format(struct vdec *v, struct v4l2_format *f, int apply) {
t.fourcc = p->pixelformat;
t.width = p->width;
t.height = p->height;
t.stream_w = p->width;
t.stream_h = p->height;
} else {
uint32_t w = p->width > t.width ? p->width : t.width, h = p->height > t.height ? p->height : t.height;
if (w < VDEC_CAP_MIN_WIDTH) w = VDEC_CAP_MIN_WIDTH;
if (h < VDEC_CAP_MIN_HEIGHT) h = VDEC_CAP_MIN_HEIGHT;
if (w < 16 || h < 16 || w > 8192 || h > 8192) return -EINVAL;
t.cap_width = (w + 15) & ~15u;
t.cap_height = (h + 15) & ~15u;
@@ -574,6 +583,7 @@ static int vd_set_format(struct vdec *v, struct v4l2_format *f, int apply) {
if (apply) {
if (t.fourcc != v->fourcc || (t.hw && (t.bpl != v->bpl || t.cap_height != v->cap_height))) vd_close_decoder(&t);
*v = t;
if (v->cap_width >= v->width && v->cap_height >= v->height) v->resizing = 0;
}
vd_fill_format(&t, f);
return 0;
@@ -615,13 +625,184 @@ static int vd_querybuf(struct vdec *v, struct v4l2_buffer *b) {
return 0;
}
struct vd_bits {
const uint8_t *data;
size_t size, pos;
};
static uint32_t vd_get_bits(struct vd_bits *b, unsigned count) {
uint32_t value = 0;
while (count--) {
size_t byte = b->pos >> 3;
value = value << 1 | (byte < b->size ? (b->data[byte] >> (7 - (b->pos & 7))) & 1u : 0u);
b->pos++;
}
return value;
}
static uint32_t vd_get_ue(struct vd_bits *b) {
unsigned zeros = 0;
while (zeros < 32 && vd_get_bits(b, 1) == 0 && (b->pos >> 3) < b->size) zeros++;
if (zeros >= 32) return 0;
return ((1u << zeros) - 1) + (zeros ? vd_get_bits(b, zeros) : 0);
}
static int32_t vd_get_se(struct vd_bits *b) {
uint32_t k = vd_get_ue(b);
return (k & 1) ? (int32_t)((k + 1) / 2) : -(int32_t)(k / 2);
}
static int vd_skip_scaling_list(struct vd_bits *b, unsigned size) {
int32_t last = 8, next = 8;
for (unsigned i = 0; i < size; i++) {
if (next != 0) {
int32_t delta = vd_get_se(b);
if (delta < -128 || delta > 127) return -1;
next = (last + delta + 256) % 256;
}
last = next == 0 ? last : next;
}
return 0;
}
/* The coded size an H.264 SPS announces, rounded up to whole macroblocks, as a V4L2 decoder reports it. */
static int vd_parse_sps_h264(const uint8_t *rbsp, size_t size, uint32_t *width, uint32_t *height) {
uint8_t buf[512];
size_t n = 0;
for (size_t i = 0; i < size && n < sizeof buf; i++) {
if (i >= 2 && rbsp[i] == 3 && rbsp[i - 1] == 0 && rbsp[i - 2] == 0) continue;
buf[n++] = rbsp[i];
}
struct vd_bits b = { buf, n, 0 };
uint32_t profile = vd_get_bits(&b, 8);
vd_get_bits(&b, 16);
vd_get_ue(&b);
uint32_t chroma = 1;
if (profile == 100 || profile == 110 || profile == 122 || profile == 244 || profile == 44 || profile == 83 ||
profile == 86 || profile == 118 || profile == 128 || profile == 138 || profile == 139 || profile == 134 || profile == 135) {
chroma = vd_get_ue(&b);
if (chroma == 3) vd_get_bits(&b, 1);
vd_get_ue(&b);
vd_get_ue(&b);
vd_get_bits(&b, 1);
if (vd_get_bits(&b, 1)) {
for (unsigned i = 0; i < (chroma != 3 ? 8u : 12u); i++)
if (vd_get_bits(&b, 1) && vd_skip_scaling_list(&b, i < 6 ? 16 : 64) != 0) return -1;
}
}
vd_get_ue(&b);
uint32_t poc = vd_get_ue(&b);
if (poc == 0) {
vd_get_ue(&b);
} else if (poc == 1) {
vd_get_bits(&b, 1);
vd_get_se(&b);
vd_get_se(&b);
uint32_t cycle = vd_get_ue(&b);
for (uint32_t i = 0; i < cycle && i < 256; i++) vd_get_se(&b);
}
vd_get_ue(&b);
vd_get_bits(&b, 1);
uint32_t mbs_wide = vd_get_ue(&b) + 1, map_units_high = vd_get_ue(&b) + 1;
if (b.pos > b.size * 8 || mbs_wide > 1024 || map_units_high > 1024) return -1;
uint32_t frame_mbs_only = vd_get_bits(&b, 1);
if (b.pos > b.size * 8) return -1;
*width = mbs_wide * 16;
*height = map_units_high * 16 * (2 - frame_mbs_only);
return 0;
}
/* Finds the first SPS in an Annex B access unit; returns its size in the stream through the out parameters. */
static int vd_stream_size_h264(const uint8_t *data, size_t size, uint32_t *width, uint32_t *height) {
for (size_t i = 0; i + 4 < size; i++) {
if (data[i] != 0 || data[i + 1] != 0 || data[i + 2] != 1 || (data[i + 3] & 0x1f) != 7) continue;
size_t start = i + 4, end = start;
while (end + 2 < size && !(data[end] == 0 && data[end + 1] == 0 && (data[end + 2] == 1 || data[end + 2] == 0))) end++;
if (end + 2 >= size) end = size;
return vd_parse_sps_h264(data + start, end - start, width, height);
}
return -1;
}
/* The same for an H.265 SPS: the luma size in samples, rounded up to 16 as the client asks for it. */
static int vd_parse_sps_h265(const uint8_t *rbsp, size_t size, uint32_t *width, uint32_t *height) {
uint8_t buf[512];
size_t n = 0;
for (size_t i = 0; i < size && n < sizeof buf; i++) {
if (i >= 2 && rbsp[i] == 3 && rbsp[i - 1] == 0 && rbsp[i - 2] == 0) continue;
buf[n++] = rbsp[i];
}
struct vd_bits b = { buf, n, 0 };
vd_get_bits(&b, 4);
uint32_t sub_layers = vd_get_bits(&b, 3);
vd_get_bits(&b, 1);
for (unsigned i = 0; i < 88; i += 8) vd_get_bits(&b, 8);
vd_get_bits(&b, 8);
uint32_t profile_present = 0, level_present = 0;
for (uint32_t i = 0; i < sub_layers && i < 8; i++) {
profile_present |= vd_get_bits(&b, 1) << i;
level_present |= vd_get_bits(&b, 1) << i;
}
if (sub_layers > 0) for (uint32_t i = sub_layers; i < 8; i++) vd_get_bits(&b, 2);
for (uint32_t i = 0; i < sub_layers && i < 8; i++) {
if (profile_present >> i & 1) for (unsigned k = 0; k < 88; k += 8) vd_get_bits(&b, 8);
if (level_present >> i & 1) vd_get_bits(&b, 8);
}
vd_get_ue(&b);
if (vd_get_ue(&b) == 3) vd_get_bits(&b, 1);
uint32_t w = vd_get_ue(&b), h = vd_get_ue(&b);
if (b.pos > b.size * 8 || w < 16 || h < 16 || w > 16384 || h > 16384) return -1;
*width = (w + 15) & ~15u;
*height = (h + 15) & ~15u;
return 0;
}
static int vd_stream_size_h265(const uint8_t *data, size_t size, uint32_t *width, uint32_t *height) {
for (size_t i = 0; i + 5 < size; i++) {
if (data[i] != 0 || data[i + 1] != 0 || data[i + 2] != 1 || ((data[i + 3] >> 1) & 0x3f) != 33) continue;
size_t start = i + 5, end = start;
while (end + 2 < size && !(data[end] == 0 && data[end + 1] == 0 && (data[end + 2] == 1 || data[end + 2] == 0))) end++;
if (end + 2 >= size) end = size;
return vd_parse_sps_h265(data + start, end - start, width, height);
}
return -1;
}
/*
* A stream can change its picture size without telling the client: the host switches games or the window
* becomes fullscreen. A V4L2 decoder reports the new size through the format of its bitstream queue, which
* the client polls; the capture buffers it already allocated stay at the old size until it reconfigures.
*/
static int vd_follow_stream_size(struct vdec *v, const uint8_t *data, size_t size) {
uint32_t width, height;
int found = v->fourcc == V4L2_PIX_FMT_HEVC ? vd_stream_size_h265(data, size, &width, &height)
: vd_stream_size_h264(data, size, &width, &height);
if (found != 0) return 0;
uint32_t known_w = v->stream_w ? v->stream_w : v->width, known_h = v->stream_h ? v->stream_h : v->height;
if (width == known_w && height == known_h) return 0;
vd_log("the stream is now %ux%u, was %ux%u", width, height, known_w, known_h);
if (width <= v->cap_width && height <= v->cap_height) {
/* The client's capture buffers already hold the new size, so only the app decoder is reopened for it. */
v->stream_w = width;
v->stream_h = height;
if (v->hw) vd_close_decoder(v);
return 1;
}
v->width = v->stream_w = width;
v->height = v->stream_h = height;
v->resizing = 1;
v->n_cap_done = 0;
return 1;
}
static int vd_qbuf(struct vdec *v, struct v4l2_buffer *b) {
if (b->m.planes == NULL || b->length < 1) return -EINVAL;
if (b->type == V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE) {
if (b->index >= v->out_count || v->n_out_done >= VDEC_BUFFERS) return -EINVAL;
uint32_t bytes = b->m.planes[0].bytesused;
if (bytes > VDEC_BITSTREAM_SIZE) bytes = VDEC_BITSTREAM_SIZE;
if (v->out_on && bytes) vd_decode(v, b->index, bytes, b->timestamp);
if (v->out_on && v->bitstream && bytes) vd_follow_stream_size(v, v->bitstream + (size_t)b->index * VDEC_BITSTREAM_SIZE, bytes);
if (v->out_on && bytes && !v->resizing) vd_decode(v, b->index, bytes, b->timestamp);
v->out_done[v->n_out_done++] = b->index;
} else if (b->type == V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE) {
if (b->index >= v->cap_count || v->cap_size == 0) return -EINVAL;
@@ -652,9 +833,15 @@ static int vd_dqbuf(struct vdec *v, struct v4l2_buffer *b) {
return 0;
}
if (b->type != V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE) return -EINVAL;
if (v->n_cap_done == 0) return -EAGAIN;
struct vd_done d = v->cap_done[0];
memmove(v->cap_done, v->cap_done + 1, --v->n_cap_done * sizeof d);
struct vd_done d;
for (;;) {
if (v->n_cap_done == 0) return -EAGAIN;
d = v->cap_done[0];
memmove(v->cap_done, v->cap_done + 1, --v->n_cap_done * sizeof d);
struct stat st;
struct vd_capture *c = &v->cap[d.index];
if (c->map && c->fd >= 0 && fstat(c->fd, &st) == 0 && st.st_ino == c->ino) break;
}
b->index = d.index;
b->memory = V4L2_MEMORY_DMABUF;
b->flags = V4L2_BUF_FLAG_DONE | V4L2_BUF_FLAG_TIMESTAMP_COPY;
+6 -6
View File
@@ -113,12 +113,12 @@ int main(void) {
f.fmt.pix_mp.width = 1280; f.fmt.pix_mp.height = 736; f.fmt.pix_mp.pixelformat = V4L2_PIX_FMT_NV12;
if (call(VIDIOC_S_FMT, &f) || f.fmt.pix_mp.num_planes != 1) return 14;
uint32_t bpl = f.fmt.pix_mp.plane_fmt[0].bytesperline, size = f.fmt.pix_mp.plane_fmt[0].sizeimage;
if (bpl != 1280 || size != 1280 * 736 * 3 / 2) return 15;
if (bpl != 4096 || size != 4096 * 2304 * 3 / 2) return 15;
r = (struct v4l2_requestbuffers){ .count = 3, .type = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE, .memory = V4L2_MEMORY_DMABUF };
if (call(VIDIOC_REQBUFS, &r) || r.count != 3) return 16;
int out[3];
for (int i = 0; i < 3; i++) {
struct create_dumb c = { .height = 736, .width = 1280, .bpp = 16 };
struct create_dumb c = { .height = 2304, .width = 4096, .bpp = 16 };
if (drm_ioctl(card, 0xc02064b2, &c) || !c.handle || c.size < size) return 17;
struct prime_handle h = { .handle = c.handle, .flags = O_CLOEXEC };
if (drm_ioctl(card, 0xc00c642d, &h)) return 18;
@@ -148,7 +148,7 @@ int main(void) {
struct v4l2_buffer cb = { .type = types[1], .memory = V4L2_MEMORY_DMABUF, .length = 1, .m.planes = &cp };
if (call(VIDIOC_DQBUF, &cb)) return 25;
unsigned char *m = mmap(NULL, size, PROT_READ, MAP_SHARED, out[cb.index], 0);
printf("%ld %u %c%c %u\n", (long)cb.timestamp.tv_usec, cb.index, m[0], m[(size_t)bpl * 736], cp.bytesused == size);
printf("%ld %u %c%c %u\n", (long)cb.timestamp.tv_usec, cb.index, m[0], m[(size_t)bpl * 2304], cp.bytesused == size);
munmap(m, size);
pf = (struct pollfd){ .fd = vfd, .events = 0x306 };
if (poll(&pf, 1, 0) != 1) return 26;
@@ -166,7 +166,7 @@ int main(void) {
size = f.fmt.pix_mp.plane_fmt[0].sizeimage;
r = (struct v4l2_requestbuffers){ .count = 1, .type = types[1], .memory = V4L2_MEMORY_DMABUF };
if (call(VIDIOC_REQBUFS, &r)) return 31;
struct create_dumb big = { .height = 1088, .width = 1920, .bpp = 16 };
struct create_dumb big = { .height = 2304, .width = 4096, .bpp = 16 };
if (drm_ioctl(card, 0xc02064b2, &big)) return 32;
struct prime_handle bh = { .handle = big.handle, .flags = O_CLOEXEC };
if (drm_ioctl(card, 0xc00c642d, &bh)) return 33;
@@ -183,7 +183,7 @@ int main(void) {
struct v4l2_buffer db = { .type = types[1], .memory = V4L2_MEMORY_DMABUF, .length = 1, .m.planes = &dp };
if (call(VIDIOC_DQBUF, &db)) return 37;
unsigned char *m = mmap(NULL, size, PROT_READ, MAP_SHARED, bh.fd, 0);
printf("%ld %u %c%c\n", (long)db.timestamp.tv_usec, db.index, m[0], m[(size_t)1920 * 1088]);
printf("%ld %u %c%c\n", (long)db.timestamp.tv_usec, db.index, m[0], m[(size_t)4096 * 2304]);
dd_vdec_closed(vfd);
return 0;
}
@@ -261,7 +261,7 @@ class VdecEmulatorTest(unittest.TestCase):
self.assertEqual(done.stdout.split('\n')[:6],
['1 0 bu 1', '2 1 cu 1', '3 2 du 1', '4 0 eu 1', '5 1 fu 1', '6 0 zu'])
self.assertEqual([c[1:6] for c in server.configs],
[(1, 1280, 720, 1280, 736), (1, 1280, 720, 1920, 1088)])
[(1, 1280, 720, 4096, 2304), (1, 1280, 720, 4096, 2304)])
self.assertEqual([p[:3] for p in server.packets],
[(1, 101, 0), (2, 102, 1), (3, 103, 2), (0, 104, 0), (1, 105, 1), (2, 50, 0)])
+140
View File
@@ -0,0 +1,140 @@
import subprocess
import tempfile
import unittest
from pathlib import Path
ROOT = Path(__file__).resolve().parents[2]
VDEC = ROOT / 'tools/linuxfs/preload/vdec.c'
class Bits:
def __init__(self):
self.bits = []
def u(self, value, count):
self.bits += [(value >> (count - 1 - i)) & 1 for i in range(count)]
def ue(self, value):
value += 1
length = value.bit_length()
self.u(0, length - 1)
self.u(value, length)
def bytes(self):
bits = self.bits + [1]
while len(bits) % 8:
bits.append(0)
raw = bytes(int(''.join(map(str, bits[i:i + 8])), 2) for i in range(0, len(bits), 8))
out = bytearray()
for i, byte in enumerate(raw):
if len(out) >= 2 and out[-1] == 0 and out[-2] == 0 and byte <= 3:
out.append(3)
out.append(byte)
return bytes(out)
def sps(width_mbs, height_units, profile=100, frame_mbs_only=1, poc_type=2):
b = Bits()
b.u(profile, 8)
b.u(0, 8)
b.u(51, 8)
b.ue(0)
if profile in (100, 110, 122, 244):
b.ue(1)
b.ue(0)
b.ue(0)
b.u(0, 1)
b.u(0, 1)
b.ue(0)
b.ue(poc_type)
if poc_type == 0:
b.ue(4)
b.ue(1)
b.u(0, 1)
b.ue(width_mbs - 1)
b.ue(height_units - 1)
b.u(frame_mbs_only, 1)
if not frame_mbs_only:
b.u(0, 1)
b.u(1, 1)
b.u(0, 1)
return b'\x00\x00\x00\x01\x67' + b.bytes() + b'\x00\x00\x00\x01\x65\x88\x84\x00'
def hevc_sps(width, height, sub_layers_minus1=0):
b = Bits()
b.u(0, 4)
b.u(sub_layers_minus1, 3)
b.u(1, 1)
b.u(0, 88)
b.u(93, 8)
for _ in range(sub_layers_minus1):
b.u(0, 2)
if sub_layers_minus1:
for _ in range(sub_layers_minus1, 8):
b.u(0, 2)
b.ue(0)
b.ue(1)
b.ue(width)
b.ue(height)
b.u(0, 1)
return b'\x00\x00\x00\x01\x42\x01' + b.bytes() + b'\x00\x00\x00\x01\x26\x01\xaf'
DRIVER = r'''
#include "vdec.c"
#include <stdio.h>
int main(int argc, char **argv) {
FILE *f = fopen(argv[1], "rb");
static uint8_t data[4096];
size_t n = fread(data, 1, sizeof data, f);
uint32_t w = 0, h = 0;
int rc = argc > 2 ? vd_stream_size_h265(data, n, &w, &h) : vd_stream_size_h264(data, n, &w, &h);
printf("%d %u %u\n", rc, w, h);
return 0;
}
'''
class StreamSizeTest(unittest.TestCase):
def run_driver(self, data, hevc=False):
with tempfile.TemporaryDirectory() as tmp:
tmp = Path(tmp)
(tmp / 'driver.c').write_text(DRIVER)
(tmp / 'stream.bin').write_bytes(data)
exe = tmp / 'driver'
subprocess.run(['gcc', '-std=gnu11', '-DDD_VDEC_ANY_ARCH', '-I', str(VDEC.parent), '-o', str(exe), str(tmp / 'driver.c'), str(VDEC.parent / 'venc.c'), '-ldl', '-lpthread'],
check=True, capture_output=True, text=True)
return subprocess.run([str(exe), str(tmp / 'stream.bin')] + (['h265'] if hevc else []), check=True, capture_output=True, text=True).stdout.split()
def test_reads_an_ultrawide_stream_size(self):
self.assertEqual(['0', '3440', '1440'], self.run_driver(sps(215, 90)))
def test_reads_a_small_stream_size(self):
self.assertEqual(['0', '800', '464'], self.run_driver(sps(50, 29)))
def test_interlaced_streams_double_the_height(self):
self.assertEqual(['0', '1920', '1088'], self.run_driver(sps(120, 34, frame_mbs_only=0)))
def test_baseline_profile_has_no_chroma_fields(self):
self.assertEqual(['0', '1280', '720'], self.run_driver(sps(80, 45, profile=66)))
def test_emulation_prevention_bytes_are_removed(self):
self.assertEqual(['0', '256', '256'], self.run_driver(sps(16, 16, profile=66)))
def test_reads_an_h265_stream_size(self):
self.assertEqual(['0', '3440', '1440'], self.run_driver(hevc_sps(3440, 1440), hevc=True))
def test_h265_sizes_round_up_to_sixteen(self):
self.assertEqual(['0', '1920', '1088'], self.run_driver(hevc_sps(1920, 1080, sub_layers_minus1=2), hevc=True))
def test_a_truncated_sps_is_rejected(self):
self.assertEqual('-1', self.run_driver(b'\x00\x00\x00\x01\x67\x64\x00\x33\xac\xb4\x02\x80\x2d')[0])
def test_a_stream_without_an_sps_is_left_alone(self):
self.assertEqual('-1', self.run_driver(b'\x00\x00\x00\x01\x65\x88\x84\x00\x00\x01')[0])
if __name__ == '__main__':
unittest.main()