summaryrefslogtreecommitdiffstats
path: root/input
diff options
context:
space:
mode:
authorDaniel Baumann <daniel.baumann@progress-linux.org>2024-04-15 20:36:56 +0000
committerDaniel Baumann <daniel.baumann@progress-linux.org>2024-04-15 20:36:56 +0000
commit51de1d8436100f725f3576aefa24a2bd2057bc28 (patch)
treec6d1d5264b6d40a8d7ca34129f36b7d61e188af3 /input
parentInitial commit. (diff)
downloadmpv-51de1d8436100f725f3576aefa24a2bd2057bc28.tar.xz
mpv-51de1d8436100f725f3576aefa24a2bd2057bc28.zip
Adding upstream version 0.37.0.upstream/0.37.0
Signed-off-by: Daniel Baumann <daniel.baumann@progress-linux.org>
Diffstat (limited to 'input')
-rw-r--r--input/cmd.c671
-rw-r--r--input/cmd.h156
-rw-r--r--input/event.c93
-rw-r--r--input/event.h43
-rw-r--r--input/input.c1695
-rw-r--r--input/input.h239
-rw-r--r--input/ipc-dummy.c19
-rw-r--r--input/ipc-unix.c444
-rw-r--r--input/ipc-win.c509
-rw-r--r--input/ipc.c414
-rw-r--r--input/keycodes.c379
-rw-r--r--input/keycodes.h270
-rw-r--r--input/meson.build20
-rw-r--r--input/sdl_gamepad.c287
14 files changed, 5239 insertions, 0 deletions
diff --git a/input/cmd.c b/input/cmd.c
new file mode 100644
index 0000000..6423214
--- /dev/null
+++ b/input/cmd.c
@@ -0,0 +1,671 @@
+/*
+ * This file is part of mpv.
+ *
+ * mpv is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * mpv is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with mpv. If not, see <http://www.gnu.org/licenses/>.
+ */
+
+#include <stddef.h>
+
+#include "misc/bstr.h"
+#include "misc/node.h"
+#include "common/common.h"
+#include "common/msg.h"
+#include "options/m_option.h"
+
+#include "cmd.h"
+#include "input.h"
+#include "misc/json.h"
+
+#include "libmpv/client.h"
+
+static void destroy_cmd(void *ptr)
+{
+ struct mp_cmd *cmd = ptr;
+ for (int n = 0; n < cmd->nargs; n++) {
+ if (cmd->args[n].type)
+ m_option_free(cmd->args[n].type, &cmd->args[n].v);
+ }
+}
+
+struct flag {
+ const char *name;
+ unsigned int remove, add;
+};
+
+static const struct flag cmd_flags[] = {
+ {"no-osd", MP_ON_OSD_FLAGS, MP_ON_OSD_NO},
+ {"osd-bar", MP_ON_OSD_FLAGS, MP_ON_OSD_BAR},
+ {"osd-msg", MP_ON_OSD_FLAGS, MP_ON_OSD_MSG},
+ {"osd-msg-bar", MP_ON_OSD_FLAGS, MP_ON_OSD_MSG | MP_ON_OSD_BAR},
+ {"osd-auto", MP_ON_OSD_FLAGS, MP_ON_OSD_AUTO},
+ {"expand-properties", 0, MP_EXPAND_PROPERTIES},
+ {"raw", MP_EXPAND_PROPERTIES, 0},
+ {"repeatable", 0, MP_ALLOW_REPEAT},
+ {"async", MP_SYNC_CMD, MP_ASYNC_CMD},
+ {"sync", MP_ASYNC_CMD, MP_SYNC_CMD},
+ {0}
+};
+
+static bool apply_flag(struct mp_cmd *cmd, bstr str)
+{
+ for (int n = 0; cmd_flags[n].name; n++) {
+ if (bstr_equals0(str, cmd_flags[n].name)) {
+ cmd->flags = (cmd->flags & ~cmd_flags[n].remove) | cmd_flags[n].add;
+ return true;
+ }
+ }
+ return false;
+}
+
+static bool find_cmd(struct mp_log *log, struct mp_cmd *cmd, bstr name)
+{
+ if (name.len == 0) {
+ mp_err(log, "Command name missing.\n");
+ return false;
+ }
+
+ char nname[80];
+ snprintf(nname, sizeof(nname), "%.*s", BSTR_P(name));
+ for (int n = 0; nname[n]; n++) {
+ if (nname[n] == '_')
+ nname[n] = '-';
+ }
+
+ for (int n = 0; mp_cmds[n].name; n++) {
+ if (strcmp(nname, mp_cmds[n].name) == 0) {
+ cmd->def = &mp_cmds[n];
+ cmd->name = (char *)cmd->def->name;
+ return true;
+ }
+ }
+ mp_err(log, "Command '%.*s' not found.\n", BSTR_P(name));
+ return false;
+}
+
+static bool is_vararg(const struct mp_cmd_def *m, int i)
+{
+ return m->vararg && (i + 1 >= MP_CMD_DEF_MAX_ARGS || !m->args[i + 1].type);
+}
+
+static const struct m_option *get_arg_type(const struct mp_cmd_def *cmd, int i)
+{
+ const struct m_option *opt = NULL;
+ if (is_vararg(cmd, i)) {
+ // The last arg in a vararg command sets all vararg types.
+ for (int n = MPMIN(i, MP_CMD_DEF_MAX_ARGS - 1); n >= 0; n--) {
+ if (cmd->args[n].type) {
+ opt = &cmd->args[n];
+ break;
+ }
+ }
+ } else if (i < MP_CMD_DEF_MAX_ARGS) {
+ opt = &cmd->args[i];
+ }
+ return opt && opt->type ? opt : NULL;
+}
+
+// Return the name of the argument, possibly as stack allocated string (which is
+// why this is a macro, and out of laziness). Otherwise as get_arg_type().
+#define get_arg_name(cmd, i) \
+ ((i) < MP_CMD_DEF_MAX_ARGS && (cmd)->args[(i)].name && \
+ (cmd)->args[(i)].name[0] \
+ ? (cmd)->args[(i)].name : mp_tprintf(10, "%d", (i) + 1))
+
+// Verify that there are no missing args, fill in missing optional args.
+static bool finish_cmd(struct mp_log *log, struct mp_cmd *cmd)
+{
+ for (int i = 0; i < MP_CMD_DEF_MAX_ARGS; i++) {
+ // (type==NULL is used for yet unset arguments)
+ if (i < cmd->nargs && cmd->args[i].type)
+ continue;
+ const struct m_option *opt = get_arg_type(cmd->def, i);
+ if (i >= cmd->nargs && (!opt || is_vararg(cmd->def, i)))
+ break;
+ if (!opt->defval && !(opt->flags & MP_CMD_OPT_ARG)) {
+ mp_err(log, "Command %s: required argument %s not set.\n",
+ cmd->name, get_arg_name(cmd->def, i));
+ return false;
+ }
+ struct mp_cmd_arg arg = {.type = opt};
+ if (opt->defval)
+ m_option_copy(opt, &arg.v, opt->defval);
+ assert(i <= cmd->nargs);
+ if (i == cmd->nargs) {
+ MP_TARRAY_APPEND(cmd, cmd->args, cmd->nargs, arg);
+ } else {
+ cmd->args[i] = arg;
+ }
+ }
+
+ if (!(cmd->flags & (MP_ASYNC_CMD | MP_SYNC_CMD)))
+ cmd->flags |= cmd->def->default_async ? MP_ASYNC_CMD : MP_SYNC_CMD;
+
+ return true;
+}
+
+static bool set_node_arg(struct mp_log *log, struct mp_cmd *cmd, int i,
+ mpv_node *val)
+{
+ const char *name = get_arg_name(cmd->def, i);
+
+ const struct m_option *opt = get_arg_type(cmd->def, i);
+ if (!opt) {
+ mp_err(log, "Command %s: has only %d arguments.\n", cmd->name, i);
+ return false;
+ }
+
+ if (i < cmd->nargs && cmd->args[i].type) {
+ mp_err(log, "Command %s: argument %s was already set.\n", cmd->name, name);
+ return false;
+ }
+
+ struct mp_cmd_arg arg = {.type = opt};
+ void *dst = &arg.v;
+ if (val->format == MPV_FORMAT_STRING) {
+ int r = m_option_parse(log, opt, bstr0(cmd->name),
+ bstr0(val->u.string), dst);
+ if (r < 0) {
+ mp_err(log, "Command %s: argument %s can't be parsed: %s.\n",
+ cmd->name, name, m_option_strerror(r));
+ return false;
+ }
+ } else {
+ int r = m_option_set_node(opt, dst, val);
+ if (r < 0) {
+ mp_err(log, "Command %s: argument %s has incompatible type.\n",
+ cmd->name, name);
+ return false;
+ }
+ }
+
+ // (leave unset arguments blank, to be set later or checked by finish_cmd())
+ while (i >= cmd->nargs) {
+ struct mp_cmd_arg t = {0};
+ MP_TARRAY_APPEND(cmd, cmd->args, cmd->nargs, t);
+ }
+
+ cmd->args[i] = arg;
+ return true;
+}
+
+static bool cmd_node_array(struct mp_log *log, struct mp_cmd *cmd, mpv_node *node)
+{
+ assert(node->format == MPV_FORMAT_NODE_ARRAY);
+ mpv_node_list *args = node->u.list;
+ int cur = 0;
+
+ while (cur < args->num) {
+ if (args->values[cur].format != MPV_FORMAT_STRING)
+ break;
+ if (!apply_flag(cmd, bstr0(args->values[cur].u.string)))
+ break;
+ cur++;
+ }
+
+ bstr cmd_name = {0};
+ if (cur < args->num && args->values[cur].format == MPV_FORMAT_STRING)
+ cmd_name = bstr0(args->values[cur++].u.string);
+ if (!find_cmd(log, cmd, cmd_name))
+ return false;
+
+ int first = cur;
+ for (int i = 0; i < args->num - first; i++) {
+ if (!set_node_arg(log, cmd, cmd->nargs, &args->values[cur++]))
+ return false;
+ }
+
+ return true;
+}
+
+static bool cmd_node_map(struct mp_log *log, struct mp_cmd *cmd, mpv_node *node)
+{
+ assert(node->format == MPV_FORMAT_NODE_MAP);
+ mpv_node_list *args = node->u.list;
+
+ mpv_node *name = node_map_get(node, "name");
+ if (!name || name->format != MPV_FORMAT_STRING)
+ return false;
+
+ if (!find_cmd(log, cmd, bstr0(name->u.string)))
+ return false;
+
+ if (cmd->def->vararg) {
+ mp_err(log, "Command %s: this command uses a variable number of "
+ "arguments, which does not work with named arguments.\n",
+ cmd->name);
+ return false;
+ }
+
+ for (int n = 0; n < args->num; n++) {
+ const char *key = args->keys[n];
+ mpv_node *val = &args->values[n];
+
+ if (strcmp(key, "name") == 0) {
+ // already handled above
+ } else if (strcmp(key, "_flags") == 0) {
+ if (val->format != MPV_FORMAT_NODE_ARRAY)
+ return false;
+ mpv_node_list *flags = val->u.list;
+ for (int i = 0; i < flags->num; i++) {
+ if (flags->values[i].format != MPV_FORMAT_STRING)
+ return false;
+ if (!apply_flag(cmd, bstr0(flags->values[i].u.string)))
+ return false;
+ }
+ } else {
+ int arg = -1;
+
+ for (int i = 0; i < MP_CMD_DEF_MAX_ARGS; i++) {
+ const char *arg_name = cmd->def->args[i].name;
+ if (arg_name && arg_name[0] && strcmp(key, arg_name) == 0) {
+ arg = i;
+ break;
+ }
+ }
+
+ if (arg < 0) {
+ mp_err(log, "Command %s: no argument %s.\n", cmd->name, key);
+ return false;
+ }
+
+ if (!set_node_arg(log, cmd, arg, val))
+ return false;
+ }
+ }
+
+ return true;
+}
+
+struct mp_cmd *mp_input_parse_cmd_node(struct mp_log *log, mpv_node *node)
+{
+ struct mp_cmd *cmd = talloc_ptrtype(NULL, cmd);
+ talloc_set_destructor(cmd, destroy_cmd);
+ *cmd = (struct mp_cmd) { .scale = 1, .scale_units = 1 };
+
+ bool res = false;
+ if (node->format == MPV_FORMAT_NODE_ARRAY) {
+ res = cmd_node_array(log, cmd, node);
+ } else if (node->format == MPV_FORMAT_NODE_MAP) {
+ res = cmd_node_map(log, cmd, node);
+ }
+
+ res = res && finish_cmd(log, cmd);
+
+ if (!res)
+ TA_FREEP(&cmd);
+
+ return cmd;
+}
+
+static bool read_token(bstr str, bstr *out_rest, bstr *out_token)
+{
+ bstr t = bstr_lstrip(str);
+ int next = bstrcspn(t, WHITESPACE "#;");
+ if (!next)
+ return false;
+ *out_token = bstr_splice(t, 0, next);
+ *out_rest = bstr_cut(t, next);
+ return true;
+}
+
+struct parse_ctx {
+ struct mp_log *log;
+ void *tmp;
+ bstr start, str;
+};
+
+static int pctx_read_token(struct parse_ctx *ctx, bstr *out)
+{
+ *out = (bstr){0};
+ ctx->str = bstr_lstrip(ctx->str);
+ bstr start = ctx->str;
+ if (bstr_eatstart0(&ctx->str, "\"")) {
+ if (!mp_append_escaped_string_noalloc(ctx->tmp, out, &ctx->str)) {
+ MP_ERR(ctx, "Broken string escapes: ...>%.*s<.\n", BSTR_P(start));
+ return -1;
+ }
+ if (!bstr_eatstart0(&ctx->str, "\"")) {
+ MP_ERR(ctx, "Unterminated double quote: ...>%.*s<.\n", BSTR_P(start));
+ return -1;
+ }
+ return 1;
+ }
+ if (bstr_eatstart0(&ctx->str, "'")) {
+ int next = bstrchr(ctx->str, '\'');
+ if (next < 0) {
+ MP_ERR(ctx, "Unterminated single quote: ...>%.*s<.\n", BSTR_P(start));
+ return -1;
+ }
+ *out = bstr_splice(ctx->str, 0, next);
+ ctx->str = bstr_cut(ctx->str, next+1);
+ return 1;
+ }
+ if (ctx->start.len > 1 && bstr_eatstart0(&ctx->str, "`")) {
+ char endquote[2] = {ctx->str.start[0], '`'};
+ ctx->str = bstr_cut(ctx->str, 1);
+ int next = bstr_find(ctx->str, (bstr){endquote, 2});
+ if (next < 0) {
+ MP_ERR(ctx, "Unterminated custom quote: ...>%.*s<.\n", BSTR_P(start));
+ return -1;
+ }
+ *out = bstr_splice(ctx->str, 0, next);
+ ctx->str = bstr_cut(ctx->str, next+2);
+ return 1;
+ }
+
+ return read_token(ctx->str, &ctx->str, out) ? 1 : 0;
+}
+
+static struct mp_cmd *parse_cmd_str(struct mp_log *log, void *tmp,
+ bstr *str, const char *loc)
+{
+ struct parse_ctx *ctx = &(struct parse_ctx){
+ .log = log,
+ .tmp = tmp,
+ .str = *str,
+ .start = *str,
+ };
+
+ struct mp_cmd *cmd = talloc_ptrtype(NULL, cmd);
+ talloc_set_destructor(cmd, destroy_cmd);
+ *cmd = (struct mp_cmd) {
+ .flags = MP_ON_OSD_AUTO | MP_EXPAND_PROPERTIES,
+ .scale = 1,
+ .scale_units = 1,
+ };
+
+ ctx->str = bstr_lstrip(ctx->str);
+
+ bstr cur_token;
+ if (pctx_read_token(ctx, &cur_token) < 0)
+ goto error;
+
+ while (1) {
+ if (!apply_flag(cmd, cur_token))
+ break;
+ if (pctx_read_token(ctx, &cur_token) < 0)
+ goto error;
+ }
+
+ if (!find_cmd(ctx->log, cmd, cur_token))
+ goto error;
+
+ for (int i = 0; i < MP_CMD_MAX_ARGS; i++) {
+ const struct m_option *opt = get_arg_type(cmd->def, i);
+ if (!opt)
+ break;
+
+ int r = pctx_read_token(ctx, &cur_token);
+ if (r < 0) {
+ MP_ERR(ctx, "Command %s: error in argument %d.\n", cmd->name, i + 1);
+ goto error;
+ }
+ if (r < 1)
+ break;
+
+ struct mp_cmd_arg arg = {.type = opt};
+ r = m_option_parse(ctx->log, opt, bstr0(cmd->name), cur_token, &arg.v);
+ if (r < 0) {
+ MP_ERR(ctx, "Command %s: argument %d can't be parsed: %s.\n",
+ cmd->name, i + 1, m_option_strerror(r));
+ goto error;
+ }
+
+ MP_TARRAY_APPEND(cmd, cmd->args, cmd->nargs, arg);
+ }
+
+ if (!finish_cmd(ctx->log, cmd))
+ goto error;
+
+ bstr dummy;
+ if (read_token(ctx->str, &dummy, &dummy) && ctx->str.len) {
+ MP_ERR(ctx, "Command %s has trailing unused arguments: '%.*s'.\n",
+ cmd->name, BSTR_P(ctx->str));
+ // Better make it fatal to make it clear something is wrong.
+ goto error;
+ }
+
+ bstr orig = {ctx->start.start, ctx->str.start - ctx->start.start};
+ cmd->original = bstrto0(cmd, bstr_strip(orig));
+
+ *str = ctx->str;
+ return cmd;
+
+error:
+ MP_ERR(ctx, "Command was defined at %s.\n", loc);
+ talloc_free(cmd);
+ *str = ctx->str;
+ return NULL;
+}
+
+mp_cmd_t *mp_input_parse_cmd_str(struct mp_log *log, bstr str, const char *loc)
+{
+ void *tmp = talloc_new(NULL);
+ bstr original = str;
+ struct mp_cmd *cmd = parse_cmd_str(log, tmp, &str, loc);
+ if (!cmd)
+ goto done;
+
+ // Handle "multi" commands
+ struct mp_cmd **p_prev = NULL;
+ while (1) {
+ str = bstr_lstrip(str);
+ // read_token just to check whether it's trailing whitespace only
+ bstr u1, u2;
+ if (!bstr_eatstart0(&str, ";") || !read_token(str, &u1, &u2))
+ break;
+ // Multi-command. Since other input.c code uses queue_next for its
+ // own purposes, a pseudo-command is used to wrap the command list.
+ if (!p_prev) {
+ struct mp_cmd *list = talloc_ptrtype(NULL, list);
+ talloc_set_destructor(list, destroy_cmd);
+ *list = (struct mp_cmd) {
+ .name = (char *)mp_cmd_list.name,
+ .def = &mp_cmd_list,
+ };
+ talloc_steal(list, cmd);
+ struct mp_cmd_arg arg = {0};
+ arg.v.p = cmd;
+ list->args = talloc_dup(list, &arg);
+ p_prev = &cmd->queue_next;
+ cmd = list;
+ }
+ struct mp_cmd *sub = parse_cmd_str(log, tmp, &str, loc);
+ if (!sub) {
+ talloc_free(cmd);
+ cmd = NULL;
+ goto done;
+ }
+ talloc_steal(cmd, sub);
+ *p_prev = sub;
+ p_prev = &sub->queue_next;
+ }
+
+ cmd->original = bstrto0(cmd, bstr_strip(
+ bstr_splice(original, 0, str.start - original.start)));
+
+ str = bstr_strip(str);
+ if (bstr_eatstart0(&str, "#") && !bstr_startswith0(str, "#")) {
+ str = bstr_strip(str);
+ if (str.len)
+ cmd->desc = bstrto0(cmd, str);
+ }
+
+done:
+ talloc_free(tmp);
+ return cmd;
+}
+
+struct mp_cmd *mp_input_parse_cmd_strv(struct mp_log *log, const char **argv)
+{
+ int count = 0;
+ while (argv[count])
+ count++;
+ mpv_node *items = talloc_zero_array(NULL, mpv_node, count);
+ mpv_node_list list = {.values = items, .num = count};
+ mpv_node node = {.format = MPV_FORMAT_NODE_ARRAY, .u = {.list = &list}};
+ for (int n = 0; n < count; n++) {
+ items[n] = (mpv_node){.format = MPV_FORMAT_STRING,
+ .u = {.string = (char *)argv[n]}};
+ }
+ struct mp_cmd *res = mp_input_parse_cmd_node(log, &node);
+ talloc_free(items);
+ return res;
+}
+
+void mp_cmd_free(mp_cmd_t *cmd)
+{
+ talloc_free(cmd);
+}
+
+mp_cmd_t *mp_cmd_clone(mp_cmd_t *cmd)
+{
+ if (!cmd)
+ return NULL;
+
+ mp_cmd_t *ret = talloc_dup(NULL, cmd);
+ talloc_set_destructor(ret, destroy_cmd);
+ ret->name = talloc_strdup(ret, cmd->name);
+ ret->args = talloc_zero_array(ret, struct mp_cmd_arg, ret->nargs);
+ for (int i = 0; i < ret->nargs; i++) {
+ ret->args[i].type = cmd->args[i].type;
+ m_option_copy(ret->args[i].type, &ret->args[i].v, &cmd->args[i].v);
+ }
+ ret->original = talloc_strdup(ret, cmd->original);
+ ret->desc = talloc_strdup(ret, cmd->desc);
+ ret->sender = NULL;
+ ret->key_name = talloc_strdup(ret, ret->key_name);
+ ret->key_text = talloc_strdup(ret, ret->key_text);
+
+ if (cmd->def == &mp_cmd_list) {
+ struct mp_cmd *prev = NULL;
+ for (struct mp_cmd *sub = cmd->args[0].v.p; sub; sub = sub->queue_next) {
+ sub = mp_cmd_clone(sub);
+ talloc_steal(ret, sub);
+ if (prev) {
+ prev->queue_next = sub;
+ } else {
+ struct mp_cmd_arg arg = {0};
+ arg.v.p = sub;
+ ret->args = talloc_dup(ret, &arg);
+ }
+ prev = sub;
+ }
+ }
+
+ return ret;
+}
+
+static int get_arg_count(const struct mp_cmd_def *cmd)
+{
+ for (int i = MP_CMD_DEF_MAX_ARGS - 1; i >= 0; i--) {
+ if (cmd->args[i].type)
+ return i + 1;
+ }
+ return 0;
+}
+
+void mp_cmd_dump(struct mp_log *log, int msgl, char *header, struct mp_cmd *cmd)
+{
+ if (!mp_msg_test(log, msgl))
+ return;
+ if (header)
+ mp_msg(log, msgl, "%s ", header);
+ if (!cmd) {
+ mp_msg(log, msgl, "(NULL)\n");
+ return;
+ }
+ mp_msg(log, msgl, "%s, flags=%d, args=[", cmd->name, cmd->flags);
+ int argc = get_arg_count(cmd->def);
+ for (int n = 0; n < cmd->nargs; n++) {
+ const char *argname = cmd->def->args[MPMIN(n, argc - 1)].name;
+ char *s = m_option_print(cmd->args[n].type, &cmd->args[n].v);
+ if (n)
+ mp_msg(log, msgl, ", ");
+ struct mpv_node node = {
+ .format = MPV_FORMAT_STRING,
+ .u.string = s ? s : "(NULL)",
+ };
+ char *esc = NULL;
+ json_write(&esc, &node);
+ mp_msg(log, msgl, "%s=%s", argname, esc ? esc : "<error>");
+ talloc_free(esc);
+ talloc_free(s);
+ }
+ mp_msg(log, msgl, "]\n");
+}
+
+bool mp_input_is_repeatable_cmd(struct mp_cmd *cmd)
+{
+ if (cmd->def == &mp_cmd_list && cmd->args[0].v.p)
+ cmd = cmd->args[0].v.p; // list - only 1st cmd is considered
+
+ return (cmd->def->allow_auto_repeat) || (cmd->flags & MP_ALLOW_REPEAT);
+}
+
+bool mp_input_is_scalable_cmd(struct mp_cmd *cmd)
+{
+ return cmd->def->scalable;
+}
+
+void mp_print_cmd_list(struct mp_log *out)
+{
+ for (int i = 0; mp_cmds[i].name; i++) {
+ const struct mp_cmd_def *def = &mp_cmds[i];
+ mp_info(out, "%-20.20s", def->name);
+ for (int j = 0; j < MP_CMD_DEF_MAX_ARGS && def->args[j].type; j++) {
+ const struct m_option *arg = &def->args[j];
+ bool is_opt = arg->defval || (arg->flags & MP_CMD_OPT_ARG);
+ mp_info(out, " %s%s=%s%s", is_opt ? "[" : "", arg->name,
+ arg->type->name, is_opt ? "]" : "");
+ }
+ if (def->vararg)
+ mp_info(out, "..."); // essentially append to last argument
+ mp_info(out, "\n");
+ }
+}
+
+static int parse_cycle_dir(struct mp_log *log, const struct m_option *opt,
+ struct bstr name, struct bstr param, void *dst)
+{
+ double val;
+ if (bstrcmp0(param, "up") == 0) {
+ val = +1;
+ } else if (bstrcmp0(param, "down") == 0) {
+ val = -1;
+ } else {
+ return m_option_type_double.parse(log, opt, name, param, dst);
+ }
+ *(double *)dst = val;
+ return 1;
+}
+
+static char *print_cycle_dir(const m_option_t *opt, const void *val)
+{
+ return talloc_asprintf(NULL, "%f", *(double *)val);
+}
+
+static void copy_opt(const m_option_t *opt, void *dst, const void *src)
+{
+ if (dst && src)
+ memcpy(dst, src, opt->type->size);
+}
+
+const struct m_option_type m_option_type_cycle_dir = {
+ .name = "up|down",
+ .parse = parse_cycle_dir,
+ .print = print_cycle_dir,
+ .copy = copy_opt,
+ .size = sizeof(double),
+};
diff --git a/input/cmd.h b/input/cmd.h
new file mode 100644
index 0000000..1c9fb3e
--- /dev/null
+++ b/input/cmd.h
@@ -0,0 +1,156 @@
+/*
+ * This file is part of mpv.
+ *
+ * mpv is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * mpv is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with mpv. If not, see <http://www.gnu.org/licenses/>.
+ */
+
+#ifndef MP_PARSE_COMMAND_H
+#define MP_PARSE_COMMAND_H
+
+#include <stdbool.h>
+
+#include "misc/bstr.h"
+#include "options/m_option.h"
+
+#define MP_CMD_DEF_MAX_ARGS 9
+#define MP_CMD_OPT_ARG M_OPT_OPTIONAL_PARAM
+
+struct mp_log;
+struct mp_cmd;
+struct mpv_node;
+
+struct mp_cmd_def {
+ const char *name; // user-visible name (as used in input.conf)
+ void (*handler)(void *ctx);
+ const struct m_option args[MP_CMD_DEF_MAX_ARGS];
+ const void *priv; // for free use by handler()
+ bool allow_auto_repeat; // react to repeated key events
+ bool on_updown; // always emit it on both up and down key events
+ bool vararg; // last argument can be given 0 to multiple times
+ bool scalable;
+ bool is_ignore;
+ bool is_noisy; // reduce log level
+ bool default_async; // default to MP_ASYNC flag if none set by user
+ // If you set this, handler() must ensure mp_cmd_ctx_complete() is called
+ // at some point (can be after handler() returns). If you don't set it, the
+ // common code will call mp_cmd_ctx_complete() when handler() returns.
+ // You must make sure that the core cannot disappear while you do work. The
+ // common code keeps the core referenced only until handler() returns.
+ bool exec_async;
+ // If set, handler() is run on a separate worker thread. This means you can
+ // use mp_core_[un]lock() to temporarily unlock and re-lock the core (while
+ // unlocked, you have no synchronized access to mpctx, but you can do long
+ // running operations without blocking playback or input handling).
+ bool spawn_thread;
+ // If this is set, mp_cmd_ctx.abort is set. Set this if handler() can do
+ // asynchronous abort of the command, and explicitly uses mp_cmd_ctx.abort.
+ // (Not setting it when it's not needed can save resources.)
+ bool can_abort;
+ // If playback ends, and the command is still running, an abort is
+ // automatically triggered.
+ bool abort_on_playback_end;
+};
+
+enum mp_cmd_flags {
+ MP_ON_OSD_NO = 0, // prefer not using OSD
+ MP_ON_OSD_AUTO = 1, // use default behavior of the specific command
+ MP_ON_OSD_BAR = 2, // force a bar, if applicable
+ MP_ON_OSD_MSG = 4, // force a message, if applicable
+ MP_EXPAND_PROPERTIES = 8, // expand strings as properties
+ MP_ALLOW_REPEAT = 16, // if used as keybinding, allow key repeat
+
+ // Exactly one of the following 2 bits is set. Which one is used depends on
+ // the command parser (prefixes and mp_cmd_def.default_async).
+ MP_ASYNC_CMD = 32, // do not wait for command to complete
+ MP_SYNC_CMD = 64, // block on command completion
+
+ MP_ON_OSD_FLAGS = MP_ON_OSD_NO | MP_ON_OSD_AUTO |
+ MP_ON_OSD_BAR | MP_ON_OSD_MSG,
+};
+
+// Arbitrary upper bound for sanity.
+#define MP_CMD_MAX_ARGS 100
+
+struct mp_cmd_arg {
+ const struct m_option *type;
+ union {
+ bool b;
+ int i;
+ int64_t i64;
+ float f;
+ double d;
+ char *s;
+ char **str_list;
+ void *p;
+ } v;
+};
+
+typedef struct mp_cmd {
+ char *name;
+ struct mp_cmd_arg *args;
+ int nargs;
+ int flags; // mp_cmd_flags bitfield
+ char *original;
+ char *desc; // (usually NULL since stripped away later)
+ char *input_section;
+ bool is_up_down : 1;
+ bool is_up : 1;
+ bool emit_on_up : 1;
+ bool is_mouse_button : 1;
+ bool repeated : 1;
+ bool mouse_move : 1;
+ int mouse_x, mouse_y;
+ struct mp_cmd *queue_next;
+ double scale; // for scaling numeric arguments
+ int scale_units;
+ const struct mp_cmd_def *def;
+ char *sender; // name of the client API user which sent this
+ char *key_name; // string representation of the key binding
+ char *key_text; // text if key is a text key
+} mp_cmd_t;
+
+extern const struct mp_cmd_def mp_cmds[];
+extern const struct mp_cmd_def mp_cmd_list;
+
+bool mp_input_is_repeatable_cmd(struct mp_cmd *cmd);
+
+bool mp_input_is_scalable_cmd(struct mp_cmd *cmd);
+
+void mp_print_cmd_list(struct mp_log *out);
+
+// Parse text and return corresponding struct mp_cmd.
+// The location parameter is for error messages.
+struct mp_cmd *mp_input_parse_cmd_str(struct mp_log *log, bstr str,
+ const char *loc);
+
+// Similar to mp_input_parse_cmd(), but takes a list of strings instead.
+// Also, MP_ON_OSD_AUTO | MP_EXPAND_PROPERTIES are not set by default.
+// Keep in mind that these functions (naturally) don't take multiple commands,
+// i.e. a ";" argument does not start a new command.
+struct mp_cmd *mp_input_parse_cmd_strv(struct mp_log *log, const char **argv);
+
+struct mp_cmd *mp_input_parse_cmd_node(struct mp_log *log, struct mpv_node *node);
+
+// After getting a command from mp_input_get_cmd you need to free it using this
+// function
+void mp_cmd_free(struct mp_cmd *cmd);
+
+void mp_cmd_dump(struct mp_log *log, int msgl, char *header, struct mp_cmd *cmd);
+
+// This creates a copy of a command (used by the auto repeat stuff).
+struct mp_cmd *mp_cmd_clone(struct mp_cmd *cmd);
+
+extern const struct m_option_type m_option_type_cycle_dir;
+
+#endif
diff --git a/input/event.c b/input/event.c
new file mode 100644
index 0000000..266e029
--- /dev/null
+++ b/input/event.c
@@ -0,0 +1,93 @@
+/*
+ * This file is part of mpv.
+ *
+ * mpv is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * mpv is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with mpv. If not, see <http://www.gnu.org/licenses/>.
+ */
+
+#include "event.h"
+#include "input.h"
+#include "common/msg.h"
+#include "player/external_files.h"
+
+void mp_event_drop_files(struct input_ctx *ictx, int num_files, char **files,
+ enum mp_dnd_action action)
+{
+ bool all_sub = true;
+ for (int i = 0; i < num_files; i++)
+ all_sub &= mp_might_be_subtitle_file(files[i]);
+
+ if (all_sub) {
+ for (int i = 0; i < num_files; i++) {
+ const char *cmd[] = {
+ "osd-auto",
+ "sub-add",
+ files[i],
+ NULL
+ };
+ mp_input_run_cmd(ictx, cmd);
+ }
+ } else {
+ for (int i = 0; i < num_files; i++) {
+ const char *cmd[] = {
+ "osd-auto",
+ "loadfile",
+ files[i],
+ /* Either start playing the dropped files right away
+ or add them to the end of the current playlist */
+ (i == 0 && action == DND_REPLACE) ? "replace" : "append-play",
+ NULL
+ };
+ mp_input_run_cmd(ictx, cmd);
+ }
+ }
+}
+
+int mp_event_drop_mime_data(struct input_ctx *ictx, const char *mime_type,
+ bstr data, enum mp_dnd_action action)
+{
+ // (text lists are the only format supported right now)
+ if (mp_event_get_mime_type_score(ictx, mime_type) >= 0) {
+ void *tmp = talloc_new(NULL);
+ int num_files = 0;
+ char **files = NULL;
+ while (data.len) {
+ bstr line = bstr_getline(data, &data);
+ line = bstr_strip_linebreaks(line);
+ if (bstr_startswith0(line, "#") || !line.start[0])
+ continue;
+ char *s = bstrto0(tmp, line);
+ MP_TARRAY_APPEND(tmp, files, num_files, s);
+ }
+ mp_event_drop_files(ictx, num_files, files, action);
+ talloc_free(tmp);
+ return num_files > 0;
+ } else {
+ return -1;
+ }
+}
+
+int mp_event_get_mime_type_score(struct input_ctx *ictx, const char *mime_type)
+{
+ // X11 and Wayland file list format.
+ if (strcmp(mime_type, "text/uri-list") == 0)
+ return 10;
+ // Just text; treat it the same for convenience.
+ if (strcmp(mime_type, "text/plain;charset=utf-8") == 0)
+ return 5;
+ if (strcmp(mime_type, "text/plain") == 0)
+ return 4;
+ if (strcmp(mime_type, "text") == 0)
+ return 0;
+ return -1;
+}
diff --git a/input/event.h b/input/event.h
new file mode 100644
index 0000000..1e2149b
--- /dev/null
+++ b/input/event.h
@@ -0,0 +1,43 @@
+/*
+ * This file is part of mpv.
+ *
+ * mpv is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * mpv is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with mpv. If not, see <http://www.gnu.org/licenses/>.
+ */
+#ifndef MP_INPUT_EVENT_H_
+#define MP_INPUT_EVENT_H_
+
+#include "misc/bstr.h"
+
+struct input_ctx;
+
+enum mp_dnd_action {
+ DND_REPLACE,
+ DND_APPEND,
+};
+
+// Enqueue files for playback after drag and drop
+void mp_event_drop_files(struct input_ctx *ictx, int num_files, char **files,
+ enum mp_dnd_action append);
+
+// Drop data in a specific format (identified by the mimetype).
+// Returns <0 on error, ==0 if data was ok but empty, >0 on success.
+int mp_event_drop_mime_data(struct input_ctx *ictx, const char *mime_type,
+ bstr data, enum mp_dnd_action append);
+
+// Many drag & drop APIs support multiple mime types, and this function returns
+// whether a type is preferred (higher integer score), or supported (scores
+// below 0 indicate unsupported types).
+int mp_event_get_mime_type_score(struct input_ctx *ictx, const char *mime_type);
+
+#endif
diff --git a/input/input.c b/input/input.c
new file mode 100644
index 0000000..b8d12aa
--- /dev/null
+++ b/input/input.c
@@ -0,0 +1,1695 @@
+/*
+ * This file is part of mpv.
+ *
+ * mpv is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * mpv is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with mpv. If not, see <http://www.gnu.org/licenses/>.
+ */
+
+#include "config.h"
+
+#include <stdlib.h>
+#include <string.h>
+#include <stdio.h>
+#include <stdbool.h>
+#include <unistd.h>
+#include <math.h>
+#include <errno.h>
+#include <sys/types.h>
+#include <sys/stat.h>
+#include <sys/time.h>
+#include <fcntl.h>
+#include <assert.h>
+
+#include "osdep/io.h"
+#include "misc/rendezvous.h"
+
+#include "input.h"
+#include "keycodes.h"
+#include "osdep/threads.h"
+#include "osdep/timer.h"
+#include "common/msg.h"
+#include "common/global.h"
+#include "options/m_config.h"
+#include "options/m_option.h"
+#include "options/path.h"
+#include "mpv_talloc.h"
+#include "options/options.h"
+#include "misc/bstr.h"
+#include "misc/node.h"
+#include "stream/stream.h"
+#include "common/common.h"
+
+#if HAVE_COCOA
+#include "osdep/macosx_events.h"
+#endif
+
+#define input_lock(ictx) mp_mutex_lock(&ictx->mutex)
+#define input_unlock(ictx) mp_mutex_unlock(&ictx->mutex)
+
+#define MP_MAX_KEY_DOWN 4
+
+struct cmd_bind {
+ int keys[MP_MAX_KEY_DOWN];
+ int num_keys;
+ char *cmd;
+ char *location; // filename/line number of definition
+ char *desc; // human readable description
+ bool is_builtin;
+ struct cmd_bind_section *owner;
+};
+
+struct cmd_bind_section {
+ char *owner;
+ struct cmd_bind *binds;
+ int num_binds;
+ char *section;
+ struct mp_rect mouse_area; // set at runtime, if at all
+ bool mouse_area_set; // mouse_area is valid and should be tested
+};
+
+#define MP_MAX_SOURCES 10
+
+#define MAX_ACTIVE_SECTIONS 50
+
+struct active_section {
+ char *name;
+ int flags;
+};
+
+struct cmd_queue {
+ struct mp_cmd *first;
+};
+
+struct wheel_state {
+ double dead_zone_accum;
+ double unit_accum;
+};
+
+struct input_ctx {
+ mp_mutex mutex;
+ struct mp_log *log;
+ struct mpv_global *global;
+ struct m_config_cache *opts_cache;
+ struct input_opts *opts;
+
+ bool using_ar;
+ bool using_cocoa_media_keys;
+
+ // Autorepeat stuff
+ short ar_state;
+ int64_t last_ar;
+
+ // history of key downs - the newest is in position 0
+ int key_history[MP_MAX_KEY_DOWN];
+ // key code of the last key that triggered MP_KEY_STATE_DOWN
+ int last_key_down;
+ int64_t last_key_down_time;
+ struct mp_cmd *current_down_cmd;
+
+ int last_doubleclick_key_down;
+ double last_doubleclick_time;
+
+ // Mouse position on the consumer side (as command.c sees it)
+ int mouse_x, mouse_y;
+ int mouse_hover; // updated on mouse-enter/leave
+ char *mouse_section; // last section to receive mouse event
+
+ // Mouse position on the producer side (as the VO sees it)
+ // Unlike mouse_x/y, this can be used to resolve mouse click bindings.
+ int mouse_vo_x, mouse_vo_y;
+
+ bool mouse_mangle, mouse_src_mangle;
+ struct mp_rect mouse_src, mouse_dst;
+
+ // Wheel state (MP_WHEEL_*)
+ struct wheel_state wheel_state_y; // MP_WHEEL_UP/MP_WHEEL_DOWN
+ struct wheel_state wheel_state_x; // MP_WHEEL_LEFT/MP_WHEEL_RIGHT
+ struct wheel_state *wheel_current; // The direction currently being scrolled
+ double last_wheel_time; // mp_time_sec() of the last wheel event
+
+ // List of command binding sections
+ struct cmd_bind_section **sections;
+ int num_sections;
+
+ // List currently active command sections
+ struct active_section active_sections[MAX_ACTIVE_SECTIONS];
+ int num_active_sections;
+
+ unsigned int mouse_event_counter;
+
+ struct mp_input_src *sources[MP_MAX_SOURCES];
+ int num_sources;
+
+ struct cmd_queue cmd_queue;
+
+ void (*wakeup_cb)(void *ctx);
+ void *wakeup_ctx;
+};
+
+static int parse_config(struct input_ctx *ictx, bool builtin, bstr data,
+ const char *location, const char *restrict_section);
+static void close_input_sources(struct input_ctx *ictx);
+
+#define OPT_BASE_STRUCT struct input_opts
+struct input_opts {
+ char *config_file;
+ int doubleclick_time;
+ // Maximum number of queued commands from keypresses (limit to avoid
+ // repeated slow commands piling up)
+ int key_fifo_size;
+ // Autorepeat config (be aware of mp_input_set_repeat_info())
+ int ar_delay;
+ int ar_rate;
+ bool use_alt_gr;
+ bool use_gamepad;
+ bool use_media_keys;
+ bool default_bindings;
+ bool builtin_bindings;
+ bool enable_mouse_movements;
+ bool vo_key_input;
+ bool test;
+ bool allow_win_drag;
+};
+
+const struct m_sub_options input_config = {
+ .opts = (const m_option_t[]) {
+ {"input-conf", OPT_STRING(config_file), .flags = M_OPT_FILE},
+ {"input-ar-delay", OPT_INT(ar_delay)},
+ {"input-ar-rate", OPT_INT(ar_rate)},
+ {"input-keylist", OPT_PRINT(mp_print_key_list)},
+ {"input-cmdlist", OPT_PRINT(mp_print_cmd_list)},
+ {"input-default-bindings", OPT_BOOL(default_bindings)},
+ {"input-builtin-bindings", OPT_BOOL(builtin_bindings)},
+ {"input-test", OPT_BOOL(test)},
+ {"input-doubleclick-time", OPT_INT(doubleclick_time),
+ M_RANGE(0, 1000)},
+ {"input-right-alt-gr", OPT_BOOL(use_alt_gr)},
+ {"input-key-fifo-size", OPT_INT(key_fifo_size), M_RANGE(2, 65000)},
+ {"input-cursor", OPT_BOOL(enable_mouse_movements)},
+ {"input-vo-keyboard", OPT_BOOL(vo_key_input)},
+ {"input-media-keys", OPT_BOOL(use_media_keys)},
+#if HAVE_SDL2_GAMEPAD
+ {"input-gamepad", OPT_BOOL(use_gamepad)},
+#endif
+ {"window-dragging", OPT_BOOL(allow_win_drag)},
+ {0}
+ },
+ .size = sizeof(struct input_opts),
+ .defaults = &(const struct input_opts){
+ .key_fifo_size = 7,
+ .doubleclick_time = 300,
+ .ar_delay = 200,
+ .ar_rate = 40,
+ .use_alt_gr = true,
+ .enable_mouse_movements = true,
+ .use_media_keys = true,
+ .default_bindings = true,
+ .builtin_bindings = true,
+ .vo_key_input = true,
+ .allow_win_drag = true,
+ },
+ .change_flags = UPDATE_INPUT,
+};
+
+static const char builtin_input_conf[] =
+#include "etc/input.conf.inc"
+;
+
+static bool test_rect(struct mp_rect *rc, int x, int y)
+{
+ return x >= rc->x0 && y >= rc->y0 && x < rc->x1 && y < rc->y1;
+}
+
+static int queue_count_cmds(struct cmd_queue *queue)
+{
+ int res = 0;
+ for (struct mp_cmd *cmd = queue->first; cmd; cmd = cmd->queue_next)
+ res++;
+ return res;
+}
+
+static void queue_remove(struct cmd_queue *queue, struct mp_cmd *cmd)
+{
+ struct mp_cmd **p_prev = &queue->first;
+ while (*p_prev != cmd) {
+ p_prev = &(*p_prev)->queue_next;
+ }
+ // if this fails, cmd was not in the queue
+ assert(*p_prev == cmd);
+ *p_prev = cmd->queue_next;
+}
+
+static struct mp_cmd *queue_remove_head(struct cmd_queue *queue)
+{
+ struct mp_cmd *ret = queue->first;
+ if (ret)
+ queue_remove(queue, ret);
+ return ret;
+}
+
+static void queue_add_tail(struct cmd_queue *queue, struct mp_cmd *cmd)
+{
+ struct mp_cmd **p_prev = &queue->first;
+ while (*p_prev)
+ p_prev = &(*p_prev)->queue_next;
+ *p_prev = cmd;
+ cmd->queue_next = NULL;
+}
+
+static struct mp_cmd *queue_peek_tail(struct cmd_queue *queue)
+{
+ struct mp_cmd *cur = queue->first;
+ while (cur && cur->queue_next)
+ cur = cur->queue_next;
+ return cur;
+}
+
+static void append_bind_info(struct input_ctx *ictx, char **pmsg,
+ struct cmd_bind *bind)
+{
+ char *msg = *pmsg;
+ struct mp_cmd *cmd = mp_input_parse_cmd(ictx, bstr0(bind->cmd),
+ bind->location);
+ char *stripped = cmd ? cmd->original : bind->cmd;
+ msg = talloc_asprintf_append(msg, " '%s'", stripped);
+ if (!cmd)
+ msg = talloc_asprintf_append(msg, " (invalid)");
+ if (strcmp(bind->owner->section, "default") != 0)
+ msg = talloc_asprintf_append(msg, " in section {%s}",
+ bind->owner->section);
+ msg = talloc_asprintf_append(msg, " in %s", bind->location);
+ if (bind->is_builtin)
+ msg = talloc_asprintf_append(msg, " (default)");
+ talloc_free(cmd);
+ *pmsg = msg;
+}
+
+static mp_cmd_t *handle_test(struct input_ctx *ictx, int code)
+{
+ if (code == MP_KEY_CLOSE_WIN) {
+ MP_WARN(ictx,
+ "CLOSE_WIN was received. This pseudo key can be remapped too,\n"
+ "but --input-test will always quit when receiving it.\n");
+ const char *args[] = {"quit", NULL};
+ mp_cmd_t *res = mp_input_parse_cmd_strv(ictx->log, args);
+ return res;
+ }
+
+ char *key_buf = mp_input_get_key_combo_name(&code, 1);
+ char *msg = talloc_asprintf(NULL, "Key %s is bound to:\n", key_buf);
+ talloc_free(key_buf);
+
+ int count = 0;
+ for (int n = 0; n < ictx->num_sections; n++) {
+ struct cmd_bind_section *bs = ictx->sections[n];
+
+ for (int i = 0; i < bs->num_binds; i++) {
+ if (bs->binds[i].num_keys && bs->binds[i].keys[0] == code) {
+ count++;
+ if (count > 1)
+ msg = talloc_asprintf_append(msg, "\n");
+ msg = talloc_asprintf_append(msg, "%d. ", count);
+ append_bind_info(ictx, &msg, &bs->binds[i]);
+ }
+ }
+ }
+
+ if (!count)
+ msg = talloc_asprintf_append(msg, "(nothing)");
+
+ MP_INFO(ictx, "%s\n", msg);
+ const char *args[] = {"show-text", msg, NULL};
+ mp_cmd_t *res = mp_input_parse_cmd_strv(ictx->log, args);
+ talloc_free(msg);
+ return res;
+}
+
+static struct cmd_bind_section *find_section(struct input_ctx *ictx,
+ bstr section)
+{
+ for (int n = 0; n < ictx->num_sections; n++) {
+ struct cmd_bind_section *bs = ictx->sections[n];
+ if (bstr_equals0(section, bs->section))
+ return bs;
+ }
+ return NULL;
+}
+
+static struct cmd_bind_section *get_bind_section(struct input_ctx *ictx,
+ bstr section)
+{
+ if (section.len == 0)
+ section = bstr0("default");
+ struct cmd_bind_section *bind_section = find_section(ictx, section);
+ if (bind_section)
+ return bind_section;
+ bind_section = talloc_ptrtype(ictx, bind_section);
+ *bind_section = (struct cmd_bind_section) {
+ .section = bstrdup0(bind_section, section),
+ .mouse_area = {INT_MIN, INT_MIN, INT_MAX, INT_MAX},
+ .mouse_area_set = true,
+ };
+ MP_TARRAY_APPEND(ictx, ictx->sections, ictx->num_sections, bind_section);
+ return bind_section;
+}
+
+static void key_buf_add(int *buf, int code)
+{
+ for (int n = MP_MAX_KEY_DOWN - 1; n > 0; n--)
+ buf[n] = buf[n - 1];
+ buf[0] = code;
+}
+
+static struct cmd_bind *find_bind_for_key_section(struct input_ctx *ictx,
+ char *section, int code)
+{
+ struct cmd_bind_section *bs = get_bind_section(ictx, bstr0(section));
+
+ if (!bs->num_binds)
+ return NULL;
+
+ int keys[MP_MAX_KEY_DOWN];
+ memcpy(keys, ictx->key_history, sizeof(keys));
+ key_buf_add(keys, code);
+
+ struct cmd_bind *best = NULL;
+
+ // Prefer user-defined keys over builtin bindings
+ for (int builtin = 0; builtin < 2; builtin++) {
+ if (builtin && !ictx->opts->default_bindings)
+ break;
+ if (best)
+ break;
+ for (int n = 0; n < bs->num_binds; n++) {
+ if (bs->binds[n].is_builtin == (bool)builtin) {
+ struct cmd_bind *b = &bs->binds[n];
+ // we have: keys=[key2 key1 keyX ...]
+ // and: b->keys=[key1 key2] (and may be just a prefix)
+ for (int i = 0; i < b->num_keys; i++) {
+ if (b->keys[i] != keys[b->num_keys - 1 - i])
+ goto skip;
+ }
+ if (!best || b->num_keys >= best->num_keys)
+ best = b;
+ skip: ;
+ }
+ }
+ }
+ return best;
+}
+
+static struct cmd_bind *find_any_bind_for_key(struct input_ctx *ictx,
+ char *force_section, int code)
+{
+ if (force_section)
+ return find_bind_for_key_section(ictx, force_section, code);
+
+ bool use_mouse = MP_KEY_DEPENDS_ON_MOUSE_POS(code);
+
+ // First look whether a mouse section is capturing all mouse input
+ // exclusively (regardless of the active section stack order).
+ if (use_mouse && MP_KEY_IS_MOUSE_BTN_SINGLE(ictx->last_key_down)) {
+ struct cmd_bind *bind =
+ find_bind_for_key_section(ictx, ictx->mouse_section, code);
+ if (bind)
+ return bind;
+ }
+
+ struct cmd_bind *best_bind = NULL;
+ for (int i = ictx->num_active_sections - 1; i >= 0; i--) {
+ struct active_section *s = &ictx->active_sections[i];
+ struct cmd_bind *bind = find_bind_for_key_section(ictx, s->name, code);
+ if (bind) {
+ struct cmd_bind_section *bs = bind->owner;
+ if (!use_mouse || (bs->mouse_area_set && test_rect(&bs->mouse_area,
+ ictx->mouse_vo_x,
+ ictx->mouse_vo_y)))
+ {
+ if (!best_bind || (best_bind->is_builtin && !bind->is_builtin))
+ best_bind = bind;
+ }
+ }
+ if (s->flags & MP_INPUT_EXCLUSIVE)
+ break;
+ if (best_bind && (s->flags & MP_INPUT_ON_TOP))
+ break;
+ }
+
+ return best_bind;
+}
+
+static mp_cmd_t *get_cmd_from_keys(struct input_ctx *ictx, char *force_section,
+ int code)
+{
+ if (ictx->opts->test)
+ return handle_test(ictx, code);
+
+ struct cmd_bind *cmd = NULL;
+
+ if (MP_KEY_IS_UNICODE(code))
+ cmd = find_any_bind_for_key(ictx, force_section, MP_KEY_ANY_UNICODE);
+ if (!cmd)
+ cmd = find_any_bind_for_key(ictx, force_section, code);
+ if (!cmd)
+ cmd = find_any_bind_for_key(ictx, force_section, MP_KEY_UNMAPPED);
+ if (!cmd) {
+ if (code == MP_KEY_CLOSE_WIN)
+ return mp_input_parse_cmd_strv(ictx->log, (const char*[]){"quit", 0});
+ int msgl = MSGL_WARN;
+ if (MP_KEY_IS_MOUSE_MOVE(code))
+ msgl = MSGL_TRACE;
+ char *key_buf = mp_input_get_key_combo_name(&code, 1);
+ MP_MSG(ictx, msgl, "No key binding found for key '%s'.\n", key_buf);
+ talloc_free(key_buf);
+ return NULL;
+ }
+ mp_cmd_t *ret = mp_input_parse_cmd(ictx, bstr0(cmd->cmd), cmd->location);
+ if (ret) {
+ ret->input_section = cmd->owner->section;
+ ret->key_name = talloc_steal(ret, mp_input_get_key_combo_name(&code, 1));
+ MP_TRACE(ictx, "key '%s' -> '%s' in '%s'\n",
+ ret->key_name, cmd->cmd, ret->input_section);
+ if (MP_KEY_IS_UNICODE(code)) {
+ bstr text = {0};
+ mp_append_utf8_bstr(ret, &text, code);
+ ret->key_text = text.start;
+ }
+ ret->is_mouse_button = code & MP_KEY_EMIT_ON_UP;
+ } else {
+ char *key_buf = mp_input_get_key_combo_name(&code, 1);
+ MP_ERR(ictx, "Invalid command for key binding '%s': '%s'\n",
+ key_buf, cmd->cmd);
+ talloc_free(key_buf);
+ }
+ return ret;
+}
+
+static void update_mouse_section(struct input_ctx *ictx)
+{
+ struct cmd_bind *bind =
+ find_any_bind_for_key(ictx, NULL, MP_KEY_MOUSE_MOVE);
+
+ char *new_section = bind ? bind->owner->section : "default";
+
+ char *old = ictx->mouse_section;
+ ictx->mouse_section = new_section;
+
+ if (strcmp(old, ictx->mouse_section) != 0) {
+ MP_TRACE(ictx, "input: switch section %s -> %s\n",
+ old, ictx->mouse_section);
+ mp_input_queue_cmd(ictx, get_cmd_from_keys(ictx, old, MP_KEY_MOUSE_LEAVE));
+ }
+}
+
+// Called when the currently held-down key is released. This (usually) sends
+// the a key-up version of the command associated with the keys that were held
+// down.
+// If the drop_current parameter is set to true, then don't send the key-up
+// command. Unless we've already sent a key-down event, in which case the
+// input receiver (the player) must get a key-up event, or it would get stuck
+// thinking a key is still held down.
+static void release_down_cmd(struct input_ctx *ictx, bool drop_current)
+{
+ if (ictx->current_down_cmd && ictx->current_down_cmd->emit_on_up &&
+ (!drop_current || ictx->current_down_cmd->def->on_updown))
+ {
+ memset(ictx->key_history, 0, sizeof(ictx->key_history));
+ ictx->current_down_cmd->is_up = true;
+ mp_input_queue_cmd(ictx, ictx->current_down_cmd);
+ } else {
+ talloc_free(ictx->current_down_cmd);
+ }
+ ictx->current_down_cmd = NULL;
+ ictx->last_key_down = 0;
+ ictx->last_key_down_time = 0;
+ ictx->ar_state = -1;
+ update_mouse_section(ictx);
+}
+
+// We don't want the append to the command queue indefinitely, because that
+// could lead to situations where recovery would take too long.
+static bool should_drop_cmd(struct input_ctx *ictx, struct mp_cmd *cmd)
+{
+ struct cmd_queue *queue = &ictx->cmd_queue;
+ return queue_count_cmds(queue) >= ictx->opts->key_fifo_size;
+}
+
+static struct mp_cmd *resolve_key(struct input_ctx *ictx, int code)
+{
+ update_mouse_section(ictx);
+ struct mp_cmd *cmd = get_cmd_from_keys(ictx, NULL, code);
+ key_buf_add(ictx->key_history, code);
+ if (cmd && !cmd->def->is_ignore && !should_drop_cmd(ictx, cmd))
+ return cmd;
+ talloc_free(cmd);
+ return NULL;
+}
+
+static void interpret_key(struct input_ctx *ictx, int code, double scale,
+ int scale_units)
+{
+ int state = code & (MP_KEY_STATE_DOWN | MP_KEY_STATE_UP);
+ code = code & ~(unsigned)state;
+
+ if (mp_msg_test(ictx->log, MSGL_TRACE)) {
+ char *key = mp_input_get_key_name(code);
+ MP_TRACE(ictx, "key code=%#x '%s'%s%s\n",
+ code, key, (state & MP_KEY_STATE_DOWN) ? " down" : "",
+ (state & MP_KEY_STATE_UP) ? " up" : "");
+ talloc_free(key);
+ }
+
+ if (MP_KEY_DEPENDS_ON_MOUSE_POS(code & ~MP_KEY_MODIFIER_MASK)) {
+ ictx->mouse_event_counter++;
+ mp_input_wakeup(ictx);
+ }
+
+ struct mp_cmd *cmd = NULL;
+
+ if (state == MP_KEY_STATE_DOWN) {
+ // Protect against VOs which send STATE_DOWN with autorepeat
+ if (ictx->last_key_down == code)
+ return;
+ // Cancel current down-event (there can be only one)
+ release_down_cmd(ictx, true);
+ cmd = resolve_key(ictx, code);
+ if (cmd) {
+ cmd->is_up_down = true;
+ cmd->emit_on_up = (code & MP_KEY_EMIT_ON_UP) || cmd->def->on_updown;
+ ictx->current_down_cmd = mp_cmd_clone(cmd);
+ }
+ ictx->last_key_down = code;
+ ictx->last_key_down_time = mp_time_ns();
+ ictx->ar_state = 0;
+ mp_input_wakeup(ictx); // possibly start timer for autorepeat
+ } else if (state == MP_KEY_STATE_UP) {
+ // Most VOs send RELEASE_ALL anyway
+ release_down_cmd(ictx, false);
+ } else {
+ // Press of key with no separate down/up events
+ // Mixing press events and up/down with the same key is not supported,
+ // and input sources shouldn't do this, but can happen anyway if
+ // multiple input sources interfere with each others.
+ if (ictx->last_key_down == code)
+ release_down_cmd(ictx, false);
+ cmd = resolve_key(ictx, code);
+ }
+
+ if (!cmd)
+ return;
+
+ // Don't emit a command on key-down if the key is designed to emit commands
+ // on key-up (like mouse buttons). Also, if the command specifically should
+ // be sent both on key down and key up, still emit the command.
+ if (cmd->emit_on_up && !cmd->def->on_updown) {
+ talloc_free(cmd);
+ return;
+ }
+
+ memset(ictx->key_history, 0, sizeof(ictx->key_history));
+
+ if (mp_input_is_scalable_cmd(cmd)) {
+ cmd->scale = scale;
+ cmd->scale_units = scale_units;
+ mp_input_queue_cmd(ictx, cmd);
+ } else {
+ // Non-scalable commands won't understand cmd->scale, so synthesize
+ // multiple commands with cmd->scale = 1
+ cmd->scale = 1;
+ cmd->scale_units = 1;
+ // Avoid spamming the player with too many commands
+ scale_units = MPMIN(scale_units, 20);
+ for (int i = 0; i < scale_units - 1; i++)
+ mp_input_queue_cmd(ictx, mp_cmd_clone(cmd));
+ if (scale_units)
+ mp_input_queue_cmd(ictx, cmd);
+ }
+}
+
+// Pre-processing for MP_WHEEL_* events. If this returns false, the caller
+// should discard the event.
+static bool process_wheel(struct input_ctx *ictx, int code, double *scale,
+ int *scale_units)
+{
+ // Size of the deadzone in scroll units. The user must scroll at least this
+ // much in any direction before their scroll is registered.
+ static const double DEADZONE_DIST = 0.125;
+ // The deadzone accumulator is reset if no scrolls happened in this many
+ // seconds, eg. the user is assumed to have finished scrolling.
+ static const double DEADZONE_SCROLL_TIME = 0.2;
+ // The scale_units accumulator is reset if no scrolls happened in this many
+ // seconds. This value should be fairly large, so commands will still be
+ // sent when the user scrolls slowly.
+ static const double UNIT_SCROLL_TIME = 0.5;
+
+ // Determine which direction is being scrolled
+ double dir;
+ struct wheel_state *state;
+ switch (code) {
+ case MP_WHEEL_UP: dir = -1; state = &ictx->wheel_state_y; break;
+ case MP_WHEEL_DOWN: dir = +1; state = &ictx->wheel_state_y; break;
+ case MP_WHEEL_LEFT: dir = -1; state = &ictx->wheel_state_x; break;
+ case MP_WHEEL_RIGHT: dir = +1; state = &ictx->wheel_state_x; break;
+ default:
+ return true;
+ }
+
+ // Reset accumulators if it's determined that the user finished scrolling
+ double now = mp_time_sec();
+ if (now > ictx->last_wheel_time + DEADZONE_SCROLL_TIME) {
+ ictx->wheel_current = NULL;
+ ictx->wheel_state_y.dead_zone_accum = 0;
+ ictx->wheel_state_x.dead_zone_accum = 0;
+ }
+ if (now > ictx->last_wheel_time + UNIT_SCROLL_TIME) {
+ ictx->wheel_state_y.unit_accum = 0;
+ ictx->wheel_state_x.unit_accum = 0;
+ }
+ ictx->last_wheel_time = now;
+
+ // Process wheel deadzone. A lot of touchpad drivers don't filter scroll
+ // input, which makes it difficult for the user to send WHEEL_UP/DOWN
+ // without accidentally triggering WHEEL_LEFT/RIGHT. We try to fix this by
+ // implementing a deadzone. When the value of either direction breaks out
+ // of the deadzone, events from the other direction will be ignored until
+ // the user finishes scrolling.
+ if (ictx->wheel_current == NULL) {
+ state->dead_zone_accum += *scale * dir;
+ if (state->dead_zone_accum * dir > DEADZONE_DIST) {
+ ictx->wheel_current = state;
+ *scale = state->dead_zone_accum * dir;
+ }
+ }
+ if (ictx->wheel_current != state)
+ return false;
+
+ // Determine scale_units. This is incremented every time the accumulated
+ // scale value crosses 1.0. Non-scalable input commands will be ran that
+ // many times.
+ state->unit_accum += *scale * dir;
+ *scale_units = trunc(state->unit_accum * dir);
+ state->unit_accum -= *scale_units * dir;
+ return true;
+}
+
+static void mp_input_feed_key(struct input_ctx *ictx, int code, double scale,
+ bool force_mouse)
+{
+ struct input_opts *opts = ictx->opts;
+
+ code = mp_normalize_keycode(code);
+ int unmod = code & ~MP_KEY_MODIFIER_MASK;
+ if (code == MP_INPUT_RELEASE_ALL) {
+ MP_TRACE(ictx, "release all\n");
+ release_down_cmd(ictx, false);
+ return;
+ }
+ if (!opts->enable_mouse_movements && MP_KEY_IS_MOUSE(unmod) && !force_mouse)
+ return;
+ if (unmod == MP_KEY_MOUSE_LEAVE || unmod == MP_KEY_MOUSE_ENTER) {
+ ictx->mouse_hover = unmod == MP_KEY_MOUSE_ENTER;
+ update_mouse_section(ictx);
+
+ mp_cmd_t *cmd = get_cmd_from_keys(ictx, NULL, code);
+ if (!cmd) // queue dummy cmd so that mouse-pos can notify observers
+ cmd = mp_input_parse_cmd(ictx, bstr0("ignore"), "<internal>");
+ mp_input_queue_cmd(ictx, cmd);
+ return;
+ }
+ double now = mp_time_sec();
+ // ignore system-doubleclick if we generate these events ourselves
+ if (!force_mouse && opts->doubleclick_time && MP_KEY_IS_MOUSE_BTN_DBL(unmod))
+ return;
+ int units = 1;
+ if (MP_KEY_IS_WHEEL(unmod) && !process_wheel(ictx, unmod, &scale, &units))
+ return;
+ interpret_key(ictx, code, scale, units);
+ if (code & MP_KEY_STATE_DOWN) {
+ code &= ~MP_KEY_STATE_DOWN;
+ if (ictx->last_doubleclick_key_down == code &&
+ now - ictx->last_doubleclick_time < opts->doubleclick_time / 1000.0)
+ {
+ if (code >= MP_MBTN_LEFT && code <= MP_MBTN_RIGHT) {
+ interpret_key(ictx, code - MP_MBTN_BASE + MP_MBTN_DBL_BASE,
+ 1, 1);
+ }
+ }
+ ictx->last_doubleclick_key_down = code;
+ ictx->last_doubleclick_time = now;
+ }
+}
+
+void mp_input_put_key(struct input_ctx *ictx, int code)
+{
+ input_lock(ictx);
+ mp_input_feed_key(ictx, code, 1, false);
+ input_unlock(ictx);
+}
+
+void mp_input_put_key_artificial(struct input_ctx *ictx, int code)
+{
+ input_lock(ictx);
+ mp_input_feed_key(ictx, code, 1, true);
+ input_unlock(ictx);
+}
+
+void mp_input_put_key_utf8(struct input_ctx *ictx, int mods, struct bstr t)
+{
+ while (t.len) {
+ int code = bstr_decode_utf8(t, &t);
+ if (code < 0)
+ break;
+ mp_input_put_key(ictx, code | mods);
+ }
+}
+
+void mp_input_put_wheel(struct input_ctx *ictx, int direction, double value)
+{
+ if (value == 0.0)
+ return;
+ input_lock(ictx);
+ mp_input_feed_key(ictx, direction, value, false);
+ input_unlock(ictx);
+}
+
+void mp_input_set_mouse_transform(struct input_ctx *ictx, struct mp_rect *dst,
+ struct mp_rect *src)
+{
+ input_lock(ictx);
+ ictx->mouse_mangle = dst || src;
+ if (ictx->mouse_mangle) {
+ ictx->mouse_dst = *dst;
+ ictx->mouse_src_mangle = !!src;
+ if (ictx->mouse_src_mangle)
+ ictx->mouse_src = *src;
+ }
+ input_unlock(ictx);
+}
+
+bool mp_input_mouse_enabled(struct input_ctx *ictx)
+{
+ input_lock(ictx);
+ bool r = ictx->opts->enable_mouse_movements;
+ input_unlock(ictx);
+ return r;
+}
+
+bool mp_input_vo_keyboard_enabled(struct input_ctx *ictx)
+{
+ input_lock(ictx);
+ bool r = ictx->opts->vo_key_input;
+ input_unlock(ictx);
+ return r;
+}
+
+void mp_input_set_mouse_pos(struct input_ctx *ictx, int x, int y)
+{
+ input_lock(ictx);
+ if (ictx->opts->enable_mouse_movements)
+ mp_input_set_mouse_pos_artificial(ictx, x, y);
+ input_unlock(ictx);
+}
+
+void mp_input_set_mouse_pos_artificial(struct input_ctx *ictx, int x, int y)
+{
+ input_lock(ictx);
+ MP_TRACE(ictx, "mouse move %d/%d\n", x, y);
+
+ if (ictx->mouse_vo_x == x && ictx->mouse_vo_y == y) {
+ input_unlock(ictx);
+ return;
+ }
+
+ if (ictx->mouse_mangle) {
+ struct mp_rect *src = &ictx->mouse_src;
+ struct mp_rect *dst = &ictx->mouse_dst;
+ x = MPCLAMP(x, dst->x0, dst->x1) - dst->x0;
+ y = MPCLAMP(y, dst->y0, dst->y1) - dst->y0;
+ if (ictx->mouse_src_mangle) {
+ x = x * 1.0 / (dst->x1 - dst->x0) * (src->x1 - src->x0) + src->x0;
+ y = y * 1.0 / (dst->y1 - dst->y0) * (src->y1 - src->y0) + src->y0;
+ }
+ MP_TRACE(ictx, "-> %d/%d\n", x, y);
+ }
+
+ ictx->mouse_event_counter++;
+ ictx->mouse_vo_x = x;
+ ictx->mouse_vo_y = y;
+
+ update_mouse_section(ictx);
+ struct mp_cmd *cmd = get_cmd_from_keys(ictx, NULL, MP_KEY_MOUSE_MOVE);
+ if (!cmd)
+ cmd = mp_input_parse_cmd(ictx, bstr0("ignore"), "<internal>");
+
+ if (cmd) {
+ cmd->mouse_move = true;
+ cmd->mouse_x = x;
+ cmd->mouse_y = y;
+ if (should_drop_cmd(ictx, cmd)) {
+ talloc_free(cmd);
+ } else {
+ // Coalesce with previous mouse move events (i.e. replace it)
+ struct mp_cmd *tail = queue_peek_tail(&ictx->cmd_queue);
+ if (tail && tail->mouse_move) {
+ queue_remove(&ictx->cmd_queue, tail);
+ talloc_free(tail);
+ }
+ mp_input_queue_cmd(ictx, cmd);
+ }
+ }
+ input_unlock(ictx);
+}
+
+unsigned int mp_input_get_mouse_event_counter(struct input_ctx *ictx)
+{
+ // Make the frontend always display the mouse cursor (as long as it's not
+ // forced invisible) if mouse input is desired.
+ input_lock(ictx);
+ if (mp_input_test_mouse_active(ictx, ictx->mouse_x, ictx->mouse_y))
+ ictx->mouse_event_counter++;
+ int ret = ictx->mouse_event_counter;
+ input_unlock(ictx);
+ return ret;
+}
+
+// adjust min time to wait until next repeat event
+static void adjust_max_wait_time(struct input_ctx *ictx, double *time)
+{
+ struct input_opts *opts = ictx->opts;
+ if (ictx->last_key_down && opts->ar_rate > 0 && ictx->ar_state >= 0) {
+ *time = MPMIN(*time, 1.0 / opts->ar_rate);
+ *time = MPMIN(*time, opts->ar_delay / 1000.0);
+ }
+}
+
+int mp_input_queue_cmd(struct input_ctx *ictx, mp_cmd_t *cmd)
+{
+ input_lock(ictx);
+ if (cmd) {
+ queue_add_tail(&ictx->cmd_queue, cmd);
+ mp_input_wakeup(ictx);
+ }
+ input_unlock(ictx);
+ return 1;
+}
+
+static mp_cmd_t *check_autorepeat(struct input_ctx *ictx)
+{
+ struct input_opts *opts = ictx->opts;
+
+ // No input : autorepeat ?
+ if (opts->ar_rate <= 0 || !ictx->current_down_cmd || !ictx->last_key_down ||
+ (ictx->last_key_down & MP_NO_REPEAT_KEY) ||
+ !mp_input_is_repeatable_cmd(ictx->current_down_cmd))
+ ictx->ar_state = -1; // disable
+
+ if (ictx->ar_state >= 0) {
+ int64_t t = mp_time_ns();
+ if (ictx->last_ar + MP_TIME_S_TO_NS(2) < t)
+ ictx->last_ar = t;
+ // First time : wait delay
+ if (ictx->ar_state == 0
+ && (t - ictx->last_key_down_time) >= MP_TIME_MS_TO_NS(opts->ar_delay))
+ {
+ ictx->ar_state = 1;
+ ictx->last_ar = ictx->last_key_down_time + MP_TIME_MS_TO_NS(opts->ar_delay);
+ // Then send rate / sec event
+ } else if (ictx->ar_state == 1
+ && (t - ictx->last_ar) >= 1e9 / opts->ar_rate) {
+ ictx->last_ar += 1e9 / opts->ar_rate;
+ } else {
+ return NULL;
+ }
+ struct mp_cmd *ret = mp_cmd_clone(ictx->current_down_cmd);
+ ret->repeated = true;
+ return ret;
+ }
+ return NULL;
+}
+
+double mp_input_get_delay(struct input_ctx *ictx)
+{
+ input_lock(ictx);
+ double seconds = INFINITY;
+ adjust_max_wait_time(ictx, &seconds);
+ input_unlock(ictx);
+ return seconds;
+}
+
+void mp_input_wakeup(struct input_ctx *ictx)
+{
+ ictx->wakeup_cb(ictx->wakeup_ctx);
+}
+
+mp_cmd_t *mp_input_read_cmd(struct input_ctx *ictx)
+{
+ input_lock(ictx);
+ struct mp_cmd *ret = queue_remove_head(&ictx->cmd_queue);
+ if (!ret)
+ ret = check_autorepeat(ictx);
+ if (ret && ret->mouse_move) {
+ ictx->mouse_x = ret->mouse_x;
+ ictx->mouse_y = ret->mouse_y;
+ }
+ input_unlock(ictx);
+ return ret;
+}
+
+void mp_input_get_mouse_pos(struct input_ctx *ictx, int *x, int *y, int *hover)
+{
+ input_lock(ictx);
+ *x = ictx->mouse_x;
+ *y = ictx->mouse_y;
+ *hover = ictx->mouse_hover;
+ input_unlock(ictx);
+}
+
+// If name is NULL, return "default".
+// Return a statically allocated name of the section (i.e. return value never
+// gets deallocated).
+static char *normalize_section(struct input_ctx *ictx, char *name)
+{
+ return get_bind_section(ictx, bstr0(name))->section;
+}
+
+void mp_input_disable_section(struct input_ctx *ictx, char *name)
+{
+ input_lock(ictx);
+ name = normalize_section(ictx, name);
+
+ // Remove old section, or make sure it's on top if re-enabled
+ for (int i = ictx->num_active_sections - 1; i >= 0; i--) {
+ struct active_section *as = &ictx->active_sections[i];
+ if (strcmp(as->name, name) == 0) {
+ MP_TARRAY_REMOVE_AT(ictx->active_sections,
+ ictx->num_active_sections, i);
+ }
+ }
+ input_unlock(ictx);
+}
+
+void mp_input_enable_section(struct input_ctx *ictx, char *name, int flags)
+{
+ input_lock(ictx);
+ name = normalize_section(ictx, name);
+
+ mp_input_disable_section(ictx, name);
+
+ MP_TRACE(ictx, "enable section '%s'\n", name);
+
+ if (ictx->num_active_sections < MAX_ACTIVE_SECTIONS) {
+ int top = ictx->num_active_sections;
+ if (!(flags & MP_INPUT_ON_TOP)) {
+ // insert before the first top entry
+ for (top = 0; top < ictx->num_active_sections; top++) {
+ if (ictx->active_sections[top].flags & MP_INPUT_ON_TOP)
+ break;
+ }
+ for (int n = ictx->num_active_sections; n > top; n--)
+ ictx->active_sections[n] = ictx->active_sections[n - 1];
+ }
+ ictx->active_sections[top] = (struct active_section){name, flags};
+ ictx->num_active_sections++;
+ }
+
+ MP_TRACE(ictx, "active section stack:\n");
+ for (int n = 0; n < ictx->num_active_sections; n++) {
+ MP_TRACE(ictx, " %s %d\n", ictx->active_sections[n].name,
+ ictx->active_sections[n].flags);
+ }
+
+ input_unlock(ictx);
+}
+
+void mp_input_disable_all_sections(struct input_ctx *ictx)
+{
+ input_lock(ictx);
+ ictx->num_active_sections = 0;
+ input_unlock(ictx);
+}
+
+void mp_input_set_section_mouse_area(struct input_ctx *ictx, char *name,
+ int x0, int y0, int x1, int y1)
+{
+ input_lock(ictx);
+ struct cmd_bind_section *s = get_bind_section(ictx, bstr0(name));
+ s->mouse_area = (struct mp_rect){x0, y0, x1, y1};
+ s->mouse_area_set = x0 != x1 && y0 != y1;
+ input_unlock(ictx);
+}
+
+static bool test_mouse(struct input_ctx *ictx, int x, int y, int rej_flags)
+{
+ input_lock(ictx);
+ bool res = false;
+ for (int i = 0; i < ictx->num_active_sections; i++) {
+ struct active_section *as = &ictx->active_sections[i];
+ if (as->flags & rej_flags)
+ continue;
+ struct cmd_bind_section *s = get_bind_section(ictx, bstr0(as->name));
+ if (s->mouse_area_set && test_rect(&s->mouse_area, x, y)) {
+ res = true;
+ break;
+ }
+ }
+ input_unlock(ictx);
+ return res;
+}
+
+bool mp_input_test_mouse_active(struct input_ctx *ictx, int x, int y)
+{
+ return test_mouse(ictx, x, y, MP_INPUT_ALLOW_HIDE_CURSOR);
+}
+
+bool mp_input_test_dragging(struct input_ctx *ictx, int x, int y)
+{
+ input_lock(ictx);
+ bool r = !ictx->opts->allow_win_drag ||
+ test_mouse(ictx, x, y, MP_INPUT_ALLOW_VO_DRAGGING);
+ input_unlock(ictx);
+ return r;
+}
+
+static void bind_dealloc(struct cmd_bind *bind)
+{
+ talloc_free(bind->cmd);
+ talloc_free(bind->location);
+ talloc_free(bind->desc);
+}
+
+// builtin: if true, remove all builtin binds, else remove all user binds
+static void remove_binds(struct cmd_bind_section *bs, bool builtin)
+{
+ for (int n = bs->num_binds - 1; n >= 0; n--) {
+ if (bs->binds[n].is_builtin == builtin) {
+ bind_dealloc(&bs->binds[n]);
+ assert(bs->num_binds >= 1);
+ bs->binds[n] = bs->binds[bs->num_binds - 1];
+ bs->num_binds--;
+ }
+ }
+}
+
+void mp_input_define_section(struct input_ctx *ictx, char *name, char *location,
+ char *contents, bool builtin, char *owner)
+{
+ if (!name || !name[0])
+ return; // parse_config() changes semantics with restrict_section==empty
+ input_lock(ictx);
+ // Delete:
+ struct cmd_bind_section *bs = get_bind_section(ictx, bstr0(name));
+ if ((!bs->owner || (owner && strcmp(bs->owner, owner) != 0)) &&
+ strcmp(bs->section, "default") != 0)
+ {
+ talloc_free(bs->owner);
+ bs->owner = talloc_strdup(bs, owner);
+ }
+ remove_binds(bs, builtin);
+ if (contents && contents[0]) {
+ // Redefine:
+ parse_config(ictx, builtin, bstr0(contents), location, name);
+ } else {
+ // Disable:
+ mp_input_disable_section(ictx, name);
+ }
+ input_unlock(ictx);
+}
+
+void mp_input_remove_sections_by_owner(struct input_ctx *ictx, char *owner)
+{
+ input_lock(ictx);
+ for (int n = 0; n < ictx->num_sections; n++) {
+ struct cmd_bind_section *bs = ictx->sections[n];
+ if (bs->owner && owner && strcmp(bs->owner, owner) == 0) {
+ mp_input_disable_section(ictx, bs->section);
+ remove_binds(bs, false);
+ remove_binds(bs, true);
+ }
+ }
+ input_unlock(ictx);
+}
+
+static bool bind_matches_key(struct cmd_bind *bind, int num_keys, const int *keys)
+{
+ if (bind->num_keys != num_keys)
+ return false;
+ for (int i = 0; i < num_keys; i++) {
+ if (bind->keys[i] != keys[i])
+ return false;
+ }
+ return true;
+}
+
+static void bind_keys(struct input_ctx *ictx, bool builtin, bstr section,
+ const int *keys, int num_keys, bstr command,
+ const char *loc, const char *desc)
+{
+ struct cmd_bind_section *bs = get_bind_section(ictx, section);
+ struct cmd_bind *bind = NULL;
+
+ assert(num_keys <= MP_MAX_KEY_DOWN);
+
+ for (int n = 0; n < bs->num_binds; n++) {
+ struct cmd_bind *b = &bs->binds[n];
+ if (bind_matches_key(b, num_keys, keys) && b->is_builtin == builtin) {
+ bind = b;
+ break;
+ }
+ }
+
+ if (!bind) {
+ struct cmd_bind empty = {{0}};
+ MP_TARRAY_APPEND(bs, bs->binds, bs->num_binds, empty);
+ bind = &bs->binds[bs->num_binds - 1];
+ }
+
+ bind_dealloc(bind);
+
+ *bind = (struct cmd_bind) {
+ .cmd = bstrdup0(bs->binds, command),
+ .location = talloc_strdup(bs->binds, loc),
+ .desc = talloc_strdup(bs->binds, desc),
+ .owner = bs,
+ .is_builtin = builtin,
+ .num_keys = num_keys,
+ };
+ memcpy(bind->keys, keys, num_keys * sizeof(bind->keys[0]));
+ if (mp_msg_test(ictx->log, MSGL_DEBUG)) {
+ char *s = mp_input_get_key_combo_name(keys, num_keys);
+ MP_TRACE(ictx, "add: section='%s' key='%s'%s cmd='%s' location='%s'\n",
+ bind->owner->section, s, bind->is_builtin ? " builtin" : "",
+ bind->cmd, bind->location);
+ talloc_free(s);
+ }
+}
+
+// restrict_section: every entry is forced to this section name
+// if NULL, load normally and allow any sections
+static int parse_config(struct input_ctx *ictx, bool builtin, bstr data,
+ const char *location, const char *restrict_section)
+{
+ int n_binds = 0;
+ int line_no = 0;
+ char *cur_loc = NULL;
+
+ while (data.len) {
+ line_no++;
+ if (cur_loc)
+ talloc_free(cur_loc);
+ cur_loc = talloc_asprintf(NULL, "%s:%d", location, line_no);
+
+ bstr line = bstr_strip_linebreaks(bstr_getline(data, &data));
+ line = bstr_lstrip(line);
+ if (line.len == 0 || bstr_startswith0(line, "#"))
+ continue;
+ if (bstr_eatstart0(&line, "default-bindings ")) {
+ bstr orig = line;
+ bstr_split_tok(line, "#", &line, &(bstr){0});
+ line = bstr_strip(line);
+ if (bstr_equals0(line, "start")) {
+ builtin = true;
+ } else {
+ MP_ERR(ictx, "Broken line: %.*s at %s\n", BSTR_P(orig), cur_loc);
+ }
+ continue;
+ }
+ struct bstr command;
+ // Find the key name starting a line
+ struct bstr keyname = bstr_split(line, WHITESPACE, &command);
+ command = bstr_strip(command);
+ if (command.len == 0) {
+ MP_ERR(ictx, "Unfinished key binding: %.*s at %s\n", BSTR_P(line),
+ cur_loc);
+ continue;
+ }
+ char *name = bstrdup0(NULL, keyname);
+ int keys[MP_MAX_KEY_DOWN];
+ int num_keys = 0;
+ if (!mp_input_get_keys_from_string(name, MP_MAX_KEY_DOWN, &num_keys, keys))
+ {
+ talloc_free(name);
+ MP_ERR(ictx, "Unknown key '%.*s' at %s\n", BSTR_P(keyname), cur_loc);
+ continue;
+ }
+ talloc_free(name);
+
+ bstr section = bstr0(restrict_section);
+ if (!section.len) {
+ if (bstr_startswith0(command, "{")) {
+ int p = bstrchr(command, '}');
+ if (p != -1) {
+ section = bstr_strip(bstr_splice(command, 1, p));
+ command = bstr_lstrip(bstr_cut(command, p + 1));
+ }
+ }
+ }
+
+ // Print warnings if invalid commands are encountered.
+ struct mp_cmd *cmd = mp_input_parse_cmd(ictx, command, cur_loc);
+ const char *desc = NULL;
+ if (cmd) {
+ desc = cmd->desc;
+ command = bstr0(cmd->original);
+ }
+
+ bind_keys(ictx, builtin, section, keys, num_keys, command, cur_loc, desc);
+ n_binds++;
+
+ talloc_free(cmd);
+ }
+
+ talloc_free(cur_loc);
+
+ return n_binds;
+}
+
+static int parse_config_file(struct input_ctx *ictx, char *file, bool warn)
+{
+ int r = 0;
+ void *tmp = talloc_new(NULL);
+ stream_t *s = NULL;
+
+ file = mp_get_user_path(tmp, ictx->global, file);
+
+ s = stream_create(file, STREAM_ORIGIN_DIRECT | STREAM_READ, NULL, ictx->global);
+ if (!s) {
+ MP_ERR(ictx, "Can't open input config file %s.\n", file);
+ goto done;
+ }
+ stream_skip_bom(s);
+ bstr data = stream_read_complete(s, tmp, 1000000);
+ if (data.start) {
+ MP_VERBOSE(ictx, "Parsing input config file %s\n", file);
+ int num = parse_config(ictx, false, data, file, NULL);
+ MP_VERBOSE(ictx, "Input config file %s parsed: %d binds\n", file, num);
+ r = 1;
+ } else {
+ MP_ERR(ictx, "Error reading input config file %s\n", file);
+ }
+
+done:
+ free_stream(s);
+ talloc_free(tmp);
+ return r;
+}
+
+struct input_ctx *mp_input_init(struct mpv_global *global,
+ void (*wakeup_cb)(void *ctx),
+ void *wakeup_ctx)
+{
+
+ struct input_ctx *ictx = talloc_ptrtype(NULL, ictx);
+ *ictx = (struct input_ctx){
+ .global = global,
+ .ar_state = -1,
+ .log = mp_log_new(ictx, global->log, "input"),
+ .mouse_section = "default",
+ .opts_cache = m_config_cache_alloc(ictx, global, &input_config),
+ .wakeup_cb = wakeup_cb,
+ .wakeup_ctx = wakeup_ctx,
+ };
+
+ ictx->opts = ictx->opts_cache->opts;
+
+ mp_mutex_init_type(&ictx->mutex, MP_MUTEX_RECURSIVE);
+
+ // Setup default section, so that it does nothing.
+ mp_input_enable_section(ictx, NULL, MP_INPUT_ALLOW_VO_DRAGGING |
+ MP_INPUT_ALLOW_HIDE_CURSOR);
+
+ return ictx;
+}
+
+static void reload_opts(struct input_ctx *ictx, bool shutdown)
+{
+ m_config_cache_update(ictx->opts_cache);
+
+#if HAVE_COCOA
+ struct input_opts *opts = ictx->opts;
+
+ if (ictx->using_cocoa_media_keys != (opts->use_media_keys && !shutdown)) {
+ ictx->using_cocoa_media_keys = !ictx->using_cocoa_media_keys;
+ if (ictx->using_cocoa_media_keys) {
+ cocoa_init_media_keys();
+ } else {
+ cocoa_uninit_media_keys();
+ }
+ }
+#endif
+}
+
+void mp_input_update_opts(struct input_ctx *ictx)
+{
+ input_lock(ictx);
+ reload_opts(ictx, false);
+ input_unlock(ictx);
+}
+
+void mp_input_load_config(struct input_ctx *ictx)
+{
+ input_lock(ictx);
+
+ reload_opts(ictx, false);
+
+ // "Uncomment" the default key bindings in etc/input.conf and add them.
+ // All lines that do not start with '# ' are parsed.
+ bstr builtin = bstr0(builtin_input_conf);
+ while (ictx->opts->builtin_bindings && builtin.len) {
+ bstr line = bstr_getline(builtin, &builtin);
+ bstr_eatstart0(&line, "#");
+ if (!bstr_startswith0(line, " "))
+ parse_config(ictx, true, line, "<builtin>", NULL);
+ }
+
+ bool config_ok = false;
+ if (ictx->opts->config_file && ictx->opts->config_file[0])
+ config_ok = parse_config_file(ictx, ictx->opts->config_file, true);
+ if (!config_ok) {
+ // Try global conf dir
+ void *tmp = talloc_new(NULL);
+ char **files = mp_find_all_config_files(tmp, ictx->global, "input.conf");
+ for (int n = 0; files && files[n]; n++)
+ parse_config_file(ictx, files[n], false);
+ talloc_free(tmp);
+ }
+
+#if HAVE_SDL2_GAMEPAD
+ if (ictx->opts->use_gamepad) {
+ mp_input_sdl_gamepad_add(ictx);
+ }
+#endif
+
+ input_unlock(ictx);
+}
+
+static void clear_queue(struct cmd_queue *queue)
+{
+ while (queue->first) {
+ struct mp_cmd *item = queue->first;
+ queue_remove(queue, item);
+ talloc_free(item);
+ }
+}
+
+void mp_input_uninit(struct input_ctx *ictx)
+{
+ if (!ictx)
+ return;
+
+ input_lock(ictx);
+ reload_opts(ictx, true);
+ input_unlock(ictx);
+
+ close_input_sources(ictx);
+ clear_queue(&ictx->cmd_queue);
+ talloc_free(ictx->current_down_cmd);
+ mp_mutex_destroy(&ictx->mutex);
+ talloc_free(ictx);
+}
+
+bool mp_input_use_alt_gr(struct input_ctx *ictx)
+{
+ input_lock(ictx);
+ bool r = ictx->opts->use_alt_gr;
+ input_unlock(ictx);
+ return r;
+}
+
+bool mp_input_use_media_keys(struct input_ctx *ictx)
+{
+ input_lock(ictx);
+ bool r = ictx->opts->use_media_keys;
+ input_unlock(ictx);
+ return r;
+}
+
+struct mp_cmd *mp_input_parse_cmd(struct input_ctx *ictx, bstr str,
+ const char *location)
+{
+ return mp_input_parse_cmd_str(ictx->log, str, location);
+}
+
+void mp_input_run_cmd(struct input_ctx *ictx, const char **cmd)
+{
+ mp_input_queue_cmd(ictx, mp_input_parse_cmd_strv(ictx->log, cmd));
+}
+
+void mp_input_bind_key(struct input_ctx *ictx, int key, bstr command)
+{
+ struct cmd_bind_section *bs = get_bind_section(ictx, (bstr){0});
+ struct cmd_bind *bind = NULL;
+
+ for (int n = 0; n < bs->num_binds; n++) {
+ struct cmd_bind *b = &bs->binds[n];
+ if (bind_matches_key(b, 1, &key) && b->is_builtin == false) {
+ bind = b;
+ break;
+ }
+ }
+
+ if (!bind) {
+ struct cmd_bind empty = {{0}};
+ MP_TARRAY_APPEND(bs, bs->binds, bs->num_binds, empty);
+ bind = &bs->binds[bs->num_binds - 1];
+ }
+
+ bind_dealloc(bind);
+
+ *bind = (struct cmd_bind) {
+ .cmd = bstrdup0(bs->binds, command),
+ .location = talloc_strdup(bs->binds, "keybind-command"),
+ .owner = bs,
+ .is_builtin = false,
+ .num_keys = 1,
+ };
+ memcpy(bind->keys, &key, 1 * sizeof(bind->keys[0]));
+ if (mp_msg_test(ictx->log, MSGL_DEBUG)) {
+ char *s = mp_input_get_key_combo_name(&key, 1);
+ MP_TRACE(ictx, "add:section='%s' key='%s'%s cmd='%s' location='%s'\n",
+ bind->owner->section, s, bind->is_builtin ? " builtin" : "",
+ bind->cmd, bind->location);
+ talloc_free(s);
+ }
+}
+
+struct mpv_node mp_input_get_bindings(struct input_ctx *ictx)
+{
+ input_lock(ictx);
+ struct mpv_node root;
+ node_init(&root, MPV_FORMAT_NODE_ARRAY, NULL);
+
+ for (int x = 0; x < ictx->num_sections; x++) {
+ struct cmd_bind_section *s = ictx->sections[x];
+ int priority = -1;
+
+ for (int i = 0; i < ictx->num_active_sections; i++) {
+ struct active_section *as = &ictx->active_sections[i];
+ if (strcmp(as->name, s->section) == 0) {
+ priority = i;
+ break;
+ }
+ }
+
+ for (int n = 0; n < s->num_binds; n++) {
+ struct cmd_bind *b = &s->binds[n];
+ struct mpv_node *entry = node_array_add(&root, MPV_FORMAT_NODE_MAP);
+
+ int b_priority = priority;
+ if (b->is_builtin && !ictx->opts->default_bindings)
+ b_priority = -1;
+
+ // Try to fixup the weird logic so consumer of this bindings list
+ // does not get too confused.
+ if (b_priority >= 0 && !b->is_builtin)
+ b_priority += ictx->num_active_sections;
+
+ node_map_add_string(entry, "section", s->section);
+ if (s->owner)
+ node_map_add_string(entry, "owner", s->owner);
+ node_map_add_string(entry, "cmd", b->cmd);
+ node_map_add_flag(entry, "is_weak", b->is_builtin);
+ node_map_add_int64(entry, "priority", b_priority);
+ if (b->desc)
+ node_map_add_string(entry, "comment", b->desc);
+
+ char *key = mp_input_get_key_combo_name(b->keys, b->num_keys);
+ node_map_add_string(entry, "key", key);
+ talloc_free(key);
+ }
+ }
+
+ input_unlock(ictx);
+ return root;
+}
+
+struct mp_input_src_internal {
+ mp_thread thread;
+ bool thread_running;
+ bool init_done;
+
+ char *cmd_buffer;
+ size_t cmd_buffer_size;
+ bool drop;
+};
+
+static struct mp_input_src *mp_input_add_src(struct input_ctx *ictx)
+{
+ input_lock(ictx);
+ if (ictx->num_sources == MP_MAX_SOURCES) {
+ input_unlock(ictx);
+ return NULL;
+ }
+
+ char name[80];
+ snprintf(name, sizeof(name), "#%d", ictx->num_sources + 1);
+ struct mp_input_src *src = talloc_ptrtype(NULL, src);
+ *src = (struct mp_input_src){
+ .global = ictx->global,
+ .log = mp_log_new(src, ictx->log, name),
+ .input_ctx = ictx,
+ .in = talloc_zero(src, struct mp_input_src_internal),
+ };
+
+ ictx->sources[ictx->num_sources++] = src;
+
+ input_unlock(ictx);
+ return src;
+}
+
+static void mp_input_src_kill(struct mp_input_src *src);
+
+static void close_input_sources(struct input_ctx *ictx)
+{
+ // To avoid lock-order issues, we first remove each source from the context,
+ // and then destroy it.
+ while (1) {
+ input_lock(ictx);
+ struct mp_input_src *src = ictx->num_sources ? ictx->sources[0] : NULL;
+ input_unlock(ictx);
+ if (!src)
+ break;
+ mp_input_src_kill(src);
+ }
+}
+
+static void mp_input_src_kill(struct mp_input_src *src)
+{
+ if (!src)
+ return;
+ struct input_ctx *ictx = src->input_ctx;
+ input_lock(ictx);
+ for (int n = 0; n < ictx->num_sources; n++) {
+ if (ictx->sources[n] == src) {
+ MP_TARRAY_REMOVE_AT(ictx->sources, ictx->num_sources, n);
+ input_unlock(ictx);
+ if (src->cancel)
+ src->cancel(src);
+ if (src->in->thread_running)
+ mp_thread_join(src->in->thread);
+ if (src->uninit)
+ src->uninit(src);
+ talloc_free(src);
+ return;
+ }
+ }
+ MP_ASSERT_UNREACHABLE();
+}
+
+void mp_input_src_init_done(struct mp_input_src *src)
+{
+ assert(!src->in->init_done);
+ assert(src->in->thread_running);
+ assert(mp_thread_id_equal(mp_thread_get_id(src->in->thread), mp_thread_current_id()));
+ src->in->init_done = true;
+ mp_rendezvous(&src->in->init_done, 0);
+}
+
+static MP_THREAD_VOID input_src_thread(void *ptr)
+{
+ void **args = ptr;
+ struct mp_input_src *src = args[0];
+ void (*loop_fn)(struct mp_input_src *src, void *ctx) = args[1];
+ void *ctx = args[2];
+
+ mp_thread_set_name("input");
+
+ src->in->thread_running = true;
+
+ loop_fn(src, ctx);
+
+ if (!src->in->init_done)
+ mp_rendezvous(&src->in->init_done, -1);
+
+ MP_THREAD_RETURN();
+}
+
+int mp_input_add_thread_src(struct input_ctx *ictx, void *ctx,
+ void (*loop_fn)(struct mp_input_src *src, void *ctx))
+{
+ struct mp_input_src *src = mp_input_add_src(ictx);
+ if (!src)
+ return -1;
+
+ void *args[] = {src, loop_fn, ctx};
+ if (mp_thread_create(&src->in->thread, input_src_thread, args)) {
+ mp_input_src_kill(src);
+ return -1;
+ }
+ if (mp_rendezvous(&src->in->init_done, 0) < 0) {
+ mp_input_src_kill(src);
+ return -1;
+ }
+ return 0;
+}
+
+#define CMD_BUFFER (4 * 4096)
+
+void mp_input_src_feed_cmd_text(struct mp_input_src *src, char *buf, size_t len)
+{
+ struct mp_input_src_internal *in = src->in;
+ if (!in->cmd_buffer)
+ in->cmd_buffer = talloc_size(in, CMD_BUFFER);
+ while (len) {
+ char *next = memchr(buf, '\n', len);
+ bool term = !!next;
+ next = next ? next + 1 : buf + len;
+ size_t copy = next - buf;
+ bool overflow = copy > CMD_BUFFER - in->cmd_buffer_size;
+ if (overflow || in->drop) {
+ in->cmd_buffer_size = 0;
+ in->drop = overflow || !term;
+ MP_WARN(src, "Dropping overlong line.\n");
+ } else {
+ memcpy(in->cmd_buffer + in->cmd_buffer_size, buf, copy);
+ in->cmd_buffer_size += copy;
+ buf += copy;
+ len -= copy;
+ if (term) {
+ bstr s = {in->cmd_buffer, in->cmd_buffer_size};
+ s = bstr_strip(s);
+ struct mp_cmd *cmd = mp_input_parse_cmd_str(src->log, s, "<>");
+ if (cmd)
+ mp_input_queue_cmd(src->input_ctx, cmd);
+ in->cmd_buffer_size = 0;
+ }
+ }
+ }
+}
+
+void mp_input_set_repeat_info(struct input_ctx *ictx, int rate, int delay)
+{
+ input_lock(ictx);
+ ictx->opts->ar_rate = rate;
+ ictx->opts->ar_delay = delay;
+ input_unlock(ictx);
+}
diff --git a/input/input.h b/input/input.h
new file mode 100644
index 0000000..5b5e7a9
--- /dev/null
+++ b/input/input.h
@@ -0,0 +1,239 @@
+/*
+ * This file is part of mpv.
+ *
+ * mpv is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * mpv is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with mpv. If not, see <http://www.gnu.org/licenses/>.
+ */
+
+#ifndef MPLAYER_INPUT_H
+#define MPLAYER_INPUT_H
+
+#include <stdbool.h>
+#include "misc/bstr.h"
+
+#include "cmd.h"
+
+struct input_ctx;
+struct mp_log;
+
+struct mp_input_src {
+ struct mpv_global *global;
+ struct mp_log *log;
+ struct input_ctx *input_ctx;
+
+ struct mp_input_src_internal *in;
+
+ // If not-NULL: called before destroying the input_src. Should unblock the
+ // reader loop, and make it exit. (Use with mp_input_add_thread_src().)
+ void (*cancel)(struct mp_input_src *src);
+ // Called after the reader thread returns, and cancel() won't be called
+ // again. This should make sure that nothing after this call accesses src.
+ void (*uninit)(struct mp_input_src *src);
+
+ // For free use by the implementer.
+ void *priv;
+};
+
+enum mp_input_section_flags {
+ // If a key binding is not defined in the current section, do not search the
+ // other sections for it (like the default section). Instead, an unbound
+ // key warning will be printed.
+ MP_INPUT_EXCLUSIVE = 1,
+ // Prefer it to other sections.
+ MP_INPUT_ON_TOP = 2,
+ // Let mp_input_test_dragging() return true, even if inside the mouse area.
+ MP_INPUT_ALLOW_VO_DRAGGING = 4,
+ // Don't force mouse pointer visible, even if inside the mouse area.
+ MP_INPUT_ALLOW_HIDE_CURSOR = 8,
+};
+
+// Add an input source that runs on a thread. The source is automatically
+// removed if the thread loop exits.
+// ctx: this is passed to loop_fn.
+// loop_fn: this is called once inside of a new thread, and should not return
+// until all input is read, or src->cancel is called by another thread.
+// You must call mp_input_src_init_done(src) early during init to signal
+// success (then src->cancel may be called at a later point); on failure,
+// return from loop_fn immediately.
+// Returns >=0 on success, <0 on failure to allocate resources.
+// Do not set src->cancel after mp_input_src_init_done() has been called.
+int mp_input_add_thread_src(struct input_ctx *ictx, void *ctx,
+ void (*loop_fn)(struct mp_input_src *src, void *ctx));
+
+// Signal successful init.
+// Must be called on the same thread as loop_fn (see mp_input_add_thread_src()).
+// Set src->cancel and src->uninit (if needed) before calling this.
+void mp_input_src_init_done(struct mp_input_src *src);
+
+// Feed text data, which will be split into lines of commands.
+void mp_input_src_feed_cmd_text(struct mp_input_src *src, char *buf, size_t len);
+
+// Process keyboard input. code is a key code from keycodes.h, possibly
+// with modifiers applied. MP_INPUT_RELEASE_ALL is also a valid value.
+void mp_input_put_key(struct input_ctx *ictx, int code);
+
+// Like mp_input_put_key(), but ignore mouse disable option for mouse buttons.
+void mp_input_put_key_artificial(struct input_ctx *ictx, int code);
+
+// Like mp_input_put_key(), but process all UTF-8 characters in the given
+// string as key events.
+void mp_input_put_key_utf8(struct input_ctx *ictx, int mods, struct bstr t);
+
+// Process scrolling input. Support for precise scrolling. Scales the given
+// scroll amount add multiplies it with the command (seeking, sub-delay, etc)
+void mp_input_put_wheel(struct input_ctx *ictx, int direction, double value);
+
+// Update mouse position (in window coordinates).
+void mp_input_set_mouse_pos(struct input_ctx *ictx, int x, int y);
+
+// Like mp_input_set_mouse_pos(), but ignore mouse disable option.
+void mp_input_set_mouse_pos_artificial(struct input_ctx *ictx, int x, int y);
+
+void mp_input_get_mouse_pos(struct input_ctx *ictx, int *x, int *y, int *hover);
+
+// Return whether we want/accept mouse input.
+bool mp_input_mouse_enabled(struct input_ctx *ictx);
+
+bool mp_input_vo_keyboard_enabled(struct input_ctx *ictx);
+
+/* Make mp_input_set_mouse_pos() mangle the mouse coordinates. Hack for certain
+ * VOs. dst=NULL, src=NULL reset it. src can be NULL.
+ */
+struct mp_rect;
+void mp_input_set_mouse_transform(struct input_ctx *ictx, struct mp_rect *dst,
+ struct mp_rect *src);
+
+// Add a command to the command queue.
+int mp_input_queue_cmd(struct input_ctx *ictx, struct mp_cmd *cmd);
+
+// Return next queued command, or NULL.
+struct mp_cmd *mp_input_read_cmd(struct input_ctx *ictx);
+
+// Parse text and return corresponding struct mp_cmd.
+// The location parameter is for error messages.
+struct mp_cmd *mp_input_parse_cmd(struct input_ctx *ictx, bstr str,
+ const char *location);
+
+// Set current input section. The section is appended on top of the list of
+// active sections, so its bindings are considered first. If the section was
+// already active, it's moved to the top as well.
+// name==NULL will behave as if name=="default"
+// flags is a bitfield of enum mp_input_section_flags values
+void mp_input_enable_section(struct input_ctx *ictx, char *name, int flags);
+
+// Undo mp_input_enable_section().
+// name==NULL will behave as if name=="default"
+void mp_input_disable_section(struct input_ctx *ictx, char *name);
+
+// Like mp_input_set_section(ictx, ..., 0) for all sections.
+void mp_input_disable_all_sections(struct input_ctx *ictx);
+
+// Set the contents of an input section.
+// name: name of the section, for mp_input_set_section() etc.
+// location: location string (like filename) for error reporting
+// contents: list of keybindings, like input.conf
+// a value of NULL deletes the section
+// builtin: create as builtin section; this means if the user defines bindings
+// using "{name}", they won't be ignored or overwritten - instead,
+// they are preferred to the bindings defined with this call
+// owner: string ID of the client which defined this, or NULL
+// If the section already exists, its bindings are removed and replaced.
+void mp_input_define_section(struct input_ctx *ictx, char *name, char *location,
+ char *contents, bool builtin, char *owner);
+
+// Remove all sections that have been defined by the given owner.
+void mp_input_remove_sections_by_owner(struct input_ctx *ictx, char *owner);
+
+// Define where on the screen the named input section should receive.
+// Setting a rectangle of size 0 unsets the mouse area.
+// A rectangle with negative size disables mouse input for this section.
+void mp_input_set_section_mouse_area(struct input_ctx *ictx, char *name,
+ int x0, int y0, int x1, int y1);
+
+// Used to detect mouse movement.
+unsigned int mp_input_get_mouse_event_counter(struct input_ctx *ictx);
+
+// Test whether there is any input section which wants to receive events.
+// Note that the mouse event is always delivered, even if this returns false.
+bool mp_input_test_mouse_active(struct input_ctx *ictx, int x, int y);
+
+// Whether input.c wants mouse drag events at this mouse position. If this
+// returns false, some VOs will initiate window dragging.
+bool mp_input_test_dragging(struct input_ctx *ictx, int x, int y);
+
+// Initialize the input system
+struct mpv_global;
+struct input_ctx *mp_input_init(struct mpv_global *global,
+ void (*wakeup_cb)(void *ctx),
+ void *wakeup_ctx);
+
+void mp_input_load_config(struct input_ctx *ictx);
+
+void mp_input_update_opts(struct input_ctx *ictx);
+
+void mp_input_uninit(struct input_ctx *ictx);
+
+// Return number of seconds until the next autorepeat event will be generated.
+// Returns INFINITY if no autorepeated key is active.
+double mp_input_get_delay(struct input_ctx *ictx);
+
+// Wake up sleeping input loop from another thread.
+void mp_input_wakeup(struct input_ctx *ictx);
+
+// If this returns true, use Right Alt key as Alt Gr to produce special
+// characters. If false, count Right Alt as the modifier Alt key.
+bool mp_input_use_alt_gr(struct input_ctx *ictx);
+
+// Return true if mpv should intercept keyboard media keys
+bool mp_input_use_media_keys(struct input_ctx *ictx);
+
+// Like mp_input_parse_cmd_strv, but also run the command.
+void mp_input_run_cmd(struct input_ctx *ictx, const char **cmd);
+
+// Binds a command to a key.
+void mp_input_bind_key(struct input_ctx *ictx, int key, bstr command);
+
+void mp_input_set_repeat_info(struct input_ctx *ictx, int rate, int delay);
+
+struct mpv_node mp_input_get_bindings(struct input_ctx *ictx);
+
+void mp_input_sdl_gamepad_add(struct input_ctx *ictx);
+
+struct mp_ipc_ctx;
+struct mp_client_api;
+struct mpv_handle;
+
+// Platform specific implementation, provided by ipc-*.c.
+struct mp_ipc_ctx *mp_init_ipc(struct mp_client_api *client_api,
+ struct mpv_global *global);
+// Start a thread for the given handle and return a socket in out_fd[0] that
+// is served by this thread. If the FD is not full-duplex, then out_fd[0] is
+// the user's read-end, and out_fd[1] the write-end, otherwise out_fd[1] is set
+// to -1.
+// returns:
+// true: out_fd[0] and out_fd[1] are set, ownership of h is transferred
+// false: out_fd are not touched, caller retains ownership of h
+bool mp_ipc_start_anon_client(struct mp_ipc_ctx *ctx, struct mpv_handle *h,
+ int out_fd[2]);
+void mp_uninit_ipc(struct mp_ipc_ctx *ctx);
+
+// Serialize the given mpv_event structure to JSON. Returns an allocated string.
+struct mpv_event;
+char *mp_json_encode_event(struct mpv_event *event);
+
+// Given the raw IPC input buffer "buf", remove the first newline-separated
+// command, execute it and return the result (if any) as an allocated string.
+struct mpv_handle;
+char *mp_ipc_consume_next_command(struct mpv_handle *client, void *ctx, bstr *buf);
+
+#endif /* MPLAYER_INPUT_H */
diff --git a/input/ipc-dummy.c b/input/ipc-dummy.c
new file mode 100644
index 0000000..f0232b2
--- /dev/null
+++ b/input/ipc-dummy.c
@@ -0,0 +1,19 @@
+#include <stddef.h>
+
+#include "input/input.h"
+
+struct mp_ipc_ctx *mp_init_ipc(struct mp_client_api *client_api,
+ struct mpv_global *global)
+{
+ return NULL;
+}
+
+bool mp_ipc_start_anon_client(struct mp_ipc_ctx *ctx, struct mpv_handle *h,
+ int out_fd[2])
+{
+ return false;
+}
+
+void mp_uninit_ipc(struct mp_ipc_ctx *ctx)
+{
+}
diff --git a/input/ipc-unix.c b/input/ipc-unix.c
new file mode 100644
index 0000000..a416b54
--- /dev/null
+++ b/input/ipc-unix.c
@@ -0,0 +1,444 @@
+/*
+ * This file is part of mpv.
+ *
+ * mpv is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * mpv is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with mpv. If not, see <http://www.gnu.org/licenses/>.
+ */
+
+#include <errno.h>
+#include <unistd.h>
+#include <limits.h>
+#include <poll.h>
+#include <signal.h>
+#include <sys/types.h>
+#include <sys/socket.h>
+#include <sys/stat.h>
+#include <sys/un.h>
+
+#include "osdep/io.h"
+#include "osdep/threads.h"
+
+#include "common/common.h"
+#include "common/global.h"
+#include "common/msg.h"
+#include "input/input.h"
+#include "libmpv/client.h"
+#include "options/m_config.h"
+#include "options/options.h"
+#include "options/path.h"
+#include "player/client.h"
+
+#ifndef MSG_NOSIGNAL
+#define MSG_NOSIGNAL 0
+#endif
+
+struct mp_ipc_ctx {
+ struct mp_log *log;
+ struct mp_client_api *client_api;
+ const char *path;
+
+ mp_thread thread;
+ int death_pipe[2];
+};
+
+struct client_arg {
+ struct mp_log *log;
+ struct mpv_handle *client;
+
+ const char *client_name;
+ int client_fd;
+ bool close_client_fd;
+ bool quit_on_close;
+
+ bool writable;
+};
+
+static int ipc_write_str(struct client_arg *client, const char *buf)
+{
+ size_t count = strlen(buf);
+ while (count > 0) {
+ ssize_t rc = send(client->client_fd, buf, count, MSG_NOSIGNAL);
+ if (rc <= 0) {
+ if (rc == 0)
+ return -1;
+
+ if (errno == EBADF || errno == ENOTSOCK) {
+ client->writable = false;
+ return 0;
+ }
+
+ if (errno == EINTR || errno == EAGAIN)
+ continue;
+
+ return rc;
+ }
+
+ count -= rc;
+ buf += rc;
+ }
+
+ return 0;
+}
+
+static MP_THREAD_VOID client_thread(void *p)
+{
+ // We don't use MSG_NOSIGNAL because the moldy fruit OS doesn't support it.
+ struct sigaction sa = { .sa_handler = SIG_IGN, .sa_flags = SA_RESTART };
+ sigfillset(&sa.sa_mask);
+ sigaction(SIGPIPE, &sa, NULL);
+
+ int rc;
+
+ struct client_arg *arg = p;
+ bstr client_msg = { talloc_strdup(NULL, ""), 0 };
+
+ char *tname = talloc_asprintf(NULL, "ipc/%s", arg->client_name);
+ mp_thread_set_name(tname);
+ talloc_free(tname);
+
+ int pipe_fd = mpv_get_wakeup_pipe(arg->client);
+ if (pipe_fd < 0) {
+ MP_ERR(arg, "Could not get wakeup pipe\n");
+ goto done;
+ }
+
+ MP_VERBOSE(arg, "Client connected\n");
+
+ struct pollfd fds[2] = {
+ {.events = POLLIN, .fd = pipe_fd},
+ {.events = POLLIN, .fd = arg->client_fd},
+ };
+
+ fcntl(arg->client_fd, F_SETFL, fcntl(arg->client_fd, F_GETFL, 0) | O_NONBLOCK);
+
+ while (1) {
+ rc = poll(fds, 2, 0);
+ if (rc == 0)
+ rc = poll(fds, 2, -1);
+ if (rc < 0) {
+ MP_ERR(arg, "Poll error\n");
+ continue;
+ }
+
+ if (fds[0].revents & POLLIN) {
+ mp_flush_wakeup_pipe(pipe_fd);
+
+ while (1) {
+ mpv_event *event = mpv_wait_event(arg->client, 0);
+
+ if (event->event_id == MPV_EVENT_NONE)
+ break;
+
+ if (event->event_id == MPV_EVENT_SHUTDOWN)
+ goto done;
+
+ if (!arg->writable)
+ continue;
+
+ char *event_msg = mp_json_encode_event(event);
+ if (!event_msg) {
+ MP_ERR(arg, "Encoding error\n");
+ goto done;
+ }
+
+ rc = ipc_write_str(arg, event_msg);
+ talloc_free(event_msg);
+ if (rc < 0) {
+ MP_ERR(arg, "Write error (%s)\n", mp_strerror(errno));
+ goto done;
+ }
+ }
+ }
+
+ if (fds[1].revents & (POLLIN | POLLHUP | POLLNVAL)) {
+ while (1) {
+ char buf[128];
+ bstr append = { buf, 0 };
+
+ ssize_t bytes = read(arg->client_fd, buf, sizeof(buf));
+ if (bytes < 0) {
+ if (errno == EAGAIN)
+ break;
+
+ MP_ERR(arg, "Read error (%s)\n", mp_strerror(errno));
+ goto done;
+ }
+
+ if (bytes == 0) {
+ MP_VERBOSE(arg, "Client disconnected\n");
+ goto done;
+ }
+
+ append.len = bytes;
+
+ bstr_xappend(NULL, &client_msg, append);
+
+ while (bstrchr(client_msg, '\n') != -1) {
+ char *reply_msg = mp_ipc_consume_next_command(arg->client,
+ NULL, &client_msg);
+
+ if (reply_msg && arg->writable) {
+ rc = ipc_write_str(arg, reply_msg);
+ if (rc < 0) {
+ MP_ERR(arg, "Write error (%s)\n", mp_strerror(errno));
+ talloc_free(reply_msg);
+ goto done;
+ }
+ }
+
+ talloc_free(reply_msg);
+ }
+ }
+ }
+ }
+
+done:
+ if (client_msg.len > 0)
+ MP_WARN(arg, "Ignoring unterminated command on disconnect.\n");
+ talloc_free(client_msg.start);
+ if (arg->close_client_fd)
+ close(arg->client_fd);
+ struct mpv_handle *h = arg->client;
+ bool quit = arg->quit_on_close;
+ talloc_free(arg);
+ if (quit) {
+ mpv_terminate_destroy(h);
+ } else {
+ mpv_destroy(h);
+ }
+ MP_THREAD_RETURN();
+}
+
+static bool ipc_start_client(struct mp_ipc_ctx *ctx, struct client_arg *client,
+ bool free_on_init_fail)
+{
+ if (!client->client)
+ client->client = mp_new_client(ctx->client_api, client->client_name);
+ if (!client->client)
+ goto err;
+
+ client->log = mp_client_get_log(client->client);
+
+ mp_thread client_thr;
+ if (mp_thread_create(&client_thr, client_thread, client))
+ goto err;
+ mp_thread_detach(client_thr);
+
+ return true;
+
+err:
+ if (free_on_init_fail) {
+ if (client->client)
+ mpv_destroy(client->client);
+
+ if (client->close_client_fd)
+ close(client->client_fd);
+ }
+
+ talloc_free(client);
+ return false;
+}
+
+static void ipc_start_client_json(struct mp_ipc_ctx *ctx, int id, int fd)
+{
+ struct client_arg *client = talloc_ptrtype(NULL, client);
+ *client = (struct client_arg){
+ .client_name =
+ id >= 0 ? talloc_asprintf(client, "ipc-%d", id) : "ipc",
+ .client_fd = fd,
+ .close_client_fd = id >= 0,
+ .quit_on_close = id < 0,
+ .writable = true,
+ };
+
+ ipc_start_client(ctx, client, true);
+}
+
+bool mp_ipc_start_anon_client(struct mp_ipc_ctx *ctx, struct mpv_handle *h,
+ int out_fd[2])
+{
+ int pair[2];
+ if (socketpair(AF_UNIX, SOCK_STREAM, 0, pair))
+ return false;
+ mp_set_cloexec(pair[0]);
+ mp_set_cloexec(pair[1]);
+
+ struct client_arg *client = talloc_ptrtype(NULL, client);
+ *client = (struct client_arg){
+ .client = h,
+ .client_name = mpv_client_name(h),
+ .client_fd = pair[1],
+ .close_client_fd = true,
+ .writable = true,
+ };
+
+ if (!ipc_start_client(ctx, client, false)) {
+ close(pair[0]);
+ close(pair[1]);
+ return false;
+ }
+
+ out_fd[0] = pair[0];
+ out_fd[1] = -1;
+ return true;
+}
+
+static MP_THREAD_VOID ipc_thread(void *p)
+{
+ int rc;
+
+ int ipc_fd;
+ struct sockaddr_un ipc_un = {0};
+
+ struct mp_ipc_ctx *arg = p;
+
+ mp_thread_set_name("ipc/socket");
+
+ MP_VERBOSE(arg, "Starting IPC master\n");
+
+ ipc_fd = socket(AF_UNIX, SOCK_STREAM, 0);
+ if (ipc_fd < 0) {
+ MP_ERR(arg, "Could not create IPC socket\n");
+ goto done;
+ }
+
+ fchmod(ipc_fd, 0600);
+
+ size_t path_len = strlen(arg->path);
+ if (path_len >= sizeof(ipc_un.sun_path) - 1) {
+ MP_ERR(arg, "Could not create IPC socket\n");
+ goto done;
+ }
+
+ ipc_un.sun_family = AF_UNIX,
+ strncpy(ipc_un.sun_path, arg->path, sizeof(ipc_un.sun_path) - 1);
+
+ unlink(ipc_un.sun_path);
+
+ if (ipc_un.sun_path[0] == '@') {
+ ipc_un.sun_path[0] = '\0';
+ path_len--;
+ }
+
+ size_t addr_len = offsetof(struct sockaddr_un, sun_path) + 1 + path_len;
+ rc = bind(ipc_fd, (struct sockaddr *) &ipc_un, addr_len);
+ if (rc < 0) {
+ MP_ERR(arg, "Could not bind IPC socket\n");
+ goto done;
+ }
+
+ rc = listen(ipc_fd, 10);
+ if (rc < 0) {
+ MP_ERR(arg, "Could not listen on IPC socket\n");
+ goto done;
+ }
+
+ MP_VERBOSE(arg, "Listening to IPC socket.\n");
+
+ int client_num = 0;
+
+ struct pollfd fds[2] = {
+ {.events = POLLIN, .fd = arg->death_pipe[0]},
+ {.events = POLLIN, .fd = ipc_fd},
+ };
+
+ while (1) {
+ rc = poll(fds, 2, -1);
+ if (rc < 0) {
+ MP_ERR(arg, "Poll error\n");
+ continue;
+ }
+
+ if (fds[0].revents & POLLIN)
+ goto done;
+
+ if (fds[1].revents & POLLIN) {
+ int client_fd = accept(ipc_fd, NULL, NULL);
+ if (client_fd < 0) {
+ MP_ERR(arg, "Could not accept IPC client\n");
+ goto done;
+ }
+
+ ipc_start_client_json(arg, client_num++, client_fd);
+ }
+ }
+
+done:
+ if (ipc_fd >= 0)
+ close(ipc_fd);
+
+ MP_THREAD_RETURN();
+}
+
+struct mp_ipc_ctx *mp_init_ipc(struct mp_client_api *client_api,
+ struct mpv_global *global)
+{
+ struct MPOpts *opts = mp_get_config_group(NULL, global, &mp_opt_root);
+
+ struct mp_ipc_ctx *arg = talloc_ptrtype(NULL, arg);
+ *arg = (struct mp_ipc_ctx){
+ .log = mp_log_new(arg, global->log, "ipc"),
+ .client_api = client_api,
+ .path = mp_get_user_path(arg, global, opts->ipc_path),
+ .death_pipe = {-1, -1},
+ };
+
+ if (opts->ipc_client && opts->ipc_client[0]) {
+ int fd = -1;
+ if (strncmp(opts->ipc_client, "fd://", 5) == 0) {
+ char *end;
+ unsigned long l = strtoul(opts->ipc_client + 5, &end, 0);
+ if (!end[0] && l <= INT_MAX)
+ fd = l;
+ }
+ if (fd < 0) {
+ MP_ERR(arg, "Invalid IPC client argument: '%s'\n", opts->ipc_client);
+ } else {
+ ipc_start_client_json(arg, -1, fd);
+ }
+ }
+
+ talloc_free(opts);
+
+ if (!arg->path || !arg->path[0])
+ goto out;
+
+ if (mp_make_wakeup_pipe(arg->death_pipe) < 0)
+ goto out;
+
+ if (mp_thread_create(&arg->thread, ipc_thread, arg))
+ goto out;
+
+ return arg;
+
+out:
+ if (arg->death_pipe[0] >= 0) {
+ close(arg->death_pipe[0]);
+ close(arg->death_pipe[1]);
+ }
+ talloc_free(arg);
+ return NULL;
+}
+
+void mp_uninit_ipc(struct mp_ipc_ctx *arg)
+{
+ if (!arg)
+ return;
+
+ (void)write(arg->death_pipe[1], &(char){0}, 1);
+ mp_thread_join(arg->thread);
+
+ close(arg->death_pipe[0]);
+ close(arg->death_pipe[1]);
+ talloc_free(arg);
+}
diff --git a/input/ipc-win.c b/input/ipc-win.c
new file mode 100644
index 0000000..b0200ea
--- /dev/null
+++ b/input/ipc-win.c
@@ -0,0 +1,509 @@
+/*
+ * This file is part of mpv.
+ *
+ * mpv is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * mpv is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with mpv. If not, see <http://www.gnu.org/licenses/>.
+ */
+
+#include <windows.h>
+#include <sddl.h>
+
+#include "osdep/io.h"
+#include "osdep/threads.h"
+#include "osdep/windows_utils.h"
+
+#include "common/common.h"
+#include "common/global.h"
+#include "common/msg.h"
+#include "input/input.h"
+#include "libmpv/client.h"
+#include "options/m_config.h"
+#include "options/options.h"
+#include "player/client.h"
+
+struct mp_ipc_ctx {
+ struct mp_log *log;
+ struct mp_client_api *client_api;
+ const wchar_t *path;
+
+ mp_thread thread;
+ HANDLE death_event;
+};
+
+struct client_arg {
+ struct mp_log *log;
+ struct mpv_handle *client;
+
+ char *client_name;
+ HANDLE client_h;
+ bool writable;
+ OVERLAPPED write_ol;
+};
+
+// Get a string SID representing the current user. Must be freed by LocalFree.
+static char *get_user_sid(void)
+{
+ char *ssid = NULL;
+ TOKEN_USER *info = NULL;
+ HANDLE t;
+ if (!OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &t))
+ goto done;
+
+ DWORD info_len;
+ if (!GetTokenInformation(t, TokenUser, NULL, 0, &info_len) &&
+ GetLastError() != ERROR_INSUFFICIENT_BUFFER)
+ goto done;
+
+ info = talloc_size(NULL, info_len);
+ if (!GetTokenInformation(t, TokenUser, info, info_len, &info_len))
+ goto done;
+ if (!info->User.Sid)
+ goto done;
+
+ ConvertSidToStringSidA(info->User.Sid, &ssid);
+done:
+ if (t)
+ CloseHandle(t);
+ talloc_free(info);
+ return ssid;
+}
+
+// Get a string SID for the process integrity level. Must be freed by LocalFree.
+static char *get_integrity_sid(void)
+{
+ char *ssid = NULL;
+ TOKEN_MANDATORY_LABEL *info = NULL;
+ HANDLE t;
+ if (!OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &t))
+ goto done;
+
+ DWORD info_len;
+ if (!GetTokenInformation(t, TokenIntegrityLevel, NULL, 0, &info_len) &&
+ GetLastError() != ERROR_INSUFFICIENT_BUFFER)
+ goto done;
+
+ info = talloc_size(NULL, info_len);
+ if (!GetTokenInformation(t, TokenIntegrityLevel, info, info_len, &info_len))
+ goto done;
+ if (!info->Label.Sid)
+ goto done;
+
+ ConvertSidToStringSidA(info->Label.Sid, &ssid);
+done:
+ if (t)
+ CloseHandle(t);
+ talloc_free(info);
+ return ssid;
+}
+
+// Create a security descriptor that only grants access to processes running
+// under the current user at the current integrity level or higher
+static PSECURITY_DESCRIPTOR create_restricted_sd(void)
+{
+ char *user_sid = get_user_sid();
+ char *integrity_sid = get_integrity_sid();
+ if (!user_sid || !integrity_sid)
+ return NULL;
+
+ char *sddl = talloc_asprintf(NULL,
+ "O:%s" // Set the owner to user_sid
+ "D:(A;;GRGW;;;%s)" // Grant GENERIC_{READ,WRITE} access to user_sid
+ "S:(ML;;NRNWNX;;;%s)", // Disallow read, write and execute permissions
+ // to integrity levels below integrity_sid
+ user_sid, user_sid, integrity_sid);
+ LocalFree(user_sid);
+ LocalFree(integrity_sid);
+
+ PSECURITY_DESCRIPTOR sd = NULL;
+ ConvertStringSecurityDescriptorToSecurityDescriptorA(sddl, SDDL_REVISION_1,
+ &sd, NULL);
+ talloc_free(sddl);
+
+ return sd;
+}
+
+static void wakeup_cb(void *d)
+{
+ HANDLE event = d;
+ SetEvent(event);
+}
+
+// Wrapper for ReadFile that treats ERROR_IO_PENDING as success
+static DWORD async_read(HANDLE file, void *buf, unsigned size, OVERLAPPED* ol)
+{
+ DWORD err = ReadFile(file, buf, size, NULL, ol) ? 0 : GetLastError();
+ return err == ERROR_IO_PENDING ? 0 : err;
+}
+
+// Wrapper for WriteFile that treats ERROR_IO_PENDING as success
+static DWORD async_write(HANDLE file, const void *buf, unsigned size, OVERLAPPED* ol)
+{
+ DWORD err = WriteFile(file, buf, size, NULL, ol) ? 0 : GetLastError();
+ return err == ERROR_IO_PENDING ? 0 : err;
+}
+
+static bool pipe_error_is_fatal(DWORD error)
+{
+ switch (error) {
+ case 0:
+ case ERROR_HANDLE_EOF:
+ case ERROR_BROKEN_PIPE:
+ case ERROR_PIPE_NOT_CONNECTED:
+ case ERROR_NO_DATA:
+ return false;
+ }
+ return true;
+}
+
+static DWORD ipc_write_str(struct client_arg *arg, const char *buf)
+{
+ DWORD error = 0;
+
+ if ((error = async_write(arg->client_h, buf, strlen(buf), &arg->write_ol)))
+ goto done;
+ if (!GetOverlappedResult(arg->client_h, &arg->write_ol, &(DWORD){0}, TRUE)) {
+ error = GetLastError();
+ goto done;
+ }
+
+done:
+ if (pipe_error_is_fatal(error)) {
+ MP_VERBOSE(arg, "Error writing to pipe: %s\n",
+ mp_HRESULT_to_str(HRESULT_FROM_WIN32(error)));
+ }
+
+ if (error)
+ arg->writable = false;
+ return error;
+}
+
+static void report_read_error(struct client_arg *arg, DWORD error)
+{
+ // Only report the error if it's not just due to the pipe closing
+ if (pipe_error_is_fatal(error)) {
+ MP_ERR(arg, "Error reading from pipe: %s\n",
+ mp_HRESULT_to_str(HRESULT_FROM_WIN32(error)));
+ } else {
+ MP_VERBOSE(arg, "Client disconnected\n");
+ }
+}
+
+static MP_THREAD_VOID client_thread(void *p)
+{
+ struct client_arg *arg = p;
+ char buf[4096];
+ HANDLE wakeup_event = CreateEventW(NULL, TRUE, FALSE, NULL);
+ OVERLAPPED ol = { .hEvent = CreateEventW(NULL, TRUE, TRUE, NULL) };
+ bstr client_msg = { talloc_strdup(NULL, ""), 0 };
+ DWORD ioerr = 0;
+ DWORD r;
+
+ char *tname = talloc_asprintf(NULL, "ipc/%s", arg->client_name);
+ mp_thread_set_name(tname);
+ talloc_free(tname);
+
+ arg->write_ol.hEvent = CreateEventW(NULL, TRUE, TRUE, NULL);
+ if (!wakeup_event || !ol.hEvent || !arg->write_ol.hEvent) {
+ MP_ERR(arg, "Couldn't create events\n");
+ goto done;
+ }
+
+ MP_VERBOSE(arg, "Client connected\n");
+
+ mpv_set_wakeup_callback(arg->client, wakeup_cb, wakeup_event);
+
+ // Do the first read operation on the pipe
+ if ((ioerr = async_read(arg->client_h, buf, 4096, &ol))) {
+ report_read_error(arg, ioerr);
+ goto done;
+ }
+
+ while (1) {
+ HANDLE handles[] = { wakeup_event, ol.hEvent };
+ int n = WaitForMultipleObjects(2, handles, FALSE, 0);
+ if (n == WAIT_TIMEOUT)
+ n = WaitForMultipleObjects(2, handles, FALSE, INFINITE);
+
+ switch (n) {
+ case WAIT_OBJECT_0: // wakeup_event
+ ResetEvent(wakeup_event);
+
+ while (1) {
+ mpv_event *event = mpv_wait_event(arg->client, 0);
+
+ if (event->event_id == MPV_EVENT_NONE)
+ break;
+
+ if (event->event_id == MPV_EVENT_SHUTDOWN)
+ goto done;
+
+ if (!arg->writable)
+ continue;
+
+ char *event_msg = mp_json_encode_event(event);
+ if (!event_msg) {
+ MP_ERR(arg, "Encoding error\n");
+ goto done;
+ }
+
+ ipc_write_str(arg, event_msg);
+ talloc_free(event_msg);
+ }
+
+ break;
+ case WAIT_OBJECT_0 + 1: // ol.hEvent
+ // Complete the read operation on the pipe
+ if (!GetOverlappedResult(arg->client_h, &ol, &r, TRUE)) {
+ report_read_error(arg, GetLastError());
+ goto done;
+ }
+
+ bstr_xappend(NULL, &client_msg, (bstr){buf, r});
+ while (bstrchr(client_msg, '\n') != -1) {
+ char *reply_msg = mp_ipc_consume_next_command(arg->client,
+ NULL, &client_msg);
+ if (reply_msg && arg->writable)
+ ipc_write_str(arg, reply_msg);
+ talloc_free(reply_msg);
+ }
+
+ // Begin the next read operation on the pipe
+ if ((ioerr = async_read(arg->client_h, buf, 4096, &ol))) {
+ report_read_error(arg, ioerr);
+ goto done;
+ }
+ break;
+ default:
+ MP_ERR(arg, "WaitForMultipleObjects failed\n");
+ goto done;
+ }
+ }
+
+done:
+ if (client_msg.len > 0)
+ MP_WARN(arg, "Ignoring unterminated command on disconnect.\n");
+
+ if (CancelIoEx(arg->client_h, &ol) || GetLastError() != ERROR_NOT_FOUND)
+ GetOverlappedResult(arg->client_h, &ol, &(DWORD){0}, TRUE);
+ if (wakeup_event)
+ CloseHandle(wakeup_event);
+ if (ol.hEvent)
+ CloseHandle(ol.hEvent);
+ if (arg->write_ol.hEvent)
+ CloseHandle(arg->write_ol.hEvent);
+
+ CloseHandle(arg->client_h);
+ mpv_destroy(arg->client);
+ talloc_free(arg);
+ MP_THREAD_RETURN();
+}
+
+static void ipc_start_client(struct mp_ipc_ctx *ctx, struct client_arg *client)
+{
+ client->client = mp_new_client(ctx->client_api, client->client_name),
+ client->log = mp_client_get_log(client->client);
+
+ mp_thread client_thr;
+ if (mp_thread_create(&client_thr, client_thread, client)) {
+ mpv_destroy(client->client);
+ CloseHandle(client->client_h);
+ talloc_free(client);
+ }
+ mp_thread_detach(client_thr);
+}
+
+static void ipc_start_client_json(struct mp_ipc_ctx *ctx, int id, HANDLE h)
+{
+ struct client_arg *client = talloc_ptrtype(NULL, client);
+ *client = (struct client_arg){
+ .client_name = talloc_asprintf(client, "ipc-%d", id),
+ .client_h = h,
+ .writable = true,
+ };
+
+ ipc_start_client(ctx, client);
+}
+
+bool mp_ipc_start_anon_client(struct mp_ipc_ctx *ctx, struct mpv_handle *h,
+ int out_fd[2])
+{
+ return false;
+}
+
+static MP_THREAD_VOID ipc_thread(void *p)
+{
+ // Use PIPE_TYPE_MESSAGE | PIPE_READMODE_BYTE so message framing is
+ // maintained for message-mode clients, but byte-mode clients can still
+ // connect, send and receive data. This is the most compatible mode.
+ static const DWORD state =
+ PIPE_TYPE_MESSAGE | PIPE_READMODE_BYTE | PIPE_WAIT |
+ PIPE_REJECT_REMOTE_CLIENTS;
+ static const DWORD mode =
+ PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED;
+ static const DWORD bufsiz = 4096;
+
+ struct mp_ipc_ctx *arg = p;
+ HANDLE server = INVALID_HANDLE_VALUE;
+ HANDLE client = INVALID_HANDLE_VALUE;
+ int client_num = 0;
+
+ mp_thread_set_name("ipc/named-pipe");
+ MP_VERBOSE(arg, "Starting IPC master\n");
+
+ OVERLAPPED ol = {0};
+ SECURITY_ATTRIBUTES sa = {
+ .nLength = sizeof sa,
+ .lpSecurityDescriptor = create_restricted_sd(),
+ };
+ if (!sa.lpSecurityDescriptor) {
+ MP_ERR(arg, "Couldn't create security descriptor");
+ goto done;
+ }
+
+ ol = (OVERLAPPED){ .hEvent = CreateEventW(NULL, TRUE, TRUE, NULL) };
+ if (!ol.hEvent) {
+ MP_ERR(arg, "Couldn't create event");
+ goto done;
+ }
+
+ server = CreateNamedPipeW(arg->path, mode | FILE_FLAG_FIRST_PIPE_INSTANCE,
+ state, PIPE_UNLIMITED_INSTANCES, bufsiz, bufsiz, 0, &sa);
+ if (server == INVALID_HANDLE_VALUE) {
+ MP_ERR(arg, "Couldn't create first pipe instance: %s\n",
+ mp_LastError_to_str());
+ goto done;
+ }
+
+ MP_VERBOSE(arg, "Listening to IPC pipe.\n");
+
+ while (1) {
+ DWORD err = ConnectNamedPipe(server, &ol) ? 0 : GetLastError();
+
+ if (err == ERROR_IO_PENDING) {
+ int n = WaitForMultipleObjects(2, (HANDLE[]) {
+ arg->death_event,
+ ol.hEvent,
+ }, FALSE, INFINITE) - WAIT_OBJECT_0;
+
+ switch (n) {
+ case 0:
+ // Stop waiting for new clients
+ CancelIo(server);
+ GetOverlappedResult(server, &ol, &(DWORD){0}, TRUE);
+ goto done;
+ case 1:
+ // Complete the ConnectNamedPipe request
+ err = GetOverlappedResult(server, &ol, &(DWORD){0}, TRUE)
+ ? 0 : GetLastError();
+ break;
+ default:
+ MP_ERR(arg, "WaitForMultipleObjects failed\n");
+ goto done;
+ }
+ }
+
+ // ERROR_PIPE_CONNECTED is returned if a client connects before
+ // ConnectNamedPipe is called. ERROR_NO_DATA is returned if a client
+ // connects, (possibly) writes data and exits before ConnectNamedPipe
+ // is called. Both cases should be handled as normal connections.
+ if (err == ERROR_PIPE_CONNECTED || err == ERROR_NO_DATA)
+ err = 0;
+
+ if (err) {
+ MP_ERR(arg, "ConnectNamedPipe failed: %s\n",
+ mp_HRESULT_to_str(HRESULT_FROM_WIN32(err)));
+ goto done;
+ }
+
+ // Create the next pipe instance before the client thread to avoid the
+ // theoretical race condition where the client thread immediately
+ // closes the handle and there are no active instances of the pipe
+ client = server;
+ server = CreateNamedPipeW(arg->path, mode, state,
+ PIPE_UNLIMITED_INSTANCES, bufsiz, bufsiz, 0, &sa);
+ if (server == INVALID_HANDLE_VALUE) {
+ MP_ERR(arg, "Couldn't create additional pipe instance: %s\n",
+ mp_LastError_to_str());
+ goto done;
+ }
+
+ ipc_start_client_json(arg, client_num++, client);
+ client = NULL;
+ }
+
+done:
+ if (sa.lpSecurityDescriptor)
+ LocalFree(sa.lpSecurityDescriptor);
+ if (client != INVALID_HANDLE_VALUE)
+ CloseHandle(client);
+ if (server != INVALID_HANDLE_VALUE)
+ CloseHandle(server);
+ if (ol.hEvent)
+ CloseHandle(ol.hEvent);
+ MP_THREAD_RETURN();
+}
+
+struct mp_ipc_ctx *mp_init_ipc(struct mp_client_api *client_api,
+ struct mpv_global *global)
+{
+ struct MPOpts *opts = mp_get_config_group(NULL, global, &mp_opt_root);
+
+ struct mp_ipc_ctx *arg = talloc_ptrtype(NULL, arg);
+ *arg = (struct mp_ipc_ctx){
+ .log = mp_log_new(arg, global->log, "ipc"),
+ .client_api = client_api,
+ };
+
+ if (!opts->ipc_path || !*opts->ipc_path)
+ goto out;
+
+ // Ensure the path is a legal Win32 pipe name by prepending \\.\pipe\ if
+ // it's not already present. Qt's QLocalSocket uses the same logic, so
+ // cross-platform programs that use paths like /tmp/mpv-socket should just
+ // work. (Win32 converts this path to \Device\NamedPipe\tmp\mpv-socket)
+ if (!strncmp(opts->ipc_path, "\\\\.\\pipe\\", 9)) {
+ arg->path = mp_from_utf8(arg, opts->ipc_path);
+ } else {
+ char *path = talloc_asprintf(NULL, "\\\\.\\pipe\\%s", opts->ipc_path);
+ arg->path = mp_from_utf8(arg, path);
+ talloc_free(path);
+ }
+
+ if (!(arg->death_event = CreateEventW(NULL, TRUE, FALSE, NULL)))
+ goto out;
+
+ if (mp_thread_create(&arg->thread, ipc_thread, arg))
+ goto out;
+
+ talloc_free(opts);
+ return arg;
+
+out:
+ if (arg->death_event)
+ CloseHandle(arg->death_event);
+ talloc_free(arg);
+ talloc_free(opts);
+ return NULL;
+}
+
+void mp_uninit_ipc(struct mp_ipc_ctx *arg)
+{
+ if (!arg)
+ return;
+
+ SetEvent(arg->death_event);
+ mp_thread_join(arg->thread);
+
+ CloseHandle(arg->death_event);
+ talloc_free(arg);
+}
diff --git a/input/ipc.c b/input/ipc.c
new file mode 100644
index 0000000..ea69fb7
--- /dev/null
+++ b/input/ipc.c
@@ -0,0 +1,414 @@
+/*
+ * This file is part of mpv.
+ *
+ * mpv is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * mpv is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with mpv. If not, see <http://www.gnu.org/licenses/>.
+ */
+
+#include "common/msg.h"
+#include "input/input.h"
+#include "misc/json.h"
+#include "misc/node.h"
+#include "options/m_option.h"
+#include "options/options.h"
+#include "options/path.h"
+#include "player/client.h"
+
+static mpv_node *mpv_node_array_get(mpv_node *src, int index)
+{
+ if (src->format != MPV_FORMAT_NODE_ARRAY)
+ return NULL;
+
+ if (src->u.list->num < (index + 1))
+ return NULL;
+
+ return &src->u.list->values[index];
+}
+
+static void mpv_node_map_add(void *ta_parent, mpv_node *src, const char *key, mpv_node *val)
+{
+ if (src->format != MPV_FORMAT_NODE_MAP)
+ return;
+
+ if (!src->u.list)
+ src->u.list = talloc_zero(ta_parent, mpv_node_list);
+
+ MP_TARRAY_GROW(src->u.list, src->u.list->keys, src->u.list->num);
+ MP_TARRAY_GROW(src->u.list, src->u.list->values, src->u.list->num);
+
+ src->u.list->keys[src->u.list->num] = talloc_strdup(ta_parent, key);
+
+ static const struct m_option type = { .type = CONF_TYPE_NODE };
+ m_option_get_node(&type, ta_parent, &src->u.list->values[src->u.list->num], val);
+
+ src->u.list->num++;
+}
+
+static void mpv_node_map_add_null(void *ta_parent, mpv_node *src, const char *key)
+{
+ mpv_node val_node = {.format = MPV_FORMAT_NONE};
+ mpv_node_map_add(ta_parent, src, key, &val_node);
+}
+
+static void mpv_node_map_add_int64(void *ta_parent, mpv_node *src, const char *key, int64_t val)
+{
+ mpv_node val_node = {.format = MPV_FORMAT_INT64, .u.int64 = val};
+ mpv_node_map_add(ta_parent, src, key, &val_node);
+}
+
+static void mpv_node_map_add_string(void *ta_parent, mpv_node *src, const char *key, const char *val)
+{
+ mpv_node val_node = {.format = MPV_FORMAT_STRING, .u.string = (char*)val};
+ mpv_node_map_add(ta_parent, src, key, &val_node);
+}
+
+// This is supposed to write a reply that looks like "normal" command execution.
+static void mpv_format_command_reply(void *ta_parent, mpv_event *event,
+ mpv_node *dst)
+{
+ assert(event->event_id == MPV_EVENT_COMMAND_REPLY);
+ mpv_event_command *cmd = event->data;
+
+ mpv_node_map_add_int64(ta_parent, dst, "request_id", event->reply_userdata);
+
+ mpv_node_map_add_string(ta_parent, dst, "error",
+ mpv_error_string(event->error));
+
+ mpv_node_map_add(ta_parent, dst, "data", &cmd->result);
+}
+
+char *mp_json_encode_event(mpv_event *event)
+{
+ void *ta_parent = talloc_new(NULL);
+
+ struct mpv_node event_node;
+ if (event->event_id == MPV_EVENT_COMMAND_REPLY) {
+ event_node = (mpv_node){.format = MPV_FORMAT_NODE_MAP, .u.list = NULL};
+ mpv_format_command_reply(ta_parent, event, &event_node);
+ } else {
+ mpv_event_to_node(&event_node, event);
+ // Abuse mpv_event_to_node() internals.
+ talloc_steal(ta_parent, node_get_alloc(&event_node));
+ }
+
+ char *output = talloc_strdup(NULL, "");
+ json_write(&output, &event_node);
+ output = ta_talloc_strdup_append(output, "\n");
+
+ talloc_free(ta_parent);
+
+ return output;
+}
+
+// Function is allowed to modify src[n].
+static char *json_execute_command(struct mpv_handle *client, void *ta_parent,
+ char *src)
+{
+ int rc;
+ const char *cmd = NULL;
+ struct mp_log *log = mp_client_get_log(client);
+
+ mpv_node msg_node;
+ mpv_node reply_node = {.format = MPV_FORMAT_NODE_MAP, .u.list = NULL};
+ mpv_node *reqid_node = NULL;
+ int64_t reqid = 0;
+ mpv_node *async_node = NULL;
+ bool async = false;
+ bool send_reply = true;
+
+ rc = json_parse(ta_parent, &msg_node, &src, MAX_JSON_DEPTH);
+ if (rc < 0) {
+ mp_err(log, "malformed JSON received: '%s'\n", src);
+ rc = MPV_ERROR_INVALID_PARAMETER;
+ goto error;
+ }
+
+ if (msg_node.format != MPV_FORMAT_NODE_MAP) {
+ rc = MPV_ERROR_INVALID_PARAMETER;
+ goto error;
+ }
+
+ async_node = node_map_get(&msg_node, "async");
+ if (async_node) {
+ if (async_node->format != MPV_FORMAT_FLAG) {
+ rc = MPV_ERROR_INVALID_PARAMETER;
+ goto error;
+ }
+ async = async_node->u.flag;
+ }
+
+ reqid_node = node_map_get(&msg_node, "request_id");
+ if (reqid_node) {
+ if (reqid_node->format == MPV_FORMAT_INT64) {
+ reqid = reqid_node->u.int64;
+ } else if (async) {
+ mp_err(log, "'request_id' must be an integer for async commands.\n");
+ rc = MPV_ERROR_INVALID_PARAMETER;
+ goto error;
+ } else {
+ mp_warn(log, "'request_id' must be an integer. Using other types is "
+ "deprecated and will trigger an error in the future!\n");
+ }
+ }
+
+ mpv_node *cmd_node = node_map_get(&msg_node, "command");
+ if (!cmd_node) {
+ rc = MPV_ERROR_INVALID_PARAMETER;
+ goto error;
+ }
+
+ if (cmd_node->format == MPV_FORMAT_NODE_ARRAY) {
+ mpv_node *cmd_str_node = mpv_node_array_get(cmd_node, 0);
+ if (!cmd_str_node || (cmd_str_node->format != MPV_FORMAT_STRING)) {
+ rc = MPV_ERROR_INVALID_PARAMETER;
+ goto error;
+ }
+
+ cmd = cmd_str_node->u.string;
+ }
+
+ if (cmd && !strcmp("client_name", cmd)) {
+ const char *client_name = mpv_client_name(client);
+ mpv_node_map_add_string(ta_parent, &reply_node, "data", client_name);
+ rc = MPV_ERROR_SUCCESS;
+ } else if (cmd && !strcmp("get_time_us", cmd)) {
+ int64_t time_us = mpv_get_time_us(client);
+ mpv_node_map_add_int64(ta_parent, &reply_node, "data", time_us);
+ rc = MPV_ERROR_SUCCESS;
+ } else if (cmd && !strcmp("get_version", cmd)) {
+ int64_t ver = mpv_client_api_version();
+ mpv_node_map_add_int64(ta_parent, &reply_node, "data", ver);
+ rc = MPV_ERROR_SUCCESS;
+ } else if (cmd && !strcmp("get_property", cmd)) {
+ mpv_node result_node;
+
+ if (cmd_node->u.list->num != 2) {
+ rc = MPV_ERROR_INVALID_PARAMETER;
+ goto error;
+ }
+
+ if (cmd_node->u.list->values[1].format != MPV_FORMAT_STRING) {
+ rc = MPV_ERROR_INVALID_PARAMETER;
+ goto error;
+ }
+
+ rc = mpv_get_property(client, cmd_node->u.list->values[1].u.string,
+ MPV_FORMAT_NODE, &result_node);
+ if (rc >= 0) {
+ mpv_node_map_add(ta_parent, &reply_node, "data", &result_node);
+ mpv_free_node_contents(&result_node);
+ }
+ } else if (cmd && !strcmp("get_property_string", cmd)) {
+ if (cmd_node->u.list->num != 2) {
+ rc = MPV_ERROR_INVALID_PARAMETER;
+ goto error;
+ }
+
+ if (cmd_node->u.list->values[1].format != MPV_FORMAT_STRING) {
+ rc = MPV_ERROR_INVALID_PARAMETER;
+ goto error;
+ }
+
+ char *result = mpv_get_property_string(client,
+ cmd_node->u.list->values[1].u.string);
+ if (result) {
+ mpv_node_map_add_string(ta_parent, &reply_node, "data", result);
+ mpv_free(result);
+ } else {
+ mpv_node_map_add_null(ta_parent, &reply_node, "data");
+ }
+ } else if (cmd && (!strcmp("set_property", cmd) ||
+ !strcmp("set_property_string", cmd)))
+ {
+ if (cmd_node->u.list->num != 3) {
+ rc = MPV_ERROR_INVALID_PARAMETER;
+ goto error;
+ }
+
+ if (cmd_node->u.list->values[1].format != MPV_FORMAT_STRING) {
+ rc = MPV_ERROR_INVALID_PARAMETER;
+ goto error;
+ }
+
+ rc = mpv_set_property(client, cmd_node->u.list->values[1].u.string,
+ MPV_FORMAT_NODE, &cmd_node->u.list->values[2]);
+ } else if (cmd && !strcmp("observe_property", cmd)) {
+ if (cmd_node->u.list->num != 3) {
+ rc = MPV_ERROR_INVALID_PARAMETER;
+ goto error;
+ }
+
+ if (cmd_node->u.list->values[1].format != MPV_FORMAT_INT64) {
+ rc = MPV_ERROR_INVALID_PARAMETER;
+ goto error;
+ }
+
+ if (cmd_node->u.list->values[2].format != MPV_FORMAT_STRING) {
+ rc = MPV_ERROR_INVALID_PARAMETER;
+ goto error;
+ }
+
+ rc = mpv_observe_property(client,
+ cmd_node->u.list->values[1].u.int64,
+ cmd_node->u.list->values[2].u.string,
+ MPV_FORMAT_NODE);
+ } else if (cmd && !strcmp("observe_property_string", cmd)) {
+ if (cmd_node->u.list->num != 3) {
+ rc = MPV_ERROR_INVALID_PARAMETER;
+ goto error;
+ }
+
+ if (cmd_node->u.list->values[1].format != MPV_FORMAT_INT64) {
+ rc = MPV_ERROR_INVALID_PARAMETER;
+ goto error;
+ }
+
+ if (cmd_node->u.list->values[2].format != MPV_FORMAT_STRING) {
+ rc = MPV_ERROR_INVALID_PARAMETER;
+ goto error;
+ }
+
+ rc = mpv_observe_property(client,
+ cmd_node->u.list->values[1].u.int64,
+ cmd_node->u.list->values[2].u.string,
+ MPV_FORMAT_STRING);
+ } else if (cmd && !strcmp("unobserve_property", cmd)) {
+ if (cmd_node->u.list->num != 2) {
+ rc = MPV_ERROR_INVALID_PARAMETER;
+ goto error;
+ }
+
+ if (cmd_node->u.list->values[1].format != MPV_FORMAT_INT64) {
+ rc = MPV_ERROR_INVALID_PARAMETER;
+ goto error;
+ }
+
+ rc = mpv_unobserve_property(client,
+ cmd_node->u.list->values[1].u.int64);
+ } else if (cmd && !strcmp("request_log_messages", cmd)) {
+ if (cmd_node->u.list->num != 2) {
+ rc = MPV_ERROR_INVALID_PARAMETER;
+ goto error;
+ }
+
+ if (cmd_node->u.list->values[1].format != MPV_FORMAT_STRING) {
+ rc = MPV_ERROR_INVALID_PARAMETER;
+ goto error;
+ }
+
+ rc = mpv_request_log_messages(client,
+ cmd_node->u.list->values[1].u.string);
+ } else if (cmd && (!strcmp("enable_event", cmd) ||
+ !strcmp("disable_event", cmd)))
+ {
+ bool enable = !strcmp("enable_event", cmd);
+
+ if (cmd_node->u.list->num != 2) {
+ rc = MPV_ERROR_INVALID_PARAMETER;
+ goto error;
+ }
+
+ if (cmd_node->u.list->values[1].format != MPV_FORMAT_STRING) {
+ rc = MPV_ERROR_INVALID_PARAMETER;
+ goto error;
+ }
+
+ char *name = cmd_node->u.list->values[1].u.string;
+ if (strcmp(name, "all") == 0) {
+ for (int n = 0; n < 64; n++)
+ mpv_request_event(client, n, enable);
+ rc = MPV_ERROR_SUCCESS;
+ } else {
+ int event = -1;
+ for (int n = 0; n < 64; n++) {
+ const char *evname = mpv_event_name(n);
+ if (evname && strcmp(evname, name) == 0)
+ event = n;
+ }
+ if (event < 0) {
+ rc = MPV_ERROR_INVALID_PARAMETER;
+ goto error;
+ }
+ rc = mpv_request_event(client, event, enable);
+ }
+ } else {
+ mpv_node result_node = {0};
+
+ if (async) {
+ rc = mpv_command_node_async(client, reqid, cmd_node);
+ if (rc >= 0)
+ send_reply = false;
+ } else {
+ rc = mpv_command_node(client, cmd_node, &result_node);
+ if (rc >= 0)
+ mpv_node_map_add(ta_parent, &reply_node, "data", &result_node);
+ }
+
+ mpv_free_node_contents(&result_node);
+ }
+
+error:
+ /* If the request contains a "request_id", copy it back into the response.
+ * This makes it easier on the requester to match up the IPC results with
+ * the original requests.
+ */
+ if (reqid_node) {
+ mpv_node_map_add(ta_parent, &reply_node, "request_id", reqid_node);
+ } else {
+ mpv_node_map_add_int64(ta_parent, &reply_node, "request_id", 0);
+ }
+
+ mpv_node_map_add_string(ta_parent, &reply_node, "error", mpv_error_string(rc));
+
+ char *output = talloc_strdup(ta_parent, "");
+
+ if (send_reply) {
+ json_write(&output, &reply_node);
+ output = ta_talloc_strdup_append(output, "\n");
+ }
+
+ return output;
+}
+
+static char *text_execute_command(struct mpv_handle *client, void *tmp, char *src)
+{
+ mpv_command_string(client, src);
+
+ return NULL;
+}
+
+char *mp_ipc_consume_next_command(struct mpv_handle *client, void *ctx, bstr *buf)
+{
+ void *tmp = talloc_new(NULL);
+
+ bstr rest;
+ bstr line = bstr_getline(*buf, &rest);
+ char *line0 = bstrto0(tmp, line);
+ talloc_steal(tmp, buf->start);
+ *buf = bstrdup(NULL, rest);
+
+ json_skip_whitespace(&line0);
+
+ char *reply_msg = NULL;
+ if (line0[0] == '\0' || line0[0] == '#') {
+ // skip
+ } else if (line0[0] == '{') {
+ reply_msg = json_execute_command(client, tmp, line0);
+ } else {
+ reply_msg = text_execute_command(client, tmp, line0);
+ }
+
+ talloc_steal(ctx, reply_msg);
+ talloc_free(tmp);
+ return reply_msg;
+}
diff --git a/input/keycodes.c b/input/keycodes.c
new file mode 100644
index 0000000..bca9e17
--- /dev/null
+++ b/input/keycodes.c
@@ -0,0 +1,379 @@
+/*
+ * This file is part of mpv.
+ *
+ * mpv is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * mpv is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with mpv. If not, see <http://www.gnu.org/licenses/>.
+ */
+
+#include <stddef.h>
+#include <string.h>
+#include <strings.h>
+
+#include "misc/bstr.h"
+#include "common/common.h"
+#include "common/msg.h"
+
+#include "keycodes.h"
+
+struct key_name {
+ int key;
+ char *name;
+};
+
+/// The names of the keys as used in input.conf
+/// If you add some new keys, you also need to add them here
+
+static const struct key_name key_names[] = {
+ { ' ', "SPACE" },
+ { '#', "SHARP" },
+ { 0x3000, "IDEOGRAPHIC_SPACE" },
+ { MP_KEY_ENTER, "ENTER" },
+ { MP_KEY_TAB, "TAB" },
+ { MP_KEY_BACKSPACE, "BS" },
+ { MP_KEY_DELETE, "DEL" },
+ { MP_KEY_INSERT, "INS" },
+ { MP_KEY_HOME, "HOME" },
+ { MP_KEY_END, "END" },
+ { MP_KEY_PAGE_UP, "PGUP" },
+ { MP_KEY_PAGE_DOWN, "PGDWN" },
+ { MP_KEY_ESC, "ESC" },
+ { MP_KEY_PRINT, "PRINT" },
+ { MP_KEY_RIGHT, "RIGHT" },
+ { MP_KEY_LEFT, "LEFT" },
+ { MP_KEY_DOWN, "DOWN" },
+ { MP_KEY_UP, "UP" },
+ { MP_KEY_F+1, "F1" },
+ { MP_KEY_F+2, "F2" },
+ { MP_KEY_F+3, "F3" },
+ { MP_KEY_F+4, "F4" },
+ { MP_KEY_F+5, "F5" },
+ { MP_KEY_F+6, "F6" },
+ { MP_KEY_F+7, "F7" },
+ { MP_KEY_F+8, "F8" },
+ { MP_KEY_F+9, "F9" },
+ { MP_KEY_F+10, "F10" },
+ { MP_KEY_F+11, "F11" },
+ { MP_KEY_F+12, "F12" },
+ { MP_KEY_F+13, "F13" },
+ { MP_KEY_F+14, "F14" },
+ { MP_KEY_F+15, "F15" },
+ { MP_KEY_F+16, "F16" },
+ { MP_KEY_F+17, "F17" },
+ { MP_KEY_F+18, "F18" },
+ { MP_KEY_F+19, "F19" },
+ { MP_KEY_F+20, "F20" },
+ { MP_KEY_F+21, "F21" },
+ { MP_KEY_F+22, "F22" },
+ { MP_KEY_F+23, "F23" },
+ { MP_KEY_F+24, "F24" },
+ { MP_KEY_KP0, "KP0" },
+ { MP_KEY_KP1, "KP1" },
+ { MP_KEY_KP2, "KP2" },
+ { MP_KEY_KP3, "KP3" },
+ { MP_KEY_KP4, "KP4" },
+ { MP_KEY_KP5, "KP5" },
+ { MP_KEY_KP6, "KP6" },
+ { MP_KEY_KP7, "KP7" },
+ { MP_KEY_KP8, "KP8" },
+ { MP_KEY_KP9, "KP9" },
+ { MP_KEY_KPDEL, "KP_DEL" },
+ { MP_KEY_KPDEC, "KP_DEC" },
+ { MP_KEY_KPINS, "KP_INS" },
+ { MP_KEY_KPHOME, "KP_HOME" },
+ { MP_KEY_KPEND, "KP_END" },
+ { MP_KEY_KPPGUP, "KP_PGUP" },
+ { MP_KEY_KPPGDOWN, "KP_PGDWN" },
+ { MP_KEY_KPRIGHT, "KP_RIGHT" },
+ { MP_KEY_KPLEFT, "KP_LEFT" },
+ { MP_KEY_KPDOWN, "KP_DOWN" },
+ { MP_KEY_KPUP, "KP_UP" },
+ { MP_KEY_KPENTER, "KP_ENTER" },
+ { MP_MBTN_LEFT, "MBTN_LEFT" },
+ { MP_MBTN_MID, "MBTN_MID" },
+ { MP_MBTN_RIGHT, "MBTN_RIGHT" },
+ { MP_WHEEL_UP, "WHEEL_UP" },
+ { MP_WHEEL_DOWN, "WHEEL_DOWN" },
+ { MP_WHEEL_LEFT, "WHEEL_LEFT" },
+ { MP_WHEEL_RIGHT, "WHEEL_RIGHT" },
+ { MP_MBTN_BACK, "MBTN_BACK" },
+ { MP_MBTN_FORWARD, "MBTN_FORWARD" },
+ { MP_MBTN9, "MBTN9" },
+ { MP_MBTN10, "MBTN10" },
+ { MP_MBTN11, "MBTN11" },
+ { MP_MBTN12, "MBTN12" },
+ { MP_MBTN13, "MBTN13" },
+ { MP_MBTN14, "MBTN14" },
+ { MP_MBTN15, "MBTN15" },
+ { MP_MBTN16, "MBTN16" },
+ { MP_MBTN17, "MBTN17" },
+ { MP_MBTN18, "MBTN18" },
+ { MP_MBTN19, "MBTN19" },
+ { MP_MBTN_LEFT_DBL, "MBTN_LEFT_DBL" },
+ { MP_MBTN_MID_DBL, "MBTN_MID_DBL" },
+ { MP_MBTN_RIGHT_DBL, "MBTN_RIGHT_DBL" },
+
+ { MP_KEY_GAMEPAD_ACTION_DOWN, "GAMEPAD_ACTION_DOWN" },
+ { MP_KEY_GAMEPAD_ACTION_RIGHT, "GAMEPAD_ACTION_RIGHT" },
+ { MP_KEY_GAMEPAD_ACTION_LEFT, "GAMEPAD_ACTION_LEFT" },
+ { MP_KEY_GAMEPAD_ACTION_UP, "GAMEPAD_ACTION_UP" },
+ { MP_KEY_GAMEPAD_BACK, "GAMEPAD_BACK" },
+ { MP_KEY_GAMEPAD_MENU, "GAMEPAD_MENU" },
+ { MP_KEY_GAMEPAD_START, "GAMEPAD_START" },
+ { MP_KEY_GAMEPAD_LEFT_SHOULDER, "GAMEPAD_LEFT_SHOULDER" },
+ { MP_KEY_GAMEPAD_RIGHT_SHOULDER, "GAMEPAD_RIGHT_SHOULDER" },
+ { MP_KEY_GAMEPAD_LEFT_TRIGGER, "GAMEPAD_LEFT_TRIGGER" },
+ { MP_KEY_GAMEPAD_RIGHT_TRIGGER, "GAMEPAD_RIGHT_TRIGGER" },
+ { MP_KEY_GAMEPAD_LEFT_STICK, "GAMEPAD_LEFT_STICK" },
+ { MP_KEY_GAMEPAD_RIGHT_STICK, "GAMEPAD_RIGHT_STICK" },
+ { MP_KEY_GAMEPAD_DPAD_UP, "GAMEPAD_DPAD_UP" },
+ { MP_KEY_GAMEPAD_DPAD_DOWN, "GAMEPAD_DPAD_DOWN" },
+ { MP_KEY_GAMEPAD_DPAD_LEFT, "GAMEPAD_DPAD_LEFT" },
+ { MP_KEY_GAMEPAD_DPAD_RIGHT, "GAMEPAD_DPAD_RIGHT" },
+ { MP_KEY_GAMEPAD_LEFT_STICK_UP, "GAMEPAD_LEFT_STICK_UP" },
+ { MP_KEY_GAMEPAD_LEFT_STICK_DOWN, "GAMEPAD_LEFT_STICK_DOWN" },
+ { MP_KEY_GAMEPAD_LEFT_STICK_LEFT, "GAMEPAD_LEFT_STICK_LEFT" },
+ { MP_KEY_GAMEPAD_LEFT_STICK_RIGHT, "GAMEPAD_LEFT_STICK_RIGHT" },
+ { MP_KEY_GAMEPAD_RIGHT_STICK_UP, "GAMEPAD_RIGHT_STICK_UP" },
+ { MP_KEY_GAMEPAD_RIGHT_STICK_DOWN, "GAMEPAD_RIGHT_STICK_DOWN" },
+ { MP_KEY_GAMEPAD_RIGHT_STICK_LEFT, "GAMEPAD_RIGHT_STICK_LEFT" },
+ { MP_KEY_GAMEPAD_RIGHT_STICK_RIGHT, "GAMEPAD_RIGHT_STICK_RIGHT" },
+
+ { MP_KEY_POWER, "POWER" },
+ { MP_KEY_MENU, "MENU" },
+ { MP_KEY_PLAY, "PLAY" },
+ { MP_KEY_PAUSE, "PAUSE" },
+ { MP_KEY_PLAYPAUSE, "PLAYPAUSE" },
+ { MP_KEY_STOP, "STOP" },
+ { MP_KEY_FORWARD, "FORWARD" },
+ { MP_KEY_REWIND, "REWIND" },
+ { MP_KEY_NEXT, "NEXT" },
+ { MP_KEY_PREV, "PREV" },
+ { MP_KEY_VOLUME_UP, "VOLUME_UP" },
+ { MP_KEY_VOLUME_DOWN, "VOLUME_DOWN" },
+ { MP_KEY_MUTE, "MUTE" },
+ { MP_KEY_HOMEPAGE, "HOMEPAGE" },
+ { MP_KEY_WWW, "WWW" },
+ { MP_KEY_MAIL, "MAIL" },
+ { MP_KEY_FAVORITES, "FAVORITES" },
+ { MP_KEY_SEARCH, "SEARCH" },
+ { MP_KEY_SLEEP, "SLEEP" },
+ { MP_KEY_CANCEL, "CANCEL" },
+ { MP_KEY_RECORD, "RECORD" },
+ { MP_KEY_CHANNEL_UP, "CHANNEL_UP" },
+ { MP_KEY_CHANNEL_DOWN,"CHANNEL_DOWN" },
+ { MP_KEY_PLAYONLY, "PLAYONLY" },
+ { MP_KEY_PAUSEONLY, "PAUSEONLY" },
+ { MP_KEY_BACK, "BACK" },
+ { MP_KEY_TOOLS, "TOOLS" },
+ { MP_KEY_ZOOMIN, "ZOOMIN" },
+ { MP_KEY_ZOOMOUT, "ZOOMOUT" },
+
+ // These are kept for backward compatibility
+ { MP_KEY_PAUSE, "XF86_PAUSE" },
+ { MP_KEY_STOP, "XF86_STOP" },
+ { MP_KEY_PREV, "XF86_PREV" },
+ { MP_KEY_NEXT, "XF86_NEXT" },
+
+ // Deprecated numeric aliases for the mouse buttons
+ { MP_MBTN_LEFT, "MOUSE_BTN0" },
+ { MP_MBTN_MID, "MOUSE_BTN1" },
+ { MP_MBTN_RIGHT, "MOUSE_BTN2" },
+ { MP_WHEEL_UP, "MOUSE_BTN3" },
+ { MP_WHEEL_DOWN, "MOUSE_BTN4" },
+ { MP_WHEEL_LEFT, "MOUSE_BTN5" },
+ { MP_WHEEL_RIGHT, "MOUSE_BTN6" },
+ { MP_MBTN_BACK, "MOUSE_BTN7" },
+ { MP_MBTN_FORWARD, "MOUSE_BTN8" },
+ { MP_MBTN9, "MOUSE_BTN9" },
+ { MP_MBTN10, "MOUSE_BTN10" },
+ { MP_MBTN11, "MOUSE_BTN11" },
+ { MP_MBTN12, "MOUSE_BTN12" },
+ { MP_MBTN13, "MOUSE_BTN13" },
+ { MP_MBTN14, "MOUSE_BTN14" },
+ { MP_MBTN15, "MOUSE_BTN15" },
+ { MP_MBTN16, "MOUSE_BTN16" },
+ { MP_MBTN17, "MOUSE_BTN17" },
+ { MP_MBTN18, "MOUSE_BTN18" },
+ { MP_MBTN19, "MOUSE_BTN19" },
+ { MP_MBTN_LEFT_DBL, "MOUSE_BTN0_DBL" },
+ { MP_MBTN_MID_DBL, "MOUSE_BTN1_DBL" },
+ { MP_MBTN_RIGHT_DBL, "MOUSE_BTN2_DBL" },
+ { MP_WHEEL_UP, "AXIS_UP" },
+ { MP_WHEEL_DOWN, "AXIS_DOWN" },
+ { MP_WHEEL_LEFT, "AXIS_LEFT" },
+ { MP_WHEEL_RIGHT, "AXIS_RIGHT" },
+
+ { MP_KEY_CLOSE_WIN, "CLOSE_WIN" },
+ { MP_KEY_MOUSE_MOVE, "MOUSE_MOVE" },
+ { MP_KEY_MOUSE_LEAVE, "MOUSE_LEAVE" },
+ { MP_KEY_MOUSE_ENTER, "MOUSE_ENTER" },
+
+ { MP_KEY_UNMAPPED, "UNMAPPED" },
+ { MP_KEY_ANY_UNICODE, "ANY_UNICODE" },
+
+ { 0, NULL }
+};
+
+static const struct key_name modifier_names[] = {
+ { MP_KEY_MODIFIER_SHIFT, "Shift" },
+ { MP_KEY_MODIFIER_CTRL, "Ctrl" },
+ { MP_KEY_MODIFIER_ALT, "Alt" },
+ { MP_KEY_MODIFIER_META, "Meta" },
+ { 0 }
+};
+
+int mp_input_get_key_from_name(const char *name)
+{
+ int modifiers = 0;
+ const char *p;
+ while ((p = strchr(name, '+'))) {
+ for (const struct key_name *m = modifier_names; m->name; m++)
+ if (!bstrcasecmp(bstr0(m->name),
+ (struct bstr){(char *)name, p - name})) {
+ modifiers |= m->key;
+ goto found;
+ }
+ if (!strcmp(name, "+"))
+ return '+' + modifiers;
+ return -1;
+found:
+ name = p + 1;
+ }
+
+ struct bstr bname = bstr0(name);
+
+ struct bstr rest;
+ int code = bstr_decode_utf8(bname, &rest);
+ if (code >= 0 && rest.len == 0)
+ return mp_normalize_keycode(code + modifiers);
+
+ if (bstr_startswith0(bname, "0x"))
+ return mp_normalize_keycode(strtol(name, NULL, 16) + modifiers);
+
+ for (int i = 0; key_names[i].name != NULL; i++) {
+ if (strcasecmp(key_names[i].name, name) == 0)
+ return mp_normalize_keycode(key_names[i].key + modifiers);
+ }
+
+ return -1;
+}
+
+static void mp_input_append_key_name(bstr *buf, int key)
+{
+ for (int i = 0; modifier_names[i].name; i++) {
+ if (modifier_names[i].key & key) {
+ bstr_xappend_asprintf(NULL, buf, "%s+", modifier_names[i].name);
+ key -= modifier_names[i].key;
+ }
+ }
+ for (int i = 0; key_names[i].name != NULL; i++) {
+ if (key_names[i].key == key) {
+ bstr_xappend_asprintf(NULL, buf, "%s", key_names[i].name);
+ return;
+ }
+ }
+
+ if (MP_KEY_IS_UNICODE(key)) {
+ mp_append_utf8_bstr(NULL, buf, key);
+ return;
+ }
+
+ // Print the hex key code
+ bstr_xappend_asprintf(NULL, buf, "0x%x", key);
+}
+
+char *mp_input_get_key_name(int key)
+{
+ bstr dst = {0};
+ mp_input_append_key_name(&dst, key);
+ return dst.start;
+}
+
+char *mp_input_get_key_combo_name(const int *keys, int max)
+{
+ bstr dst = {0};
+ while (max > 0) {
+ mp_input_append_key_name(&dst, *keys);
+ if (--max && *++keys)
+ bstr_xappend(NULL, &dst, bstr0("-"));
+ else
+ break;
+ }
+ return dst.start;
+}
+
+int mp_input_get_keys_from_string(char *name, int max_num_keys,
+ int *out_num_keys, int *keys)
+{
+ char *end, *ptr;
+ int n = 0;
+
+ ptr = name;
+ n = 0;
+ for (end = strchr(ptr, '-'); ; end = strchr(ptr, '-')) {
+ if (end && end[1] != '\0') {
+ if (end[1] == '-')
+ end = &end[1];
+ end[0] = '\0';
+ }
+ keys[n] = mp_input_get_key_from_name(ptr);
+ if (keys[n] < 0)
+ return 0;
+ n++;
+ if (end && end[1] != '\0' && n < max_num_keys)
+ ptr = &end[1];
+ else
+ break;
+ }
+ *out_num_keys = n;
+ return 1;
+}
+
+void mp_print_key_list(struct mp_log *out)
+{
+ mp_info(out, "\n");
+ for (int i = 0; key_names[i].name != NULL; i++)
+ mp_info(out, "%s\n", key_names[i].name);
+}
+
+char **mp_get_key_list(void)
+{
+ char **list = NULL;
+ int num = 0;
+ for (int i = 0; key_names[i].name != NULL; i++)
+ MP_TARRAY_APPEND(NULL, list, num, talloc_strdup(NULL, key_names[i].name));
+ MP_TARRAY_APPEND(NULL, list, num, NULL);
+ return list;
+}
+
+int mp_normalize_keycode(int keycode)
+{
+ if (keycode <= 0)
+ return keycode;
+ int code = keycode & ~MP_KEY_MODIFIER_MASK;
+ int mod = keycode & MP_KEY_MODIFIER_MASK;
+ /* On normal keyboards shift changes the character code of non-special
+ * keys, so don't count the modifier separately for those. In other words
+ * we want to have "a" and "A" instead of "a" and "Shift+A"; but a separate
+ * shift modifier is still kept for special keys like arrow keys. */
+ if (code >= 32 && code < MP_KEY_BASE) {
+ /* Still try to support ASCII case-modifications properly. For example,
+ * we want to change "Shift+a" to "A", not "a". Doing this for unicode
+ * in general would require huge lookup tables, or a libc with proper
+ * unicode support, so we don't do that. */
+ if (code >= 'a' && code <= 'z' && (mod & MP_KEY_MODIFIER_SHIFT))
+ code &= 0x5F;
+ mod &= ~MP_KEY_MODIFIER_SHIFT;
+ }
+ return code | mod;
+}
diff --git a/input/keycodes.h b/input/keycodes.h
new file mode 100644
index 0000000..a5a746a
--- /dev/null
+++ b/input/keycodes.h
@@ -0,0 +1,270 @@
+/*
+ * This file is part of mpv.
+ *
+ * mpv is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * mpv is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with mpv. If not, see <http://www.gnu.org/licenses/>.
+ */
+
+#ifndef MPLAYER_KEYCODES_H
+#define MPLAYER_KEYCODES_H
+
+// Keys in the range [0, MP_KEY_BASE) follow unicode.
+// Special keys come after this.
+#define MP_KEY_BASE (1<<21)
+
+// printable, and valid unicode range (we don't care too much about whether
+// certain sub-ranges are reserved and disallowed, like surrogate pairs)
+#define MP_KEY_IS_UNICODE(key) ((key) >= 32 && (key) <= 0x10FFFF)
+
+#define MP_KEY_ENTER 13
+#define MP_KEY_TAB 9
+
+/* Control keys */
+#define MP_KEY_BACKSPACE (MP_KEY_BASE+0)
+#define MP_KEY_DELETE (MP_KEY_BASE+1)
+#define MP_KEY_INSERT (MP_KEY_BASE+2)
+#define MP_KEY_HOME (MP_KEY_BASE+3)
+#define MP_KEY_END (MP_KEY_BASE+4)
+#define MP_KEY_PAGE_UP (MP_KEY_BASE+5)
+#define MP_KEY_PAGE_DOWN (MP_KEY_BASE+6)
+#define MP_KEY_ESC (MP_KEY_BASE+7)
+#define MP_KEY_PRINT (MP_KEY_BASE+8)
+
+/* Control keys short name */
+#define MP_KEY_BS MP_KEY_BACKSPACE
+#define MP_KEY_DEL MP_KEY_DELETE
+#define MP_KEY_INS MP_KEY_INSERT
+#define MP_KEY_PGUP MP_KEY_PAGE_UP
+#define MP_KEY_PGDOWN MP_KEY_PAGE_DOWN
+#define MP_KEY_PGDWN MP_KEY_PAGE_DOWN
+
+/* Cursor movement */
+#define MP_KEY_CRSR (MP_KEY_BASE+0x10)
+#define MP_KEY_RIGHT (MP_KEY_CRSR+0)
+#define MP_KEY_LEFT (MP_KEY_CRSR+1)
+#define MP_KEY_DOWN (MP_KEY_CRSR+2)
+#define MP_KEY_UP (MP_KEY_CRSR+3)
+
+/* Multimedia/internet keyboard/remote keys */
+#define MP_KEY_MM_BASE (MP_KEY_BASE+0x20)
+#define MP_KEY_POWER (MP_KEY_MM_BASE+0)
+#define MP_KEY_MENU (MP_KEY_MM_BASE+1)
+#define MP_KEY_PLAY (MP_KEY_MM_BASE+2)
+#define MP_KEY_PAUSE (MP_KEY_MM_BASE+3)
+#define MP_KEY_PLAYPAUSE (MP_KEY_MM_BASE+4)
+#define MP_KEY_STOP (MP_KEY_MM_BASE+5)
+#define MP_KEY_FORWARD (MP_KEY_MM_BASE+6)
+#define MP_KEY_REWIND (MP_KEY_MM_BASE+7)
+#define MP_KEY_NEXT (MP_KEY_MM_BASE+8)
+#define MP_KEY_PREV (MP_KEY_MM_BASE+9)
+#define MP_KEY_VOLUME_UP (MP_KEY_MM_BASE+10)
+#define MP_KEY_VOLUME_DOWN (MP_KEY_MM_BASE+11)
+#define MP_KEY_MUTE (MP_KEY_MM_BASE+12)
+#define MP_KEY_HOMEPAGE (MP_KEY_MM_BASE+13)
+#define MP_KEY_WWW (MP_KEY_MM_BASE+14)
+#define MP_KEY_MAIL (MP_KEY_MM_BASE+15)
+#define MP_KEY_FAVORITES (MP_KEY_MM_BASE+16)
+#define MP_KEY_SEARCH (MP_KEY_MM_BASE+17)
+#define MP_KEY_SLEEP (MP_KEY_MM_BASE+18)
+#define MP_KEY_CANCEL (MP_KEY_MM_BASE+19)
+#define MP_KEY_RECORD (MP_KEY_MM_BASE+20)
+#define MP_KEY_CHANNEL_UP (MP_KEY_MM_BASE+21)
+#define MP_KEY_CHANNEL_DOWN (MP_KEY_MM_BASE+22)
+#define MP_KEY_PLAYONLY (MP_KEY_MM_BASE+23)
+#define MP_KEY_PAUSEONLY (MP_KEY_MM_BASE+24)
+#define MP_KEY_BACK (MP_KEY_MM_BASE+25)
+#define MP_KEY_TOOLS (MP_KEY_MM_BASE+26)
+#define MP_KEY_ZOOMIN (MP_KEY_MM_BASE+27)
+#define MP_KEY_ZOOMOUT (MP_KEY_MM_BASE+28)
+
+/* Function keys */
+#define MP_KEY_F (MP_KEY_BASE+0x40)
+
+/* Keypad keys */
+#define MP_KEY_KEYPAD (MP_KEY_BASE+0x60)
+#define MP_KEY_KP0 (MP_KEY_KEYPAD+0)
+#define MP_KEY_KP1 (MP_KEY_KEYPAD+1)
+#define MP_KEY_KP2 (MP_KEY_KEYPAD+2)
+#define MP_KEY_KP3 (MP_KEY_KEYPAD+3)
+#define MP_KEY_KP4 (MP_KEY_KEYPAD+4)
+#define MP_KEY_KP5 (MP_KEY_KEYPAD+5)
+#define MP_KEY_KP6 (MP_KEY_KEYPAD+6)
+#define MP_KEY_KP7 (MP_KEY_KEYPAD+7)
+#define MP_KEY_KP8 (MP_KEY_KEYPAD+8)
+#define MP_KEY_KP9 (MP_KEY_KEYPAD+9)
+#define MP_KEY_KPDEC (MP_KEY_KEYPAD+10)
+#define MP_KEY_KPINS (MP_KEY_KEYPAD+11)
+#define MP_KEY_KPDEL (MP_KEY_KEYPAD+12)
+#define MP_KEY_KPENTER (MP_KEY_KEYPAD+13)
+#define MP_KEY_KPHOME (MP_KEY_KEYPAD+14)
+#define MP_KEY_KPEND (MP_KEY_KEYPAD+15)
+#define MP_KEY_KPPGUP (MP_KEY_KEYPAD+16)
+#define MP_KEY_KPPGDOWN (MP_KEY_KEYPAD+17)
+#define MP_KEY_KPRIGHT (MP_KEY_KEYPAD+18)
+#define MP_KEY_KPLEFT (MP_KEY_KEYPAD+19)
+#define MP_KEY_KPDOWN (MP_KEY_KEYPAD+20)
+#define MP_KEY_KPUP (MP_KEY_KEYPAD+21)
+
+// Mouse events from VOs
+#define MP_MBTN_BASE ((MP_KEY_BASE+0xA0)|MP_NO_REPEAT_KEY|MP_KEY_EMIT_ON_UP)
+#define MP_MBTN_LEFT (MP_MBTN_BASE+0)
+#define MP_MBTN_MID (MP_MBTN_BASE+1)
+#define MP_MBTN_RIGHT (MP_MBTN_BASE+2)
+#define MP_WHEEL_UP (MP_MBTN_BASE+3)
+#define MP_WHEEL_DOWN (MP_MBTN_BASE+4)
+#define MP_WHEEL_LEFT (MP_MBTN_BASE+5)
+#define MP_WHEEL_RIGHT (MP_MBTN_BASE+6)
+#define MP_MBTN_BACK (MP_MBTN_BASE+7)
+#define MP_MBTN_FORWARD (MP_MBTN_BASE+8)
+#define MP_MBTN9 (MP_MBTN_BASE+9)
+#define MP_MBTN10 (MP_MBTN_BASE+10)
+#define MP_MBTN11 (MP_MBTN_BASE+11)
+#define MP_MBTN12 (MP_MBTN_BASE+12)
+#define MP_MBTN13 (MP_MBTN_BASE+13)
+#define MP_MBTN14 (MP_MBTN_BASE+14)
+#define MP_MBTN15 (MP_MBTN_BASE+15)
+#define MP_MBTN16 (MP_MBTN_BASE+16)
+#define MP_MBTN17 (MP_MBTN_BASE+17)
+#define MP_MBTN18 (MP_MBTN_BASE+18)
+#define MP_MBTN19 (MP_MBTN_BASE+19)
+#define MP_MBTN_END (MP_MBTN_BASE+20)
+
+#define MP_KEY_IS_MOUSE_BTN_SINGLE(code) \
+ ((code) >= MP_MBTN_BASE && (code) < MP_MBTN_END)
+#define MP_KEY_IS_WHEEL(code) \
+ ((code) >= MP_WHEEL_UP && (code) <= MP_WHEEL_RIGHT)
+
+#define MP_MBTN_DBL_BASE ((MP_KEY_BASE+0xC0)|MP_NO_REPEAT_KEY)
+#define MP_MBTN_LEFT_DBL (MP_MBTN_DBL_BASE+0)
+#define MP_MBTN_MID_DBL (MP_MBTN_DBL_BASE+1)
+#define MP_MBTN_RIGHT_DBL (MP_MBTN_DBL_BASE+2)
+#define MP_MBTN_DBL_END (MP_MBTN_DBL_BASE+20)
+
+#define MP_KEY_IS_MOUSE_BTN_DBL(code) \
+ ((code) >= MP_MBTN_DBL_BASE && (code) < MP_MBTN_DBL_END)
+
+#define MP_KEY_MOUSE_BTN_COUNT (MP_MBTN_END - MP_MBTN_BASE)
+
+/* game controller keys */
+#define MP_KEY_GAMEPAD (MP_KEY_BASE+0xF0)
+#define MP_KEY_GAMEPAD_ACTION_DOWN (MP_KEY_GAMEPAD+0)
+#define MP_KEY_GAMEPAD_ACTION_RIGHT (MP_KEY_GAMEPAD+1)
+#define MP_KEY_GAMEPAD_ACTION_LEFT (MP_KEY_GAMEPAD+2)
+#define MP_KEY_GAMEPAD_ACTION_UP (MP_KEY_GAMEPAD+3)
+#define MP_KEY_GAMEPAD_BACK (MP_KEY_GAMEPAD+4)
+#define MP_KEY_GAMEPAD_MENU (MP_KEY_GAMEPAD+5)
+#define MP_KEY_GAMEPAD_START (MP_KEY_GAMEPAD+6)
+#define MP_KEY_GAMEPAD_LEFT_SHOULDER (MP_KEY_GAMEPAD+7)
+#define MP_KEY_GAMEPAD_RIGHT_SHOULDER (MP_KEY_GAMEPAD+8)
+#define MP_KEY_GAMEPAD_LEFT_TRIGGER (MP_KEY_GAMEPAD+9)
+#define MP_KEY_GAMEPAD_RIGHT_TRIGGER (MP_KEY_GAMEPAD+10)
+#define MP_KEY_GAMEPAD_LEFT_STICK (MP_KEY_GAMEPAD+11)
+#define MP_KEY_GAMEPAD_RIGHT_STICK (MP_KEY_GAMEPAD+12)
+#define MP_KEY_GAMEPAD_DPAD_UP (MP_KEY_GAMEPAD+13)
+#define MP_KEY_GAMEPAD_DPAD_DOWN (MP_KEY_GAMEPAD+14)
+#define MP_KEY_GAMEPAD_DPAD_LEFT (MP_KEY_GAMEPAD+15)
+#define MP_KEY_GAMEPAD_DPAD_RIGHT (MP_KEY_GAMEPAD+16)
+#define MP_KEY_GAMEPAD_LEFT_STICK_UP (MP_KEY_GAMEPAD+17)
+#define MP_KEY_GAMEPAD_LEFT_STICK_DOWN (MP_KEY_GAMEPAD+18)
+#define MP_KEY_GAMEPAD_LEFT_STICK_LEFT (MP_KEY_GAMEPAD+19)
+#define MP_KEY_GAMEPAD_LEFT_STICK_RIGHT (MP_KEY_GAMEPAD+20)
+#define MP_KEY_GAMEPAD_RIGHT_STICK_UP (MP_KEY_GAMEPAD+21)
+#define MP_KEY_GAMEPAD_RIGHT_STICK_DOWN (MP_KEY_GAMEPAD+22)
+#define MP_KEY_GAMEPAD_RIGHT_STICK_LEFT (MP_KEY_GAMEPAD+23)
+#define MP_KEY_GAMEPAD_RIGHT_STICK_RIGHT (MP_KEY_GAMEPAD+24)
+
+// Reserved area. Can be used for keys that have no explicit names assigned,
+// but should be mappable by the user anyway.
+#define MP_KEY_UNKNOWN_RESERVED_START (MP_KEY_BASE+0x10000)
+#define MP_KEY_UNKNOWN_RESERVED_LAST (MP_KEY_BASE+0x20000-1)
+
+/* Special keys */
+#define MP_KEY_INTERN (MP_KEY_BASE+0x20000)
+#define MP_KEY_CLOSE_WIN (MP_KEY_INTERN+0)
+// Generated by input.c (VOs use mp_input_set_mouse_pos())
+#define MP_KEY_MOUSE_MOVE ((MP_KEY_INTERN+1)|MP_NO_REPEAT_KEY)
+#define MP_KEY_MOUSE_LEAVE ((MP_KEY_INTERN+2)|MP_NO_REPEAT_KEY)
+#define MP_KEY_MOUSE_ENTER ((MP_KEY_INTERN+3)|MP_NO_REPEAT_KEY)
+
+#define MP_KEY_IS_MOUSE_CLICK(code) \
+ (MP_KEY_IS_MOUSE_BTN_SINGLE(code) || MP_KEY_IS_MOUSE_BTN_DBL(code))
+
+#define MP_KEY_IS_MOUSE_MOVE(code) \
+ ((code) == MP_KEY_MOUSE_MOVE || (code) == MP_KEY_MOUSE_ENTER || \
+ (code) == MP_KEY_MOUSE_LEAVE)
+
+// Whether to dispatch the key binding by current mouse position.
+#define MP_KEY_DEPENDS_ON_MOUSE_POS(code) \
+ (MP_KEY_IS_MOUSE_CLICK(code) || (code) == MP_KEY_MOUSE_MOVE)
+
+#define MP_KEY_IS_MOUSE(code) \
+ (MP_KEY_IS_MOUSE_CLICK(code) || MP_KEY_IS_MOUSE_MOVE(code))
+
+// No input source should generate this.
+#define MP_KEY_UNMAPPED (MP_KEY_INTERN+4)
+#define MP_KEY_ANY_UNICODE (MP_KEY_INTERN+5)
+// For mp_input_put_key(): release all keys that are down.
+#define MP_INPUT_RELEASE_ALL (MP_KEY_INTERN+6)
+
+// Emit a command even on key-up (normally key-up is ignored). This means by
+// default they binding will be triggered on key-up instead of key-down.
+// This is a fixed part of the keycode, not a modifier than can change.
+#define MP_KEY_EMIT_ON_UP (1u<<22)
+
+// Use this when the key shouldn't be auto-repeated (like mouse buttons)
+// Also means both key-down key-up events produce emit bound commands.
+// This is a fixed part of the keycode, not a modifier than can change.
+#define MP_NO_REPEAT_KEY (1u<<23)
+
+/* Modifiers added to individual keys */
+#define MP_KEY_MODIFIER_SHIFT (1u<<24)
+#define MP_KEY_MODIFIER_CTRL (1u<<25)
+#define MP_KEY_MODIFIER_ALT (1u<<26)
+#define MP_KEY_MODIFIER_META (1u<<27)
+
+// Flag for key events. Multiple down events are idempotent. Release keys by
+// sending the key code with KEY_STATE_UP set, or by sending
+// MP_INPUT_RELEASE_ALL as key code.
+#define MP_KEY_STATE_DOWN (1u<<28)
+
+// Flag for key events. Releases a key previously held down with
+// MP_KEY_STATE_DOWN. Do not send redundant UP events and do not forget to
+// release keys at all with UP. If input is unreliable, use MP_INPUT_RELEASE_ALL
+// or don't use MP_KEY_STATE_DOWN in the first place.
+#define MP_KEY_STATE_UP (1u<<29)
+
+#define MP_KEY_MODIFIER_MASK (MP_KEY_MODIFIER_SHIFT | MP_KEY_MODIFIER_CTRL | \
+ MP_KEY_MODIFIER_ALT | MP_KEY_MODIFIER_META | \
+ MP_KEY_STATE_DOWN | MP_KEY_STATE_UP)
+
+// Makes adjustments like turning "shift+z" into "Z"
+int mp_normalize_keycode(int keycode);
+
+// Get input key from its name.
+int mp_input_get_key_from_name(const char *name);
+
+// Return given key (plus modifiers) as talloc'ed name.
+char *mp_input_get_key_name(int key);
+
+// Combination of multiple keys to string.
+char *mp_input_get_key_combo_name(const int *keys, int max);
+
+// String containing combination of multiple string to keys.
+int mp_input_get_keys_from_string(char *str, int max_num_keys,
+ int *out_num_keys, int *keys);
+
+struct mp_log;
+void mp_print_key_list(struct mp_log *out);
+char **mp_get_key_list(void);
+
+#endif /* MPLAYER_KEYCODES_H */
diff --git a/input/meson.build b/input/meson.build
new file mode 100644
index 0000000..12fe732
--- /dev/null
+++ b/input/meson.build
@@ -0,0 +1,20 @@
+icons = ['16', '32', '64', '128']
+foreach size: icons
+ name = 'mpv-icon-8bit-'+size+'x'+size+'.png'
+ icon = custom_target(name,
+ input: join_paths(source_root, 'etc', name),
+ output: name + '.inc',
+ command: [file2string, '@INPUT@', '@OUTPUT@'],
+ )
+ sources += icon
+endforeach
+
+etc_files = ['input.conf', 'builtin.conf']
+foreach file: etc_files
+ etc_file = custom_target(file,
+ input: join_paths(source_root, 'etc', file),
+ output: file + '.inc',
+ command: [file2string, '@INPUT@', '@OUTPUT@'],
+ )
+ sources += etc_file
+endforeach
diff --git a/input/sdl_gamepad.c b/input/sdl_gamepad.c
new file mode 100644
index 0000000..790c945
--- /dev/null
+++ b/input/sdl_gamepad.c
@@ -0,0 +1,287 @@
+/*
+ * This file is part of mpv.
+ *
+ * mpv is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * mpv is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with mpv. If not, see <http://www.gnu.org/licenses/>.
+ */
+
+#include <stdbool.h>
+
+#include <SDL.h>
+
+#include "common/common.h"
+#include "common/msg.h"
+#include "input.h"
+#include "input/keycodes.h"
+#include "osdep/threads.h"
+
+struct gamepad_priv {
+ SDL_GameController *controller;
+};
+
+static Uint32 gamepad_cancel_wakeup;
+
+static void initialize_events(void)
+{
+ gamepad_cancel_wakeup = SDL_RegisterEvents(1);
+}
+
+static mp_once events_initialized = MP_STATIC_ONCE_INITIALIZER;
+
+#define INVALID_KEY -1
+
+static const int button_map[][2] = {
+ { SDL_CONTROLLER_BUTTON_A, MP_KEY_GAMEPAD_ACTION_DOWN },
+ { SDL_CONTROLLER_BUTTON_B, MP_KEY_GAMEPAD_ACTION_RIGHT },
+ { SDL_CONTROLLER_BUTTON_X, MP_KEY_GAMEPAD_ACTION_LEFT },
+ { SDL_CONTROLLER_BUTTON_Y, MP_KEY_GAMEPAD_ACTION_UP },
+ { SDL_CONTROLLER_BUTTON_BACK, MP_KEY_GAMEPAD_BACK },
+ { SDL_CONTROLLER_BUTTON_GUIDE, MP_KEY_GAMEPAD_MENU },
+ { SDL_CONTROLLER_BUTTON_START, MP_KEY_GAMEPAD_START },
+ { SDL_CONTROLLER_BUTTON_LEFTSTICK, MP_KEY_GAMEPAD_LEFT_STICK },
+ { SDL_CONTROLLER_BUTTON_RIGHTSTICK, MP_KEY_GAMEPAD_RIGHT_STICK },
+ { SDL_CONTROLLER_BUTTON_LEFTSHOULDER, MP_KEY_GAMEPAD_LEFT_SHOULDER },
+ { SDL_CONTROLLER_BUTTON_RIGHTSHOULDER, MP_KEY_GAMEPAD_RIGHT_SHOULDER },
+ { SDL_CONTROLLER_BUTTON_DPAD_UP, MP_KEY_GAMEPAD_DPAD_UP },
+ { SDL_CONTROLLER_BUTTON_DPAD_DOWN, MP_KEY_GAMEPAD_DPAD_DOWN },
+ { SDL_CONTROLLER_BUTTON_DPAD_LEFT, MP_KEY_GAMEPAD_DPAD_LEFT },
+ { SDL_CONTROLLER_BUTTON_DPAD_RIGHT, MP_KEY_GAMEPAD_DPAD_RIGHT },
+};
+
+static const int analog_map[][5] = {
+ // 0 -> sdl enum
+ // 1 -> negative state
+ // 2 -> neutral-negative state
+ // 3 -> neutral-positive state
+ // 4 -> positive state
+ { SDL_CONTROLLER_AXIS_LEFTX,
+ MP_KEY_GAMEPAD_LEFT_STICK_LEFT | MP_KEY_STATE_DOWN,
+ MP_KEY_GAMEPAD_LEFT_STICK_LEFT | MP_KEY_STATE_UP,
+ MP_KEY_GAMEPAD_LEFT_STICK_RIGHT | MP_KEY_STATE_UP,
+ MP_KEY_GAMEPAD_LEFT_STICK_RIGHT | MP_KEY_STATE_DOWN },
+
+ { SDL_CONTROLLER_AXIS_LEFTY,
+ MP_KEY_GAMEPAD_LEFT_STICK_UP | MP_KEY_STATE_DOWN,
+ MP_KEY_GAMEPAD_LEFT_STICK_UP | MP_KEY_STATE_UP,
+ MP_KEY_GAMEPAD_LEFT_STICK_DOWN | MP_KEY_STATE_UP,
+ MP_KEY_GAMEPAD_LEFT_STICK_DOWN | MP_KEY_STATE_DOWN },
+
+ { SDL_CONTROLLER_AXIS_RIGHTX,
+ MP_KEY_GAMEPAD_RIGHT_STICK_LEFT | MP_KEY_STATE_DOWN,
+ MP_KEY_GAMEPAD_RIGHT_STICK_LEFT | MP_KEY_STATE_UP,
+ MP_KEY_GAMEPAD_RIGHT_STICK_RIGHT | MP_KEY_STATE_UP,
+ MP_KEY_GAMEPAD_RIGHT_STICK_RIGHT | MP_KEY_STATE_DOWN },
+
+ { SDL_CONTROLLER_AXIS_RIGHTY,
+ MP_KEY_GAMEPAD_RIGHT_STICK_UP | MP_KEY_STATE_DOWN,
+ MP_KEY_GAMEPAD_RIGHT_STICK_UP | MP_KEY_STATE_UP,
+ MP_KEY_GAMEPAD_RIGHT_STICK_DOWN | MP_KEY_STATE_UP,
+ MP_KEY_GAMEPAD_RIGHT_STICK_DOWN | MP_KEY_STATE_DOWN },
+
+ { SDL_CONTROLLER_AXIS_TRIGGERLEFT,
+ INVALID_KEY,
+ INVALID_KEY,
+ MP_KEY_GAMEPAD_LEFT_TRIGGER | MP_KEY_STATE_UP,
+ MP_KEY_GAMEPAD_LEFT_TRIGGER | MP_KEY_STATE_DOWN },
+
+ { SDL_CONTROLLER_AXIS_TRIGGERRIGHT,
+ INVALID_KEY,
+ INVALID_KEY,
+ MP_KEY_GAMEPAD_RIGHT_TRIGGER | MP_KEY_STATE_UP,
+ MP_KEY_GAMEPAD_RIGHT_TRIGGER | MP_KEY_STATE_DOWN },
+};
+
+static int lookup_button_mp_key(int sdl_key)
+{
+ for (int i = 0; i < MP_ARRAY_SIZE(button_map); i++) {
+ if (button_map[i][0] == sdl_key) {
+ return button_map[i][1];
+ }
+ }
+ return INVALID_KEY;
+}
+
+static int lookup_analog_mp_key(int sdl_key, int16_t value)
+{
+ const int sdl_axis_max = 32767;
+ const int negative = 1;
+ const int negative_neutral = 2;
+ const int positive_neutral = 3;
+ const int positive = 4;
+
+ const float activation_threshold = sdl_axis_max * 0.33;
+ const float noise_threshold = sdl_axis_max * 0.06;
+
+ // sometimes SDL just keeps shitting out low values around 0 that mess
+ // with key repeating code
+ if (value < noise_threshold && value > -noise_threshold) {
+ return INVALID_KEY;
+ }
+
+ int state = value > 0 ? positive_neutral : negative_neutral;
+
+ if (value >= sdl_axis_max - activation_threshold) {
+ state = positive;
+ }
+
+ if (value <= activation_threshold - sdl_axis_max) {
+ state = negative;
+ }
+
+ for (int i = 0; i < MP_ARRAY_SIZE(analog_map); i++) {
+ if (analog_map[i][0] == sdl_key) {
+ return analog_map[i][state];
+ }
+ }
+
+ return INVALID_KEY;
+}
+
+
+static void request_cancel(struct mp_input_src *src)
+{
+ MP_VERBOSE(src, "exiting...\n");
+ SDL_Event event = { .type = gamepad_cancel_wakeup };
+ SDL_PushEvent(&event);
+}
+
+static void uninit(struct mp_input_src *src)
+{
+ MP_VERBOSE(src, "exited.\n");
+}
+
+#define GUID_LEN 33
+
+static void add_gamepad(struct mp_input_src *src, int id)
+{
+ struct gamepad_priv *p = src->priv;
+
+ if (p->controller) {
+ MP_WARN(src, "can't add more than one controller\n");
+ return;
+ }
+
+ if (SDL_IsGameController(id)) {
+ SDL_GameController *controller = SDL_GameControllerOpen(id);
+
+ if (controller) {
+ const char *name = SDL_GameControllerName(controller);
+ MP_INFO(src, "added controller: %s\n", name);
+ p->controller = controller;
+ return;
+ }
+ }
+}
+
+static void remove_gamepad(struct mp_input_src *src, int id)
+{
+ struct gamepad_priv *p = src->priv;
+ SDL_GameController *controller = p->controller;
+ SDL_Joystick* j = SDL_GameControllerGetJoystick(controller);
+ SDL_JoystickID jid = SDL_JoystickInstanceID(j);
+
+ if (controller && jid == id) {
+ const char *name = SDL_GameControllerName(controller);
+ MP_INFO(src, "removed controller: %s\n", name);
+ SDL_GameControllerClose(controller);
+ p->controller = NULL;
+ }
+}
+
+static void read_gamepad_thread(struct mp_input_src *src, void *param)
+{
+ SDL_SetHint(SDL_HINT_JOYSTICK_THREAD, "1");
+
+ if (SDL_WasInit(SDL_INIT_EVENTS)) {
+ MP_ERR(src, "Another component is using SDL already.\n");
+ mp_input_src_init_done(src);
+ return;
+ }
+
+ if (SDL_InitSubSystem(SDL_INIT_GAMECONTROLLER)) {
+ MP_ERR(src, "SDL_Init failed\n");
+ mp_input_src_init_done(src);
+ return;
+ }
+
+ mp_exec_once(&events_initialized, initialize_events);
+
+ if (gamepad_cancel_wakeup == (Uint32)-1) {
+ MP_ERR(src, "Can't register SDL custom events\n");
+ mp_input_src_init_done(src);
+ return;
+ }
+
+ struct gamepad_priv *p =src->priv = talloc_zero(src, struct gamepad_priv);
+ src->cancel = request_cancel;
+ src->uninit = uninit;
+
+ mp_input_src_init_done(src);
+
+ SDL_Event ev;
+
+ while (SDL_WaitEvent(&ev) != 0) {
+ if (ev.type == gamepad_cancel_wakeup) {
+ break;
+ }
+
+ switch (ev.type) {
+ case SDL_CONTROLLERDEVICEADDED: {
+ add_gamepad(src, ev.cdevice.which);
+ continue;
+ }
+ case SDL_CONTROLLERDEVICEREMOVED: {
+ remove_gamepad(src, ev.cdevice.which);
+ continue;
+ }
+ case SDL_CONTROLLERBUTTONDOWN: {
+ const int key = lookup_button_mp_key(ev.cbutton.button);
+ if (key != INVALID_KEY) {
+ mp_input_put_key(src->input_ctx, key | MP_KEY_STATE_DOWN);
+ }
+ continue;
+ }
+ case SDL_CONTROLLERBUTTONUP: {
+ const int key = lookup_button_mp_key(ev.cbutton.button);
+ if (key != INVALID_KEY) {
+ mp_input_put_key(src->input_ctx, key | MP_KEY_STATE_UP);
+ }
+ continue;
+ }
+ case SDL_CONTROLLERAXISMOTION: {
+ const int key =
+ lookup_analog_mp_key(ev.caxis.axis, ev.caxis.value);
+ if (key != INVALID_KEY) {
+ mp_input_put_key(src->input_ctx, key);
+ }
+ continue;
+ }
+
+ }
+ }
+
+ if (p->controller) {
+ SDL_Joystick* j = SDL_GameControllerGetJoystick(p->controller);
+ SDL_JoystickID jid = SDL_JoystickInstanceID(j);
+ remove_gamepad(src, jid);
+ }
+
+ // must be called on the same thread of SDL_InitSubSystem, so uninit
+ // callback can't be used for this
+ SDL_QuitSubSystem(SDL_INIT_GAMECONTROLLER);
+}
+
+void mp_input_sdl_gamepad_add(struct input_ctx *ictx)
+{
+ mp_input_add_thread_src(ictx, NULL, read_gamepad_thread);
+}