This commit is contained in:
ksyasuda 2025-03-10 02:07:25 -07:00
parent afa6c8e2c0
commit c2e9ae47e1
No known key found for this signature in database
8 changed files with 581 additions and 1300 deletions

1
.gitignore vendored
View File

@ -1 +1,2 @@
immersive-data
.ytdl_preload/

View File

@ -200,3 +200,8 @@ CTRL+0 no-osd change-list glsl-shaders clr ""; show-text "GLSL shaders cleared"
ctrl+K cycle-values keep-open "yes" "no"
ctrl+r script-binding reload-scripts
ctrl+s script_binding autosubsync-menu
ctrl+g script-binding sponsorblock/set_segment
ctrl+G script-binding sponsorblock/submit_segment
ctrl+h script-binding sponsorablock/upvote_setment
ctrl+H script-binding sponsorablock/downvote_segment

View File

@ -165,16 +165,12 @@ video-sync=display-resample
osc=no
no-border
ytdl-raw-options=ignore-config=,sub-lang=en,write-auto-sub=
ytdl-raw-options=sub-langs=en.*,write-auto-subs=
ytdl-format=bestvideo+bestaudio/best
# get subtitles for videos automatically
# sub-auto=fuzzy
sub-auto=fuzzy
slang=en,eng
# disable subtitles by default = no
sid=no
video-sync=display-resample
# CATPPUCCIN MACHIATTO
# Main mpv options
@ -222,4 +218,17 @@ profile-cond=p["idle-active"]
profile-restore=copy-equal
title=' '
keepaspect=no
# background=1
[immersion]
cookies=yes
cookies-file=/truenas/sudacode/japanese/cookies.txt
ytdl-raw-options=mark-watched=,write-auto-subs=,sub-langs=ja.*
ytdl-raw-options-append=cookies=/truenas/sudacode/japanese/cookies.txt
ytdl-raw-options-append=sponsorblock-mark=all
ytdl-raw-options-append=sponsorblock-remove=sponsor
ytdl-format=bestvideo+bestaudio/best
# get subtitles for videos automatically
sub-auto=fuzzy
slang=ja,jpn
alang=ja,jpn
vlang=ja,jpn

1
script-opts/stats.conf Normal file
View File

@ -0,0 +1 @@
plot_tonemapping_lut=yes

View File

