/*
 * The player: libmpv decodes and keeps time, and draws each frame with
 * OpenGL on a surface of our own that lies under the window's (a
 * subsurface below it; the window is see-through there, so the controls
 * c8ui draws are over the video).
 *
 * An ordinary video mpv draws straight onto that surface. A 3D or
 * all-round one it draws whole into a texture, and our shader shows what
 * was asked of it: one eye's half, both through coloured glasses, or the
 * part of a sphere you are looking at.
 *
 * In XR glasses the compositor does that instead, since only it knows
 * what each eye sees (cont8nuum-stereo-v1): where it says so, the whole
 * frame goes on the surface, at the frame's own size, with a word about
 * how it is laid out. A 3D video then has an eye each, and an all-round
 * one is round you, turning with your head.
 *
 * Everything here runs on the main loop; mpv's threads only wake it.
 */
#include <math.h>
#include <stdlib.h>
#include <string.h>
#include <locale.h>
#include <EGL/egl.h>
#include <EGL/eglext.h>
#include <GLES2/gl2.h>
#include <wayland-egl.h>
#include <mpv/client.h>
#include <mpv/render.h>
#include <mpv/render_gl.h>
#include "viewporter-client-protocol.h"
#include "idle-inhibit-unstable-v1-client-protocol.h"
#include "cont8nuum-stereo-v1-client-protocol.h"
#include "video.h"

/* A hidden window gets no frame callbacks: draw anyway this often, so
 * mpv isn't left waiting on every frame */
#define HIDDEN_MS 250
/* How near the end counts as watched: nothing to carry on from */
#define END_S 10

/* The compositor is given no more than this across a frame */
#define FRAME_MAX 8192

/* Who shows the picture, and how */
enum mode {
	MODE_PLAIN, // mpv, straight onto the window's size
	MODE_SHADER, // mpv into a texture, our shader from that
	MODE_EYES, // the whole frame: the compositor gives each eye its half
	MODE_AROUND, // the whole frame: the compositor puts it round you
};

struct vd_state vd;

static struct {
	struct c8ui_app *app;
	mpv_handle *mpv;
	void (*changed)(unsigned changes);
	unsigned pending; // changes not yet told
	guint tell;
	char *uri; // what is open
	bool waiting; // to be opened once there is something to draw with

	/* The surface */
	struct c8ui_window *win;
	struct wl_compositor *compositor;
	struct wl_subcompositor *subcompositor;
	struct wp_viewporter *viewporter;
	struct zwp_idle_inhibit_manager_v1 *inhibit_manager;
	struct zwp_idle_inhibitor_v1 *inhibitor;
	struct wl_surface *surface;
	struct wl_subsurface *sub;
	struct wp_viewport *viewport;
	struct c8_stereo_manager_v1 *stereo_manager;
	struct c8_stereo_surface_v1 *stereo;
	uint32_t shows; // what the compositor does with 3D and spheres now
	uint32_t said_layout, said_first, said_projection; // as it was told
	enum mode mode;
	struct c8ui_rect placed; // the surface in the window, as last put
	struct wl_egl_window *egl_window;
	struct wl_callback *frame_cb;
	int width, height; // buffer pixels
	bool want; // a frame to draw once the last one was shown
	guint hidden_timer;

	/* GL */
	EGLDisplay display;
	EGLConfig config;
	EGLContext context;
	EGLSurface egl_surface;
	mpv_render_context *render;
	GLuint program, vbo, fbo, texture;
	GLint u_tex, u_shape, u_rect, u_eye_l, u_eye_r, u_ana, u_dean, u_pick, u_ml, u_mr,
		u_rot, u_tan, u_remap;
	int tex_w, tex_h, max_texture;

	struct vd_view view;
	bool keepaspect; // as mpv was last told
	void (*leaving)(void); // a file is about to be let go
	bool sub_bitmap; // the subtitles chosen are pictures (DVD, Blu-ray)
	bool subs_hidden; // mpv was told not to draw subtitles
	bool bits_tried; // we read those pictures ourselves, or tried to
	double sub_delay; // mpv's sub-delay: they show this much later
} p;

static void queue_draw(void);
static void load_now(void);

/* Telling the app: once per turn of the main loop, however many of
 * mpv's properties moved */

static gboolean tell_now(gpointer data) {
	p.tell = 0;
	unsigned changes = p.pending;
	p.pending = 0;
	if (p.changed && changes) {
		p.changed(changes);
	}
	return G_SOURCE_REMOVE;
}

static void tell(unsigned changes) {
	p.pending |= changes;
	if (p.tell == 0) {
		p.tell = g_idle_add(tell_now, NULL);
	}
}

/* Screens stay on while a video plays */
static void update_inhibit(void) {
	bool playing = vd.loaded && !vd.paused && !vd.ended && vd.width > 0;
	if (playing && p.inhibitor == NULL && p.inhibit_manager && p.surface) {
		p.inhibitor = zwp_idle_inhibit_manager_v1_create_inhibitor(
			p.inhibit_manager, c8ui_window_surface(p.win));
	} else if (!playing && p.inhibitor) {
		zwp_idle_inhibitor_v1_destroy(p.inhibitor);
		p.inhibitor = NULL;
	}
}

/* mpv's events */

static void set_string(char **slot, const char *value) {
	if (g_strcmp0(*slot, value) != 0) {
		g_free(*slot);
		*slot = g_strdup(value);
	}
}

static void clear_chapters(void) {
	for (guint i = 0; vd.chapters && i < vd.chapters->len; i++) {
		g_free(g_array_index(vd.chapters, struct vd_chapter, i).title);
	}
	if (vd.chapters) {
		g_array_set_size(vd.chapters, 0);
	}
}

static void read_chapters(mpv_node *list) {
	clear_chapters();
	for (int i = 0; list && list->format == MPV_FORMAT_NODE_ARRAY &&
			i < list->u.list->num; i++) {
		mpv_node *item = &list->u.list->values[i];
		if (item->format != MPV_FORMAT_NODE_MAP) {
			continue;
		}
		struct vd_chapter c = { 0 };
		const char *title = NULL;
		for (int k = 0; k < item->u.list->num; k++) {
			const char *key = item->u.list->keys[k];
			mpv_node *v = &item->u.list->values[k];
			if (strcmp(key, "time") == 0 && v->format == MPV_FORMAT_DOUBLE) {
				c.time = v->u.double_;
			} else if (strcmp(key, "title") == 0 &&
					v->format == MPV_FORMAT_STRING) {
				title = v->u.string;
			}
		}
		c.title = title && title[0] ? g_strdup(title) :
			g_strdup_printf("Chapter %u", vd.chapters->len + 1);
		g_array_append_val(vd.chapters, c);
	}
}

/* Subtitles that are pictures: no text from mpv, bitsubs.c reads them */
static bool is_bitmap_codec(const char *codec) {
	static const char *const bitmap[] = { "pgs", "dvd_sub", "dvb_sub",
		"xsub", "vobsub", NULL };
	for (int i = 0; bitmap[i]; i++) {
		if (strstr(codec, bitmap[i])) {
			return true;
		}
	}
	return false;
}

/* The picture subtitle showing now, if we draw them */
static void show_subpicture(void) {
	const struct vd_subpicture *pic = vd.own_subtitles ?
		bitsubs_at(vd.position - p.sub_delay) : NULL;
	if (pic != vd.subpicture) {
		vd.subpicture = pic;
		tell(VD_CH_SUBTITLES);
	}
}

/* Another track or file, or mpv draws them again: let the reader go
 * (at once: vd.subpicture points into its list) */
static void bits_stop(void) {
	bitsubs_close();
	p.bits_tried = false;
	if (vd.subpicture) {
		vd.subpicture = NULL;
		tell(VD_CH_SUBTITLES);
	}
}

static void bits_changed(bool failed) {
	if (failed) {
		/* Not to be read: mpv draws them, split or not */
		vd.subpicture = NULL;
		queue_draw();
		tell(VD_CH_SUBTITLES);
		return;
	}
	show_subpicture();
}

/* Read the chosen track ourselves: the file mpv plays (or the file of
 * subtitles added), and the stream by FFmpeg's count, which mpv keeps */
static void bits_start(void) {
	p.bits_tried = true;
	int external = 0;
	int64_t index = -1;
	mpv_get_property(p.mpv, "current-tracks/sub/external", MPV_FORMAT_FLAG,
		&external);
	bool indexed = mpv_get_property(p.mpv, "current-tracks/sub/ff-index",
		MPV_FORMAT_INT64, &index) >= 0;
	char *path = mpv_get_property_string(p.mpv, external ?
		"current-tracks/sub/external-filename" : "path");
	if (path && (indexed || external)) {
		bitsubs_open(path, indexed ? index : -1, vd.width, vd.height,
			bits_changed);
	}
	mpv_free(path);
}

static void property(mpv_event_property *prop) {
	const char *name = prop->name;
	bool flag = prop->format == MPV_FORMAT_FLAG && *(int *)prop->data;
	double num = prop->format == MPV_FORMAT_DOUBLE ? *(double *)prop->data : 0;
	int64_t whole = prop->format == MPV_FORMAT_INT64 ?
		*(int64_t *)prop->data : 0;
	const char *text = prop->format == MPV_FORMAT_STRING ?
		*(char **)prop->data : NULL;
	if (strcmp(name, "pause") == 0) {
		vd.paused = flag;
		tell(VD_CH_STATE);
	} else if (strcmp(name, "eof-reached") == 0) {
		vd.ended = flag;
		tell(VD_CH_STATE);
	} else if (strcmp(name, "paused-for-cache") == 0) {
		vd.buffering = flag;
		tell(VD_CH_STATE);
	} else if (strcmp(name, "seekable") == 0) {
		vd.seekable = flag;
		tell(VD_CH_TIME);
	} else if (strcmp(name, "time-pos") == 0) {
		/* Four times a second is enough for a seek bar */
		if (floor(num * 4) != floor(vd.position * 4)) {
			tell(VD_CH_TIME);
		}
		vd.position = num;
		bitsubs_tell(num - p.sub_delay);
		show_subpicture();
	} else if (strcmp(name, "sub-delay") == 0) {
		p.sub_delay = num;
		show_subpicture();
	} else if (strcmp(name, "duration") == 0) {
		vd.duration = num;
		tell(VD_CH_TIME);
	} else if (strcmp(name, "volume") == 0) {
		if (prop->format == MPV_FORMAT_DOUBLE) {
			vd.volume = num / 100;
			tell(VD_CH_VOLUME);
		}
	} else if (strcmp(name, "mute") == 0) {
		vd.muted = flag;
		tell(VD_CH_VOLUME);
	} else if (strcmp(name, "speed") == 0) {
		vd.speed = prop->format == MPV_FORMAT_DOUBLE ? num : 1;
		tell(VD_CH_STATE);
	} else if (strcmp(name, "media-title") == 0) {
		set_string(&vd.title, text);
		tell(VD_CH_TITLE);
	} else if (strcmp(name, "video-params/w") == 0) {
		vd.width = whole;
		tell(VD_CH_PICTURE);
		queue_draw();
	} else if (strcmp(name, "video-params/h") == 0) {
		vd.height = whole;
		tell(VD_CH_PICTURE);
		queue_draw();
	} else if (strcmp(name, "video-params/aspect") == 0) {
		vd.aspect = num;
		tell(VD_CH_PICTURE);
		queue_draw();
	} else if (strcmp(name, "video-params/stereo-in") == 0) {
		set_string(&vd.stereo, text);
		tell(VD_CH_PICTURE);
	} else if (strcmp(name, "track-list") == 0) {
		tell(VD_CH_TRACKS);
	} else if (strcmp(name, "chapter-list") == 0) {
		read_chapters(prop->format == MPV_FORMAT_NODE ? prop->data : NULL);
		tell(VD_CH_CHAPTERS);
	} else if (strcmp(name, "chapter") == 0) {
		vd.chapter = prop->format == MPV_FORMAT_INT64 ? whole : -1;
		tell(VD_CH_CHAPTERS);
	} else if (strcmp(name, "sub-text") == 0) {
		/* Nothing on screen reads the same as no subtitles at all */
		set_string(&vd.subtitle, text && text[0] ? text : NULL);
		tell(VD_CH_SUBTITLES);
	} else if (strcmp(name, "current-tracks/sub/codec") == 0) {
		p.sub_bitmap = text && is_bitmap_codec(text);
		bits_stop();
		queue_draw();
	} else if (strcmp(name, "current-tracks/sub/id") == 0) {
		/* Another track of the same kind */
		bits_stop();
		queue_draw();
	}
	update_inhibit();
}

static gboolean events(gpointer data) {
	while (p.mpv) {
		mpv_event *ev = mpv_wait_event(p.mpv, 0);
		if (ev->event_id == MPV_EVENT_NONE) {
			break;
		}
		switch (ev->event_id) {
		case MPV_EVENT_PROPERTY_CHANGE:
			property(ev->data);
			break;
		case MPV_EVENT_START_FILE:
			bits_stop();
			vd.active = true;
			vd.loaded = false;
			tell(VD_CH_STATE);
			break;
		case MPV_EVENT_FILE_LOADED:
			vd.loaded = true;
			g_clear_pointer(&vd.error, g_free);
			tell(VD_CH_STATE | VD_CH_LOADED | VD_CH_TRACKS);
			break;
		case MPV_EVENT_END_FILE: {
			mpv_event_end_file *end = ev->data;
			if (end->reason == MPV_END_FILE_REASON_ERROR) {
				set_string(&vd.error, mpv_error_string(end->error));
				vd.active = false;
			} else if (end->reason != MPV_END_FILE_REASON_REDIRECT &&
					end->reason != MPV_END_FILE_REASON_STOP) {
				vd.active = false;
			}
			vd.loaded = false;
			tell(VD_CH_STATE);
			break;
		}
		default:
			break;
		}
	}
	update_inhibit();
	return G_SOURCE_REMOVE;
}

/* From one of mpv's threads */
static void wakeup(void *data) {
	g_idle_add(events, NULL);
}

/* Drawing */

static const char vertex_src[] =
	"attribute vec2 pos;\n"
	"varying vec2 st;\n"
	"void main() {\n"
	"	st = vec2(pos.x * 0.5 + 0.5, 0.5 - pos.y * 0.5);\n"
	"	gl_Position = vec4(pos, 0.0, 1.0);\n"
	"}\n";

/* st: the window, 0,0 its top left. shape 0 is a flat picture in rect;
 * 1 a whole sphere, 2 the half in front, 3 the half in front as a
 * fisheye lens took it (equidistant, its circle filling the eye's
 * picture), seen along rot with the view's half size tan; with remap
 * the fisheye made into an equirectangular half, for the compositor. Each eye's picture is a piece of the frame (eye_l,
 * eye_r: offset and size); ana mixes the two for coloured glasses. A
 * frame made for red and cyan glasses (dean: 1, or 2 with the colours
 * the other way round) has the left eye's picture in its red and the
 * right's in its green and blue, so each comes out grey; pick 1 shows
 * the right eye's. */
