~emersion/vaapi-decoder

ref: cd01be8cdfd82d3e2704d0e7d3d414e52fa0e439 vaapi-decoder/main.c -rw-r--r-- 15.1 KiB
cd01be8cSimon Ser Get modifier list from linux-dmabuf 8 months ago
                                                                                
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
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
#include <poll.h>
#include <stdbool.h>
#include <stdio.h>
#include <unistd.h>

#include <drm_fourcc.h>
#include <libavcodec/avcodec.h>
#include <libavformat/avformat.h>
#include <libavutil/hwcontext.h>
#include <libavutil/hwcontext_drm.h>
#include <libavutil/hwcontext_vaapi.h>
#include <libavutil/pixdesc.h>
#include <wayland-client.h>
#include <xcb/xcb.h>
#include <va/va_drmcommon.h>

#include "gamescope-xwayland-client-protocol.h"
#include "linux-dmabuf-unstable-v1-client-protocol.h"

static AVFormatContext *input_ctx = NULL;
static int video_stream = -1;
static AVCodecContext *decoder_ctx = NULL;
static enum AVPixelFormat hw_pix_fmt = AV_PIX_FMT_NONE;

static struct wl_compositor *compositor = NULL;
static struct gamescope_xwayland *gamescope_xwayland = NULL;
static struct zwp_linux_dmabuf_v1 *zwp_linux_dmabuf_v1 = NULL;

static struct wl_surface *surface = NULL;

#define MAX_FRAMES_IN_FLIGHT 10
static int frames_in_flight = 0;

static uint64_t modifiers[64];
static size_t modifiers_len = 0;

static const struct {
	uint32_t format;
	int nb_layers;
	uint32_t layers[AV_DRM_MAX_PLANES];
} drm_format_map[] = {
	{ DRM_FORMAT_NV12, 2, { DRM_FORMAT_R8, DRM_FORMAT_GR88 } },
};

static uint32_t get_drm_frame_format(const AVDRMFrameDescriptor *drm_frame_desc) {
	if (drm_frame_desc->nb_layers == 1) {
		return drm_frame_desc->layers[0].format;
	}
	for (size_t i = 0; i < sizeof(drm_format_map) / sizeof(drm_format_map[0]); i++) {
		if (drm_format_map[i].nb_layers != drm_frame_desc->nb_layers) {
			continue;
		}
		bool match = true;
		for (int j = 0; j < drm_frame_desc->nb_layers; j++) {
			match &= drm_frame_desc->layers[j].format == drm_format_map[i].layers[j];
		}
		if (match) {
			return drm_format_map[i].format;
		}
	}
	return DRM_FORMAT_INVALID;
}

static int check_hw_device_type(enum AVHWDeviceType type) {
	enum AVHWDeviceType t = AV_HWDEVICE_TYPE_NONE;
	while (1) {
		t = av_hwdevice_iterate_types(t);
		if (t == AV_HWDEVICE_TYPE_NONE) {
			break;
		}
		if (t == type) {
			return 0;
		}
	}
	return -1;
}

VADRMFormatModifierList vaapi_modifier_list = {0};
VASurfaceAttrib vaapi_surface_attrib = {
	.type = VASurfaceAttribDRMFormatModifiers,
	.flags = VA_SURFACE_ATTRIB_SETTABLE,
	.value.type = VAGenericValueTypePointer,
	.value.value.p = &vaapi_modifier_list,
};

static enum AVPixelFormat get_hw_format(AVCodecContext *decoder_ctx,
		const enum AVPixelFormat *pix_fmts) {
	bool found = false;
	for (size_t i = 0; pix_fmts[i] != AV_PIX_FMT_NONE; i++) {
		if (pix_fmts[i] == hw_pix_fmt) {
			found = true;
			break;
		}
	}
	if (!found) {
		fprintf(stderr, "Failed to find HW pixel format\n");
		return AV_PIX_FMT_NONE;
	}

	int ret;
	ret = avcodec_get_hw_frames_parameters(decoder_ctx, decoder_ctx->hw_device_ctx, hw_pix_fmt, &decoder_ctx->hw_frames_ctx);
	if (ret != 0) {
		fprintf(stderr, "Failed to get HW frames context params\n");
		return AV_PIX_FMT_NONE;
	}
	AVHWFramesContext *hw_frames_ctx = (AVHWFramesContext *)(decoder_ctx->hw_frames_ctx->data);
	AVVAAPIFramesContext *vaapi_frames_ctx = hw_frames_ctx->hwctx;
	vaapi_frames_ctx->attributes = &vaapi_surface_attrib;
	vaapi_frames_ctx->nb_attributes = 1;

	ret = av_hwframe_ctx_init(decoder_ctx->hw_frames_ctx);
	if (ret < 0) {
		fprintf(stderr, "Failed to init HW frames context\n");
		return AV_PIX_FMT_NONE;
	}

	return hw_pix_fmt;
}

static int decode_frame(AVFormatContext *input_ctx, int video_stream,
		AVCodecContext *decoder_ctx, AVFrame **frame_ptr) {
	int ret;
	while (1) {
		AVPacket packet;
		ret = av_read_frame(input_ctx, &packet);
		if (ret < 0) {
			fprintf(stderr, "Failed to read frames into packet\n");
			return ret;
		}

		if (video_stream != packet.stream_index) {
			av_packet_unref(&packet);
			continue;
		}

		ret = avcodec_send_packet(decoder_ctx, &packet);
		if (ret < 0) {
			fprintf(stderr, "Failed to send packet to decoder\n");
			return ret;
		}
		av_packet_unref(&packet);

		AVFrame *frame = av_frame_alloc();
		if (!frame) {
			fprintf(stderr, "Failed to allocate frame\n");
			return AVERROR(ENOMEM);
		}

		while (1) {
			ret = avcodec_receive_frame(decoder_ctx, frame);
			if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF) {
				break;
			} else if (ret < 0) {
				fprintf(stderr, "Failed to receive frame from decoder\n");
				return ret;
			}

			if (frame->format != hw_pix_fmt) {
				continue;
			}

			*frame_ptr = frame;
			return 0;
		}

		av_frame_free(&frame);
	}

	return AVERROR_EOF;
}

static void print_drm_frame_desc(const AVDRMFrameDescriptor *drm_frame_desc) {
	fprintf(stderr, "DRM frame:\n");
	for (int i = 0; i < drm_frame_desc->nb_objects; i++) {
		const AVDRMObjectDescriptor *drm_object = &drm_frame_desc->objects[i];
		fprintf(stderr, "  objectdecoder_ctx, #%i: fd = %d, size = %zu, "
			"format_modifier = 0x%lX\n", i, drm_object->fd,
			drm_object->size, drm_object->format_modifier);
	}
	for (int i = 0; i < drm_frame_desc->nb_layers; i++) {
		const AVDRMLayerDescriptor *drm_layer = &drm_frame_desc->layers[i];
		fprintf(stderr, "  layer #%d: format = 0x%X\n",
			i, drm_layer->format);
		for (int j = 0; j < drm_layer->nb_planes; j++) {
			const AVDRMPlaneDescriptor *drm_plane = &drm_layer->planes[j];
			fprintf(stderr, "    plane #%d: object_index = %d, "
				"offset = %ld, pitch = %ld\n", j, drm_plane->object_index,
				drm_plane->offset, drm_plane->pitch);
		}
	}
}

static void handle_global(void *data, struct wl_registry *registry,
		uint32_t name, const char *interface, uint32_t version) {
	if (strcmp(interface, wl_compositor_interface.name) == 0) {
		compositor =
			wl_registry_bind(registry, name, &wl_compositor_interface, 1);
	} else if (strcmp(interface, gamescope_xwayland_interface.name) == 0) {
		gamescope_xwayland =
			wl_registry_bind(registry, name, &gamescope_xwayland_interface, 1);
	} else if (strcmp(interface, zwp_linux_dmabuf_v1_interface.name) == 0) {
		zwp_linux_dmabuf_v1 =
			wl_registry_bind(registry, name, &zwp_linux_dmabuf_v1_interface, 3);
	}
}

static void handle_global_remove(void *data, struct wl_registry *registry,
		uint32_t name) {
	// This space is intentionally left blank
}

static const struct wl_registry_listener registry_listener = {
	.global = handle_global,
	.global_remove = handle_global_remove,
};

static struct wl_buffer *import_drm_frame_desc(
		const AVDRMFrameDescriptor *drm_frame_desc, int width, int height) {
	// VA-API drivers may use separate layers with one plane each, or a single
	// layer with multiple planes. We need to handle both.
	uint32_t drm_format = get_drm_frame_format(drm_frame_desc);
	if (drm_format == DRM_FORMAT_INVALID) {
		fprintf(stderr, "Failed to get DRM frame format\n");
		return NULL;
	}
	fprintf(stderr, "DRM format: 0x%X\n", drm_format);

	struct zwp_linux_buffer_params_v1 *dmabuf_params =
		zwp_linux_dmabuf_v1_create_params(zwp_linux_dmabuf_v1);
	int k = 0;
	for (int i = 0; i < drm_frame_desc->nb_layers; i++) {
		const AVDRMLayerDescriptor *drm_layer = &drm_frame_desc->layers[i];

		for (int j = 0; j < drm_layer->nb_planes; j++) {
			const AVDRMPlaneDescriptor *drm_plane = &drm_layer->planes[j];
			const AVDRMObjectDescriptor *drm_object =
				&drm_frame_desc->objects[drm_plane->object_index];

			uint32_t modifier_hi = drm_object->format_modifier >> 32;
			uint32_t modifier_lo = drm_object->format_modifier & 0xFFFFFFFF;

			zwp_linux_buffer_params_v1_add(dmabuf_params, drm_object->fd, k,
				drm_plane->offset, drm_plane->pitch, modifier_hi, modifier_lo);
			k++;
		}
	}

	return zwp_linux_buffer_params_v1_create_immed(dmabuf_params,
		width, height, drm_format, 0);
}

static void push_frame(void);

static void handle_buffer_release(void *data, struct wl_buffer *buffer) {
	AVFrame *frame = data;
	av_frame_free(&frame);
	wl_buffer_destroy(buffer);

	bool resume = frames_in_flight == MAX_FRAMES_IN_FLIGHT;
	frames_in_flight--;
	if (resume) {
		push_frame();
	}
}

static const struct wl_buffer_listener buffer_listener = {
	.release = handle_buffer_release,
};

static void handle_frame_callback_done(void *data, struct wl_callback *callback,
		uint32_t time) {
	if (frames_in_flight < MAX_FRAMES_IN_FLIGHT) {
		push_frame();
	}
}

static const struct wl_callback_listener frame_callback_listener = {
	.done = handle_frame_callback_done,
};

static void handle_dmabuf_format(void *data, struct zwp_linux_dmabuf_v1 *linux_dmabuf,
		uint32_t format) {
	// Superseded by handle_dmabuf_modifier
}

static void handle_dmabuf_modifier(void *data, struct zwp_linux_dmabuf_v1 *linux_dmabuf,
		uint32_t format, uint32_t modifier_hi, uint32_t modifier_lo) {
	// TODO: accumulate modifiers for all formats, don't assume we'll get NV12
	if (format != DRM_FORMAT_NV12) {
		return;
	}

	uint64_t mod = ((uint64_t)modifier_hi << 32) | modifier_lo;

	// We want an explicit modifier, not INVALID which indicates an implicit
	// buffer tiling.
	if (mod == DRM_FORMAT_MOD_INVALID) {
		return;
	}

	// Ignore LINEAR, because AMD hardware can't directly scan-out rotated
	// LINEAR buffers.
	if (mod == DRM_FORMAT_MOD_LINEAR) {
		return;
	}

	modifiers[modifiers_len] = mod;
	modifiers_len++;

	fprintf(stderr, "Supported NV12 modifier: 0x%"PRIX64"\n", mod);
}

static const struct zwp_linux_dmabuf_v1_listener zwp_linux_dmabuf_v1_listener = {
	.format = handle_dmabuf_format,
	.modifier = handle_dmabuf_modifier,
};