@ -3,7 +3,7 @@
-- This script skips sponsored segments of YouTube videos
-- using data from https://github.com/ajayyy/SponsorBlock
local ON_WINDOWS = package.config:sub(1,1) ~= "/"
local ON_WINDOWS = package.config:sub(1, 1) ~= "/"
local options = {
server_address = "https://sponsor.ajay.app",
@ -64,7 +64,7 @@ local options = {
fast_forward = false,
-- Playback speed modifier when fast forwarding, applied once every second until cap is reached
fast_forward_increase = .2,
fast_forward_increase = 0.2,
-- Playback speed cap
fast_forward_cap = 2,
@ -77,10 +77,10 @@ local options = {
local_pattern = "",
-- Legacy option, use skip_categories instead
skip = true
skip = true,
}
mp.options = require "mp.options"
mp.options = require("mp.options")
mp.options.read_options(options, "sponsorblock")
local legacy = mp.command_native_async == nil
@ -91,24 +91,26 @@ end
--]]
options.local_database = false
local utils = require "mp.utils"
local utils = require("mp.utils")
scripts_dir = mp.find_config_file("scripts")
local sponsorblock = utils.join_path(scripts_dir, "sponsorblock_shared/sponsorblock.py")
local uid_path = utils.join_path(scripts_dir, "sponsorblock_shared/sponsorblock.txt")
local database_file = options.local_database and utils.join_path(scripts_dir, "sponsorblock_shared/sponsorblock.db") or ""
local database_file = options.local_database and utils.join_path(scripts_dir, "sponsorblock_shared/sponsorblock.db")
or ""
local youtube_id = nil
local ranges = {}
local init = false
local segment = {a = 0, b = 0, progress = 0, first = true}
local segment = { a = 0, b = 0, progress = 0, first = true }
local retrying = false
local last_skip = {uuid = "", dir = nil}
local last_skip = { uuid = "", dir = nil }
local speed_timer = nil
local fade_timer = nil
local fade_dir = nil
local volume_before = mp.get_property_number("volume")
local categories = {}
local all_categories = {"sponsor", "intro", "outro", "interaction", "selfpromo", "preview", "music_offtopic", "filler"}
local all_categories =
{ "sponsor", "intro", "outro", "interaction", "selfpromo", "preview", "music_offtopic", "filler" }
local chapter_cache = {}
for category in string.gmatch(options.skip_categories, "([^,]+)") do
@ -116,13 +118,20 @@ for category in string.gmatch(options.skip_categories, "([^,]+)") do
end
function file_exists(name)
local f = io.open(name,"r")
if f ~= nil then io.close(f) return true else return false end
local f = io.open(name, "r")
if f ~= nil then
io.close(f)
return true
else
return false
end
end
function t_count(t)
local count = 0
for _ in pairs(t) do count = count + 1 end
for _ in pairs(t) do
count = count + 1
end
return count
end
@ -135,9 +144,11 @@ end
function parse_update_interval()
local s = options.auto_update_interval
if s == "" then return 0 end -- Interval Disabled
if s == "" then
return 0
end -- Interval Disabled
local num, mod = s:match "^(%d+)([hdm])$"
local num, mod = s:match("^(%d+)([hdm])$")
if num == nil or mod == nil then
mp.osd_message("[sponsorblock] auto_update_interval " .. s .. " is invalid", 5)
@ -167,7 +178,11 @@ end
function create_chapter(chapter_title, chapter_time)
local chapters = mp.get_property_native("chapter-list")
local duration = mp.get_property_native("duration")
table.insert(chapters, {title=chapter_title, time=(duration == nil or duration > chapter_time) and chapter_time or duration - .001})
table.insert(
chapters,
{ title = chapter_title, time = (duration == nil or duration > chapter_time) and chapter_time
or duration - 0.001 }
)
table.sort(chapters, time_sort)
mp.set_property_native("chapter-list", chapters)
end
@ -176,7 +191,10 @@ function process(uuid, t, new_ranges)
start_time = tonumber(string.match(t, "[^,]+"))
end_time = tonumber(string.sub(string.match(t, ",[^,]+"), 2))
for o_uuid, o_t in pairs(ranges) do
if (start_time >= o_t.start_time and start_time <= o_t.end_time) or (o_t.start_time >= start_time and o_t.start_time <= end_time) then
if
(start_time >= o_t.start_time and start_time <= o_t.end_time)
or (o_t.start_time >= start_time and o_t.start_time <= end_time)
then
new_ranges[o_uuid] = o_t
return
end
@ -187,7 +205,7 @@ function process(uuid, t, new_ranges)
start_time = start_time,
end_time = end_time,
category = category,
skipped = false
skipped = false,
}
end
if options.make_chapters and not chapter_cache[uuid] then
@ -201,12 +219,16 @@ end
function getranges(_, exists, db, more)
if type(exists) == "table" and exists["status"] == "1" then
if options.server_fallback then
mp.add_timeout(0, function() getranges(true, true, "") end)
mp.add_timeout(0, function()
getranges(true, true, "")
end)
else
return mp.osd_message("[sponsorblock] database update failed, gave up")
end
end
if db ~= "" and db ~= database_file then db = database_file end
if db ~= "" and db ~= database_file then
db = database_file
end
if exists ~= true and not file_exists(db) then
if not retrying then
mp.osd_message("[sponsorblock] database update failed, retrying...")
@ -227,19 +249,25 @@ function getranges(_, exists, db, more)
options.server_address,
youtube_id,
options.categories,
tostring(options.sha256_length)
tostring(options.sha256_length),
}
if not legacy then
sponsors = mp.command_native({name = "subprocess", capture_stdout = true, playback_only = false, args = args})
sponsors = mp.command_native({ name = "subprocess", capture_stdout = true, playback_only = false, args = args })
else
sponsors = utils.subprocess({args = args})
sponsors = utils.subprocess({ args = args })
end
mp.msg.debug("Got: " .. string.gsub(sponsors.stdout, "[\n\r]", ""))
if not string.match(sponsors.stdout, "^%s*(.*%S)") then return end
if string.match(sponsors.stdout, "error") then return getranges(true, true) end
if not string.match(sponsors.stdout, "^%s*(.*%S)") then
return
end
if string.match(sponsors.stdout, "error") then
return getranges(true, true)
end
local new_ranges = {}
local r_count = 0
if more then r_count = -1 end
if more then
r_count = -1
end
for t in string.gmatch(sponsors.stdout, "[^:%s]+") do
uuid = string.match(t, "([^,]+),[^,]+$")
if ranges[uuid] then
@ -262,7 +290,9 @@ function fast_forward()
end
local last_speed = mp.get_property_number("speed")
local new_speed = math.min(last_speed + options.fast_forward_increase, options.fast_forward_cap)
if new_speed <= last_speed then return end
if new_speed <= last_speed then
return
end
mp.set_property("speed", new_speed)
end
@ -270,8 +300,12 @@ function fade_audio(step)
local last_volume = mp.get_property_number("volume")
local new_volume = math.max(options.audio_fade_cap, math.min(last_volume + step, volume_before))
if new_volume == last_volume then
if step >= 0 then fade_dir = nil end
if fade_timer ~= nil then fade_timer:kill() end
if step >= 0 then
fade_dir = nil
end
if fade_timer ~= nil then
fade_timer:kill()
end
fade_timer = nil
return
end
@ -279,11 +313,19 @@ function fade_audio(step)
end
function skip_ads(name, pos)
if pos == nil then return end
if pos == nil then
return
end
local sponsor_ahead = false
for uuid, t in pairs(ranges) do
if (options.fast_forward == uuid or not options.skip_once or not t.skipped) and t.start_time <= pos and t.end_time > pos then
if options.fast_forward == uuid then return end
if
(options.fast_forward == uuid or not options.skip_once or not t.skipped)
and t.start_time <= pos
and t.end_time > pos
then
if options.fast_forward == uuid then
return
end
if options.fast_forward == false then
mp.osd_message("[sponsorblock] " .. t.category .. " skipped")
mp.set_property("time-pos", t.end_time)
@ -291,7 +333,7 @@ function skip_ads(name, pos)
mp.osd_message("[sponsorblock] skipping " .. t.category)
end
t.skipped = true
last_skip = {uuid = uuid, dir = nil}
last_skip = { uuid = uuid, dir = nil }
if options.report_views or options.auto_upvote then
local args = {
options.python_path,
@ -304,17 +346,19 @@ function skip_ads(name, pos)
options.report_views and "1" or "",
uid_path,
options.user_id,
options.auto_upvote and "1" or ""
options.auto_upvote and "1" or "",
}
if not legacy then
mp.command_native_async({name = "subprocess", playback_only = false, args = args}, function () end)
mp.command_native_async({ name = "subprocess", playback_only = false, args = args }, function() end)
else
utils.subprocess_detached({args = args})
utils.subprocess_detached({ args = args })
end
end
if options.fast_forward ~= false then
options.fast_forward = uuid
if speed_timer ~= nil then speed_timer:kill() end
if speed_timer ~= nil then
speed_timer:kill()
end
speed_timer = mp.add_periodic_timer(1, fast_forward)
end
return
@ -325,15 +369,25 @@ function skip_ads(name, pos)
if options.audio_fade then
if sponsor_ahead then
if fade_dir ~= false then
if fade_dir == nil then volume_before = mp.get_property_number("volume") end
if fade_timer ~= nil then fade_timer:kill() end
if fade_dir == nil then
volume_before = mp.get_property_number("volume")
end
if fade_timer ~= nil then
fade_timer:kill()
end
fade_dir = false
fade_timer = mp.add_periodic_timer(.1, function() fade_audio(-options.audio_fade_step) end)
fade_timer = mp.add_periodic_timer(0.1, function()
fade_audio(-options.audio_fade_step)
end)
end
elseif fade_dir == false then
fade_dir = true
if fade_timer ~= nil then fade_timer:kill() end
fade_timer = mp.add_periodic_timer(.1, function() fade_audio(options.audio_fade_step) end)
if fade_timer ~= nil then
fade_timer:kill()
end
fade_timer = mp.add_periodic_timer(0.1, function()
fade_audio(options.audio_fade_step)
end)
end
end
if options.fast_forward and options.fast_forward ~= true then
@ -345,9 +399,13 @@ function skip_ads(name, pos)
end
function vote(dir)
if last_skip.uuid == "" then return mp.osd_message("[sponsorblock] no sponsors skipped, can't submit vote") end
if last_skip.uuid == "" then
return mp.osd_message("[sponsorblock] no sponsors skipped, can't submit vote")
end
local updown = dir == "1" and "up" or "down"
if last_skip.dir == dir then return mp.osd_message("[sponsorblock] " .. updown .. "vote already submitted") end
if last_skip.dir == dir then
return mp.osd_message("[sponsorblock] " .. updown .. "vote already submitted")
end
last_skip.dir = dir
local args = {
options.python_path,
@ -360,31 +418,38 @@ function vote(dir)
"",
uid_path,
options.user_id,
dir
dir,
}
if not legacy then
mp.command_native_async({name = "subprocess", playback_only = false, args = args}, function () end)
mp.command_native_async({ name = "subprocess", playback_only = false, args = args }, function() end)
else
utils.subprocess({args = args})
utils.subprocess({ args = args })
end
mp.osd_message("[sponsorblock] " .. updown .. "vote submitted")
end
function update()
mp.command_native_async({name = "subprocess", playback_only = false, args = {
mp.command_native_async(
{
name = "subprocess",
playback_only = false,
args = {
options.python_path,
sponsorblock,
"update",
database_file,
options.server_address
}}, getranges)
options.server_address,
},
},
getranges
)
end
function file_loaded()
local initialized = init
ranges = {}
segment = {a = 0, b = 0, progress = 0, first = true}
last_skip = {uuid = "", dir = nil}
segment = { a = 0, b = 0, progress = 0, first = true }
last_skip = { uuid = "", dir = nil }
chapter_cache = {}
local video_path = mp.get_property("path", "")
mp.msg.debug("Path: " .. video_path)
@ -395,16 +460,20 @@ function file_loaded()
"https?://youtu%.be/([%w-_]+).*",
"https?://w?w?w?%.?youtube%.com/v/([%w-_]+).*",
"/watch.*[?&]v=([%w-_]+).*",
"/embed/([%w-_]+).*"
"/embed/([%w-_]+).*",
}
youtube_id = nil
for i, url in ipairs(urls) do
youtube_id = youtube_id or string.match(video_path, url) or string.match(video_referer, url)
if youtube_id then break end
if youtube_id then
break
end
end
youtube_id = youtube_id or string.match(video_path, options.local_pattern)
if not youtube_id or string.len(youtube_id) < 11 or (local_pattern and string.len(youtube_id) ~= 11) then return end
if not youtube_id or string.len(youtube_id) < 11 or (local_pattern and string.len(youtube_id) ~= 11) then
return
end
youtube_id = string.sub(youtube_id, 1, 11)
mp.msg.debug("Found YouTube ID: " .. youtube_id)
init = true
@ -414,14 +483,20 @@ function file_loaded()
local exists = file_exists(database_file)
if exists and options.server_fallback then
getranges(true, true)
mp.add_timeout(0, function() getranges(true, true, "", true) end)
mp.add_timeout(0, function()
getranges(true, true, "", true)
end)
elseif exists then
getranges(true, true)
elseif options.server_fallback then
mp.add_timeout(0, function() getranges(true, true, "") end)
mp.add_timeout(0, function()
getranges(true, true, "")
end)
end
end
if initialized then return end
if initialized then
return
end
if options.skip then
mp.observe_property("time-pos", "native", skip_ads)
end
@ -437,30 +512,38 @@ function file_loaded()
"",
uid_path,
options.user_id,
options.display_name
options.display_name,
}
if not legacy then
mp.command_native_async({name = "subprocess", playback_only = false, args = args}, function () end)
mp.command_native_async({ name = "subprocess", playback_only = false, args = args }, function() end)
else
utils.subprocess_detached({args = args})
utils.subprocess_detached({ args = args })
end
end
if not options.local_database or (not options.auto_update and file_exists(database_file)) then return end
if not options.local_database or (not options.auto_update and file_exists(database_file)) then
return
end
if file_exists(database_file) then
local db_info = utils.file_info(database_file)
local cur_time = os.time(os.date("*t"))
local upd_interval = parse_update_interval()
if upd_interval == nil or os.difftime(cur_time, db_info.mtime) < upd_interval then return end
if upd_interval == nil or os.difftime(cur_time, db_info.mtime) < upd_interval then
return
end
end
update()
end
function set_segment()
if not youtube_id then return end
if not youtube_id then
return
end
local pos = mp.get_property_number("time-pos")
if pos == nil then return end
if pos == nil then
return
end
if segment.progress > 1 then
segment.progress = segment.progress - 2
end
@ -487,14 +570,16 @@ end
function select_category(selected)
for category in string.gmatch(options.categories, "([^,]+)") do
mp.remove_key_binding("select_category_"..category)
mp.remove_key_binding("kp_select_category_"..category)
mp.remove_key_binding("select_category_" .. category)
mp.remove_key_binding("kp_select_category_" .. category)
end
submit_segment(selected)
end
function submit_segment(category)
if not youtube_id then return end
if not youtube_id then
return
end
local start_time = math.min(segment.a, segment.b)
local end_time = math.max(segment.a, segment.b)
if end_time - start_time == 0 or end_time == 0 then
@ -505,10 +590,27 @@ function submit_segment(category)
for category_id, category in pairs(all_categories) do
local category_title = (category:gsub("^%l", string.upper):gsub("_", " "))
category_list = category_list .. category_id .. ": " .. category_title .. "\n"
mp.add_forced_key_binding(tostring(category_id), "select_category_"..category, function() select_category(category) end)
mp.add_forced_key_binding("KP"..tostring(category_id), "kp_select_category_"..category, function() select_category(category) end)
mp.add_forced_key_binding(tostring(category_id), "select_category_" .. category, function()
select_category(category)
end)
mp.add_forced_key_binding("KP" .. tostring(category_id), "kp_select_category_" .. category, function()
select_category(category)
end)
end
mp.osd_message(string.format("[sponsorblock] press a number to select category for segment: %.2d:%.2d:%.2d to %.2d:%.2d:%.2d\n\n" .. category_list .. "\nyou can press Shift+G again for default (Sponsor) or hide this message with g", math.floor(start_time/(60*60)), math.floor(start_time/60%60), math.floor(start_time%60), math.floor(end_time/(60*60)), math.floor(end_time/60%60), math.floor(end_time%60)), 30)
mp.osd_message(
string.format(
"[sponsorblock] press a number to select category for segment: %.2d:%.2d:%.2d to %.2d:%.2d:%.2d\n\n"
.. category_list
.. "\nyou can press Shift+G again for default (Sponsor) or hide this message with g",
math.floor(start_time / (60 * 60)),
math.floor(start_time / 60 % 60),
math.floor(start_time % 60),
math.floor(end_time / (60 * 60)),
math.floor(end_time / 60 % 60),
math.floor(end_time % 60)
),
30
)
else
mp.osd_message("[sponsorblock] submitting segment...", 30)
local submit
@ -523,15 +625,16 @@ function submit_segment(category)
tostring(end_time),
uid_path,
options.user_id,
category or "sponsor"
category or "sponsor",
}
if not legacy then
submit = mp.command_native({name = "subprocess", capture_stdout = true, playback_only = false, args = args})
submit =
mp.command_native({ name = "subprocess", capture_stdout = true, playback_only = false, args = args })
else
submit = utils.subprocess({args = args})
submit = utils.subprocess({ args = args })
end
if string.match(submit.stdout, "success") then
segment = {a = 0, b = 0, progress = 0, first = true}
segment = { a = 0, b = 0, progress = 0, first = true }
mp.osd_message("[sponsorblock] segment submitted")
if options.make_chapters then
clean_chapters()
@ -544,12 +647,12 @@ function submit_segment(category)
mp.osd_message("[sponsorblock] segment submission failed, server is down. try again", 5)
elseif string.match(submit.stdout, "400") then
mp.osd_message("[sponsorblock] segment submission failed, impossible inputs", 5)
segment = {a = 0, b = 0, progress = 0, first = true}
segment = { a = 0, b = 0, progress = 0, first = true }
elseif string.match(submit.stdout, "429") then
mp.osd_message("[sponsorblock] segment submission failed, rate limited. try again", 5)
elseif string.match(submit.stdout, "409") then
mp.osd_message("[sponsorblock] segment already submitted", 3)
segment = {a = 0, b = 0, progress = 0, first = true}
segment = { a = 0, b = 0, progress = 0, first = true }
else
mp.osd_message("[sponsorblock] segment submission failed", 5)
end
@ -557,12 +660,20 @@ function submit_segment(category)
end
mp.register_event("file-loaded", file_loaded)
mp.add_key_binding("g", "set_segment", set_segment)
mp.add_key_binding("G", "submit_segment", submit_segment)
mp.add_key_binding("h", "upvote_segment", function() return vote("1") end)
mp.add_key_binding("H", "downvote_segment", function() return vote("0") end)
mp.add_key_binding("ctrl+g", "set_segment", set_segment)
mp.add_key_binding("ctrl+G", "submit_segment", submit_segment)
mp.add_key_binding("ctrl+h", "upvote_segment", function()
return vote("1")
end)
mp.add_key_binding("ctrl+H", "downvote_segment", function()
return vote("0")
end)
-- Bindings below are for backwards compatibility and could be removed at any time
mp.add_key_binding(nil, "sponsorblock_set_segment", set_segment)
mp.add_key_binding(nil, "sponsorblock_submit_segment", submit_segment)
mp.add_key_binding(nil, "sponsorblock_upvote", function() return vote("1") end)
mp.add_key_binding(nil, "sponsorblock_downvote", function() return vote("0") end)
mp.add_key_binding(nil, "sponsorblock_upvote", function()
return vote("1")
end)
mp.add_key_binding(nil, "sponsorblock_downvote", function()
return vote("0")
end)