static const char fragment_src[] =
	"#ifdef GL_FRAGMENT_PRECISION_HIGH\n"
	"precision highp float;\n"
	"#else\n"
	"precision mediump float;\n"
	"#endif\n"
	"varying vec2 st;\n"
	"uniform sampler2D tex;\n"
	"uniform float shape, ana, dean, pick, remap;\n"
	"uniform vec4 rect, eye_l, eye_r;\n"
	"uniform mat3 ml, mr, rot;\n"
	"uniform vec2 tanfov;\n"
	"const float PI = 3.14159265358979;\n"
	"void main() {\n"
	"	vec2 uv;\n"
	"	float ok = 1.0;\n"
	"	if (shape < 0.5) {\n"
	"		uv = (st - rect.xy) / rect.zw;\n"
	"		if (uv.x < 0.0 || uv.x > 1.0 || uv.y < 0.0 || uv.y > 1.0) {\n"
	"			ok = 0.0;\n"
	"		}\n"
	"	} else {\n"
	"		vec3 d;\n"
	"		if (remap > 0.5) {\n"
	"			float lo = (st.x - 0.5) * PI, la = (0.5 - st.y) * PI;\n"
	"			d = vec3(cos(la) * sin(lo), sin(la), -cos(la) * cos(lo));\n"
	"		} else {\n"
	"			d = normalize(rot * vec3((st.x * 2.0 - 1.0) * tanfov.x,\n"
	"				(1.0 - st.y * 2.0) * tanfov.y, -1.0));\n"
	"		}\n"
	"		float lon = atan(d.x, -d.z);\n"
	"		float lat = asin(clamp(d.y, -1.0, 1.0));\n"
	"		if (shape < 1.5) {\n"
	"			uv = vec2(lon / (2.0 * PI) + 0.5, 0.5 - lat / PI);\n"
	"		} else if (shape < 2.5) {\n"
	"			uv = vec2(lon / PI + 0.5, 0.5 - lat / PI);\n"
	"			if (abs(lon) > PI / 2.0) {\n"
	"				ok = 0.0;\n"
	"			}\n"
	"		} else {\n"
	"			float th = acos(clamp(-d.z, -1.0, 1.0));\n"
	"			float len = length(d.xy);\n"
	"			vec2 dir = len > 1e-6 ? d.xy / len : vec2(0.0);\n"
	"			uv = vec2(0.5) + th / PI * vec2(dir.x, -dir.y);\n"
	"			if (th > PI / 2.0) {\n"
	"				ok = 0.0;\n"
	"			}\n"
	"		}\n"
	"	}\n"
	"	uv = clamp(uv, 0.0, 1.0);\n"
	"	vec3 c = texture2D(tex, eye_l.xy + uv * eye_l.zw).rgb;\n"
	"	vec3 r = c;\n"
	"	if (dean > 0.5) {\n"
	"		vec3 red = vec3(c.r);\n"
	"		vec3 cyan = vec3(dot(c.gb, vec2(0.7, 0.3)));\n"
	"		c = dean < 1.5 ? red : cyan;\n"
	"		r = dean < 1.5 ? cyan : red;\n"
	"	} else if (ana > 0.5) {\n"
	"		r = texture2D(tex, eye_r.xy + uv * eye_r.zw).rgb;\n"
	"	}\n"
	"	if (ana > 0.5) {\n"
	"		c = clamp(ml * c + mr * r, 0.0, 1.0);\n"
	"	} else if (pick > 0.5) {\n"
	"		c = r;\n"
	"	}\n"
	"	gl_FragColor = vec4(c * ok, 1.0);\n"
	"}\n";

/* Dubois' least-squares mixes: rows are the red, green and blue shown,
 * from the left eye's colours and from the right's */
static const float anaglyph[3][2][9] = {
	[0] = { // red and cyan
		{ 0.456f, 0.500f, 0.176f, -0.040f, -0.038f, -0.016f,
			-0.015f, -0.021f, -0.005f },
		{ -0.043f, -0.088f, -0.002f, 0.378f, 0.734f, -0.018f,
			-0.072f, -0.113f, 1.226f },
	},
	[1] = { // green and magenta
		{ -0.062f, -0.158f, -0.039f, 0.284f, 0.668f, 0.143f,
			-0.015f, -0.027f, 0.021f },
		{ 0.529f, 0.705f, 0.024f, -0.016f, -0.015f, -0.065f,
			0.009f, 0.075f, 0.937f },
	},
	[2] = { // amber and blue
		{ 1.062f, -0.205f, 0.299f, -0.026f, 0.908f, 0.068f,
			-0.038f, -0.173f, 0.022f },
		{ -0.016f, -0.123f, -0.017f, 0.006f, 0.062f, -0.017f,
			0.094f, 0.185f, 0.911f },
	},
};

static GLuint compile(GLenum type, const char *src) {
	GLuint shader = glCreateShader(type);
	glShaderSource(shader, 1, &src, NULL);
	glCompileShader(shader);
	GLint ok = 0;
	glGetShaderiv(shader, GL_COMPILE_STATUS, &ok);
	if (!ok) {
		char log[512];
		glGetShaderInfoLog(shader, sizeof(log), NULL, log);
		g_warning("video: shader: %s", log);
	}
	return shader;
}

static void make_program(void) {
	GLuint vs = compile(GL_VERTEX_SHADER, vertex_src);
	GLuint fs = compile(GL_FRAGMENT_SHADER, fragment_src);
	p.program = glCreateProgram();
	glAttachShader(p.program, vs);
	glAttachShader(p.program, fs);
	glBindAttribLocation(p.program, 0, "pos");
	glLinkProgram(p.program);
	glDeleteShader(vs);
	glDeleteShader(fs);
	p.u_tex = glGetUniformLocation(p.program, "tex");
	p.u_shape = glGetUniformLocation(p.program, "shape");
	p.u_rect = glGetUniformLocation(p.program, "rect");
	p.u_eye_l = glGetUniformLocation(p.program, "eye_l");
	p.u_eye_r = glGetUniformLocation(p.program, "eye_r");
	p.u_ana = glGetUniformLocation(p.program, "ana");
	p.u_dean = glGetUniformLocation(p.program, "dean");
	p.u_pick = glGetUniformLocation(p.program, "pick");
	p.u_ml = glGetUniformLocation(p.program, "ml");
	p.u_mr = glGetUniformLocation(p.program, "mr");
	p.u_rot = glGetUniformLocation(p.program, "rot");
	p.u_tan = glGetUniformLocation(p.program, "tanfov");
	p.u_remap = glGetUniformLocation(p.program, "remap");
	static const float quad[] = { -1, -1, 1, -1, -1, 1, 1, 1 };
	glGenBuffers(1, &p.vbo);
	glBindBuffer(GL_ARRAY_BUFFER, p.vbo);
	glBufferData(GL_ARRAY_BUFFER, sizeof(quad), quad, GL_STATIC_DRAW);
	glBindBuffer(GL_ARRAY_BUFFER, 0);
	glGetIntegerv(GL_MAX_TEXTURE_SIZE, &p.max_texture);
}

/* The texture mpv draws a whole frame into, at the frame's own size */
static bool frame_texture(void) {
	int w = vd.width, h = vd.height;
	if (w <= 0 || h <= 0) {
		return false;
	}
	double fit = fmin(1, fmin((double)p.max_texture / w,
		(double)p.max_texture / h));
	w = fmax(1, floor(w * fit));
	h = fmax(1, floor(h * fit));
	if (p.texture && w == p.tex_w && h == p.tex_h) {
		return true;
	}
	if (p.texture == 0) {
		glGenTextures(1, &p.texture);
		glGenFramebuffers(1, &p.fbo);
	}
	glBindTexture(GL_TEXTURE_2D, p.texture);
	glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, w, h, 0, GL_RGBA,
		GL_UNSIGNED_BYTE, NULL);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
	glBindFramebuffer(GL_FRAMEBUFFER, p.fbo);
	glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0,
		GL_TEXTURE_2D, p.texture, 0);
	bool ok = glCheckFramebufferStatus(GL_FRAMEBUFFER) ==
		GL_FRAMEBUFFER_COMPLETE;
	glBindFramebuffer(GL_FRAMEBUFFER, 0);
	glBindTexture(GL_TEXTURE_2D, 0);
	p.tex_w = ok ? w : 0;
	p.tex_h = ok ? h : 0;
	return ok;
}

/* Where each eye's picture is in the frame (offset and size, in texture
 * coordinates, half a pixel in from the other eye's so they don't run
 * into each other), and the shape one eye's picture should have */
/* One eye's picture is shown, not the frame as it is */
static bool halved(void) {
	return (p.view.layout == VD_SBS || p.view.layout == VD_TB) &&
		(p.view.show != VD_BOTH || p.mode == MODE_EYES ||
		p.mode == MODE_AROUND);
}

