summaryrefslogtreecommitdiff
path: root/main.lua
blob: cc9da6b6f29e636182137b9b3f49c74febc791dd (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
-- mpvSockets, one socket per instance, removes socket on exit

package.path = mp.command_native({"expand-path", "~~/script-modules/?.lua;"})..package.path
local input = require "user-input-module"
local utils = require 'mp.utils'

local sock_dir = os.getenv("MPV_SOCKET_DIR") or
  utils.join_path(os.getenv("XDG_RUNTIME_DIR"), "mpv/sockets")
mp.command_native({capture_stdout = true, capture_stderr = true,
args = {"mkdir", "-p", sock_dir}, name = "subprocess", playback_only = false})

local sock_file = utils.join_path(sock_dir,
mp.get_opt("mpv_socket") or utils.getpid())

mp.set_property("options/input-ipc-server", sock_file)

local function check_active_socket(file_name)
  return mp.command_native({
    name = "subprocess",
    capture_stdout = true,
    capture_stderr = true,
    args = {"nc", "-NU", file_name},
    playback_only = false,
    stdin_data = '{ "command": ["get_property", "path"] }\n',
  }).status == 0
end

local function change_sockname()
  input.get_user_input(function(line, _)
    if line then
      local new_sock_file = utils.join_path(sock_dir, line)
      if check_active_socket(new_sock_file) then
        change_sockname()
      else
        mp.set_property("options/input-ipc-server", new_sock_file)
      end
    end
  end, { request_text = "set socket name:" })
end

mp.add_key_binding("alt+s", "NameIPCSocket", change_sockname)

local function update_socket_name()
  local new_name = mp.get_property("options/input-ipc-server")
  if sock_file ~= new_name then
    os.remove(sock_file)
  end
  sock_file = new_name
end

mp.observe_property("options/input-ipc-server", nil, update_socket_name)

local function shutdown_handler()
  os.remove(mp.get_property("options/input-ipc-server"))
end
mp.register_event("shutdown", shutdown_handler)