View File

@ -1,92 +0,0 @@
-- Rebuild the terminal status line as a lua script
-- Be aware that this will require more cpu power!
-- Also, this is based on a rather old version of the
-- builtin mpv status line.
-- Add a string to the status line
function atsl(s)
newStatus = newStatus .. s
end
function update_status_line()
-- Reset the status line
newStatus = ""
if mp.get_property_bool("pause") then
atsl("(Paused) ")
elseif mp.get_property_bool("paused-for-cache") then
atsl("(Buffering) ")
end
if mp.get_property("aid") ~= "no" then
atsl("A")
end
if mp.get_property("vid") ~= "no" then
atsl("V")
end
atsl(": ")
atsl(mp.get_property_osd("time-pos"))
atsl(" / ");
atsl(mp.get_property_osd("duration"));
atsl(" (")
atsl(mp.get_property_osd("percent-pos", -1))
atsl("%)")
local r = mp.get_property_number("speed", -1)
if r ~= 1 then
atsl(string.format(" x%4.2f", r))
end
r = mp.get_property_number("avsync", nil)
if r ~= nil then
atsl(string.format(" A-V: %f", r))
end
r = mp.get_property("total-avsync-change", 0)
if math.abs(r) > 0.05 then
atsl(string.format(" ct:%7.3f", r))
end
r = mp.get_property_number("decoder-drop-frame-count", -1)
if r > 0 then
atsl(" Late: ")
atsl(r)
end
r = mp.get_property_osd("video-bitrate")
if r ~= nil and r ~= "" then
atsl(" Vb: ")
atsl(r)
end
r = mp.get_property_osd("audio-bitrate")
if r ~= nil and r ~= "" then
atsl(" Ab: ")
atsl(r)
end
r = mp.get_property_number("cache", 0)
if r > 0 then
atsl(string.format(" Cache: %d%% ", r))
end
-- Set the new status line
mp.set_property("options/term-status-msg", newStatus)
end
timer = mp.add_periodic_timer(1, update_status_line)
function on_pause_change(name, value)
if value == false then
timer:resume()
else
timer:stop()
end
mp.add_timeout(0.1, update_status_line)
end
mp.observe_property("pause", "bool", on_pause_change)
mp.register_event("seek", update_status_line)

View File

@ -1 +1 @@
ytdl-preload/ytdl-preload.lua
../ytdl-preload/ytdl-preload.lua

754
stats.lua
View File

@ -1,754 +0,0 @@
-- Display some stats.
--
-- Please consult the readme for information about usage and configuration:
-- https://github.com/Argon-/mpv-stats
--
-- Please note: not every property is always available and therefore not always
-- visible.
local mp = require 'mp'
local options = require 'mp.options'
local utils = require 'mp.utils'
-- Options
local o = {
-- Default key bindings
key_oneshot = "i",
key_toggle = "I",
key_page_1 = "1",
key_page_2 = "2",
key_page_3 = "3",
duration = 4,
redraw_delay = 1, -- acts as duration in the toggling case
ass_formatting = true,
persistent_overlay = false, -- whether the stats can be overwritten by other output
print_perfdata_passes = false, -- when true, print the full information about all passes
filter_params_max_length = 100, -- a filter list longer than this many characters will be shown one filter per line instead
debug = false,
-- Graph options and style
plot_perfdata = true,
plot_vsync_ratio = true,
plot_vsync_jitter = true,
skip_frames = 5,
global_max = true,
flush_graph_data = true, -- clear data buffers when toggling
plot_bg_border_color = "0000FF",
plot_bg_color = "262626",
plot_color = "FFFFFF",
-- Text style
font = "Source Sans Pro",
font_mono = "Source Sans Pro", -- monospaced digits are sufficient
font_size = 8,
font_color = "FFFFFF",
border_size = 0.8,
border_color = "262626",
shadow_x_offset = 0.0,
shadow_y_offset = 0.0,
shadow_color = "000000",
alpha = "11",
-- Custom header for ASS tags to style the text output.
-- Specifying this will ignore the text style values above and just
-- use this string instead.
custom_header = "",
-- Text formatting
-- With ASS
ass_nl = "\\N",
ass_indent = "\\h\\h\\h\\h\\h",
ass_prefix_sep = "\\h\\h",
ass_b1 = "{\\b1}",
ass_b0 = "{\\b0}",
ass_it1 = "{\\i1}",
ass_it0 = "{\\i0}",
-- Without ASS
no_ass_nl = "\n",
no_ass_indent = "\t",
no_ass_prefix_sep = " ",
no_ass_b1 = "\027[1m",
no_ass_b0 = "\027[0m",
no_ass_it1 = "\027[3m",
no_ass_it0 = "\027[0m",
}
options.read_options(o)
local format = string.format
local max = math.max
local min = math.min
-- Function used to record performance data
local recorder = nil
-- Timer used for redrawing (toggling) and clearing the screen (oneshot)
local display_timer = nil
-- Current page and <page key>:<page function> mappings
local curr_page = o.key_page_1
local pages = {}
-- Save these sequences locally as we'll need them a lot
local ass_start = mp.get_property_osd("osd-ass-cc/0")
local ass_stop = mp.get_property_osd("osd-ass-cc/1")
-- Ring buffers for the values used to construct a graph.
-- .pos denotes the current position, .len the buffer length
-- .max is the max value in the corresponding buffer
local vsratio_buf, vsjitter_buf
local function init_buffers()
vsratio_buf = {0, pos = 1, len = 50, max = 0}
vsjitter_buf = {0, pos = 1, len = 50, max = 0}
end
-- Save all properties known to this version of mpv
local property_list = {}
for p in string.gmatch(mp.get_property("property-list"), "([^,]+)") do property_list[p] = true end
-- Mapping of properties to their deprecated names
local property_aliases = {
["decoder-frame-drop-count"] = "drop-frame-count",
["frame-drop-count"] = "vo-drop-frame-count",
["container-fps"] = "fps",
}
-- Return deprecated name for the given property
local function compat(p)
while not property_list[p] and property_aliases[p] do
p = property_aliases[p]
end
return p
end
local function set_ASS(b)
if not o.use_ass or o.persistent_overlay then
return ""
end
return b and ass_start or ass_stop
end
local function no_ASS(t)
return set_ASS(false) .. t .. set_ASS(true)
end
local function b(t)
return o.b1 .. t .. o.b0
end
local function it(t)
return o.it1 .. t .. o.it0
end
local function text_style()
if not o.use_ass then
return ""
end
if o.custom_header and o.custom_header ~= "" then
return set_ASS(true) .. o.custom_header
else
return format("%s{\\r}{\\an7}{\\fs%d}{\\fn%s}{\\bord%f}{\\3c&H%s&}" ..
"{\\1c&H%s&}{\\alpha&H%s&}{\\xshad%f}{\\yshad%f}{\\4c&H%s&}",
set_ASS(true), o.font_size, o.font, o.border_size,
o.border_color, o.font_color, o.alpha, o.shadow_x_offset,
o.shadow_y_offset, o.shadow_color)
end
end
local function has_vo_window()
return mp.get_property("vo-configured") == "yes"
end
local function has_ansi()
local is_windows = type(package) == 'table'
and type(package.config) == 'string'
and package.config:sub(1, 1) == '\\'
if is_windows then
return os.getenv("ANSICON")
end
return true
end
-- Generate a graph from the given values.
-- Returns an ASS formatted vector drawing as string.
--
-- values: Array/table of numbers representing the data. Used like a ring buffer
-- it will get iterated backwards `len` times starting at position `i`.
-- i : Index of the latest data value in `values`.
-- len : The length/amount of numbers in `values`.
-- v_max : The maximum number in `values`. It is used to scale all data
-- values to a range of 0 to `v_max`.
-- v_avg : The average number in `values`. It is used to try and center graphs
-- if possible. May be left as nil
-- scale : A value that will be multiplied with all data values.
-- x_tics: Horizontal width multiplier for the steps
local function generate_graph(values, i, len, v_max, v_avg, scale, x_tics)
-- Check if at least one value exists
if not values[i] then
return ""
end
local x_max = (len - 1) * x_tics
local y_offset = o.border_size
local y_max = o.font_size * 0.66
local x = 0
-- try and center the graph if possible, but avoid going above `scale`
if v_avg then
scale = min(scale, v_max / (2 * v_avg))
end
local s = {format("m 0 0 n %f %f l ", x, y_max - (y_max * values[i] / v_max * scale))}
i = ((i - 2) % len) + 1
for p = 1, len - 1 do
if values[i] then
x = x - x_tics
s[#s+1] = format("%f %f ", x, y_max - (y_max * values[i] / v_max * scale))
end
i = ((i - 2) % len) + 1
end
s[#s+1] = format("%f %f %f %f", x, y_max, 0, y_max)
local bg_box = format("{\\bord0.5}{\\3c&H%s&}{\\1c&H%s&}m 0 %f l %f %f %f 0 0 0",
o.plot_bg_border_color, o.plot_bg_color, y_max, x_max, y_max, x_max)
return format("%s{\\r}{\\pbo%f}{\\shad0}{\\alpha&H00}{\\p1}%s{\\p0}{\\bord0}{\\1c&H%s}{\\p1}%s{\\p0}%s",
o.prefix_sep, y_offset, bg_box, o.plot_color, table.concat(s), text_style())
end
local function append(s, str, attr)
if not str then
return false
end
attr.prefix_sep = attr.prefix_sep or o.prefix_sep
attr.indent = attr.indent or o.indent
attr.nl = attr.nl or o.nl
attr.suffix = attr.suffix or ""
attr.prefix = attr.prefix or ""
attr.no_prefix_markup = attr.no_prefix_markup or false
attr.prefix = attr.no_prefix_markup and attr.prefix or b(attr.prefix)
s[#s+1] = format("%s%s%s%s%s%s", attr.nl, attr.indent,
attr.prefix, attr.prefix_sep, no_ASS(str), attr.suffix)
return true
end
-- Format and append a property.
-- A property whose value is either `nil` or empty (hereafter called "invalid")
-- is skipped and not appended.
-- Returns `false` in case nothing was appended, otherwise `true`.
--
-- s : Table containing strings.
-- prop : The property to query and format (based on its OSD representation).
-- attr : Optional table to overwrite certain (formatting) attributes for
-- this property.
-- exclude: Optional table containing keys which are considered invalid values
-- for this property. Specifying this will replace empty string as
-- default invalid value (nil is always invalid).
local function append_property(s, prop, attr, excluded)
excluded = excluded or {[""] = true}
local ret = mp.get_property_osd(prop)
if not ret or excluded[ret] then
if o.debug then
print("No value for property: " .. prop)
end
return false
end
return append(s, ret, attr)
end
local function append_perfdata(s, dedicated_page)
local vo_p = mp.get_property_native("vo-passes")
if not vo_p then
return
end
local ds = mp.get_property_bool("display-sync-active", false)
local target_fps = ds and mp.get_property_number("display-fps", 0)
or mp.get_property_number(compat("container-fps"), 0)
if target_fps > 0 then target_fps = 1 / target_fps * 1e9 end
-- Sums of all last/avg/peak values
local last_s, avg_s, peak_s = {}, {}, {}
for frame, data in pairs(vo_p) do
last_s[frame], avg_s[frame], peak_s[frame] = 0, 0, 0
for _, pass in ipairs(data) do
last_s[frame] = last_s[frame] + pass["last"]
avg_s[frame] = avg_s[frame] + pass["avg"]
peak_s[frame] = peak_s[frame] + pass["peak"]
end
end
-- Pretty print measured time
local function pp(i)
-- rescale to microseconds for a saner display
return format("%05d", i / 1000)
end
-- Format n/m with a font weight based on the ratio
local function p(n, m)
local i = 0
if m > 0 then
i = tonumber(n) / m
end
-- Calculate font weight. 100 is minimum, 400 is normal, 700 bold, 900 is max
local w = (700 * math.sqrt(i)) + 200
return format("{\\b%d}%02d%%{\\b0}", w, i * 100)
end
s[#s+1] = format("%s%s%s%s{\\fs%s}%s{\\fs%s}",
dedicated_page and "" or o.nl, dedicated_page and "" or o.indent,
b("Frame Timings:"), o.prefix_sep, o.font_size * 0.66,
"(last/average/peak μs)", o.font_size)
for frame, data in pairs(vo_p) do
local f = "%s%s%s{\\fn%s}%s / %s / %s %s%s{\\fn%s}%s%s%s"
if dedicated_page then
s[#s+1] = format("%s%s%s:", o.nl, o.indent,
b(frame:gsub("^%l", string.upper)))
for _, pass in ipairs(data) do
s[#s+1] = format(f, o.nl, o.indent, o.indent,
o.font_mono, pp(pass["last"]),
pp(pass["avg"]), pp(pass["peak"]),
o.prefix_sep .. o.prefix_sep, p(pass["last"], last_s[frame]),
o.font, o.prefix_sep, o.prefix_sep, pass["desc"])
if o.plot_perfdata and o.use_ass then
s[#s+1] = generate_graph(pass["samples"], pass["count"],
pass["count"], pass["peak"],
pass["avg"], 0.9, 0.25)
end
end
-- Print sum of timing values as "Total"
s[#s+1] = format(f, o.nl, o.indent, o.indent,
o.font_mono, pp(last_s[frame]),
pp(avg_s[frame]), pp(peak_s[frame]), "", "", o.font,
o.prefix_sep, o.prefix_sep, b("Total"))
else
-- for the simplified view, we just print the sum of each pass
s[#s+1] = format(f, o.nl, o.indent, o.indent, o.font_mono,
pp(last_s[frame]), pp(avg_s[frame]), pp(peak_s[frame]),
"", "", o.font, o.prefix_sep, o.prefix_sep,
frame:gsub("^%l", string.upper))
end
end
end
local function append_display_sync(s)
if not mp.get_property_bool("display-sync-active", false) then
return
end
local vspeed = append_property(s, "video-speed-correction", {prefix="DS:"})
if vspeed then
append_property(s, "audio-speed-correction",
{prefix="/", nl="", indent=" ", prefix_sep=" ", no_prefix_markup=true})
else
append_property(s, "audio-speed-correction",
{prefix="DS:" .. o.prefix_sep .. " - / ", prefix_sep=""})
end
append_property(s, "mistimed-frame-count", {prefix="Mistimed:", nl=""})
append_property(s, "vo-delayed-frame-count", {prefix="Delayed:", nl=""})
-- As we need to plot some graphs we print jitter and ratio on their own lines
if not display_timer.oneshot and (o.plot_vsync_ratio or o.plot_vsync_jitter) and o.use_ass then
local ratio_graph = ""
local jitter_graph = ""
if o.plot_vsync_ratio then
ratio_graph = generate_graph(vsratio_buf, vsratio_buf.pos, vsratio_buf.len, vsratio_buf.max, nil, 0.8, 1)
end
if o.plot_vsync_jitter then
jitter_graph = generate_graph(vsjitter_buf, vsjitter_buf.pos, vsjitter_buf.len, vsjitter_buf.max, nil, 0.8, 1)
end
append_property(s, "vsync-ratio", {prefix="VSync Ratio:", suffix=o.prefix_sep .. ratio_graph})
append_property(s, "vsync-jitter", {prefix="VSync Jitter:", suffix=o.prefix_sep .. jitter_graph})
else
-- Since no graph is needed we can print ratio/jitter on the same line and save some space
local vratio = append_property(s, "vsync-ratio", {prefix="VSync Ratio:"})
append_property(s, "vsync-jitter", {prefix="VSync Jitter:", nl="" or o.nl})
end
end
local function append_filters(s, prop, prefix)
local length = 0
local filters = {}
for _,f in ipairs(mp.get_property_native(prop, {})) do
local n = f.name
if f.enabled ~= nil and not f.enabled then
n = n .. " (disabled)"
end
local p = {}
for key,value in pairs(f.params) do
p[#p+1] = key .. "=" .. value
end
if #p > 0 then
p = " [" .. table.concat(p, " ") .. "]"
else
p = ""
end
length = length + n:len() + p:len()
filters[#filters+1] = no_ASS(n) .. it(no_ASS(p))
end
if #filters > 0 then
local ret
if length < o.filter_params_max_length then
ret = table.concat(filters, ", ")
else
local sep = o.nl .. o.indent .. o.indent
ret = sep .. table.concat(filters, sep)
end
s[#s+1] = o.nl .. o.indent .. b(prefix) .. o.prefix_sep .. ret
end
end
local function add_header(s)
s[#s+1] = text_style()
end
local function add_file(s)
append(s, "", {prefix="File:", nl="", indent=""})
append_property(s, "filename", {prefix_sep="", nl="", indent=""})
if not (mp.get_property_osd("filename") == mp.get_property_osd("media-title")) then
append_property(s, "media-title", {prefix="Title:"})
end
local ch_index = mp.get_property_number("chapter")
if ch_index and ch_index >= 0 then
append_property(s, "chapter-list/" .. tostring(ch_index) .. "/title", {prefix="Chapter:"})
append_property(s, "chapter-list/count",
{prefix="(" .. tostring(ch_index + 1) .. "/", suffix=")", nl="",
indent=" ", prefix_sep=" ", no_prefix_markup=true})
end
local demuxer_cache = mp.get_property_native("demuxer-cache-state", {})
if demuxer_cache["fw-bytes"] then
demuxer_cache = demuxer_cache["fw-bytes"] -- returns bytes
else
demuxer_cache = 0
end
local demuxer_secs = mp.get_property_number("demuxer-cache-duration", 0)
local stream_cache = mp.get_property_number("cache-used", 0) * 1024 -- returns KiB
if stream_cache + demuxer_cache + demuxer_secs > 0 then
append(s, utils.format_bytes_humanized(stream_cache + demuxer_cache), {prefix="Total Cache:"})
append(s, utils.format_bytes_humanized(demuxer_cache), {prefix="(Demuxer:",
suffix=",", nl="", no_prefix_markup=true, indent=o.prefix_sep})
append(s, format("%.1f", demuxer_secs), {suffix=" sec)", nl="", indent="",
no_prefix_markup=true})
local speed = mp.get_property_number("cache-speed", 0)
if speed > 0 then
append(s, utils.format_bytes_humanized(speed) .. "/s", {prefix="Speed:", nl="",
indent=o.prefix_sep, no_prefix_markup=true})
end
end
append_property(s, "file-size", {prefix="Size:"})
end
local function add_video(s)
local r = mp.get_property_native("video-params")
-- in case of e.g. lavi-complex there can be no input video, only output
if not r then
r = mp.get_property_native("video-out-params")
end
if not r then
return
end
append(s, "", {prefix=o.nl .. o.nl .. "Video:", nl="", indent=""})
if append_property(s, "video-codec", {prefix_sep="", nl="", indent=""}) then
append_property(s, "hwdec-current", {prefix="(hwdec:", nl="", indent=" ",
no_prefix_markup=true, suffix=")"}, {no=true, [""]=true})
end
append_property(s, "avsync", {prefix="A-V:"})
if append_property(s, compat("decoder-frame-drop-count"),
{prefix="Dropped Frames:", suffix=" (decoder)"}) then
append_property(s, compat("frame-drop-count"), {suffix=" (output)", nl="", indent=""})
end
if append_property(s, "display-fps", {prefix="Display FPS:", suffix=" (specified)"}) then
append_property(s, "estimated-display-fps",
{suffix=" (estimated)", nl="", indent=""})
else
append_property(s, "estimated-display-fps",
{prefix="Display FPS:", suffix=" (estimated)"})
end
if append_property(s, compat("container-fps"), {prefix="FPS:", suffix=" (specified)"}) then
append_property(s, "estimated-vf-fps",
{suffix=" (estimated)", nl="", indent=""})
else
append_property(s, "estimated-vf-fps",
{prefix="FPS:", suffix=" (estimated)"})
end
append_display_sync(s)
append_perfdata(s, o.print_perfdata_passes)
if append(s, r["w"], {prefix="Native Resolution:"}) then
append(s, r["h"], {prefix="x", nl="", indent=" ", prefix_sep=" ", no_prefix_markup=true})
end
append_property(s, "window-scale", {prefix="Window Scale:"})
append(s, format("%.2f", r["aspect"]), {prefix="Aspect Ratio:"})
append(s, r["pixelformat"], {prefix="Pixel Format:"})
-- Group these together to save vertical space
local prim = append(s, r["primaries"], {prefix="Primaries:"})
local cmat = append(s, r["colormatrix"], {prefix="Colormatrix:", nl=prim and "" or o.nl})
append(s, r["colorlevels"], {prefix="Levels:", nl=cmat and "" or o.nl})
-- Append HDR metadata conditionally (only when present and interesting)
local hdrpeak = r["sig-peak"] or 0
local hdrinfo = ""
if hdrpeak > 1 then
hdrinfo = " (HDR peak: " .. format("%.2f", hdrpeak) .. ")"
end
append(s, r["gamma"], {prefix="Gamma:", suffix=hdrinfo})
append_property(s, "packet-video-bitrate", {prefix="Bitrate:", suffix=" kbps"})
append_filters(s, "vf", "Filters:")
end
local function add_audio(s)
local r = mp.get_property_native("audio-params")
-- in case of e.g. lavi-complex there can be no input audio, only output
if not r then
r = mp.get_property_native("audio-out-params")
end
if not r then
return
end
append(s, "", {prefix=o.nl .. o.nl .. "Audio:", nl="", indent=""})
append_property(s, "audio-codec", {prefix_sep="", nl="", indent=""})
append(s, r["format"], {prefix="Format:"})
append(s, r["samplerate"], {prefix="Sample Rate:", suffix=" Hz"})
append(s, r["channel-count"], {prefix="Channels:"})
append_property(s, "packet-audio-bitrate", {prefix="Bitrate:", suffix=" kbps"})
append_filters(s, "af", "Filters:")
end
-- Determine whether ASS formatting shall/can be used and set formatting sequences
local function eval_ass_formatting()
o.use_ass = o.ass_formatting and has_vo_window()
if o.use_ass then
o.nl = o.ass_nl
o.indent = o.ass_indent
o.prefix_sep = o.ass_prefix_sep
o.b1 = o.ass_b1
o.b0 = o.ass_b0
o.it1 = o.ass_it1
o.it0 = o.ass_it0
else
o.nl = o.no_ass_nl
o.indent = o.no_ass_indent
o.prefix_sep = o.no_ass_prefix_sep
if not has_ansi() then
o.b1 = ""
o.b0 = ""
o.it1 = ""
o.it0 = ""
else
o.b1 = o.no_ass_b1
o.b0 = o.no_ass_b0
o.it1 = o.no_ass_it1
o.it0 = o.no_ass_it0
end
end
end
-- Returns an ASS string with "normal" stats
local function default_stats()
local stats = {}
eval_ass_formatting()
add_header(stats)
add_file(stats)
add_video(stats)
add_audio(stats)
return table.concat(stats)
end
-- Returns an ASS string with extended VO stats
local function vo_stats()
local stats = {}
eval_ass_formatting()
add_header(stats)
append_perfdata(stats, true)
return table.concat(stats)
end
-- Returns an ASS string with stats about filters/profiles/shaders
local function filter_stats()
return "coming soon"
end
-- Current page and <page key>:<page function> mapping
curr_page = o.key_page_1
pages = {
[o.key_page_1] = { f = default_stats, desc = "Default" },
[o.key_page_2] = { f = vo_stats, desc = "Extended Frame Timings" },
--[o.key_page_3] = { f = filter_stats, desc = "Dummy" },
}
-- Returns a function to record vsratio/jitter with the specified `skip` value
local function record_data(skip)
init_buffers()
skip = max(skip, 0)
local i = skip
return function()
if i < skip then
i = i + 1
return
else
i = 0
end
if o.plot_vsync_jitter then
local r = mp.get_property_number("vsync-jitter", nil)
if r then
vsjitter_buf.pos = (vsjitter_buf.pos % vsjitter_buf.len) + 1
vsjitter_buf[vsjitter_buf.pos] = r
vsjitter_buf.max = max(vsjitter_buf.max, r)
end
end
if o.plot_vsync_ratio then
local r = mp.get_property_number("vsync-ratio", nil)
if r then
vsratio_buf.pos = (vsratio_buf.pos % vsratio_buf.len) + 1
vsratio_buf[vsratio_buf.pos] = r
vsratio_buf.max = max(vsratio_buf.max, r)
end
end
end
end
-- Call the function for `page` and print it to OSD
local function print_page(page)
if o.persistent_overlay then
mp.set_osd_ass(0, 0, pages[page].f())
else
mp.osd_message(pages[page].f(), display_timer.oneshot and o.duration or o.redraw_delay + 1)
end
end
local function clear_screen()
if o.persistent_overlay then mp.set_osd_ass(0, 0, "") else mp.osd_message("", 0) end
end
-- Add keybindings for every page
local function add_page_bindings()
local function a(k)
return function()
curr_page = k
print_page(k)
if display_timer.oneshot then display_timer:kill() ; display_timer:resume() end
end
end
for k, _ in pairs(pages) do
mp.add_forced_key_binding(k, k, a(k), {repeatable=true})
end
end
-- Remove keybindings for every page
local function remove_page_bindings()
for k, _ in pairs(pages) do
mp.remove_key_binding(k)
end
end
local function process_key_binding(oneshot)
-- Stats are already being displayed
if display_timer:is_enabled() then
-- Previous and current keys were oneshot -> restart timer
if display_timer.oneshot and oneshot then
display_timer:kill()
print_page(curr_page)
display_timer:resume()
-- Previous and current keys were toggling -> end toggling
elseif not display_timer.oneshot and not oneshot then
display_timer:kill()
clear_screen()
remove_page_bindings()
if recorder then
mp.unregister_event(recorder)
recorder = nil
end
end
-- No stats are being displayed yet
else
if not oneshot and (o.plot_vsync_jitter or o.plot_vsync_ratio) then
recorder = record_data(o.skip_frames)
mp.register_event("tick", recorder)
end
display_timer:kill()
display_timer.oneshot = oneshot
display_timer.timeout = oneshot and o.duration or o.redraw_delay
add_page_bindings()
print_page(curr_page)
display_timer:resume()
end
end
-- Create the timer used for redrawing (toggling) or clearing the screen (oneshot)
-- The duration here is not important and always set in process_key_binding()
display_timer = mp.add_periodic_timer(o.duration,
function()
if display_timer.oneshot then
display_timer:kill() ; clear_screen() ; remove_page_bindings()
else
print_page(curr_page)
end
end)
display_timer:kill()
-- Single invocation key binding
mp.add_key_binding(o.key_oneshot, "display-stats", function() process_key_binding(true) end,
{repeatable=true})
-- Toggling key binding
mp.add_key_binding(o.key_toggle, "display-stats-toggle", function() process_key_binding(false) end,
{repeatable=false})
-- Single invocation bindings without key, can be used in input.conf to create
-- bindings for a specific page: "e script-binding stats/display-page-2"
for k, _ in pairs(pages) do
mp.add_key_binding(nil, "display-page-" .. k, function() process_key_binding(true) end,
{repeatable=true})
end
-- Reprint stats immediately when VO was reconfigured, only when toggled
mp.register_event("video-reconfig",
function()
if display_timer:is_enabled() then
print_page(curr_page)
end
end)