/* A frame made for red and cyan glasses is shown as it was made: that
 * is what those glasses want, and what "as they are" asks for */
static bool as_made(void) {
	const struct vd_view *v = &p.view;
	return v->layout == VD_ANAGLYPH && (v->show == VD_BOTH ||
		(v->show == VD_RED_CYAN && !v->swap));
}

/* The compositor gives each eye its picture, and we must make the two
 * from a frame for red and cyan glasses first */
static bool eyes_apart(void) {
	return p.mode == MODE_EYES && p.view.layout == VD_ANAGLYPH;
}

/* The compositor knows equirectangular halves, not fisheyes: each eye's
 * circle is made into one first, in the same place in the buffer */
static bool fisheye_around(void) {
	return p.mode == MODE_AROUND && p.view.shape == VD_FISHEYE;
}

/* The shape one eye's picture should have: each half squeezed to half
 * its width or height (a frame of a usual shape), or whole (a frame
 * twice as wide or high) */
static double eye_aspect(void) {
	const struct vd_view *v = &p.view;
	double aspect = vd.aspect > 0 ? vd.aspect :
		vd.height > 0 ? (double)vd.width / vd.height : 16.0 / 9;
	if (!halved()) {
		return aspect;
	}
	if (v->layout == VD_SBS) {
		return aspect >= 2.5 ? aspect / 2 : aspect;
	}
	return aspect <= 1.2 ? aspect * 2 : aspect;
}

static double eye_rects(float left[4], float right[4]) {
	const struct vd_view *v = &p.view;
	double aspect = eye_aspect();
	float a[4] = { 0, 0, 1, 1 }, b[4] = { 0, 0, 1, 1 };
	float px = p.tex_w > 0 ? 0.5f / p.tex_w : 0;
	float py = p.tex_h > 0 ? 0.5f / p.tex_h : 0;
	if (!halved()) {
		/* The frame as it is */
	} else if (v->layout == VD_SBS) {
		a[2] = b[2] = 0.5f - px;
		b[0] = 0.5f + px;
	} else {
		a[3] = b[3] = 0.5f - py;
		b[1] = 0.5f + py;
	}
	memcpy(left, v->swap ? b : a, sizeof(a));
	memcpy(right, v->swap ? a : b, sizeof(a));
	return aspect;
}

/* Into the buffer's pixels from x, y (GL's: from the bottom), wide by
 * high. eye 0 or 1: that eye's picture alone, filling them (part of a
 * buffer the compositor takes apart; a fisheye made equirectangular);
 * -1: as "Show 3D" says, fitted into them */
static void draw_shaped(int x, int y, int wide, int high, int eye) {
	const struct vd_view *v = &p.view;
	float left[4], right[4];
	double aspect = eye_rects(left, right);
	bool remap = eye >= 0 && fisheye_around();
	glBindFramebuffer(GL_FRAMEBUFFER, 0);
	glViewport(x, y, wide, high);
	glDisable(GL_BLEND);
	glUseProgram(p.program);
	glActiveTexture(GL_TEXTURE0);
	glBindTexture(GL_TEXTURE_2D, p.texture);
	glUniform1i(p.u_tex, 0);
	glUniform1f(p.u_shape, eye >= 0 && !remap ? VD_FLAT : v->shape);
	glUniform1f(p.u_remap, remap);
	glUniform4fv(p.u_eye_l, 1, left);
	glUniform4fv(p.u_eye_r, 1, right);
	bool ana = eye < 0 && v->layout != VD_MONO && !as_made() &&
		v->show >= VD_RED_CYAN && v->show <= VD_AMBER_BLUE;
	glUniform1f(p.u_ana, ana);
	glUniform1f(p.u_dean, v->layout != VD_ANAGLYPH || as_made() || remap ?
		0 : v->swap ? 2 : 1);
	glUniform1f(p.u_pick, eye == 1);
	if (ana) {
		/* Ours are by rows, GL's by columns */
		const float *l = anaglyph[v->show - VD_RED_CYAN][0];
		const float *r = anaglyph[v->show - VD_RED_CYAN][1];
		float ml[9], mr[9];
		for (int i = 0; i < 9; i++) {
			ml[i] = l[(i % 3) * 3 + i / 3];
			mr[i] = r[(i % 3) * 3 + i / 3];
		}
		glUniformMatrix3fv(p.u_ml, 1, GL_FALSE, ml);
		glUniformMatrix3fv(p.u_mr, 1, GL_FALSE, mr);
	}
	double win = (double)wide / high;
	if (remap) {
		/* The shader works it out from where it is */
	} else if (eye >= 0) {
		glUniform4f(p.u_rect, 0, 0, 1, 1);
	} else if (v->shape == VD_FLAT) {
		/* Whole in the window, black beside or above and below */
		float w = 1, h = 1;
		if (aspect > win) {
			h = win / aspect;
		} else {
			w = aspect / win;
		}
		glUniform4f(p.u_rect, (1 - w) / 2, (1 - h) / 2, w, h);
	} else {
		/* Turn by pitch about x, then by yaw about y */
		float cy = cos(v->yaw), sy = sin(v->yaw);
		float cp = cos(v->pitch), sp = sin(v->pitch);
		float rot[9] = { // by columns
			cy, 0, sy,
			-sy * sp, cp, cy * sp,
			-sy * cp, -sp, cy * cp,
		};
		glUniformMatrix3fv(p.u_rot, 1, GL_FALSE, rot);
		float t = tan(v->fov / 2);
		/* A narrow window keeps its width's view instead */
		if (win < 1) {
			glUniform2f(p.u_tan, t, t / win);
		} else {
			glUniform2f(p.u_tan, t * win, t);
		}
	}
	glBindBuffer(GL_ARRAY_BUFFER, p.vbo);
	glEnableVertexAttribArray(0);
	glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 0, NULL);
	glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
	glDisableVertexAttribArray(0);
	glBindBuffer(GL_ARRAY_BUFFER, 0);
	glBindTexture(GL_TEXTURE_2D, 0);
	glUseProgram(0);
}

static void frame_done(void *data, struct wl_callback *cb, uint32_t time);
static const struct wl_callback_listener frame_listener = {
	.done = frame_done,
};

static enum mode mode_now(void) {
	const struct vd_view *v = &p.view;
	bool ours = p.stereo && p.viewport;
	if (vd.width <= 0 || vd.height <= 0) {
		return MODE_PLAIN;
	}
	if (v->shape != VD_FLAT) {
		if (ours && (p.shows & C8_STEREO_SURFACE_V1_SHOWS_SURROUND)) {
			return MODE_AROUND;
		}
		return as_made() ? MODE_PLAIN : MODE_SHADER;
	}
	if (v->layout == VD_MONO) {
		return MODE_PLAIN;
	}
	/* With an eye each to be had, that is how 3D is shown: "Show 3D" is
	 * about flat screens */
	if (ours && (p.shows & C8_STEREO_SURFACE_V1_SHOWS_STEREO)) {
		return MODE_EYES;
	}
	if (v->layout == VD_ANAGLYPH) {
		return as_made() ? MODE_PLAIN : MODE_SHADER;
	}
	return v->show == VD_BOTH ? MODE_PLAIN : MODE_SHADER;
}

/* Where the surface is in the window and how big its buffers are: the
 * window's size, or for the compositor the frame's own pixels, shown as
 * big as one eye's picture fits */
