// SPDX-License-Identifier: GPL-2.0-or-later // Copyright (C) 2026 Pooya Parsa // va-encode: kwva's VP9 encode driven through the driver's vtable, without // libva or a display (a test program for va/build.sh's guest and native // builds): dlopens the driver, encodes FRAMES frames of a moving test // pattern as ffmpeg's vp9_vaapi does (CQP or a bitrate, a key frame every // GOP frames, P frames referring to the last, vaSyncBuffer, the coded // buffer's segments) and writes them as IVF. The pattern reaches the input // surfaces by vaPutImage (-m put), through a derived image mapped for // writing (-m derive, ffmpeg's hwupload) or not at all after the first // frame of each surface (-m same: unchanged surfaces, which the host keeps); // -s FILE also writes the pattern as raw I420 (to compare a decode of the // IVF with). Prints the frames per second and the time spent writing // pixels and in vaEndPicture. // // -c DEVICE encodes the camera instead (a V4L2 device, kwcam): NV12 of // W x H at -r FPS, -S MMAP buffers (default 4), each exported as a dma-buf // (VIDIOC_EXPBUF) and imported as the input surface (vaCreateSurfaces2, // DRM PRIME 2), as GStreamer's v4l2src io-mode=dmabuf into vavp9enc does: // each frame dequeued, encoded, synced, queued again. With kwva and the // host keeping the camera's frames the pixels never cross (va.md, Camera // to encoder). -s RAW writes each frame as I420 (read through a read-only // mapping of the buffer, which keeps the fast path), -W maps the buffers // writable (the driver then sends their pixels). Prints each frame's // sequence number (-v) and the gaps. // // va-encode [-d DRIVER.so] [-w W] [-h H] [-n FRAMES] [-g GOP] [-b BPS | -q QINDEX] [-m put|derive|same] [-S SURFACES] [-s RAW] // [-c DEVICE [-r FPS] [-W] [-v]] OUT.ivf #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include static double now(void) { struct timespec t; clock_gettime(CLOCK_MONOTONIC, &t); return t.tv_sec + t.tv_nsec / 1e9; } #define CHECK(x) \ do { \ VAStatus st_ = (x); \ if (st_ != VA_STATUS_SUCCESS) { \ fprintf(stderr, "va-encode: %s: status %#x (line %d)\n", #x, st_, __LINE__); \ exit(1); \ } \ } while (0) /* the test pattern of frame n into NV12 rows (pitch, chroma at uv) */ static void pattern(uint8_t *y, uint8_t *uv, uint32_t py, uint32_t puv, int w, int h, int n) { for (int r = 0; r < h; r++) for (int x = 0; x < w; x++) y[(size_t)r * py + x] = (uint8_t)(((x >> 2) + (r >> 2) + 3 * n) & 0xff) ^ (((x / 64 + r / 64 + n / 8) & 1) ? 0x40 : 0); for (int r = 0; r < (h + 1) / 2; r++) for (int x = 0; x < (w + 1) / 2; x++) { uv[(size_t)r * puv + 2 * x] = (uint8_t)(128 + ((x + n) & 63) - 32); uv[(size_t)r * puv + 2 * x + 1] = (uint8_t)(128 + ((r - n) & 63) - 32); } } static void le32(uint8_t *p, uint32_t v) { for (int i = 0; i < 4; i++) p[i] = (uint8_t)(v >> (8 * i)); } static int xioctl(int fd, unsigned long req, void *arg) { int r; do r = ioctl(fd, req, arg); while (r < 0 && errno == EINTR); return r; } /* -c: the camera's buffers as dma-bufs, each an imported input surface */ struct cam { int fd, n, writable; int dmafd[16]; void *map[16]; size_t len[16]; uint32_t pitch; }; static void cam_die(const char *what) { fprintf(stderr, "va-encode: camera: %s: %s\n", what, strerror(errno)); exit(1); } static void cam_open(struct cam *c, const char *dev, int w, int h, int fps, int nbuf) { c->fd = open(dev, O_RDWR | O_CLOEXEC); if (c->fd < 0) cam_die(dev); struct v4l2_format f = {.type = V4L2_BUF_TYPE_VIDEO_CAPTURE}; f.fmt.pix.width = (uint32_t)w; f.fmt.pix.height = (uint32_t)h; f.fmt.pix.pixelformat = V4L2_PIX_FMT_NV12; if (xioctl(c->fd, VIDIOC_S_FMT, &f) < 0) cam_die("VIDIOC_S_FMT"); if (f.fmt.pix.pixelformat != V4L2_PIX_FMT_NV12 || f.fmt.pix.width != (uint32_t)w || f.fmt.pix.height != (uint32_t)h) { fprintf(stderr, "va-encode: camera: no NV12 %dx%d (got %ux%u)\n", w, h, f.fmt.pix.width, f.fmt.pix.height); exit(1); } c->pitch = f.fmt.pix.bytesperline; struct v4l2_streamparm sp = {.type = V4L2_BUF_TYPE_VIDEO_CAPTURE}; sp.parm.capture.timeperframe.numerator = 1; sp.parm.capture.timeperframe.denominator = (uint32_t)fps; xioctl(c->fd, VIDIOC_S_PARM, &sp); struct v4l2_requestbuffers rb = {.count = (uint32_t)nbuf, .type = V4L2_BUF_TYPE_VIDEO_CAPTURE, .memory = V4L2_MEMORY_MMAP}; if (xioctl(c->fd, VIDIOC_REQBUFS, &rb) < 0) cam_die("VIDIOC_REQBUFS"); c->n = (int)rb.count > 16 ? 16 : (int)rb.count; for (int i = 0; i < c->n; i++) { struct v4l2_buffer b = {.index = (uint32_t)i, .type = V4L2_BUF_TYPE_VIDEO_CAPTURE, .memory = V4L2_MEMORY_MMAP}; if (xioctl(c->fd, VIDIOC_QUERYBUF, &b) < 0) cam_die("VIDIOC_QUERYBUF"); struct v4l2_exportbuffer e = {.type = V4L2_BUF_TYPE_VIDEO_CAPTURE, .index = (uint32_t)i, .flags = O_RDWR | O_CLOEXEC}; if (xioctl(c->fd, VIDIOC_EXPBUF, &e) < 0) cam_die("VIDIOC_EXPBUF"); c->dmafd[i] = e.fd; c->len[i] = b.length; /* read-only (what -s reads), or writable (-W: the driver must then send the pixels) */ c->map[i] = mmap(NULL, b.length, c->writable ? PROT_READ | PROT_WRITE : PROT_READ, MAP_SHARED, c->fd, b.m.offset); if (c->map[i] == MAP_FAILED) cam_die("mmap"); } } static void cam_qbuf(struct cam *c, int i) { struct v4l2_buffer b = {.index = (uint32_t)i, .type = V4L2_BUF_TYPE_VIDEO_CAPTURE, .memory = V4L2_MEMORY_MMAP}; if (xioctl(c->fd, VIDIOC_QBUF, &b) < 0) cam_die("VIDIOC_QBUF"); } static int cam_dqbuf(struct cam *c, uint32_t *seq) { struct pollfd pfd = {.fd = c->fd, .events = POLLIN}; if (poll(&pfd, 1, 5000) <= 0) { fprintf(stderr, "va-encode: camera: no frame within 5 s\n"); exit(1); } struct v4l2_buffer b = {.type = V4L2_BUF_TYPE_VIDEO_CAPTURE, .memory = V4L2_MEMORY_MMAP}; if (xioctl(c->fd, VIDIOC_DQBUF, &b) < 0) cam_die("VIDIOC_DQBUF"); *seq = b.sequence; return (int)b.index; } int main(int argc, char **argv) { const char *drvpath = "/usr/lib/aarch64-linux-gnu/dri/kw_drv_video.so", *raw = NULL, *mode = "derive", *camdev = NULL; int w = 640, h = 360, frames = 60, gop = 30, nsurf = 4, qindex = 100, fps = 30, verbose = 0; unsigned bps = 0; struct cam cam = {.fd = -1}; int o; while ((o = getopt(argc, argv, "d:w:h:n:g:b:q:m:S:s:c:r:Wv")) != -1) { switch (o) { case 'd': drvpath = optarg; break; case 'w': w = atoi(optarg); break; case 'h': h = atoi(optarg); break; case 'n': frames = atoi(optarg); break; case 'g': gop = atoi(optarg); break; case 'b': bps = (unsigned)atoi(optarg); break; case 'q': qindex = atoi(optarg); break; case 'm': mode = optarg; break; case 'S': nsurf = atoi(optarg); break; case 's': raw = optarg; break; case 'c': camdev = optarg; break; case 'r': fps = atoi(optarg); break; case 'W': cam.writable = 1; break; case 'v': verbose = 1; break; default: goto usage; } } if (optind + 1 != argc || w <= 0 || h <= 0 || frames <= 0 || nsurf <= 0 || nsurf > 16 || (strcmp(mode, "put") && strcmp(mode, "derive") && strcmp(mode, "same"))) { usage: fprintf(stderr, "usage: va-encode [-d DRIVER.so] [-w W] [-h H] [-n FRAMES] [-g GOP] [-b BPS | -q QINDEX] [-m put|derive|same] [-S SURFACES] [-s RAW] [-c DEVICE [-r FPS] [-W] [-v]] OUT.ivf\n"); return 2; } void *so = dlopen(drvpath, RTLD_NOW | RTLD_LOCAL); if (!so) { fprintf(stderr, "va-encode: %s\n", dlerror()); return 1; } char name[64]; snprintf(name, sizeof name, "__vaDriverInit_%d_%d", VA_MAJOR_VERSION, VA_MINOR_VERSION); VAStatus (*init)(VADriverContextP) = (VAStatus(*)(VADriverContextP))dlsym(so, name); if (!init) { fprintf(stderr, "va-encode: no %s in %s\n", name, drvpath); return 1; } struct VADriverContext c = {0}; c.vtable = calloc(1, sizeof *c.vtable); c.vtable_vpp = calloc(1, sizeof *c.vtable_vpp); CHECK(init(&c)); struct VADriverVTable *vt = c.vtable; VADriverContextP ctx = &c; /* the config: CQP, or VBR at bps (as ffmpeg asks: the maximum twice the target, 50%) */ VAConfigAttrib rc = {.type = VAConfigAttribRateControl, .value = bps ? VA_RC_VBR : VA_RC_CQP}; VAConfigID cfg; CHECK(vt->vaCreateConfig(ctx, VAProfileVP9Profile0, VAEntrypointEncSlice, &rc, 1, &cfg)); int sw = (w + 63) & ~63, sh = (h + 63) & ~63; VASurfaceID in[16], recon[4]; if (camdev) { /* each camera buffer's dma-buf as an input surface (one object, NV12 in one layer) */ cam_open(&cam, camdev, w, h, fps, nsurf); nsurf = cam.n; for (int i = 0; i < cam.n; i++) { VADRMPRIMESurfaceDescriptor d = {.fourcc = VA_FOURCC_NV12, .width = (uint32_t)w, .height = (uint32_t)h, .num_objects = 1, .num_layers = 1}; d.objects[0].fd = cam.dmafd[i]; d.objects[0].size = (uint32_t)cam.len[i]; d.objects[0].drm_format_modifier = 0; /* LINEAR */ d.layers[0].drm_format = 0x3231564e; /* DRM_FORMAT_NV12 */ d.layers[0].num_planes = 2; d.layers[0].pitch[0] = d.layers[0].pitch[1] = cam.pitch; d.layers[0].offset[1] = cam.pitch * (uint32_t)h; VASurfaceAttrib a[2] = { {.type = VASurfaceAttribMemoryType, .flags = VA_SURFACE_ATTRIB_SETTABLE, .value = {.type = VAGenericValueTypeInteger, .value.i = VA_SURFACE_ATTRIB_MEM_TYPE_DRM_PRIME_2}}, {.type = VASurfaceAttribExternalBufferDescriptor, .flags = VA_SURFACE_ATTRIB_SETTABLE, .value = {.type = VAGenericValueTypePointer, .value.p = &d}}, }; CHECK(vt->vaCreateSurfaces2(ctx, VA_RT_FORMAT_YUV420, w, h, &in[i], 1, a, 2)); cam_qbuf(&cam, i); } enum v4l2_buf_type t = V4L2_BUF_TYPE_VIDEO_CAPTURE; if (xioctl(cam.fd, VIDIOC_STREAMON, &t) < 0) cam_die("VIDIOC_STREAMON"); mode = "camera"; } else CHECK(vt->vaCreateSurfaces2(ctx, VA_RT_FORMAT_YUV420, w, h, in, nsurf, NULL, 0)); CHECK(vt->vaCreateSurfaces2(ctx, VA_RT_FORMAT_YUV420, sw, sh, recon, 4, NULL, 0)); VAContextID vctx; CHECK(vt->vaCreateContext(ctx, cfg, sw, sh, VA_PROGRESSIVE, recon, 4, &vctx)); VABufferID coded[2]; for (int i = 0; i < 2; i++) CHECK(vt->vaCreateBuffer(ctx, vctx, VAEncCodedBufferType, 3 * sw * sh + (1 << 16), 1, NULL, &coded[i])); VAImageFormat nv12 = {.fourcc = VA_FOURCC_NV12, .byte_order = VA_LSB_FIRST, .bits_per_pixel = 12}; VAImage img; CHECK(vt->vaCreateImage(ctx, &nv12, w, h, &img)); FILE *out = fopen(argv[optind], "wb"), *rawf = raw ? fopen(raw, "wb") : NULL; if (!out || (raw && !rawf)) { perror("va-encode: open"); return 1; } uint8_t hdr[32] = "DKIF"; hdr[4] = 0, hdr[5] = 0, hdr[6] = 32, hdr[7] = 0; memcpy(hdr + 8, "VP90", 4); hdr[12] = (uint8_t)w, hdr[13] = (uint8_t)(w >> 8), hdr[14] = (uint8_t)h, hdr[15] = (uint8_t)(h >> 8); le32(hdr + 16, 30), le32(hdr + 20, 1), le32(hdr + 24, (uint32_t)frames); fwrite(hdr, 1, 32, out); uint8_t *tmp = malloc((size_t)w * h * 3 / 2 + w + h + 4); double t0 = now(), tpix = 0, tend = 0, tsync = 0; size_t bytes = 0; int keys = 0, gaps = 0; uint32_t lastseq = 0; for (int n = 0; n < frames; n++) { VASurfaceID s = in[n % nsurf]; int ci = -1; /* the input's pixels */ double tp = now(); if (camdev) { /* the camera's next frame (tpix: the wait for it) */ uint32_t seq; ci = cam_dqbuf(&cam, &seq); s = in[ci]; if (n && seq != lastseq + 1) gaps++; lastseq = seq; if (verbose) printf("frame %d buffer %d seq %u\n", n, ci, seq); if (rawf) { const uint8_t *p = cam.map[ci]; int cw = (w + 1) / 2, ch = (h + 1) / 2; for (int r = 0; r < h; r++) fwrite(p + (size_t)r * cam.pitch, 1, (size_t)w, rawf); for (int pl = 0; pl < 2; pl++) for (int r = 0; r < ch; r++) for (int x = 0; x < cw; x++) fputc(p[(size_t)cam.pitch * h + (size_t)r * cam.pitch + 2 * x + pl], rawf); } } else if (!strcmp(mode, "put")) { void *p; CHECK(vt->vaMapBuffer(ctx, img.buf, &p)); pattern((uint8_t *)p + img.offsets[0], (uint8_t *)p + img.offsets[1], img.pitches[0], img.pitches[1], w, h, n); CHECK(vt->vaUnmapBuffer(ctx, img.buf)); CHECK(vt->vaPutImage(ctx, s, img.image_id, 0, 0, w, h, 0, 0, w, h)); } else if (!strcmp(mode, "derive") || n < nsurf) { VAImage di; void *p; CHECK(vt->vaDeriveImage(ctx, s, &di)); if (vt->vaMapBuffer2) CHECK(vt->vaMapBuffer2(ctx, di.buf, &p, VA_MAPBUFFER_FLAG_WRITE)); else CHECK(vt->vaMapBuffer(ctx, di.buf, &p)); pattern((uint8_t *)p + di.offsets[0], (uint8_t *)p + di.offsets[1], di.pitches[0], di.pitches[1], w, h, n); CHECK(vt->vaUnmapBuffer(ctx, di.buf)); CHECK(vt->vaDestroyImage(ctx, di.image_id)); } tpix += now() - tp; if (rawf && !camdev) { /* what the surface holds: frame n, or (same) the frame that first went into it */ int m = !strcmp(mode, "same") && n >= nsurf ? n % nsurf : n; pattern(tmp, tmp + (size_t)w * h, w, w, w, h, m); /* NV12 to I420 */ int cw = (w + 1) / 2, ch = (h + 1) / 2; fwrite(tmp, 1, (size_t)w * h, rawf); for (int pl = 0; pl < 2; pl++) for (int r = 0; r < ch; r++) for (int x = 0; x < cw; x++) fputc(tmp[(size_t)w * h + (size_t)r * w + 2 * x + pl], rawf); } /* the picture as ffmpeg's vaapi_encode_vp9.c makes it: a key frame each GOP, else P referring to slot 0 */ int key = n % gop == 0; VAEncSequenceParameterBufferVP9 seq = {.max_frame_width = w, .max_frame_height = h, .bits_per_second = bps, .intra_period = gop}; VAEncPictureParameterBufferVP9 pp = {0}; pp.frame_width_src = pp.frame_width_dst = w; pp.frame_height_src = pp.frame_height_dst = h; pp.reconstructed_frame = recon[n % 4]; for (int i = 0; i < 8; i++) pp.reference_frames[i] = VA_INVALID_SURFACE; if (!key) pp.reference_frames[0] = recon[(n + 3) % 4]; pp.coded_buf = coded[n % 2]; pp.ref_flags.bits.force_kf = key; pp.ref_flags.bits.ref_frame_ctrl_l0 = key ? 0 : 1; pp.pic_flags.bits.frame_type = !key; pp.pic_flags.bits.show_frame = 1; pp.refresh_frame_flags = 0xff; pp.luma_ac_qindex = (uint8_t)qindex; pp.filter_level = 16; pp.sharpness_level = 4; /* VAEncMiscParameterBuffer: its type, then the parameters */ struct { uint32_t type; VAEncMiscParameterRateControl rc; } mrc = {VAEncMiscParameterTypeRateControl, {.bits_per_second = 2 * bps, .target_percentage = 50, .window_size = 1000}}; struct { uint32_t type; VAEncMiscParameterFrameRate fr; } mfr = {VAEncMiscParameterTypeFrameRate, {.framerate = 30}}; VABufferID bufs[4]; int nb = 0; if (key) { CHECK(vt->vaCreateBuffer(ctx, vctx, VAEncSequenceParameterBufferType, sizeof seq, 1, &seq, &bufs[nb++])); if (bps) CHECK(vt->vaCreateBuffer(ctx, vctx, VAEncMiscParameterBufferType, sizeof mrc, 1, &mrc, &bufs[nb++])); CHECK(vt->vaCreateBuffer(ctx, vctx, VAEncMiscParameterBufferType, sizeof mfr, 1, &mfr, &bufs[nb++])); } CHECK(vt->vaCreateBuffer(ctx, vctx, VAEncPictureParameterBufferType, sizeof pp, 1, &pp, &bufs[nb++])); double te = now(); CHECK(vt->vaBeginPicture(ctx, vctx, s)); CHECK(vt->vaRenderPicture(ctx, vctx, bufs, nb)); CHECK(vt->vaEndPicture(ctx, vctx)); tend += now() - te; for (int i = 0; i < nb; i++) vt->vaDestroyBuffer(ctx, bufs[i]); /* the coded buffer: synced, its segments as one IVF frame */ double ts = now(); CHECK(vt->vaSyncBuffer(ctx, pp.coded_buf, VA_TIMEOUT_INFINITE)); tsync += now() - ts; VACodedBufferSegment *seg; CHECK(vt->vaMapBuffer(ctx, pp.coded_buf, (void **)&seg)); size_t len = 0; for (VACodedBufferSegment *x = seg; x; x = x->next) len += x->size; uint8_t fh[12]; le32(fh, (uint32_t)len), le32(fh + 4, (uint32_t)n), le32(fh + 8, 0); fwrite(fh, 1, 12, out); for (VACodedBufferSegment *x = seg; x; x = x->next) fwrite(x->buf, 1, x->size, out); /* a key frame: frame_marker 2, profile 0, show_existing 0, frame_type 0 */ if (len && (((uint8_t *)seg->buf)[0] & 0xe4) == 0x80 && !(((uint8_t *)seg->buf)[0] & 0x04)) keys++; CHECK(vt->vaUnmapBuffer(ctx, pp.coded_buf)); bytes += len; if (ci >= 0) cam_qbuf(&cam, ci); } double t = now() - t0; printf("va-encode: %d frames %dx%d (%s, %d surfaces) in %.2f s: %.1f frames/s; %zu bytes (%.0f kbit/s at 30 fps), %d key frames; per frame: %s %.2f ms, vaEndPicture %.2f ms, sync %.2f ms", frames, w, h, mode, nsurf, t, frames / t, bytes, bytes * 8.0 * 30 / frames / 1000, keys, camdev ? "camera wait" : "pixels", tpix * 1000 / frames, tend * 1000 / frames, tsync * 1000 / frames); if (camdev) printf("; %d gaps in the sequence", gaps); printf("\n"); if (camdev) { enum v4l2_buf_type t2 = V4L2_BUF_TYPE_VIDEO_CAPTURE; xioctl(cam.fd, VIDIOC_STREAMOFF, &t2); } fclose(out); if (rawf) fclose(rawf); vt->vaDestroyImage(ctx, img.image_id); vt->vaDestroyContext(ctx, vctx); vt->vaDestroySurfaces(ctx, in, nsurf); vt->vaDestroySurfaces(ctx, recon, 4); vt->vaDestroyConfig(ctx, cfg); vt->vaTerminate(ctx); return 0; }