-
Notifications
You must be signed in to change notification settings - Fork 1
/
lrc.lua
458 lines (378 loc) · 12.6 KB
/
lrc.lua
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
local options = {
musixmatch_token = '220215b052d6aeaa3e9a410986f6c3ae7ea9f5238731cb918d05ea',
mark_as_ja = false,
chinese_to_kanji_path = '',
strip_artists = false,
}
local utils = require 'mp.utils'
require 'mp.options'.read_options(options)
local function show_error(message)
mp.msg.error(message)
if mp.get_property_native('vo-configured') then
mp.osd_message(message, 5)
end
end
local function curl(args)
local r = mp.command_native({name = 'subprocess', capture_stdout = true, args = args})
if r.killed_by_us then
-- don't print an error when curl fails because the playlist index was changed
return
end
if r.status < 0 then
show_error('subprocess error: ' .. r.error_string)
return
end
if r.status > 0 then
show_error('curl failed with code ' .. r.status)
return
end
local response, error = utils.parse_json(r.stdout)
if error then
show_error('Unable to parse the JSON response')
return
end
return response
end
local function get_metadata()
local metadata = mp.get_property_native('metadata')
if metadata == nil then
return false, 'Metadata not yet loaded'
end
local title = metadata.title or metadata.TITLE or metadata.Title
local artist = metadata.artist or metadata.ARTIST or metadata.Artist
local album = metadata.album or metadata.ALBUM or metadata.Album
if not title then
return false, 'This song has no title metadata'
end
if not artist then
return false, 'This song has no artist metadata'
end
return title, artist, album
end
local function is_japanese(lyrics)
-- http://lua-users.org/wiki/LuaUnicode Lua patterns don't support Unicode
-- ranges, and you can't even iterate over \u{XXX} sequences in Lua 5.1 and
-- 5.2, so just search for some Hiragana characters.
for _, kana in pairs({
'あ', 'い', 'う', 'え', 'お',
'か', 'き', 'く', 'け', 'こ',
'さ', 'し', 'す', 'せ', 'そ',
'た', 'ち', 'つ', 'て', 'と',
'な', 'に', 'ぬ', 'ね', 'の',
'は', 'ひ', 'ふ', 'へ', 'ほ',
'ま', 'み', 'む', 'め', 'も',
'や', 'ゆ', 'よ',
'ら', 'り', 'る', 'れ', 'ろ',
'わ', 'を',
}) do
if lyrics:find(kana) then
return true
end
end
end
local function chinese_to_kanji(lyrics)
local mappings, error = io.open(
mp.command_native({'expand-path', options.chinese_to_kanji_path})
)
if mappings == nil then
show_error(error)
return lyrics
end
-- Save the original lyrics to compare them.
local original = io.open('/tmp/original.lrc', 'w')
if original then
original:write(lyrics)
original:close()
end
for mapping in mappings:lines() do
local num_matches
-- gsub on Unicode lyrics seems to stop at the first match. I have
-- no idea why this works.
repeat
lyrics, num_matches = lyrics:gsub(
mapping:gsub(' .*', ''),
mapping:gsub('.* ', '')
)
until num_matches == 0
end
mappings:close()
-- Also remove the pointless owari line when present.
for _, pattern in pairs({
'おわり',
'【 おわり 】',
' ?終わり',
'終わる',
'END',
}) do
lyrics = lyrics:gsub(']' .. pattern .. '\n', ']\n')
end
return lyrics
end
local function strip_artists(lyrics)
for _, pattern in pairs({'作词', '作詞', '作曲', '制作人', '编曲', '編曲', '詞', '曲'}) do
lyrics = lyrics:gsub('%[[%d:%.]*] ?' .. pattern .. ' ?[::] ?.-\n', '')
end
return lyrics
end
local function save_lyrics(lyrics)
-- NetEase can return 2-line LRCs with just the names of the artists, treat them as not found.
if lyrics == '' or select(2, lyrics:gsub('\n', '')) == 2 then
show_error('Lyrics not found')
return
end
local current_sub_path = mp.get_property('current-tracks/sub/external-filename')
if current_sub_path and lyrics:find('^%[') == nil then
show_error("Only lyrics without timestamps are available, so the existing LRC file won't be overwritten")
return
end
-- NetEase's LRCs can have 3-digit milliseconds, which messes up the sub's timings in mpv.
lyrics = lyrics:gsub('(%.%d%d)%d]', '%1]')
local path = mp.get_property('path')
local lrc_path = (path:match('(.*)%.[^/]*$') or path)
if is_japanese(lyrics) then
if options.mark_as_ja then
lrc_path = lrc_path .. '.ja'
end
if options.chinese_to_kanji_path ~= '' then
lyrics = chinese_to_kanji(lyrics)
end
end
if options.strip_artists then
lyrics = strip_artists(lyrics)
end
lrc_path = lrc_path .. '.lrc'
if path:find('://') then
if lyrics:find('^%[') then
mp.commandv('sub-add', 'memory://' .. lyrics)
mp.osd_message('LRC added')
else
mp.osd_message('These lyrics have no timestamps, so they can\'t be added as a subtitle track')
end
return
end
local success_message = 'LRC downloaded'
if current_sub_path then
-- os.rename only works across the same filesystem
local _, current_sub_filename = utils.split_path(current_sub_path)
local current_sub = io.open(current_sub_path)
local backup = io.open('/tmp/' .. current_sub_filename, 'w')
if current_sub and backup then
backup:write(current_sub:read('*a'))
success_message = success_message .. '. The old one has been backupped to /tmp.'
end
if current_sub then
current_sub:close()
end
if backup then
backup:close()
end
end
local lrc, error = io.open(lrc_path, 'w')
if lrc == nil then
show_error(error)
return
end
lrc:write(lyrics)
lrc:close()
if lyrics:find('^%[') then
mp.command(current_sub_path and 'sub-reload' or 'rescan-external-files')
mp.osd_message(success_message)
else
mp.osd_message('Lyrics without timestamps downloaded')
end
end
mp.add_key_binding('Alt+m', 'musixmatch-download', function()
local title, artist = get_metadata()
if title == false then
show_error(artist)
return
end
mp.osd_message('Downloading lyrics')
local response = curl({
'curl',
'--silent',
'--get',
'--cookie', 'x-mxm-token-guid=' .. options.musixmatch_token, -- avoids a redirect
'https://apic-desktop.musixmatch.com/ws/1.1/macro.subtitles.get',
'--data', 'app_id=web-desktop-app-v1.0',
'--data', 'usertoken=' .. options.musixmatch_token,
'--data-urlencode', 'q_track=' .. title,
'--data-urlencode', 'q_artist=' .. artist,
})
if not response then
return
end
if response.message.header.status_code == 401 and response.message.header.hint == 'renew' then
show_error('The Musixmatch token has been rate limited. script-opts/lrc.conf explains how to generate a new one.')
return
end
if response.message.header.status_code ~= 200 then
show_error('Request failed with status code ' .. response.message.header.status_code .. '. Hint: ' .. response.message.header.hint)
return
end
local body = response.message.body.macro_calls
local lyrics = ''
if body['matcher.track.get'].message.header.status_code == 200 then
if body['matcher.track.get'].message.body.track.has_subtitles == 1 then
lyrics = body['track.subtitles.get'].message.body.subtitle_list[1].subtitle.subtitle_body
elseif body['matcher.track.get'].message.body.track.has_lyrics == 1 then -- lyrics without timestamps
lyrics = body['track.lyrics.get'].message.body.lyrics.lyrics_body
elseif body['matcher.track.get'].message.body.track.instrumental == 1 then
show_error('This is an instrumental track')
return
end
end
save_lyrics(lyrics)
end)
local songs
local result, input = pcall(require, 'mp.input')
if not result or not input.select then
input = nil
end
local function select_netease_lyrics()
local items = {}
for _, song in ipairs(songs) do
items[#items+1] = song.artists[1].name .. ' - ' .. song.name .. ' (' ..
song.album.name .. ')'
end
input.select({
prompt = 'Select a song:',
items = items,
submit = function(id)
local response = curl({
'curl',
'--silent',
'https://music.xianqiao.wang/neteaseapiv2/lyric?id=' .. songs[id].id,
})
if response then
save_lyrics(response.lrc.lyric)
end
end
})
end
mp.add_key_binding('Alt+n', 'netease-download', function()
if songs and input then
select_netease_lyrics()
return
end
local title, artist, album = get_metadata()
local keywords
if title then
keywords = title .. ' ' .. artist
else
keywords = mp.get_property('media-title')
if not keywords then
show_error('No metadata or media-title are loaded')
return
end
end
mp.osd_message('Downloading lyrics')
local response = curl({
'curl',
'--silent',
'--get',
'https://music.xianqiao.wang/neteaseapiv2/search?limit=9',
'--data-urlencode', 'keywords=' .. keywords,
})
if not response then
return
end
if not response.result then
show_error('Lyrics not found')
return
end
songs = response.result.songs
if songs == nil or #songs == 0 then
show_error('Lyrics not found')
return
end
if input then
if #songs == 1 then
response = curl({
'curl',
'--silent',
'https://music.xianqiao.wang/neteaseapiv2/lyric?id=' .. songs[1].id,
})
if response then
save_lyrics(response.lrc.lyric)
end
return
end
select_netease_lyrics()
return
end
for _, song in ipairs(songs) do
mp.msg.info(
'Found lyrics for the song with id ' .. song.id ..
', name ' .. song.name ..
', artist ' .. song.artists[1].name ..
', album ' .. song.album.name ..
', url https://music.xianqiao.wang/neteaseapiv2/lyric?id=' .. song.id
)
end
local song = songs[1]
if album then
album = album:lower()
for _, loop_song in ipairs(songs) do
if loop_song.album.name:lower() == album then
song = loop_song
break
end
end
end
mp.msg.info(
'Downloading lyrics for the song with id ' .. song.id ..
', name ' .. song.name ..
', artist ' .. song.artists[1].name ..
', album ' .. song.album.name
)
response = curl({
'curl',
'--silent',
'https://music.xianqiao.wang/neteaseapiv2/lyric?id=' .. song.id,
})
if response then
save_lyrics(response.lrc.lyric)
end
end)
if input then
mp.register_event('end-file', function()
songs = nil
end)
-- Allow retrieving different lyrics after changing media-title in the
-- console.
mp.observe_property('force-media-title', 'native', function()
songs = nil
end)
end
mp.add_key_binding('Alt+o', 'offset-sub', function()
local sub_path = mp.get_property('current-tracks/sub/external-filename')
if not sub_path then
show_error('No external subtitle is loaded')
return
end
local r = mp.command_native({
name = 'subprocess',
capture_stdout = true,
args = {'ffmpeg', '-loglevel', 'quiet', '-itsoffset', mp.get_property('sub-delay'), '-i', sub_path, '-f', sub_path:match('[^%.]+$'), '-fflags', '+bitexact', '-'}
})
if r.status < 0 then
show_error('subprocess error: ' .. r.error_string)
return
end
if r.status > 0 then
show_error('ffmpeg failed with code ' .. r.status)
return
end
local sub_file, error = io.open(sub_path, 'w')
if sub_file == nil then
show_error(error)
return
end
-- ffmpeg leaves a blank line at the top if there is no metadata, so strip it.
sub_file:write((r.stdout:gsub('^\n', '')))
sub_file:close()
mp.set_property('sub-delay', 0)
mp.command('sub-reload')
mp.osd_message('Subtitles updated')
end)