static void place(void) {
	struct c8ui_root *root = c8ui_window_root(p.win);
	double lw = floor(c8ui_root_width(root)), lh = floor(c8ui_root_height(root));
	if (lw <= 0 || lh <= 0) {
		return;
	}
	double scale = c8ui_window_scale(p.win);
	if (p.viewport == NULL) {
		/* Without a viewport only whole scales can be said */
		scale = ceil(scale);
		wl_surface_set_buffer_scale(p.surface, scale);
	}
	struct c8ui_rect r = { 0, 0, lw, lh };
	int w = round(lw * scale), h = round(lh * scale);
	if (p.mode == MODE_EYES || p.mode == MODE_AROUND) {
		/* The two eyes of a red and cyan frame go side by side, each
		 * the frame's size where that fits */
		double fw = vd.width * (eyes_apart() ? 2.0 : 1.0);
		double fit = fmin(1, fmin((double)FRAME_MAX / fw,
			(double)FRAME_MAX / vd.height));
		w = fmax(2, floor(fw * fit));
		h = fmax(1, floor(vd.height * fit));
	}
	if (p.mode == MODE_EYES) {
		double aspect = eye_aspect();
		if (aspect > lw / lh) {
			r.height = fmax(1, round(lw / aspect));
			r.y = floor((lh - r.height) / 2);
		} else {
			r.width = fmax(1, round(lh * aspect));
			r.x = floor((lw - r.width) / 2);
		}
	}
	if (p.viewport) {
		wp_viewport_set_destination(p.viewport, r.width, r.height);
	}
	struct wl_region *all = wl_compositor_create_region(p.compositor);
	wl_region_add(all, 0, 0, r.width, r.height);
	wl_surface_set_opaque_region(p.surface, all);
	wl_region_destroy(all);
	if (r.x != p.placed.x || r.y != p.placed.y) {
		/* A subsurface moves when its parent next commits */
		wl_subsurface_set_position(p.sub, r.x, r.y);
		wl_surface_commit(c8ui_window_surface(p.win));
	}
	p.placed = r;
	if (w != p.width || h != p.height) {
		wl_egl_window_resize(p.egl_window, w, h, 0, 0);
		p.width = w;
		p.height = h;
	}
}

/* What the buffer about to be shown holds, said just before it */
static void say(void) {
	if (p.stereo == NULL) {
		return;
	}
	const struct vd_view *v = &p.view;
	bool whole = p.mode == MODE_EYES || p.mode == MODE_AROUND;
	uint32_t layout = C8_STEREO_SURFACE_V1_LAYOUT_MONO;
	if (whole && (v->layout == VD_SBS || eyes_apart())) {
		layout = C8_STEREO_SURFACE_V1_LAYOUT_SIDE_BY_SIDE;
	} else if (whole && v->layout == VD_TB) {
		layout = C8_STEREO_SURFACE_V1_LAYOUT_TOP_BOTTOM;
	}
	/* Ours are drawn left first whichever colour is whose */
	/* A fisheye's two are put in the same places, left first */
	uint32_t first = eyes_apart() || fisheye_around() ? 0 : v->swap;
	uint32_t projection = p.mode != MODE_AROUND ?
		C8_STEREO_SURFACE_V1_PROJECTION_FLAT : v->shape == VD_SPHERE ?
		C8_STEREO_SURFACE_V1_PROJECTION_SPHERE :
		C8_STEREO_SURFACE_V1_PROJECTION_HALF_SPHERE;
	if (layout != p.said_layout || first != p.said_first) {
		c8_stereo_surface_v1_set_layout(p.stereo, layout, first);
		p.said_layout = layout;
		p.said_first = first;
	}
	if (projection != p.said_projection) {
		c8_stereo_surface_v1_set_projection(p.stereo, projection);
		p.said_projection = projection;
	}
}

static void draw(void) {
	if (p.egl_surface == EGL_NO_SURFACE || p.render == NULL) {
		return;
	}
	p.want = false;
	if (p.hidden_timer) {
		g_source_remove(p.hidden_timer);
		p.hidden_timer = 0;
	}
	p.mode = mode_now();
	place();
	/* mpv fits the picture into the window itself, but must fill a
	 * frame that is taken apart after, by us or the compositor */
	bool keep = p.mode == MODE_PLAIN;
	if (keep != p.keepaspect) {
		p.keepaspect = keep;
		mpv_set_property_string(p.mpv, "keepaspect", keep ? "yes" : "no");
	}
	/* Taken apart, mpv's subtitles would be split between the eyes or
	 * lie behind you: the stage draws them over it instead, the text
	 * mpv hands over, or pictures (DVD, Blu-ray) we decode ourselves.
	 * Those that can't be read mpv keeps. */
	bool bits = p.mode != MODE_PLAIN && p.sub_bitmap;
	if (bits && !bitsubs_running() && !p.bits_tried) {
		bits_start();
	} else if (!bits && bitsubs_running()) {
		bits_stop();
	}
	bool own = p.mode != MODE_PLAIN && (!p.sub_bitmap || bitsubs_running());
	if (own != p.subs_hidden) {
		p.subs_hidden = own;
		mpv_set_property_string(p.mpv, "sub-visibility", own ? "no" : "yes");
	}
	if (own != vd.own_subtitles) {
		vd.own_subtitles = own;
		show_subpicture();
		tell(VD_CH_SUBTITLES);
	}
	int block = 0;
	if ((p.mode == MODE_SHADER || eyes_apart() || fisheye_around()) &&
			frame_texture()) {
		mpv_opengl_fbo fbo = { .fbo = p.fbo, .w = p.tex_w, .h = p.tex_h };
		int flip = 0;
		mpv_render_param params[] = {
			{ MPV_RENDER_PARAM_OPENGL_FBO, &fbo },
			{ MPV_RENDER_PARAM_FLIP_Y, &flip },
			{ MPV_RENDER_PARAM_BLOCK_FOR_TARGET_TIME, &block },
			{ 0 },
		};
		mpv_render_context_render(p.render, params);
		int hw = p.width / 2, hh = p.height / 2;
		if (eyes_apart() || (fisheye_around() && p.view.layout == VD_SBS)) {
			draw_shaped(0, 0, hw, p.height, 0);
			draw_shaped(hw, 0, p.width - hw, p.height, 1);
		} else if (fisheye_around() && p.view.layout == VD_TB) {
			/* The first eye on top: GL counts from the bottom */
			draw_shaped(0, p.height - hh, p.width, hh, 0);
			draw_shaped(0, 0, p.width, p.height - hh, 1);
		} else if (fisheye_around()) {
			draw_shaped(0, 0, p.width, p.height, 0);
		} else {
			draw_shaped(0, 0, p.width, p.height, -1);
		}
	} else {
		mpv_opengl_fbo fbo = { .fbo = 0, .w = p.width, .h = p.height };
		int flip = 1;
		mpv_render_param params[] = {
			{ MPV_RENDER_PARAM_OPENGL_FBO, &fbo },
			{ MPV_RENDER_PARAM_FLIP_Y, &flip },
			{ MPV_RENDER_PARAM_BLOCK_FOR_TARGET_TIME, &block },
			{ 0 },
		};
		mpv_render_context_render(p.render, params);
	}
	if (p.frame_cb == NULL) {
		p.frame_cb = wl_surface_frame(p.surface);
		wl_callback_add_listener(p.frame_cb, &frame_listener, NULL);
	}
	say();
	eglSwapBuffers(p.display, p.egl_surface);
	mpv_render_context_report_swap(p.render);
}

static gboolean hidden_due(gpointer data) {
	p.hidden_timer = 0;
	if (p.want) {
		draw();
	}
	return G_SOURCE_REMOVE;
}

/* A frame at a time: the next is drawn when the compositor has shown
 * the last */
static void queue_draw(void) {
	if (p.egl_surface == EGL_NO_SURFACE) {
		return;
	}
	if (p.frame_cb == NULL) {
		draw();
		return;
	}
	p.want = true;
	if (p.hidden_timer == 0) {
		p.hidden_timer = g_timeout_add(HIDDEN_MS, hidden_due, NULL);
	}
}

static void frame_done(void *data, struct wl_callback *cb, uint32_t time) {
	wl_callback_destroy(cb);
	p.frame_cb = NULL;
	if (p.want) {
		draw();
	}
}

static gboolean render_update(gpointer data) {
	if (p.render &&
			(mpv_render_context_update(p.render) & MPV_RENDER_UPDATE_FRAME)) {
		queue_draw();
	}
	return G_SOURCE_REMOVE;
}

/* From one of mpv's threads: a new frame is due */
static void render_wakeup(void *data) {
	g_idle_add(render_update, NULL);
}

static void *get_proc(void *ctx, const char *name) {
	return (void *)eglGetProcAddress(name);
}

/* The surface under the window */

static bool egl_init(void) {
	if (p.display != EGL_NO_DISPLAY) {
		return p.context != EGL_NO_CONTEXT;
	}
	p.display = eglGetDisplay(
		(EGLNativeDisplayType)c8ui_app_display(p.app));
	if (p.display == EGL_NO_DISPLAY || !eglInitialize(p.display, NULL, NULL)) {
		g_warning("video: no EGL");
		return false;
	}
	eglBindAPI(EGL_OPENGL_ES_API);
	static const EGLint attrs[] = {
		EGL_SURFACE_TYPE, EGL_WINDOW_BIT,
		EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT,
		EGL_RED_SIZE, 8, EGL_GREEN_SIZE, 8, EGL_BLUE_SIZE, 8,
		EGL_ALPHA_SIZE, 0,
		EGL_NONE,
	};
	EGLint n = 0;
	if (!eglChooseConfig(p.display, attrs, &p.config, 1, &n) || n < 1) {
		g_warning("video: no EGL config");
		return false;
	}
	/* ES 3 if there is one (mpv does more with it), else 2 */
	for (int version = 3; version >= 2 && p.context == EGL_NO_CONTEXT;
			version--) {
		EGLint ctx_attrs[] = { EGL_CONTEXT_CLIENT_VERSION, version, EGL_NONE };
		p.context = eglCreateContext(p.display, p.config, EGL_NO_CONTEXT,
			ctx_attrs);
	}
	if (p.context == EGL_NO_CONTEXT) {
		g_warning("video: no OpenGL ES");
		return false;
	}
	return true;
}

/* The GL side, once the window has a size */
static void size_surface(void) {
	struct c8ui_root *root = c8ui_window_root(p.win);
	int lw = c8ui_root_width(root), lh = c8ui_root_height(root);
	if (lw <= 0 || lh <= 0) {
		return;
	}
	if (p.egl_window == NULL) {
		p.width = lw;
		p.height = lh;
		p.egl_window = wl_egl_window_create(p.surface, lw, lh);
		p.egl_surface = eglCreateWindowSurface(p.display, p.config,
			(EGLNativeWindowType)p.egl_window, NULL);
		if (p.egl_surface == EGL_NO_SURFACE) {
			g_warning("video: no EGL surface");
			return;
		}
		eglMakeCurrent(p.display, p.egl_surface, p.egl_surface, p.context);
		/* Never wait in eglSwapBuffers: we pace by frame callbacks, and a
		 * hidden window would hold the main loop there */
		eglSwapInterval(p.display, 0);
		make_program();
		mpv_opengl_init_params gl = { .get_proc_address = get_proc };
		mpv_render_param params[] = {
			{ MPV_RENDER_PARAM_API_TYPE, MPV_RENDER_API_TYPE_OPENGL },
			{ MPV_RENDER_PARAM_OPENGL_INIT_PARAMS, &gl },
			{ MPV_RENDER_PARAM_WL_DISPLAY, c8ui_app_display(p.app) },
			{ 0 },
		};
		if (mpv_render_context_create(&p.render, p.mpv, params) < 0) {
			g_warning("video: mpv can't draw with this OpenGL");
			p.render = NULL;
			return;
		}
		mpv_render_context_set_update_callback(p.render, render_wakeup, NULL);
		if (p.waiting && p.uri) {
			load_now();
		}
	}
	queue_draw();
}

void player_resize(void) {
	if (p.win && p.surface) {
		size_surface();
	}
}

static void scale_changed(struct c8ui_window *win, void *data) {
	player_resize();
}

/* Glasses came or went, or changed to or from their 3D mode */
static void stereo_shows(void *data, struct c8_stereo_surface_v1 *stereo,
		uint32_t shows) {
	p.shows = shows;
	queue_draw();
}

static const struct c8_stereo_surface_v1_listener stereo_listener = {
	.shows = stereo_shows,
};

void player_attach(struct c8ui_window *win) {
	if (p.win || p.mpv == NULL) {
		return;
	}
	p.win = win;
	if (p.compositor == NULL) {
		p.compositor = c8ui_app_bind(p.app, &wl_compositor_interface, 4);
		p.subcompositor = c8ui_app_bind(p.app, &wl_subcompositor_interface, 1);
		p.viewporter = c8ui_app_bind(p.app, &wp_viewporter_interface, 1);
		p.inhibit_manager = c8ui_app_bind(p.app,
			&zwp_idle_inhibit_manager_v1_interface, 1);
		p.stereo_manager = c8ui_app_bind(p.app,
			&c8_stereo_manager_v1_interface, 1);
	}
	if (p.compositor == NULL || p.subcompositor == NULL || !egl_init()) {
		return;
	}
	struct wl_surface *parent = c8ui_window_surface(win);
	p.surface = wl_compositor_create_surface(p.compositor);
	p.sub = wl_subcompositor_get_subsurface(p.subcompositor, p.surface,
		parent);
	wl_subsurface_place_below(p.sub, parent);
	wl_subsurface_set_position(p.sub, 0, 0);
	wl_subsurface_set_desync(p.sub);
	/* Everything pressed goes to the window over it */
	struct wl_region *none = wl_compositor_create_region(p.compositor);
	wl_surface_set_input_region(p.surface, none);
	wl_region_destroy(none);
	if (p.viewporter) {
		p.viewport = wp_viewporter_get_viewport(p.viewporter, p.surface);
	}
	if (p.stereo_manager) {
		p.stereo = c8_stereo_manager_v1_get_stereo_surface(p.stereo_manager,
			p.surface);
		c8_stereo_surface_v1_add_listener(p.stereo, &stereo_listener, NULL);
	}
	p.placed = (struct c8ui_rect){ 0 };
	p.said_layout = p.said_first = p.said_projection = 0;
	c8ui_window_on_scale(win, scale_changed, NULL);
	size_surface();
}

void player_detach(void) {
	if (p.win == NULL) {
		return;
	}
	player_stop();
	if (p.hidden_timer) {
		g_source_remove(p.hidden_timer);
		p.hidden_timer = 0;
	}
	if (p.render) {
		mpv_render_context_set_update_callback(p.render, NULL, NULL);
		mpv_render_context_free(p.render);
		p.render = NULL;
	}
	if (p.egl_surface != EGL_NO_SURFACE) {
		if (p.texture) {
			glDeleteTextures(1, &p.texture);
			glDeleteFramebuffers(1, &p.fbo);
			p.texture = p.fbo = 0;
			p.tex_w = p.tex_h = 0;
		}
		glDeleteProgram(p.program);
		glDeleteBuffers(1, &p.vbo);
		eglMakeCurrent(p.display, EGL_NO_SURFACE, EGL_NO_SURFACE,
			EGL_NO_CONTEXT);
		eglDestroySurface(p.display, p.egl_surface);
		p.egl_surface = EGL_NO_SURFACE;
	}
	if (p.egl_window) {
		wl_egl_window_destroy(p.egl_window);
		p.egl_window = NULL;
	}
	if (p.frame_cb) {
		wl_callback_destroy(p.frame_cb);
		p.frame_cb = NULL;
	}
	if (p.inhibitor) {
		zwp_idle_inhibitor_v1_destroy(p.inhibitor);
		p.inhibitor = NULL;
	}
	if (p.viewport) {
		wp_viewport_destroy(p.viewport);
		p.viewport = NULL;
	}
	if (p.stereo) {
		c8_stereo_surface_v1_destroy(p.stereo);
		p.stereo = NULL;
	}
	p.shows = 0;
	if (p.sub) {
		wl_subsurface_destroy(p.sub);
		p.sub = NULL;
	}
	if (p.surface) {
		wl_surface_destroy(p.surface);
		p.surface = NULL;
	}
	p.keepaspect = false;
	p.want = false;
	p.win = NULL;
	if (p.subs_hidden && p.mpv) {
		mpv_set_property_string(p.mpv, "sub-visibility", "yes");
	}
	p.subs_hidden = vd.own_subtitles = false;
	bits_stop();
}

