sponsorblock.lua

main
mpv-sponsorblock/sponsorblock.lua history · blame · raw

194 lines · 5026 bytes

  1-- sponsorblock_minimal.lua
  2--
  3-- This script skips sponsored segments of YouTube videos
  4-- using data from https://github.com/ajayyy/SponsorBlock
  5
  6local opt = require 'mp.options'
  7local utils = require 'mp.utils'
  8
  9local ON = false
 10local ranges = nil
 11
 12local category_names = {
 13	["Chapter"] = "chapter",
 14	["Endcards/Credits"] = "outro",
 15	["Filler Tangent"] = "filler",
 16	["Highlight"] = "poi_highlight",
 17	["Interaction Reminder"] = "interaction",
 18	["Intermission/Intro Animation"] = "intro",
 19	["Non-Music Section"] = "music_offtopic",
 20	["Preview/Recap"] = "preview",
 21	["Sponsor"] = "sponsor",
 22	["Unpaid/Self Promotion"] = "selfpromo",
 23}
 24
 25local options = {
 26	server = "https://sponsor.ajay.app/api/skipSegments",
 27
 28	-- Categories to fetch and skip
 29	categories = "sponsor",
 30
 31	-- Set this to "true" to use sha256HashPrefix instead of videoID
 32	hash = ""
 33}
 34
 35opt.read_options(options)
 36
 37local categories = {}
 38for str in string.gmatch(string.lower(options.categories), "([^;]+)") do
 39	categories[#categories + 1] = str
 40end
 41
 42function skip_ads(name,pos)
 43	if pos then
 44		for _, i in pairs(ranges) do
 45			v = i.segment[2]
 46			if i.segment[1] <= pos and v > pos then
 47				--this message may sometimes be wrong
 48				--it only seems to be a visual thing though
 49				mp.osd_message(("[sponsorblock] skipping forward %ds"):format(math.floor(v-mp.get_property("time-pos"))))
 50				--need to do the +0.01 otherwise mpv will start spamming skip sometimes
 51				--example: https://www.youtube.com/watch?v=4ypMJzeNooo
 52				mp.set_property("time-pos",v+0.01)
 53				return
 54			end
 55		end
 56	end
 57end
 58
 59function fetch_sponsor_segments(youtube_id)
 60	local args = {"curl", "-L", "-s", "-G", "--data-urlencode", ("categories=%s"):format(utils.format_json(categories))}
 61	local url = options.server
 62	if options.hash == "true" then
 63		local sha = mp.command_native{
 64			name = "subprocess",
 65			capture_stdout = true,
 66			args = {"sha256sum"},
 67			stdin_data = youtube_id
 68		}
 69		url = ("%s/%s"):format(url, string.sub(sha.stdout, 0, 4))
 70	else
 71		table.insert(args, "--data-urlencode")
 72		table.insert(args, "videoID=" .. youtube_id)
 73	end
 74	table.insert(args, url)
 75
 76	local sponsors = mp.command_native{
 77		name = "subprocess",
 78		capture_stdout = true,
 79		playback_only = false,
 80		args = args
 81	}
 82	if sponsors.stdout then
 83		local json = utils.parse_json(sponsors.stdout)
 84		if type(json) == "table" then
 85			if options.hash == "true" then
 86				for _, i in pairs(json) do
 87					if i.videoID == youtube_id then
 88						return i.segments
 89					end
 90				end
 91			else
 92				return json
 93			end
 94		end
 95	end
 96end
 97
 98function fetch_ranges()
 99	local video_path = mp.get_property("path", "")
100	local video_referer = string.match(mp.get_property("http-header-fields", ""), "Referer:([^,]+)") or ""
101
102	local urls = {
103		"ytdl://youtu%.be/([%w-_]+).*",
104		"ytdl://w?w?w?%.?youtube%.com/v/([%w-_]+).*",
105		"https?://youtu%.be/([%w-_]+).*",
106		"https?://w?w?w?%.?youtube%.com/v/([%w-_]+).*",
107		"/watch.*[?&]v=([%w-_]+).*",
108		"/embed/([%w-_]+).*",
109		"^ytdl://([%w-_]+)$",
110		"-([%w-_]+)%."
111	}
112	local youtube_id = nil
113	local purl = mp.get_property("metadata/by-key/PURL", "")
114	for i,url in ipairs(urls) do
115		youtube_id = youtube_id or string.match(video_path, url) or string.match(video_referer, url) or string.match(purl, url)
116		if youtube_id then break end
117	end
118
119	if youtube_id and string.len(youtube_id) >= 11 then
120		youtube_id = string.sub(youtube_id, 1, 11)
121		return fetch_sponsor_segments(youtube_id)
122	end
123end
124
125function get_ranges_from_chapters()
126	local skipped_categories = {}
127	for _, category in ipairs(categories) do
128		skipped_categories[category] = true
129	end
130
131	local ranges = {}
132
133	local chapters = mp.get_property_native("chapter-list")
134	local duration = mp.get_property_native("duration")
135	local have_sponsorblock_chapters = false
136
137	for i, chapter in ipairs(chapters) do
138		local categories_string = string.match(chapter.title, "%[SponsorBlock%]:%s(.+)")
139
140		if categories_string then
141			have_sponsorblock_chapters = true
142
143			for category_name in string.gmatch(categories_string, "([^,]+),?%s?") do
144				local category = category_names[category_name]
145				if skipped_categories[category] then
146					local to = duration
147					if i < #chapters then
148						to = chapters[i+1].time
149					end
150					table.insert(ranges, {["segment"] = {chapter.time, to}, ["category"] = category})
151				end
152			end
153		end
154	end
155
156	if not have_sponsorblock_chapters then
157		return nil
158	end
159
160	return ranges
161end
162
163function file_loaded()
164	ranges = get_ranges_from_chapters() or fetch_ranges()
165
166	if ranges then
167		ON = true
168		mp.add_key_binding("b","sponsorblock",toggle)
169		mp.observe_property("time-pos", "native", skip_ads)
170	end
171end
172
173function end_file()
174	if not ON then return end
175	mp.unobserve_property(skip_ads)
176	ranges = nil
177	ON = false
178end
179
180function toggle()
181	if ON then
182		mp.unobserve_property(skip_ads)
183		mp.osd_message("[sponsorblock] off")
184		ON = false
185	else
186		mp.observe_property("time-pos", "native", skip_ads)
187		mp.osd_message("[sponsorblock] on")
188		ON = true
189	end
190end
191
192mp.register_event("file-loaded", file_loaded)
193mp.register_event("end-file", end_file)
194