sponsorblock_minimal.lua (2313B)
1 -- sponsorblock_minimal.lua 2 -- https://codeberg.org/jouni/mpv_sponsorblock_minimal 3 -- This script skips sponsored segments of YouTube videos 4 -- using data from https://github.com/ajayyy/SponsorBlock 5 6 local options = { 7 API = "https://sponsor.ajay.app/api/skipSegments", 8 9 -- Categories to fetch and skip 10 categories = '"sponsor","intro","outro","interaction","selfpromo"' 11 } 12 13 function getranges() 14 local args = { 15 "curl", 16 "-s", 17 "-d", 18 "videoID="..youtube_id, 19 "-d", 20 "categories=["..options.categories.."]", 21 "-G", 22 options.API} 23 local sponsors = mp.command_native({name = "subprocess", capture_stdout = true, playback_only = false, args = args}) 24 25 if string.match(sponsors.stdout,"%[(.-)%]") then 26 ranges = {} 27 for i in string.gmatch(string.sub(sponsors.stdout,2,-2),"%[(.-)%]") do 28 k,v = string.match(i,"(%d+.?%d*),(%d+.?%d*)") 29 ranges[k] = v 30 end 31 end 32 return 33 end 34 35 function skip_ads(name,pos) 36 if pos ~= nil then 37 for k,v in pairs(ranges) do 38 if tonumber(k) <= pos and tonumber(v) > pos then 39 mp.osd_message("[sponsorblock] skipping forward "..math.floor(tonumber(v)-mp.get_property("time-pos")).."s") 40 mp.set_property("time-pos",tonumber(v)+0.01) 41 return 42 end 43 end 44 end 45 return 46 end 47 48 function file_loaded() 49 local video_path = mp.get_property("path") 50 local youtube_id1 = string.match(video_path, "https?://youtu%.be/([%w-_]+).*") 51 local youtube_id2 = string.match(video_path, "https?://w?w?w?%.?youtube%.com/v/([%w-_]+).*") 52 local youtube_id3 = string.match(video_path, "/watch.*[?&]v=([%w-_]+).*") 53 local youtube_id4 = string.match(video_path, "/embed/([%w-_]+).*") 54 youtube_id = youtube_id1 or youtube_id2 or youtube_id3 or youtube_id4 55 if not youtube_id or string.len(youtube_id) < 11 then return end 56 youtube_id = string.sub(youtube_id, 1, 11) 57 58 getranges() 59 if ranges then 60 ON = true 61 mp.add_key_binding("b","sponsorblock",toggle) 62 mp.observe_property("time-pos", "native", skip_ads) 63 end 64 return 65 end 66 67 function toggle() 68 if ON then 69 mp.unobserve_property(skip_ads) 70 mp.osd_message("[sponsorblock] off") 71 ON = false 72 return 73 end 74 mp.observe_property("time-pos", "native", skip_ads) 75 mp.osd_message("[sponsorblock] on") 76 ON = true 77 return 78 end 79 80 mp.register_event("file-loaded", file_loaded)