static void push_frame(void) {
	AVFrame *frame = NULL;
	int ret = decode_frame(input_ctx, video_stream, decoder_ctx, &frame);
	if (ret == AVERROR_EOF) {
		exit(0);
	} else if (ret < 0) {
		exit(1);
	}

	fprintf(stderr, "Got %dx%d frame!\n", frame->width, frame->height);

	AVFrame *drm_frame = av_frame_alloc();
	drm_frame->format = AV_PIX_FMT_DRM_PRIME;
	drm_frame->hw_frames_ctx = av_buffer_ref(frame->hw_frames_ctx);

	// Convert the VA-API frame into a DMA-BUF frame
	ret = av_hwframe_map(drm_frame, frame, 0);
	if (ret < 0) {
		fprintf(stderr, "Failed to map frame: %s\n", av_err2str(ret));
		exit(1);
	}

	AVDRMFrameDescriptor *drm_frame_desc = (void *)drm_frame->data[0];
	print_drm_frame_desc(drm_frame_desc);

	struct wl_buffer *buffer = import_drm_frame_desc(drm_frame_desc,
		drm_frame->width, drm_frame->height);
	if (!buffer) {
		exit(1);
	}
	wl_buffer_add_listener(buffer, &buffer_listener, frame);

	struct wl_callback *callback = wl_surface_frame(surface);
	wl_callback_add_listener(callback, &frame_callback_listener, NULL);

	wl_surface_damage(surface, 0, 0, INT32_MAX, INT32_MAX);
	wl_surface_attach(surface, buffer, 0, 0);
	wl_surface_commit(surface);

	av_frame_free(&drm_frame);

	frames_in_flight++;
}

int main(int argc, char *argv[]) {
	if (argc < 2) {
		fprintf(stderr, "usage: %s <file>\n", argv[0]);
		return 1;
	}

	enum AVHWDeviceType type = AV_HWDEVICE_TYPE_VAAPI;
	int ret = check_hw_device_type(type);
	if (ret != 0) {
		fprintf(stderr, "VA-API not supported\n");
		return 1;
	}

	if (avformat_open_input(&input_ctx, argv[1], NULL, NULL) != 0) {
		fprintf(stderr, "Failed to open input file\n");
		return 1;
	}

	if (avformat_find_stream_info(input_ctx, NULL) < 0) {
		fprintf(stderr, "Failed to find input stream info\n");
		return 1;
	}

	AVCodec *decoder = NULL;
	video_stream = av_find_best_stream(input_ctx, AVMEDIA_TYPE_VIDEO,
		-1, -1, &decoder, 0);
	if (video_stream < 0) {
		fprintf(stderr, "Failed to find video stream in input file\n");
		return 1;
	}
	fprintf(stderr, "Selected decoder %s\n", decoder->name);

	int i = 0;
	while (1) {
		const AVCodecHWConfig *config = avcodec_get_hw_config(decoder, i);
		if (!config) {
			fprintf(stderr, "Decoder %s doesn't support device type %s\n",
				decoder->name, av_hwdevice_get_type_name(type));
			return 1;
		}

		if ((config->methods & AV_CODEC_HW_CONFIG_METHOD_HW_DEVICE_CTX) &&
				config->device_type == type) {
			hw_pix_fmt = config->pix_fmt;
			break;
		}

		i++;
	}
	fprintf(stderr, "Selected pixel format %s\n", av_get_pix_fmt_name(hw_pix_fmt));

	decoder_ctx = avcodec_alloc_context3(decoder);
	if (!decoder_ctx) {
		fprintf(stderr, "Failed to allocate decoder context\n");
		return 1;
	}

	AVStream *video = input_ctx->streams[video_stream];
	if (avcodec_parameters_to_context(decoder_ctx, video->codecpar) < 0) {
		fprintf(stderr, "Failed to fill decoder context from video parameters\n");
		return 1;
	}
	fprintf(stderr, "Stream geometry: %dx%d\n", decoder_ctx->width, decoder_ctx->height);
	fprintf(stderr, "Stream pixel format %s\n", av_get_pix_fmt_name(decoder_ctx->pix_fmt));

	decoder_ctx->get_format = get_hw_format;

	AVBufferRef *hw_device_ctx = NULL;
	ret = av_hwdevice_ctx_create(&hw_device_ctx, type, NULL, NULL, 0);
	if (ret < 0) {
		fprintf(stderr, "Failed to create HW device context\n");
		return 1;
	}
	decoder_ctx->hw_device_ctx = av_buffer_ref(hw_device_ctx);

	ret = avcodec_open2(decoder_ctx, decoder, NULL);
	if (ret < 0) {
		fprintf(stderr, "Failed to open codec for stream #%u\n", video_stream);
		return 1;
	}

	const char *display_name = getenv("GAMESCOPE_WAYLAND_DISPLAY");
	if (!display_name) {
		fprintf(stderr, "Gamescope is not running\n");
		return 1;
	}

	struct wl_display *display = wl_display_connect(display_name);
	if (!display) {
		fprintf(stderr, "Failed to connect to Wayland display\n");
		return 1;
	}

	struct wl_registry *registry = wl_display_get_registry(display);
	wl_registry_add_listener(registry, &registry_listener, NULL);
	wl_display_roundtrip(display);

	if (compositor == NULL || gamescope_xwayland == NULL || zwp_linux_dmabuf_v1 == NULL) {
		fprintf(stderr, "Missing wl_compositor, xdg_wm_base or zwp_linux_dmabuf_v1 support\n");
		return 1;
	}

	zwp_linux_dmabuf_v1_add_listener(zwp_linux_dmabuf_v1, &zwp_linux_dmabuf_v1_listener, NULL);

	// Second roundtrip to get DMA-BUF format modifiers
	wl_display_roundtrip(display);

	if (modifiers_len == 0) {
		fprintf(stderr, "zwp_linux_dmabuf_v1 doesn't support any modifier\n");
		return 1;
	}

	// Fill our VA-API modifier allow-list
	vaapi_modifier_list.num_modifiers = modifiers_len;
	vaapi_modifier_list.modifiers = modifiers;

	xcb_connection_t *conn = xcb_connect(NULL, NULL);
	if (!conn || xcb_connection_has_error(conn)) {
		fprintf(stderr, "Failed to connect to X11 display\n");
		return 1;
	}

	xcb_screen_t *screen = xcb_setup_roots_iterator(xcb_get_setup(conn)).data;

	xcb_window_t window = xcb_generate_id(conn);

	surface = wl_compositor_create_surface(compositor);
	gamescope_xwayland_override_window_content(gamescope_xwayland, surface, window);
	wl_surface_commit(surface);

	wl_display_flush(display);

	xcb_create_window(conn, XCB_COPY_FROM_PARENT, window, screen->root, 0, 0, decoder_ctx->width, decoder_ctx->height, 0, XCB_WINDOW_CLASS_INPUT_OUTPUT, screen->root_visual, 0, NULL);
	xcb_map_window(conn, window);
	xcb_flush(conn);

	push_frame();
	wl_display_flush(display);

	while(1) {
		struct pollfd fds[2] = {
			{ .fd = wl_display_get_fd(display), .events = POLLIN },
			{ .fd = xcb_get_file_descriptor(conn), .events = POLLIN },
		};
		if (poll(fds, 2, -1) < 0) {
			perror("poll failed");
			return 1;
		}

		if ((fds[0].revents & POLLHUP) || (fds[1].revents & POLLHUP)) {
			break;
		}

		if (fds[0].revents & POLLIN) {
			if (wl_display_dispatch(display) < 0) {
				fprintf(stderr, "Failed to dispatch Wayland display\n");
				return 1;
			}
		}
		if (fds[1].revents & POLLIN) {
			xcb_generic_event_t *event;
			while ((event = xcb_poll_for_event(conn))) {
				free(event);
			}
		}

		wl_display_flush(display);
		xcb_flush(conn);
	}

	wl_surface_destroy(surface);

	avcodec_free_context(&decoder_ctx);
	avformat_close_input(&input_ctx);
	av_buffer_unref(&hw_device_ctx);

	return 0;
}