Skip to content

Instantly share code, notes, and snippets.

@intelfx
Forked from CyberShadow/autosave.lua
Last active August 31, 2024 17:29
Show Gist options
  • Save intelfx/972269b9fbd2bbbabf1d364b5cec97f9 to your computer and use it in GitHub Desktop.
Save intelfx/972269b9fbd2bbbabf1d364b5cec97f9 to your computer and use it in GitHub Desktop.
-- autosave.lua
--
-- Periodically saves "watch later" data during playback, rather than only saving on quit.
-- This lets you easily recover your position in the case of an ungraceful shutdown of mpv (crash, power failure, etc.).
--
-- You can configure the save period by creating a "lua-settings" directory inside your mpv configuration directory.
-- Inside the "lua-settings" directory, create a file named "autosave.conf".
-- The save period can be set like so:
--
-- save_period=60
--
-- This will set the save period to once every 60 seconds of playback, time while paused is not counted towards the save period timer.
-- The default save period is 30 seconds.
local options = require 'mp.options'
local o = {
save_period = 30,
trailing_time_short = 450, -- tv series: 5 minute credits
trailing_time_long = 900, -- full length: 10-15 minute credits
}
options.read_options(o)
local mp = require 'mp'
-- Do not issue repeated delete-watch-later-config commands
local last_delete = nil
local function delete(path)
if not path then
return
end
if last_delete == path then
return
end
last_delete = path
mp.commandv("delete-watch-later-config", path)
end
local function save()
last_delete = nil
mp.commandv("set", "msg-level", "cplayer=warn")
mp.command("write-watch-later-config")
mp.commandv("set", "msg-level", "cplayer=status")
end
local function trailing_time(duration)
-- tv series (5 minutes credits)
if duration < 3600 then
return o.trailing_time_short
end
-- full length movies (10-15 minutes credits)
return o.trailing_time_long
end
local function save_or_delete(path)
local pos = mp.get_property_native("time-pos")
local duration = mp.get_property_native("duration")
local remaining = mp.get_property_native("time-remaining")
if duration and remaining and remaining < trailing_time(duration) then
local path = mp.get_property_native("path")
delete(path)
else
save()
end
end
local save_period_timer = mp.add_periodic_timer(o.save_period, save_or_delete)
local function pause(name, paused)
save_or_delete()
if paused then
save_period_timer:stop()
else
save_period_timer:resume()
end
end
mp.observe_property("pause", "bool", pause)
mp.register_event("file-loaded", save)
local function end_file(data)
if data.reason == 'eof' or data.reason == 'stop' then
local playlist = mp.get_property_native('playlist')
for i, entry in pairs(playlist) do
if entry.id == playlist_entry_id then
delete(entry.filename)
return
end
end
end
end
mp.register_event("end-file", end_file)
mp.add_hook("on_unload", 50, save_or_delete)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment