-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmpvsubsync.lua
More file actions
1967 lines (1747 loc) · 62.1 KB
/
mpvsubsync.lua
File metadata and controls
1967 lines (1747 loc) · 62.1 KB
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
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
-- Usage:
-- default keybinding: n
-- add the following to your input.conf to change the default keybinding:
-- keyname script_binding mpvsubsync-menu
local mp = require('mp')
local utils = require('mp.utils')
local mpopt = require('mp.options')
local menu = require('menu')
local sub = require('subtitle')
local h = require('helpers')
local progress = require('progress')
local progress_bar = progress:new()
local ref_selector
local engine_selector
local track_selector
math.randomseed(os.time())
local get_staging_path
local remove_file
local compute_current_cache_candidates
local active_job = {
id = 0,
running = false,
command_id = nil,
cancelled = false,
reset_requested = false,
reset_paths = nil,
}
local last_reset_paths = nil
local last_loaded_retimed_paths = {}
local last_sync_request = nil
local menu_visible = false
local pending_job_action = nil
-- Config
-- Options can be changed here or in a separate config file.
-- Config path: ~/.config/mpv/script-opts/mpvsubsync.conf
local config = {
-- Change the following lines if the locations of executables differ from the defaults
-- If set to empty, the path will be guessed.
ffmpeg_path = "",
ffsubsync_path = "",
alass_path = "",
-- Choose what tool to use. Allowed options: ffsubsync, alass, ask.
-- If set to ask, the add-on will ask to choose the tool every time.
audio_subsync_tool = "ask",
altsub_subsync_tool = "ask",
-- Cache extracted reference audio and generated retimed subtitles.
-- This makes sync attempts resumable and avoids repeating ffmpeg/ffsubsync
-- work when the same media + subtitle pair is processed again.
cache_enabled = true,
-- Cache directory for extracted reference audio and retimed subtitles.
cache_dir = (function()
if package.config:sub(1, 1) == "\\" then
return (os.getenv("LOCALAPPDATA") or os.getenv("APPDATA") or "~") .. "\\mpvsubsync\\cache\\"
end
return (os.getenv("HOME") or "~") .. "/.cache/mpvsubsync/"
end)(),
-- Fast mode for streamed media: extract only a percentage of the
-- reference audio, starting from the beginning of the file.
fast_stream_mode = false,
fast_stream_percent = 30,
-- Verbose debug logging in mpv console/log.
debug_logging = false,
}
local DEFAULT_CONFIG_TEXT = [[
# mpvsubsync — generated on first run. Edit to customize.
# Removing this file will recreate it next time mpv loads the script.
# --- Backends (leave empty to auto-discover in PATH) ---
# ffmpeg_path=
# ffsubsync_path=
# alass_path=
# Preferred tool per mode: ffsubsync, alass, or ask
audio_subsync_tool=ask
altsub_subsync_tool=ask
# --- Caching ---
cache_enabled=yes
cache_dir=~/.cache/mpvsubsync/
# --- Performance ---
fast_stream_mode=no
fast_stream_percent=30
# --- Debug ---
debug_logging=no
]]
local function write_default_config_if_missing()
local target = mp.command_native({ "expand-path", "~~/script-opts/mpvsubsync.conf" })
if target == nil or target == "" then return end
local probe = io.open(target, "r")
if probe ~= nil then
probe:close()
return
end
local dir = target:match("(.+)[/\\][^/\\]+$")
if dir ~= nil then
local is_win = package.config:sub(1, 1) == "\\"
local args = is_win and { "cmd", "/C", "mkdir", dir } or { "mkdir", "-p", dir }
mp.command_native({ name = "subprocess", args = args, playback_only = false, capture_stdout = true, capture_stderr = true })
end
local f = io.open(target, "w")
if f == nil then return end
f:write(DEFAULT_CONFIG_TEXT)
f:close()
mp.msg.info("mpvsubsync: wrote default config to " .. target)
end
write_default_config_if_missing()
mpopt.read_options(config, 'mpvsubsync')
local is_windows = package.config:sub(1, 1) == "\\"
local function os_temp()
if is_windows then
return os.getenv("TEMP") or os.getenv("TMP") or "."
end
return "/tmp/"
end
local function notify(message, level, duration)
level = level or 'info'
duration = duration or 1
mp.msg[level](message)
mp.osd_message(message, duration)
end
local function log_debug(message)
if config.debug_logging then
mp.msg.info("mpvsubsync: " .. message)
end
end
local function shell_quote(arg)
if arg == nil then
return "''"
end
local s = tostring(arg)
if s == "" then
return "''"
end
if s:match("^[%w%._%-%+/:=@,]+$") then
return s
end
return "'" .. s:gsub("'", [['"'"']]) .. "'"
end
local function format_args(args)
local formatted = {}
for _, arg in ipairs(args) do
table.insert(formatted, shell_quote(arg))
end
return table.concat(formatted, " ")
end
local function subprocess(args)
log_debug("running subprocess: " .. format_args(args))
local ret = mp.command_native {
name = "subprocess",
playback_only = false,
capture_stdout = true,
capture_stderr = true,
args = args
}
if ret == nil then
log_debug("subprocess returned nil")
return nil
end
log_debug(string.format("subprocess finished with status=%s", tostring(ret.status)))
if not h.is_empty(ret.stderr) then
mp.msg.info("mpvsubsync stderr: " .. ret.stderr:gsub("%s+$", ""))
end
if not h.is_empty(ret.stdout) then
mp.msg.verbose("mpvsubsync stdout: " .. ret.stdout:gsub("%s+$", ""))
end
return ret
end
local function try_remove(path)
if h.is_empty(path) or not h.file_exists(path) then
return false
end
local ok, err = os.remove(path)
if not ok then
log_debug(string.format("failed to remove %s: %s", path, tostring(err)))
return false
end
log_debug("removed cache file: " .. path)
return true
end
local function gather_reset_paths(extra)
local out = {}
local seen = {}
local function add(path)
if h.is_empty(path) or seen[path] then return end
seen[path] = true
table.insert(out, path)
end
if extra ~= nil then
for _, p in ipairs(extra) do add(p) end
end
if last_reset_paths ~= nil then
for _, p in ipairs(last_reset_paths) do add(p) end
end
for _, p in ipairs(last_loaded_retimed_paths) do add(p) end
if compute_current_cache_candidates ~= nil then
for _, p in ipairs(compute_current_cache_candidates()) do add(p) end
end
return out
end
local function remember_loaded_retimed_path(path)
if h.is_empty(path) then return end
for _, p in ipairs(last_loaded_retimed_paths) do
if p == path then return end
end
table.insert(last_loaded_retimed_paths, path)
end
local function is_retimed_filename(fn)
if h.is_empty(fn) then return false end
local basename = fn:match("([^/\\]+)$") or fn
local stem = (basename:gsub("%.%w+$", "")):lower()
return stem:match("retimed$") ~= nil or stem:match("^retimed%-") ~= nil
end
local function unload_retimed_subtitle_tracks()
local tracks = mp.get_property_native("track-list")
if tracks == nil then return end
local sids_to_remove = {}
local fallback_sub_id = nil
for _, t in ipairs(tracks) do
if t.type == "sub" then
local fn = t.external and t["external-filename"] or nil
local decoded = fn and fn:gsub("^file://", ""):gsub("+", " "):gsub("%%(%x%x)", function(x) return string.char(tonumber(x, 16)) end)
local matches = is_retimed_filename(fn) or (decoded and is_retimed_filename(decoded))
if matches then
table.insert(sids_to_remove, t.id)
elseif fallback_sub_id == nil then
fallback_sub_id = t.id
end
end
end
if fallback_sub_id ~= nil then
mp.set_property("sid", tostring(fallback_sub_id))
end
for _, sid in ipairs(sids_to_remove) do
mp.commandv("sub_remove", sid)
end
end
local function delete_cache_paths(paths)
if paths == nil then
return false
end
unload_retimed_subtitle_tracks()
local removed = false
local seen = {}
for _, path in ipairs(paths) do
if not h.is_empty(path) and not seen[path] then
seen[path] = true
if try_remove(path) then removed = true end
if try_remove(get_staging_path(path)) then removed = true end
end
end
last_loaded_retimed_paths = {}
return removed
end
local function set_job_reset_paths(paths)
active_job.reset_paths = paths
if paths ~= nil then
last_reset_paths = paths
end
end
local function remember_reset_paths(paths)
if paths == nil then
return
end
local copy = {}
for i, path in ipairs(paths) do
copy[i] = path
end
last_reset_paths = copy
end
local function start_job(reset_paths)
if active_job.running then
notify("Autosubsync is already running.", "warn", 3)
return nil
end
active_job.id = active_job.id + 1
active_job.running = true
active_job.command_id = nil
active_job.cancelled = false
active_job.reset_requested = false
set_job_reset_paths(reset_paths)
return active_job.id
end
local function is_job_active(job_id)
return active_job.running and active_job.id == job_id
end
local function finish_job(job_id)
if active_job.id ~= job_id then
return
end
local reset_requested = active_job.reset_requested
local reset_paths = active_job.reset_paths
active_job.running = false
active_job.command_id = nil
active_job.cancelled = false
active_job.reset_requested = false
active_job.reset_paths = nil
progress_bar:hide()
if reset_requested then
if delete_cache_paths(gather_reset_paths(reset_paths)) then
notify("Autosubsync cache reset.", nil, 2)
else
notify("Autosubsync reset: nothing to clear.", "warn", 2)
end
end
if pending_job_action ~= nil then
local action = pending_job_action
pending_job_action = nil
action()
end
end
local function stop_active_job()
pending_job_action = nil
if not active_job.running then
return notify("Autosubsync is not running.", "warn", 2)
end
active_job.cancelled = true
active_job.reset_requested = false
if active_job.command_id ~= nil then
mp.abort_async_command(active_job.command_id)
notify("Stopping mpvsubsync...", nil, 2)
else
finish_job(active_job.id)
notify("Autosubsync stopped.", nil, 2)
end
end
local function reset_active_job()
if not active_job.running then
if delete_cache_paths(gather_reset_paths(nil)) then
return notify("Autosubsync cache reset.", nil, 2)
end
return notify("No mpvsubsync cache to reset.", "warn", 2)
end
active_job.cancelled = true
active_job.reset_requested = true
if active_job.command_id ~= nil then
mp.abort_async_command(active_job.command_id)
notify("Resetting mpvsubsync...", nil, 2)
else
finish_job(active_job.id)
end
end
local function subprocess_async(job_id, args, on_done)
log_debug("running subprocess: " .. format_args(args))
local command_id = mp.command_native_async({
name = "subprocess",
playback_only = false,
capture_stdout = true,
capture_stderr = true,
args = args
}, function(success, result, err)
if active_job.id == job_id then
active_job.command_id = nil
end
result = result or {}
if not h.is_empty(result.stderr) then
mp.msg.info("mpvsubsync stderr: " .. result.stderr:gsub("%s+$", ""))
end
if not h.is_empty(result.stdout) then
mp.msg.verbose("mpvsubsync stdout: " .. result.stdout:gsub("%s+$", ""))
end
if active_job.id == job_id and active_job.cancelled then
notify(active_job.reset_requested and "Autosubsync reset." or "Autosubsync stopped.", nil, 2)
return on_done(false, { status = -1, cancelled = true }, err or "cancelled")
end
log_debug(string.format("subprocess finished with status=%s", tostring(result.status)))
return on_done(success, result, err)
end)
if command_id == nil then
log_debug("subprocess_async returned nil")
return false
end
active_job.command_id = command_id
return true
end
local function set_last_sync_request(fn)
last_sync_request = fn
end
local function restart_last_sync()
if last_sync_request == nil then
return notify("No mpvsubsync run to restart.", "warn", 2)
end
if active_job.running then
pending_job_action = last_sync_request
return reset_active_job()
end
delete_cache_paths(gather_reset_paths(nil))
last_sync_request()
end
local function clone_table(tbl)
if tbl == nil then
return nil
end
local copy = {}
for k, v in pairs(tbl) do
copy[k] = v
end
return copy
end
local url_decode = function(url)
local function hex_to_char(x)
return string.char(tonumber(x, 16))
end
if url ~= nil then
url = url:gsub("^file://", "")
url = url:gsub("+", " ")
url = url:gsub("%%(%x%x)", hex_to_char)
if is_windows then
url = url:gsub("^/([a-zA-Z]:)", "%1")
end
return url
else
return
end
end
local function get_loaded_tracks(track_type)
local result = {}
local track_list = mp.get_property_native('track-list')
for _, track in pairs(track_list) do
if track.type == track_type then
track['external-filename'] = track.external and url_decode(track['external-filename'])
table.insert(result, track)
end
end
return result
end
local function get_active_track(track_type)
local track_list = mp.get_property_native('track-list')
for num, track in ipairs(track_list) do
if track.type == track_type and track.selected == true then
if track.external and not h.file_exists(track['external-filename']) then
track['external-filename'] = url_decode(track['external-filename'])
end
if not (track_type == 'sub' and track.id == mp.get_property_native('secondary-sid')) then
return num, track
end
end
end
return notify(string.format("Error: no track of type '%s' selected", track_type), "error", 3)
end
local function remove_extension(filename)
return filename:gsub('%.%w+$', '')
end
local function get_extension(filename)
return filename:match("^.+(%.%w+)$")
end
local function startswith(str, prefix)
return string.sub(str, 1, string.len(prefix)) == prefix
end
local function is_uri(path)
return not h.is_empty(path) and not not path:match("^%a[%w+.-]*://")
end
local function is_local_path(path)
return not h.is_empty(path) and (not is_uri(path) or startswith(path, "file://"))
end
local function sanitize_filename(name)
if h.is_empty(name) then
return "mpvsubsync"
end
return name:gsub("[/\\:*?\"<>|]", "_"):gsub("%s+$", "")
end
local function build_temp_path(stem, ext)
return utils.join_path(
os_temp(),
string.format("%s_%d_%06d.%s", stem, os.time(), math.random(0, 999999), ext)
)
end
local function expand_path(path)
if h.is_empty(path) then
return path
end
local home = os.getenv("HOME")
if home ~= nil then
if path == "~" then
path = home
elseif startswith(path, "~/") then
path = utils.join_path(home, path:sub(3))
end
end
return path
end
local function get_cache_dir()
if not h.is_empty(config.cache_dir) then
return expand_path(config.cache_dir)
end
return utils.join_path(os_temp(), "mpvsubsync-cache")
end
local function ensure_dir(path)
if h.is_empty(path) then
return false
end
local info = utils.file_info(path)
if info and info.is_dir then
return true
end
local args
if is_windows then
args = { "cmd", "/C", "mkdir", path }
else
args = { "mkdir", "-p", path }
end
local ret = subprocess(args)
info = utils.file_info(path)
return ret ~= nil and ret.status == 0 and info and info.is_dir or false
end
local function hash_string(value)
local hash = 5381
for i = 1, #value do
hash = ((hash * 33) + value:byte(i)) % 4294967296
end
return string.format("%08x", hash)
end
local function stat_fingerprint(path)
if h.is_empty(path) then
return "missing"
end
local info = utils.file_info(path)
if info == nil then
return "missing:" .. path
end
return table.concat({
path,
tostring(info.size or ""),
tostring(info.mtime or ""),
}, "|")
end
local function descriptor_fingerprint(value)
if h.is_empty(value) then
return "missing"
end
if h.file_exists(value) then
return stat_fingerprint(value)
end
return value
end
local function build_cache_path(kind, descriptor, ext)
local cache_dir = get_cache_dir()
if not ensure_dir(cache_dir) then
return nil
end
local stem = string.format("%s-%s", kind, hash_string(descriptor))
return utils.join_path(cache_dir, string.format("%s.%s", stem, ext))
end
local function current_media_stem()
return sanitize_filename(
mp.get_property("filename/no-ext")
or mp.get_property("media-title")
or "stream"
)
end
local function get_playback_source()
local path = mp.get_property("path")
local stream_path = mp.get_property("stream-open-filename")
local source = stream_path or path
if h.is_empty(source) then
return nil
end
source = url_decode(source)
if startswith(source, "ytdl://") then
return source:gsub("^ytdl://", "")
end
log_debug("source: " .. source)
return source
end
local function get_active_audio_track()
local _, track = get_active_track('audio')
return track
end
local function get_track_extension(track)
if track == nil then
return nil
end
if track.external and not h.is_empty(track['external-filename']) then
return get_extension(track['external-filename'])
end
local codec_ext_map = { subrip = ".srt", ass = ".ass" }
return codec_ext_map[track['codec']]
end
local function get_media_descriptor(playback_source)
return table.concat({
current_media_stem(),
descriptor_fingerprint(playback_source),
}, "|")
end
local function get_track_descriptor(track, playback_source, role)
if track == nil then
return "missing-track"
end
local origin
if track.external and not h.is_empty(track['external-filename']) then
origin = descriptor_fingerprint(track['external-filename'])
else
origin = table.concat({
"internal",
get_media_descriptor(playback_source),
tostring(track['type'] or ""),
tostring(track['id'] or ""),
tostring(track['ff-index'] or ""),
}, "|")
end
return table.concat({
role or "track",
origin,
tostring(track['codec'] or ""),
tostring(track['lang'] or ""),
tostring(track['title'] or ""),
}, "|")
end
local function get_audio_reference_descriptor(reference_input_path)
local audio_track = get_active_audio_track()
return table.concat({
"audio",
get_media_descriptor(reference_input_path),
tostring(audio_track and audio_track['ff-index'] or ""),
tostring(audio_track and audio_track['id'] or ""),
tostring(config.fast_stream_mode or ""),
tostring(config.fast_stream_percent or ""),
"start",
}, "|")
end
local function get_reference_audio_cache_path(reference_input_path)
if not config.cache_enabled then
return nil
end
return build_cache_path("reference", get_audio_reference_descriptor(reference_input_path), "wav")
end
local function get_stream_extract_window(reference_input_path)
if is_local_path(reference_input_path) or not config.fast_stream_mode then
return nil, nil
end
local duration = mp.get_property_number("duration")
local percent = tonumber(config.fast_stream_percent) or 30
percent = math.max(1, math.min(100, percent))
if duration == nil or duration <= 0 then
return nil, nil
end
local length = duration * (percent / 100)
if length >= duration then
return 0, duration
end
return 0, length
end
local function get_reference_descriptor(ref_sub_path, ref_track, playback_source)
if ref_sub_path == nil then
return get_audio_reference_descriptor(playback_source)
end
if ref_track ~= nil then
return "subtitle|" .. get_track_descriptor(ref_track, playback_source, "reference")
end
return table.concat({
"subtitle",
descriptor_fingerprint(ref_sub_path),
}, "|")
end
local function get_retimed_cache_path(reference_descriptor, subtitle_descriptor, subtitle_ext)
if h.is_empty(subtitle_ext) then
return nil
end
local descriptor = table.concat({
reference_descriptor,
subtitle_descriptor,
}, "||")
return build_cache_path("retimed", descriptor, subtitle_ext:gsub("^%.", ""))
end
local function get_active_sub_track_quiet()
local track_list = mp.get_property_native('track-list')
local secondary_sid = mp.get_property_native('secondary-sid')
if track_list == nil then return nil end
for _, track in ipairs(track_list) do
if track.type == 'sub' and track.selected == true and track.id ~= secondary_sid then
if track.external and not h.file_exists(track['external-filename']) then
track['external-filename'] = url_decode(track['external-filename'])
end
return track
end
end
return nil
end
compute_current_cache_candidates = function()
local paths = {}
if not config.cache_enabled then return paths end
local playback_source = get_playback_source()
if h.is_empty(playback_source) then return paths end
local ref_path = get_reference_audio_cache_path(playback_source)
if ref_path ~= nil then table.insert(paths, ref_path) end
local sub_track = get_active_sub_track_quiet()
if sub_track ~= nil then
local subtitle_ext = get_track_extension(sub_track)
if not h.is_empty(subtitle_ext) then
local subtitle_descriptor = get_track_descriptor(sub_track, playback_source, "subtitle")
local audio_descriptor = get_audio_reference_descriptor(playback_source)
local retimed_path = get_retimed_cache_path(audio_descriptor, subtitle_descriptor, subtitle_ext)
if retimed_path ~= nil then table.insert(paths, retimed_path) end
end
end
return paths
end
local function get_retimed_output_path(track)
local ext = get_track_extension(track)
if h.is_empty(ext) then
return nil
end
return utils.join_path(os_temp(), current_media_stem() .. "_retimed" .. ext)
end
local function copy_file(source_path, destination_path)
if h.is_empty(source_path) or h.is_empty(destination_path) then
return false
end
local src = io.open(source_path, "rb")
if src == nil then
return false
end
local content = src:read("*a")
src:close()
local dest = io.open(destination_path, "wb")
if dest == nil then
return false
end
dest:write(content)
dest:close()
return true
end
remove_file = function(path)
if not h.is_empty(path) and h.file_exists(path) then
os.remove(path)
end
end
get_staging_path = function(final_path)
if h.is_empty(final_path) then
return nil
end
local ext = get_extension(final_path)
if h.is_empty(ext) then
return final_path .. ".part"
end
return final_path:sub(1, #final_path - #ext) .. ".part" .. ext
end
local function finalize_staged_file(staging_path, final_path)
if h.is_empty(staging_path) or h.is_empty(final_path) then
return false
end
if staging_path == final_path then
return h.file_exists(final_path)
end
remove_file(final_path)
local ok = os.rename(staging_path, final_path)
if ok then
return true
end
if copy_file(staging_path, final_path) then
remove_file(staging_path)
return true
end
return false
end
local function materialize_cached_subtitle(cache_path, output_path)
if h.is_empty(output_path) or cache_path == output_path then
return cache_path
end
log_debug(string.format("copying cached subtitle from %s to %s", cache_path, output_path))
if copy_file(cache_path, output_path) then
return output_path
end
log_debug("failed to copy cached subtitle to output path, falling back to cached file")
return cache_path
end
local function resolve_retimed_write_path(cache_path, output_path)
if not h.is_empty(cache_path) then
return get_staging_path(cache_path)
end
return output_path
end
local function should_materialize_retimed_output(_track, _cache_path, _output_path)
return false
end
local function engine_is_set()
local tool = config.audio_subsync_tool
if ref_selector:get_ref() == 'sub' then
tool = config.altsub_subsync_tool
end
return not h.is_empty(tool) and tool ~= "ask"
end
local function extract_to_file(subtitle_track, input_path)
if h.is_path(config.ffmpeg_path) and not h.file_exists(config.ffmpeg_path) then
return notify("Can't find ffmpeg executable.\nPlease specify the correct path in the config.", "error", 5)
end
local codec_ext_map = { subrip = "srt", ass = "ass" }
local ext = codec_ext_map[subtitle_track['codec']]
if ext == nil then
return notify(string.format("Error: unsupported codec: %s", subtitle_track['codec']), "error", 3)
end
local temp_sub_fp = build_temp_path("mpvsubsync_extracted", ext)
notify("Extracting internal subtitles...", nil, 3)
progress_bar:update({ stage = "extracting subtitles", elapsed_start = mp.get_time() })
progress_bar:show()
log_debug(string.format(
"sub extract: id=%s ff=%s codec=%s src=%s out=%s",
tostring(subtitle_track and subtitle_track['id'] or ""),
tostring(subtitle_track and subtitle_track['ff-index'] or ""),
tostring(subtitle_track and subtitle_track['codec'] or ""),
tostring(input_path or get_playback_source()),
temp_sub_fp
))
local ret = subprocess {
config.ffmpeg_path,
"-hide_banner",
"-nostdin",
"-y",
"-loglevel", "error",
"-an",
"-vn",
"-i", input_path or get_playback_source(),
"-map", "0:" .. (subtitle_track and subtitle_track['ff-index'] or 's'),
"-f", ext,
temp_sub_fp
}
if ret == nil or ret.status ~= 0 or not h.file_exists(temp_sub_fp) then
return notify("Couldn't extract internal subtitle.\nMake sure the video has internal subtitles.", "error", 7)
end
return temp_sub_fp
end
local function extract_to_file_async(job_id, subtitle_track, input_path, on_done)
if h.is_path(config.ffmpeg_path) and not h.file_exists(config.ffmpeg_path) then
notify("Can't find ffmpeg executable.\nPlease specify the correct path in the config.", "error", 5)
return on_done(nil)
end
local codec_ext_map = { subrip = "srt", ass = "ass" }
local ext = codec_ext_map[subtitle_track['codec']]
if ext == nil then
notify(string.format("Error: unsupported codec: %s", subtitle_track['codec']), "error", 3)
return on_done(nil)
end
local temp_sub_fp = build_temp_path("mpvsubsync_extracted", ext)
notify("Extracting internal subtitles...", nil, 3)
log_debug(string.format(
"sub extract: id=%s ff=%s codec=%s src=%s out=%s",
tostring(subtitle_track and subtitle_track['id'] or ""),
tostring(subtitle_track and subtitle_track['ff-index'] or ""),
tostring(subtitle_track and subtitle_track['codec'] or ""),
tostring(input_path or get_playback_source()),
temp_sub_fp
))
local ok = subprocess_async(job_id, {
config.ffmpeg_path,
"-hide_banner",
"-nostdin",
"-y",
"-loglevel", "error",
"-an",
"-vn",
"-i", input_path or get_playback_source(),
"-map", "0:" .. (subtitle_track and subtitle_track['ff-index'] or 's'),
"-f", ext,
temp_sub_fp
}, function(_, ret)
if ret.cancelled then
return on_done(nil, true)
end
if ret.status ~= 0 or not h.file_exists(temp_sub_fp) then
notify("Couldn't extract internal subtitle.\nMake sure the video has internal subtitles.", "error", 7)
return on_done(nil)
end
return on_done(temp_sub_fp)
end)
if not ok then
notify("Couldn't start subtitle extraction.", "error", 5)
return on_done(nil)
end
end
local function materialize_subtitle_input(subtitle_path)
local ext = get_extension(subtitle_path)
if ext ~= '.srt' and ext ~= '.ass' then
return nil, notify(string.format("Unsupported external subtitle format: %s", subtitle_path), "error", 5)
end
local temp_sub_fp = build_temp_path("mpvsubsync_remote_sub", ext:gsub("^%.", ""))
notify("Downloading external subtitles...", nil, 3)
progress_bar:update({ stage = "downloading subtitles", elapsed_start = mp.get_time() })
progress_bar:show()
log_debug(string.format("sub fetch: %s -> %s", subtitle_path, temp_sub_fp))
local ret = subprocess {
config.ffmpeg_path,