/* Playing */

static void command(const char *const *args) {
	if (p.mpv) {
		mpv_command_async(p.mpv, 0, (const char **)args);
	}
}

/* Where a video was left is kept by mpv, in a folder of ours */
static void keep_place(void) {
	if (p.mpv == NULL || !vd.loaded || p.uri == NULL) {
		return;
	}
	if (p.leaving) {
		p.leaving();
	}
	bool watched = vd.ended || vd.duration <= 0 ||
		vd.position > vd.duration - END_S || vd.position < END_S;
	const char *args[] = { prefs.resume && !watched ?
		"write-watch-later-config" : "delete-watch-later-config", NULL };
	mpv_command(p.mpv, args);
}

static void load_now(void) {
	p.waiting = false;
	mpv_set_property_string(p.mpv, "resume-playback",
		prefs.resume ? "yes" : "no");
	mpv_set_property_string(p.mpv, "pause", "no");
	/* mpv opens paths and addresses, not file:// */
	char *path = g_filename_from_uri(p.uri, NULL, NULL);
	const char *args[] = { "loadfile", path ? path : p.uri, NULL };
	command(args);
	g_free(path);
}

void player_load(const char *uri) {
	if (p.mpv == NULL) {
		return;
	}
	keep_place();
	set_string(&p.uri, uri);
	g_clear_pointer(&vd.error, g_free);
	vd.active = true;
	vd.loaded = vd.ended = false;
	vd.position = vd.duration = 0;
	vd.width = vd.height = 0;
	tell(VD_CH_STATE | VD_CH_TIME | VD_CH_PICTURE);
	/* mpv gives a video up if it has nothing to draw with yet: a window
	 * opened with a file has no size until the compositor says */
	p.waiting = p.render == NULL;
	if (!p.waiting) {
		load_now();
	}
}

void player_stop(void) {
	if (p.mpv == NULL) {
		return;
	}
	keep_place();
	const char *args[] = { "stop", NULL };
	mpv_command(p.mpv, args);
	g_clear_pointer(&p.uri, g_free);
	p.waiting = false;
	bits_stop();
	vd.active = vd.loaded = false;
	update_inhibit();
}

void player_set_paused(bool paused) {
	if (p.mpv == NULL) {
		return;
	}
	if (!paused && vd.ended) {
		/* Play at the end starts it again */
		player_seek(0);
	}
	mpv_set_property_string(p.mpv, "pause", paused ? "yes" : "no");
}

void player_seek(double seconds) {
	char at[32];
	g_ascii_formatd(at, sizeof(at), "%.3f", fmax(0, seconds));
	const char *args[] = { "seek", at, "absolute", NULL };
	command(args);
}

void player_seek_by(double seconds) {
	char by[32];
	g_ascii_formatd(by, sizeof(by), "%.3f", seconds);
	/* Short steps land on the frame; long ones on the nearest the file
	 * can start from, which is at once */
	const char *args[] = { "seek", by,
		fabs(seconds) < 10 ? "relative+exact" : "relative", NULL };
	command(args);
}

void player_set_volume(double volume) {
	if (p.mpv) {
		double v = CLAMP(volume, 0, 1) * 100;
		mpv_set_property_async(p.mpv, 0, "volume", MPV_FORMAT_DOUBLE, &v);
	}
}

void player_set_muted(bool muted) {
	if (p.mpv) {
		mpv_set_property_string(p.mpv, "mute", muted ? "yes" : "no");
	}
}

void player_set_speed(double speed) {
	if (p.mpv) {
		mpv_set_property_async(p.mpv, 0, "speed", MPV_FORMAT_DOUBLE, &speed);
	}
}

void player_step(bool back) {
	const char *args[] = { back ? "frame-back-step" : "frame-step", NULL };
	command(args);
}

/* The frame now as a small PNG for the tile: one eye's picture of a 3D
 * one, the part in front of an all-round one. bgr0 is laid out as
 * cairo's RGB24 (on little-endian machines, which we build for). */
bool player_snapshot(const char *path, int width) {
	if (p.mpv == NULL || !vd.loaded || vd.width <= 0) {
		return false;
	}
	const char *args[] = { "screenshot-raw", "video", "bgr0", NULL };
	mpv_node shot;
	if (mpv_command_ret(p.mpv, args, &shot) < 0) {
		return false;
	}
	int64_t w = 0, h = 0, stride = 0;
	mpv_byte_array *data = NULL;
	for (int k = 0; shot.format == MPV_FORMAT_NODE_MAP &&
			k < shot.u.list->num; k++) {
		const char *key = shot.u.list->keys[k];
		mpv_node *v = &shot.u.list->values[k];
		if (strcmp(key, "w") == 0 && v->format == MPV_FORMAT_INT64) {
			w = v->u.int64;
		} else if (strcmp(key, "h") == 0 && v->format == MPV_FORMAT_INT64) {
			h = v->u.int64;
		} else if (strcmp(key, "stride") == 0 &&
				v->format == MPV_FORMAT_INT64) {
			stride = v->u.int64;
		} else if (strcmp(key, "data") == 0 &&
				v->format == MPV_FORMAT_BYTE_ARRAY) {
			data = v->u.ba;
		}
	}
	bool ok = false;
	if (w > 0 && h > 0 && stride >= w * 4 && data &&
			data->size >= (size_t)(stride * (h - 1) + w * 4)) {
		/* The piece to keep */
		const struct vd_view *v = &p.view;
		double x = 0, y = 0, cw = w, ch = h;
		if (v->layout == VD_SBS) {
			cw = w / 2.0;
			x = v->swap ? cw : 0;
		} else if (v->layout == VD_TB) {
			ch = h / 2.0;
			y = v->swap ? ch : 0;
		}
		if (v->shape != VD_FLAT) {
			/* Straight ahead, 16:9 */
			double fw = v->shape == VD_SPHERE ? cw / 4 : cw / 2;
			double fh = fmin(ch, fw * 9 / 16);
			x += (cw - fw) / 2;
			y += (ch - fh) / 2;
			cw = fw;
			ch = fh;
		}
		double aspect = vd.aspect > 0 ? vd.aspect : (double)w / h;
		double look = cw / ch * (aspect / ((double)w / h));
		int tw = width, th = fmax(1, round(width / look));
		cairo_surface_t *src = cairo_image_surface_create_for_data(
			(unsigned char *)data->data, CAIRO_FORMAT_RGB24, w, h, stride);
		cairo_surface_t *dst = cairo_image_surface_create(CAIRO_FORMAT_RGB24,
			tw, th);
		cairo_t *cr = cairo_create(dst);
		cairo_scale(cr, tw / cw, th / ch);
		cairo_set_source_surface(cr, src, -x, -y);
		cairo_pattern_set_filter(cairo_get_source(cr), CAIRO_FILTER_GOOD);
		cairo_paint(cr);
		cairo_destroy(cr);
		ok = cairo_surface_write_to_png(dst, path) == CAIRO_STATUS_SUCCESS;
		cairo_surface_destroy(dst);
		cairo_surface_destroy(src);
	}
	mpv_free_node_contents(&shot);
	return ok;
}

void player_set_chapter(int index) {
	if (p.mpv && index >= 0 && index < (int)vd.chapters->len) {
		int64_t i = index;
		mpv_set_property_async(p.mpv, 0, "chapter", MPV_FORMAT_INT64, &i);
	}
}

GArray *player_tracks(char type) {
	GArray *out = g_array_new(FALSE, TRUE, sizeof(struct vd_track));
	mpv_node list;
	if (p.mpv == NULL || mpv_get_property(p.mpv, "track-list",
			MPV_FORMAT_NODE, &list) < 0) {
		return out;
	}
	for (int i = 0; list.format == MPV_FORMAT_NODE_ARRAY &&
			i < list.u.list->num; i++) {
		mpv_node *item = &list.u.list->values[i];
		if (item->format != MPV_FORMAT_NODE_MAP) {
			continue;
		}
		const char *kind = NULL, *title = NULL, *lang = NULL;
		struct vd_track t = { 0 };
		for (int k = 0; k < item->u.list->num; k++) {
			const char *key = item->u.list->keys[k];
			mpv_node *v = &item->u.list->values[k];
			if (strcmp(key, "type") == 0 && v->format == MPV_FORMAT_STRING) {
				kind = v->u.string;
			} else if (strcmp(key, "title") == 0 &&
					v->format == MPV_FORMAT_STRING) {
				title = v->u.string;
			} else if (strcmp(key, "lang") == 0 &&
					v->format == MPV_FORMAT_STRING) {
				lang = v->u.string;
			} else if (strcmp(key, "id") == 0 &&
					v->format == MPV_FORMAT_INT64) {
				t.id = v->u.int64;
			} else if (strcmp(key, "selected") == 0 &&
					v->format == MPV_FORMAT_FLAG) {
				t.selected = v->u.flag;
			}
		}
		if (kind == NULL || kind[0] != type) {
			continue;
		}
		t.type = type;
		if (title && lang) {
			t.label = g_strdup_printf("%s (%s)", title, lang);
		} else if (title || lang) {
			t.label = g_strdup(title ? title : lang);
		} else {
			t.label = g_strdup_printf("Track %d", t.id);
		}
		g_array_append_val(out, t);
	}
	mpv_free_node_contents(&list);
	return out;
}

void player_tracks_free(GArray *tracks) {
	for (guint i = 0; tracks && i < tracks->len; i++) {
		g_free(g_array_index(tracks, struct vd_track, i).label);
	}
	if (tracks) {
		g_array_unref(tracks);
	}
}

void player_set_track(char type, int id) {
	if (p.mpv == NULL) {
		return;
	}
	const char *name = type == 'a' ? "aid" : type == 's' ? "sid" : "vid";
	char value[16];
	g_snprintf(value, sizeof(value), "%d", id);
	mpv_set_property_string(p.mpv, name, id > 0 ? value : "no");
}

void player_add_subtitles(const char *uri) {
	char *path = g_filename_from_uri(uri, NULL, NULL);
	const char *args[] = { "sub-add", path ? path : uri, "select", NULL };
	command(args);
	g_free(path);
}

struct c8ui_rect player_picture(void) {
	struct c8ui_rect r = { 0 };
	if (p.win == NULL) {
		return r;
	}
	struct c8ui_root *root = c8ui_window_root(p.win);
	r.width = floor(c8ui_root_width(root));
	r.height = floor(c8ui_root_height(root));
	if (p.view.shape != VD_FLAT || r.width <= 0 || r.height <= 0) {
		/* All round: what is looked at fills the window */
		return r;
	}
	double aspect = eye_aspect();
	if (aspect > r.width / r.height) {
		double h = round(r.width / aspect);
		r.y = floor((r.height - h) / 2);
		r.height = h;
	} else {
		double w = round(r.height * aspect);
		r.x = floor((r.width - w) / 2);
		r.width = w;
	}
	return r;
}

const struct vd_view *player_view(void) {
	return &p.view;
}

void player_set_view(const struct vd_view *view) {
	p.view = *view;
	p.view.pitch = CLAMP(p.view.pitch, -G_PI / 2, G_PI / 2);
	p.view.fov = CLAMP(p.view.fov, VD_FOV_MIN, VD_FOV_MAX);
	queue_draw();
}

void player_on_change(void (*fn)(unsigned changes)) {
	p.changed = fn;
}

void player_on_leave(void (*fn)(void)) {
	p.leaving = fn;
}

bool player_init(struct c8ui_app *app, char **error) {
	p.app = app;
	p.display = EGL_NO_DISPLAY;
	p.context = EGL_NO_CONTEXT;
	p.egl_surface = EGL_NO_SURFACE;
	p.view.fov = VD_FOV_DEFAULT;
	vd.speed = 1;
	vd.chapters = g_array_new(FALSE, TRUE, sizeof(struct vd_chapter));
	vd.chapter = -1;
	vd.volume = prefs.volume;
	/* mpv reads numbers its way: it refuses to start otherwise */
	setlocale(LC_NUMERIC, "C");
	p.mpv = mpv_create();
	if (p.mpv == NULL) {
		*error = g_strdup("mpv didn't start.");
		return false;
	}
	char *later = g_build_filename(g_get_user_state_dir(), "cont8nuum",
		"video", "watch-later", NULL);
	g_mkdir_with_parents(later, 0700);
	char volume[32];
	g_ascii_formatd(volume, sizeof(volume), "%.1f", prefs.volume * 100);
	const char *options[][2] = {
		{ "vo", "libmpv" },
		{ "hwdec", prefs.hwdec ? "auto-safe" : "no" },
		{ "idle", "yes" },
		/* Stay on the last frame at the end; what comes next is ours */
		{ "keep-open", "always" },
		{ "osc", "no" },
		{ "osd-level", "0" },
		{ "input-default-bindings", "no" },
		{ "input-vo-keyboard", "no" },
		{ "terminal", "no" },
		/* We draw when the frame is due, without waiting in the call */
		{ "video-timing-offset", "0" },
		{ "watch-later-dir", later },
		{ "watch-later-options", "start" },
		{ "volume-max", "100" },
		{ "volume", volume },
		{ "audio-client-name", "Video" },
		{ "screenshot-directory", "~/Pictures/Screenshots" },
	};
	for (size_t i = 0; i < G_N_ELEMENTS(options); i++) {
		if (mpv_set_option_string(p.mpv, options[i][0], options[i][1]) < 0) {
			g_debug("video: mpv has no %s", options[i][0]);
		}
	}
	g_free(later);
	int err = mpv_initialize(p.mpv);
	if (err < 0) {
		*error = g_strdup_printf("mpv didn't start: %s.",
			mpv_error_string(err));
		mpv_destroy(p.mpv);
		p.mpv = NULL;
		return false;
	}
	static const struct {
		const char *name;
		mpv_format format;
	} watched[] = {
		{ "pause", MPV_FORMAT_FLAG },
		{ "eof-reached", MPV_FORMAT_FLAG },
		{ "paused-for-cache", MPV_FORMAT_FLAG },
		{ "seekable", MPV_FORMAT_FLAG },
		{ "time-pos", MPV_FORMAT_DOUBLE },
		{ "duration", MPV_FORMAT_DOUBLE },
		{ "volume", MPV_FORMAT_DOUBLE },
		{ "mute", MPV_FORMAT_FLAG },
		{ "speed", MPV_FORMAT_DOUBLE },
		{ "media-title", MPV_FORMAT_STRING },
		{ "video-params/w", MPV_FORMAT_INT64 },
		{ "video-params/h", MPV_FORMAT_INT64 },
		{ "video-params/aspect", MPV_FORMAT_DOUBLE },
		{ "video-params/stereo-in", MPV_FORMAT_STRING },
		{ "track-list", MPV_FORMAT_NONE },
		{ "chapter-list", MPV_FORMAT_NODE },
		{ "chapter", MPV_FORMAT_INT64 },
		{ "sub-text", MPV_FORMAT_STRING },
		{ "current-tracks/sub/codec", MPV_FORMAT_STRING },
		{ "current-tracks/sub/id", MPV_FORMAT_INT64 },
		{ "sub-delay", MPV_FORMAT_DOUBLE },
	};
	for (size_t i = 0; i < G_N_ELEMENTS(watched); i++) {
		mpv_observe_property(p.mpv, 0, watched[i].name, watched[i].format);
	}
	mpv_set_wakeup_callback(p.mpv, wakeup, NULL);
	return true;
}

void player_shutdown(void) {
	player_detach();
	if (p.tell) {
		g_source_remove(p.tell);
		p.tell = 0;
	}
	if (p.mpv) {
		mpv_set_wakeup_callback(p.mpv, NULL, NULL);
		mpv_terminate_destroy(p.mpv);
		p.mpv = NULL;
	}
	g_clear_pointer(&p.uri, g_free);
	clear_chapters();
}
