Skip to content

Instantly share code, notes, and snippets.

@TheDrHax
Created October 5, 2019 23:10
Show Gist options
  • Save TheDrHax/3b7bc7d819effa101e09f355d9390578 to your computer and use it in GitHub Desktop.
Save TheDrHax/3b7bc7d819effa101e09f355d9390578 to your computer and use it in GitHub Desktop.
MPV script that speeds up playback to maintain synchronization with live streams
-- keepsync.lua
--
-- Attempts to maintain initial offset of the live stream in case of
-- network or hardware lags by slightly speeding up playback until
-- synchronization is restored.
--
-- Initial offset is calculated right at the start of playback. If playback
-- immediately starts to lag, you can increase offset by pressing Shift+LEFT.
-- If your connection to stream source is good enough, you can also try to
-- decrease offset by pressing Shift+RIGHT. Both hotkeys are changing offset
-- by 1 second.
--
-- This script was tested only with streamlink, both with and without the low
-- latency patch.
local initial_offset
local offset
local sync_timer
local synced
local function get_offset()
return mp.get_time() - mp.get_property("time-pos")
end
local function get_offset_delta()
return get_offset() - offset
end
local function keep_sync()
delta = get_offset_delta()
if delta > 0.1 and synced then
mp.msg.info("Speeding up playback")
synced = false
mp.set_property_number("speed", 1.2)
elseif delta < -0.1 and synced then
mp.msg.info("Slowing down playback")
synced = false
mp.set_property_number("speed", 0.8)
elseif delta < 0.1 and delta > -0.1 and not synced then
mp.msg.info("Synced successfully")
synced = true
mp.set_property_number("speed", 1)
end
end
local function pause(name, paused)
if paused then
sync_timer:stop()
else
sync_timer:resume()
end
end
local function seek_back(name)
offset = offset + 1
synced = true
mp.msg.info(string.format(
"Increasing offset. New value: %f (%d)", offset, offset - initial_offset
))
end
local function seek_forward(name)
offset = offset - 1
synced = true
mp.msg.info(string.format(
"Decreasing offset. New value: %f (%d)", offset, offset - initial_offset
))
end
local function init()
if mp.get_property_bool("seekable", true) then
return
end
initial_offset = get_offset()
offset = initial_offset
synced = true
sync_timer = mp.add_periodic_timer(0.5, keep_sync)
mp.observe_property("pause", "bool", pause)
mp.msg.info(string.format("Initialization complete. Offset: %f", offset))
mp.add_key_binding("Shift+LEFT", seek_back)
mp.add_key_binding("Shift+RIGHT", seek_forward)
end
mp.register_event("file-loaded", init)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment