-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwinframes.lua
More file actions
425 lines (342 loc) · 15 KB
/
Copy pathwinframes.lua
File metadata and controls
425 lines (342 loc) · 15 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
-- use ChangeScreenResolution command to set output to best fitting fps rate
-- when playing videos with mpv.
local utils = require 'mp.utils'
mp.options = require "mp.options"
local opts = {
["exec-path"] = "ChangeScreenResolution.exe",
["winframes-blacklist"] = "",
["output-mode"] = "",
["old-monitor-handling"] = false,
["wait-for-fullscreen"] = false,
["restore-outside-fullscreen"] = false,
}
mp.options.read_options(opts,"winframes")
-- if you want your display output switched to a certain mode during playback,
-- use e.g. "--script-opts=winframes-output-mode=1920x1080"
local winframes_output_mode = opts["output-mode"]
local winframes_exec_path = opts["exec-path"] --mp.get_opt("winframes-exec-path") or 'ChangeScreenResolution.exe'
local adjust = true
local winframes_blacklist = {}
local function winframes_parse_blacklist()
-- use e.g. "--script-opts=winframes-blacklist=25" to have xrand.lua not use 25Hz refresh rate
-- Parse the optional "blacklist" from a string into an array for later use.
-- For now, we only support a list of rates, since the "mode" is not subject
-- to automatic change (mpv is better at scaling than most displays) and
-- this also makes the blacklist option more easy to specify:
local b = opts["winframes-blacklist"]
if (b == "") then
return
end
local i = 1
for s in string.gmatch(b, "([^, ]+)") do
winframes_blacklist[i] = 0.0 + s
i = i+1
end
end
winframes_parse_blacklist()
local function cmdToString(p)
local cmd_as_string = ""
for k, v in pairs(p["args"]) do
cmd_as_string = cmd_as_string .. v .. " "
end
return cmd_as_string
end
local function trimmer(s)
return string.gsub(string.gsub(s or '', '^%s+', ''),'%s+$','')
end
local function winframes_check_blacklist(mode, rate)
-- check if (mode, rate) is black-listed - e.g. because the
-- computer display output is known to be incompatible with the
-- display at this specific mode/rate
for i=1,#winframes_blacklist do
r = winframes_blacklist[i]
if (r == rate) then
mp.msg.log("v", "will not use mode '" .. mode .. "' with rate " .. rate .. " because option --script-opts=winframes-blacklist said so")
return true
end
end
return false
end
local winframes_detect_done = false
local winframes_modes = {}
local winframes_connected_outputs = {}
local function winframes_detect_available_rates()
if (winframes_detect_done) then
return
end
winframes_detect_done = true
-- ChangeScreenResolution.exe doesn't show the which mode is currently active, so we need to query it separately.
local p = {
name="subprocess",
playback_only=false,
capture_stdout = true,
args = {winframes_exec_path, "/l"}
}
local res = mp.command_native(p)
if (res.error_string ~= "") then
mp.msg.log("info", "failed to execute '"..cmdToString(p).."', error message: " .. res.error_string)
return
end
local q = {
name="subprocess",
playback_only=false,
capture_stdout = true,
args = {winframes_exec_path, "/m"}
}
local qes = mp.command_native(q)
if (qes.error_string ~= "") then
mp.msg.log("info", "failed to execute '"..cmdToString(q).."', error message: " .. qes.error_string)
return
end
mp.msg.log("v",cmdToString(p).."\n" .. res.stdout)
for found in string.gmatch(res.stdout, '(%[[^%[]+)') do
local currentSettings = trimmer(string.match(found,'Settings: ([^\\n]+)'))
--displays without settings are definitely not connected
if currentSettings ~= '' then
local index = trimmer(string.match(found,'^%[(%d+)%]'))
local output = trimmer(string.match(found,'^%[%d+%] +([^\n ]+)'))
local old_mode,rate = string.match(currentSettings,'([0-9x]+) %d+bit @(%d+)Hz .+')
local matcher = trimmer(string.gsub(currentSettings,'@'..rate..'Hz','@(%%d+)Hz'))
local _, __, rawlist = string.find(qes.stdout,'Display modes for '..output..':([^D]+)')
local mls = trimmer(rawlist)
table.insert(winframes_connected_outputs, output)
-- the first line with a "*" after the match contains the rates associated with the current mode
-- local mls = string.match(res["stdout"], "\n" .. string.gsub(output, "%p", "%%%1") .. " connected.*")
local mode = nil
-- old_rate = 0 means "no old rate known to switch to after playback"
local old_rate = 0.0+trimmer(rate)
if (winframes_output_mode ~= "") then
local specialMatcher = trimmer(string.gsub(matcher,'^'..old_mode,winframes_output_mode))
-- special case: user specified a certain preferred mode to use for playback
mp.msg.log("v", "looking for refresh rates for user supplied output mode " .. winframes_output_mode)
found = string.match(mls, specialMatcher)
if (mode == nil) then
mp.msg.log("info", "user preferred output mode " .. winframes_output_mode .. " not found for output " .. output .. " - will use current mode")
mode = old_mode
else
mp.msg.log("info", "using user preferred winframes_output_mode " .. winframes_output_mode .. " for output " .. output)
matcher = specialMatcher
mode = winframes_output_mode
mp.msg.log("v", "old_rate=" .. old_rate .. " found for old_mode=" .. tostring(old_mode))
end
else
mode = old_mode
end
mp.msg.log("info", "output " .. output .. " mode=" .. mode .. " old rate=" .. old_rate)
winframes_modes[output] = { index=index, mode = mode, old_mode = old_mode, rates = {}, old_rate = old_rate }
for s in string.gmatch(mls, matcher) do
-- check if rate "r" is black-listed - this is checked here because
if (not winframes_check_blacklist(mode, 0.0 + s)) then
winframes_modes[output].rates[#winframes_modes[output].rates+1] = 0.0 + s
end
end
end
end
end
local function winframes_find_best_fitting_rate(fps, output)
local winframes_rates = winframes_modes[output].rates
mp.msg.log("info", "output " .. output .. " fps=" .. fps.." available rates="..#winframes_rates)
local ratis = ""
for i = 1, #winframes_rates do
ratis = ratis..";"..winframes_rates[i]
end
mp.msg.log("info","THE RATES: "..ratis)
local fps_rounded = math.floor(fps)
local best_fitting_rate = nil
local best_fitting_ratio = math.huge
-- try integer multipliers of 1 to 10 (given that high-fps displays exist these days)
for m=1,10 do
for i=1,#winframes_rates do
local r = winframes_rates[i]
local ratio = r / (m * (m==1 and fps_rounded or fps))
if (ratio < 1.0) then
ratio = 1.0 / ratio
end
-- If the ratio is more than "very insignificantly off",
-- then add a tiny additional score that will prefer faster
-- over slower display frame rates, because those will cause
-- shorter "stutters" when the display needs to skip or
-- duplicate one source frame.
-- If the ratio is very close to 1.0, then we rather not
-- choose the higher of the existing display rates, because
-- displays performing frame interpolation work better when
-- presented the actual, non-repeated source material frames.
if (ratio > 1.0001) then
ratio = ratio + (0.00000001 * (1000.0 - r))
end
-- mp.msg.log("info", "ratio " .. ratio .. " for r == " .. r)
if (ratio < best_fitting_ratio) then
best_fitting_ratio = ratio
-- the xrand -q output may print nearby frequencies as the same
-- rounded numbers - therefore, if our multiplier is == 1,
-- we better return the video's frame rate, which ChangeScreenResolution
-- is then likely to set the best rate for, even if the mode
-- has some "odd" rate
if (m == 1) then
r = fps
end
best_fitting_rate = r
end
end
end
return best_fitting_rate
end
local winframes_active_outputs = {}
local function winframes_set_active_outputs()
local dn = mp.get_property("display-names")
if (dn ~= nil) then
mp.msg.log("v","display-names=" .. dn)
winframes_active_outputs = {}
for w in (dn .. ","):gmatch("([^,]*),") do
table.insert(winframes_active_outputs, w)
end
end
end
-- last detected non-nil video frame rate:
local winframes_cfps = nil
--we keep track if we changed the refresh rate of multiple monitors
local monitor_trigger = false
local multi_monitor = false
-- for each output, we remember which refresh rate we set last, so
-- we do not unnecessarily set the same refresh rate again
local winframes_previously_set = {}
local function winframes_set_rate()
if not adjust then return end
local f = mp.get_property_native("container-fps")
if ( f == nil or (f == winframes_cfps and not monitor_trigger)) then
-- either no change or no frame rate information, so don't set anything
return
end
monitor_trigger = false
winframes_cfps = f
winframes_detect_available_rates()
winframes_set_active_outputs()
-- unless "--script-opts=xrandr-ignore_unknown_oldrate=true" is set,
-- xrandr.lua will not touch display outputs for which it cannot
-- get information on the current refresh rate for - assuming that
-- such outputs are "disabled" somehow.
local ignore_unknown_oldrate = mp.get_opt("winframes-ignore_unknown_oldrate")
if (ignore_unknown_oldrate == nil) then
ignore_unknown_oldrate = false
end
local outs = {}
if (#winframes_active_outputs == 0) then
-- No active outputs - probably because vo (like with vdpau) does
-- not provide the information which outputs are covered.
-- As a fall-back, let's assume all connected outputs are relevant.
mp.msg.log("v","no output is known to be used by mpv, assuming all connected outputs are used.")
outs = winframes_connected_outputs
else
outs = winframes_active_outputs
end
-- iterate over all relevant outputs used by mpv's output:
for n, output in ipairs(outs) do
if (ignore_unknown_oldrate == false and winframes_modes[output].old_rate == 0) then
mp.msg.log("info", "not touching output " .. output .. " because winframes did not indicate a used refresh rate for it - use --script-opts=winframes-ignore_unknown_oldrate=true if that is not what you want.")
else
local bfr = winframes_find_best_fitting_rate(winframes_cfps, output)
if (bfr == 0.0) then
mp.msg.log("info", "no non-blacklisted rate available, not invoking winframes")
else
mp.msg.log("info", "container fps is " .. winframes_cfps .. "Hz, for output " .. output .. " mode " .. winframes_modes[output].mode .. " the best fitting display rate we will pass to winframes is " .. bfr .. "Hz")
if (bfr == winframes_previously_set[output]) then
mp.msg.log("v", "output " .. output .. " was already set to " .. bfr .. "Hz before - not changing")
else
-- invoke ChangeScreenResolution to set the best fitting refresh rate for output
local p = {
name="subprocess",
playback_only = false,
args = {
winframes_exec_path,
"/d="..winframes_modes[output].index,
"/f="..math.floor(bfr) -- ChangeScreenResolution doesn't accept decimals so 23.976 -> 23, 59.94 -> 59, etc
}
}
if(winframes_modes[output].mode ~= winframes_modes[output].old_mode) then
p.args[#p.args+1] = "/w="..string.match(winframes_modes[output].mode, "^[0-9]+")
p.args[#p.args+1] = "/h="..string.match(winframes_modes[output].mode, "[0-9]+$")
end
mp.msg.log("debug", "executing as subprocess: \"" .. cmdToString(p) .. "\"")
local res = mp.command_native(p)
if (res.error_string ~= "") then
mp.msg.log("error", "failed to set refresh rate for output " .. output .. " using ChangeScreenResolution, error message: " .. res.error_string)
else
winframes_previously_set[output] = bfr
end
end
end
end
end
end
local function winframes_set_old_rate()
local outs = {}
if (#winframes_active_outputs == 0 or multi_monitor) then
-- No active outputs - probably because vo (like with vdpau) does
-- not provide the information which outputs are covered.
-- As a fall-back, let's assume all connected outputs are relevant.
-- If we set the refresh rate for multiple monitors, we also iterate all.
if not multi_monitor then mp.msg.log("v","no output is known to be used by mpv, assuming all connected outputs are used.") end
outs = winframes_connected_outputs
else
outs = winframes_active_outputs
end
-- iterate over all relevant outputs used by mpv's output:
for n, output in ipairs(outs) do
local old_rate = winframes_modes[output].old_rate
if (old_rate == 0 or winframes_previously_set[output] == nil ) then
mp.msg.log("v", "no previous frame rate known for output " .. output .. " - so no switching back.")
else
if (math.abs(old_rate-winframes_previously_set[output]) < 0.001) then
mp.msg.log("v", "output " .. output .. " is already set to " .. old_rate .. "Hz - no switching back required")
else
mp.msg.log("info", "switching output " .. output .. " that was set for replay to mode " .. winframes_modes[output].mode .. " at " .. winframes_previously_set[output] .. "Hz back to mode " .. winframes_modes[output].old_mode .. " with refresh rate " .. old_rate .. "Hz")
-- invoke ChangeScreenResolution to set the best fitting refresh rate for output
local p = {
name="subprocess",
playback_only = false,
args = {
winframes_exec_path,
"/d=".. winframes_modes[output].index,
"/f="..math.floor(old_rate) -- ChangeScreenResolution doesn't accept decimals so 23.976 -> 23, 59.94 -> 59, etc
}
}
if(winframes_modes[output].mode ~= winframes_modes[output].old_mode) then
p.args[#p.args+1] = "/w="..string.match(winframes_modes[output].old_mode, "^[0-9]+")
p.args[#p.args+1] = "/h="..string.match(winframes_modes[output].old_mode, "[0-9]+$")
end
local res = mp.command_native(p)
if (res.error_string ~= "") then
mp.msg.log("error", "failed to set refresh rate for output " .. output .. " using xrandr, error message: " .. res.error_string)
else
winframes_previously_set[output] = old_rate
end
end
end
end
end
-- we'll consider setting refresh rates whenever the video fps or the active outputs change:
mp.observe_property("container-fps", "native", function()
if opts["wait-for-fullscreen"] and not mp.get_property_bool("fullscreen") then return end
winframes_set_rate()
end)
mp.observe_property("display-names", "native", function()
if not opts["old-monitor-handling"] then
monitor_trigger = true
multi_monitor = true
end
if not opts["wait-for-fullscreen"] or mp.get_property_bool("fullscreen") then winframes_set_rate() end
end)
mp.observe_property("fullscreen", "bool",function(_,c)
if not opts["wait-for-fullscreen"] then return end
if c then winframes_set_rate() elseif opts["restore-outside-fullscreen"] then
winframes_set_old_rate()
end
end)
local function toggle_adjustment()
adjust = not adjust
mp.commandv("show-text", "winframes: refresh rate adjustments turned "..(adjust and "on" or "off"), 5000)
if adjust and (not opts["wait-for-fullscreen"] or mp.get_property_bool("fullscreen")) then winframes_set_rate() end
end
mp.add_key_binding("Ctrl+f", "toggle_adjustment", toggle_adjustment)
-- and we'll try to revert the refresh rate when mpv is shut down
mp.register_event("shutdown", winframes_set_old_rate)