-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathchapterskip.lua
More file actions
1147 lines (1008 loc) · 37.3 KB
/
chapterskip.lua
File metadata and controls
1147 lines (1008 loc) · 37.3 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
--[[
* chapterskip.lua v.2026-04-13
*
* AUTHORS: detuur, microraptor, Eisa01, dyphire
* License: MIT
* link: https://github.com/detuur/mpv-scripts
*
* This script skips to the next silence in the file. The
* intended use for this is to skip until the end of an
* opening sequence, at which point there's often a short
* period of silence.
*
* The default keybind is F3. You can change this by adding
* the following line to your input.conf:
* KEY script-binding skip-to-silence
*
* In order to tweak the script parameters, you can place the
* text below, between the template markers, in a new file at
* script-opts/chapterskip.conf in mpv's user folder. The
* parameters will be automatically loaded on start.
*
* Dev note about the used filters:
* - `silencedetect` is an audio filter that listens for silence and
* emits text output with details whenever silence is detected.
* Filter documentation: https://ffmpeg.org/ffmpeg-filters.html
****************** TEMPLATE FOR chapterskip.conf ******************
#--(#number). Maximum amount of noise to trigger, in terms of dB. Lower is more sensitive.
silence_audio_level=-40
#--(#number). Duration of the silence that will be detected to trigger skipping.
silence_duration=0.7
#--(0/#number). The first detcted silence_duration will be ignored for the defined seconds in this option, and it will continue skipping until the next silence_duration.
# (0 for disabled, or specify seconds).
ignore_silence_duration=1
#--(0/#number). Minimum amount of seconds accepted to skip until the configured silence_duration.
# (0 for disabled, or specify seconds)
min_skip_duration=0
#--(0/#number). Maximum amount of seconds accepted to skip until the configured silence_duration.
# (0 for disabled, or specify seconds)
max_skip_duration=120
#--(yes/no). Default is muted, however if audio was enabled due to custom mpv settings, the fast-forwarded audio can sound jarring.
force_mute_on_skip=no
#--(yes/no). Enable position-based inference for chapters (opening/ending detection for videos with chapters)
enable_position_inference=yes
#--(yes/no). Enable position-based inference for history entries in non-chapter files
# When disabled, history entries will show generic "Skip Segment" instead of "Skip Opening/Ending"
# Useful to prevent false positives in non-episodic content
enable_history_position_inference=yes
#--(#number). Time window (in seconds) from the start to consider as intro/opening area
intro_time_window=200
#--(#number). Time window (in seconds) from the end to consider as outro/ending area
outro_time_window=300
************************** END OF TEMPLATE **************************
--]]
local msg = require 'mp.msg'
local assdraw = require 'mp.assdraw'
local options = require "mp.options"
local utils = require 'mp.utils'
local categories = {
prologue = "^[Pp]rologue/^[Ii]ntro",
opening = "^OP/ OP$/^[Oo]pening/[Oo]pening$/^Intro%s*Start/オープニング$/^片头$/片头开始$",
ending = "^ED/ ED$/^[Ee]nding/[Ee]nding$/エンディング$",
credits = "^[Cc]redits/[Cc]redits$",
preview = "[Pp]review$"
}
local o = {
mode = "manual",
-- eng=English, chs=Chinese Simplified
language = 'eng',
timeout = 20,
categories = "",
skip = "",
enable_position_inference = true,
enable_history_position_inference = false,
intro_time_window = 200,
outro_time_window = 300,
silence_audio_level = -40,
silence_duration = 0.7,
ignore_silence_duration=1,
min_skip_duration = 0,
max_skip_duration = 120,
force_mute_on_skip = false,
history_path = "~~/chapterskip_history.json",
-- Button styling
button_font_size = 24,
button_padding_x = 20,
button_padding_y = 15,
button_margin = 60,
button_border = 2,
button_radius = 13,
-- Button colors (BGR format: BBGGRR)
button_progress_color = "2442F4",
button_progress_hover_color = "2442F4",
button_remaining_color = "FFFFFF",
button_remaining_hover_color = "111111",
button_text_color = "000000",
button_text_hover_color = "FFFFFF",
button_border_color = "FFFFFF",
}
options.read_options(o, _, function() end)
local speed_state = 1
local pause_state = false
local mute_state = false
local sub_state = nil
local secondary_sub_state = nil
local vid_state = nil
local geometry_state = nil
local skip_flag = false
local initial_skip_time = 0
local state = {}
local skipped = {}
local parsed = {}
local chapter_skip = {}
local active_skips = {}
local skip_prompt_queue = {}
local skip_timer = nil
local history_path = mp.command_native({ "expand-path", o.history_path })
local locals = {
['eng'] = {
skip_detected = 'Skip Segment',
auto_skip = 'Auto-skip: %s-%s',
chapter_mode = 'Chapter skip mode: ',
mark_fragment_empty = 'Mark fragment is empty',
mark_start_pos = 'Marked %s as start position',
mark_fragment = 'Mark skip fragment: %s-%s',
no_audio = 'No audio stream detected',
skipped_to_silence = 'Skipped to silence at %s',
skip_cancel_min = 'Skipping Cancelled - Silence is less than configured minimum',
skip_cancel_max = 'Skipping Cancelled - Silence is more than configured maximum',
failed_timestamp = 'Failed to get timestamp'
},
['chs'] = {
skip_detected = '跳过片段',
auto_skip = '已跳过: %s-%s',
chapter_mode = '跳过章节模式: ',
mark_fragment_empty = '标记片段为空',
mark_start_pos = '标记 %s 为起始位置',
mark_fragment = '标记跳过片段: %s-%s',
no_audio = '未检测到音频流',
skipped_to_silence = '已跳过到静音点 %s',
skip_cancel_min = '取消跳过 - 静音时长低于最小值',
skip_cancel_max = '取消跳过 - 静音时长超过最大值',
failed_timestamp = '获取时间戳失败'
}
}
local texts = locals[o.language] or locals['eng']
local function is_protocol(path)
return type(path) == "string" and (path:find("^%a[%w.+-]-://") ~= nil or path:find("^%a[%w.+-]-:%?") ~= nil)
end
local function hex_to_char(x)
return string.char(tonumber(x, 16))
end
local function url_decode(str)
if str ~= nil then
str = str:gsub("^%a[%a%d-_]+://", "")
:gsub("^%a[%a%d-_]+:\\?", "")
:gsub("%%(%x%x)", hex_to_char)
if str:find("://localhost:?") then
str = str:gsub("^.*/", "")
end
str = str:gsub("%?.+", "")
:gsub("%+", " ")
return str
else
return
end
end
local function timestamp(duration)
local hours = math.floor(duration / 3600)
local minutes = math.floor(duration % 3600 / 60)
local seconds = duration % 60
return string.format("%02d:%02d:%06.3f", hours, minutes, seconds)
end
local function normalize(path)
if normalize_path ~= nil then
if normalize_path then
path = mp.command_native({"normalize-path", path})
else
local directory = mp.get_property_native("working-directory", "")
path = utils.join_path(directory, path:gsub('^%.[\\/]',''))
if platform == "windows" then path = path:gsub("\\", "/") end
end
return path
end
normalize_path = false
local commands = mp.get_property_native("command-list", {})
for _, command in ipairs(commands) do
if command.name == "normalize-path" then
normalize_path = true
break
end
end
return normalize(path)
end
local function get_parent_dir(path)
local dir = nil
if path and not is_protocol(path) then
path = normalize(path)
dir = utils.split_path(path)
end
return dir
end
local function split_by_numbers(filename)
local parts = {}
local pattern = "([^%d]*)(%d+)([^%d]*)"
for pre, num, post in string.gmatch(filename, pattern) do
table.insert(parts, {pre = pre, num = tonumber(num), post = post})
end
return parts
end
local function compare_filenames(fname1, fname2)
local parts1 = split_by_numbers(fname1)
local parts2 = split_by_numbers(fname2)
local min_len = math.min(#parts1, #parts2)
for i = 1, min_len do
local part1 = parts1[i]
local part2 = parts2[i]
if part1.pre ~= part2.pre then
return false
end
if part1.num ~= part2.num then
return part1.num, part2.num
end
if part1.post ~= part2.post then
return false
end
end
return false
end
-- Read config file
local function read_config(file_path)
local file = io.open(file_path, "r")
if not file then
return {}
end
local content = file:read("*a")
file:close()
return utils.parse_json(content)
end
-- Write config file
local function write_config(file_path, data)
local file = io.open(file_path, "w")
if not file then
return
end
file:write(utils.format_json(data))
file:close()
end
-- Write history file
local function write_history(path)
local dir = get_parent_dir(path)
local fname = mp.get_property("filename")
local title = mp.get_property_native("media-title"):gsub("%.[^%.]+$", "")
local duration = mp.get_property_native("duration")
if is_protocol(fname) then
title = url_decode(title)
fname = title
end
if not dir then
local media_title, season, episode = title:match("^(.-)%s*[sS](%d+).-[eE](%d+)")
if season then
dir = (media_title ~= "" and media_title or title) .. " S" .. season
else
dir = media_title ~= "" and media_title or title
end
end
local history = read_config(history_path) or {}
history[dir] = {}
history[dir].fname = fname
history[dir].chapterskip = chapter_skip
history[dir].duration = duration
write_config(history_path, history)
end
local function format_message(msg, color)
return string.format("{\\1c&H%s&}%s", color, msg)
end
-- Send a message to the OSD
message_overlay = mp.create_osd_overlay('ass-events')
message_timer = mp.add_timeout(1, function ()
message_overlay:remove()
end, true)
local function show_message(msg, time, color)
local text = color and format_message(msg, color) or msg
message_timer:kill()
message_timer.timeout = time or 1
message_overlay.data = text
message_overlay:update()
message_timer:resume()
end
local function info(s)
msg.info(s)
show_message(s, 2)
end
-- Button UI state
local button_state = {
overlay = nil,
visible = false,
message = "",
mouse_hover = false,
countdown_timer = nil,
countdown_remaining = 0,
countdown_total = 0,
action = nil,
skip_obj = nil,
}
-- Forward declarations
local hide_button
local render_button
local bind_button_click
local unbind_button_click
-- Initialize button overlay
local function init_button_overlay()
if not button_state.overlay then
button_state.overlay = mp.create_osd_overlay("ass-events")
if button_state.overlay then
button_state.overlay.z = 2000 -- Set high z-index to ensure visibility
end
end
end
-- Mouse position helper
local function is_mouse_in_button(bx, by, bw, bh, mx, my)
return mx >= bx and mx <= bx + bw and my >= by and my <= by + bh
end
-- Render button with progress
render_button = function()
if not button_state.visible then
return
end
init_button_overlay()
-- Get display size using osd-dimensions (same as notify_skip)
local dims = mp.get_property_native("osd-dimensions")
local screen_width, screen_height
if dims then
screen_width = dims.w
screen_height = dims.h
else
screen_width = 1920
screen_height = 1080
end
-- Calculate scale (same as notify_skip)
local scale = screen_height / 1080 local button_padding_x = o.button_padding_x * scale
local button_padding_y = o.button_padding_y * scale
local font_size = o.button_font_size * scale
local hint_font_size = font_size * 0.9 -- Smaller font for hint
-- Calculate button dimensions with hint text
local message_width = #button_state.message * font_size * 0.6
local hint_text = "[y/n]"
local hint_width = #hint_text * hint_font_size * 0.6
local max_text_width = math.max(message_width, hint_width)
local button_width = max_text_width + button_padding_x * 2
local line_spacing = font_size * 0.1
local button_height = font_size + line_spacing + hint_font_size + button_padding_y * 2
-- Position button: bottom right, same as notify_skip
local margin = o.button_margin * scale
local button_x = screen_width - button_width - margin
local button_y = screen_height - button_height - margin - (80 * scale)
-- Check mouse hover (same method as notify_skip)
local pos = mp.get_property_native("mouse-pos")
local mouse_x, mouse_y, mouse_hover
if pos then
mouse_x = pos.x
mouse_y = pos.y
mouse_hover = pos.hover
else
mouse_x = 0
mouse_y = 0
mouse_hover = false
end
local is_hover = mouse_hover and is_mouse_in_button(button_x, button_y, button_width, button_height, mouse_x, mouse_y)
button_state.mouse_hover = is_hover
-- Colors
local text_color = is_hover and o.button_text_hover_color or o.button_text_color
local border_color = o.button_border_color
-- Calculate progress
local progress = 0
if button_state.countdown_total > 0 and button_state.countdown_remaining > 0 then
progress = 1 - (button_state.countdown_remaining / button_state.countdown_total)
elseif button_state.countdown_remaining == 0 then
progress = 1
end
local progress_color = is_hover and o.button_progress_hover_color or o.button_progress_color
local remaining_color = is_hover and o.button_remaining_hover_color or o.button_remaining_color
local ass = assdraw.ass_new()
ass:new_event()
ass:pos(0, 0)
ass:append("{\\blur0\\bord0\\1c&HFFFFFF&\\3c&HFFFFFF&}")
-- Draw border
ass:draw_start()
ass:append("{\\1c&H000000&\\3c&H" .. border_color .. "&\\bord" .. (o.button_border * scale) .. "}")
ass:round_rect_cw(button_x, button_y, button_x + button_width, button_y + button_height, o.button_radius * scale)
ass:draw_stop()
-- Draw progress fill (left part)
if progress > 0 then
local progress_width = button_width * progress
ass:new_event()
ass:pos(0, 0)
ass:append("{\\blur0\\bord0}")
ass:draw_start()
ass:append("{\\1c&H" .. progress_color .. "&}")
if progress >= 1 then
ass:round_rect_cw(button_x, button_y, button_x + button_width, button_y + button_height, o.button_radius * scale)
else
ass:round_rect_cw(button_x, button_y, button_x + progress_width, button_y + button_height, o.button_radius * scale, 0)
end
ass:draw_stop()
end
-- Draw remaining fill (right part)
if progress < 1 then
local progress_width = button_width * progress
ass:new_event()
ass:pos(0, 0)
ass:append("{\\blur0\\bord0}")
ass:draw_start()
ass:append("{\\1c&H" .. remaining_color .. "&}")
if progress > 0 then
ass:round_rect_cw(button_x + progress_width, button_y, button_x + button_width, button_y + button_height, 0, o.button_radius * scale)
else
ass:round_rect_cw(button_x, button_y, button_x + button_width, button_y + button_height, o.button_radius * scale)
end
ass:draw_stop()
end
-- Draw text (main message)
local text_x = button_x + button_width / 2
local text_y = button_y + button_height / 2 - (hint_font_size + line_spacing) / 2
ass:new_event()
ass:append("{\\an5\\fs" .. font_size .. "\\b1\\bord0\\shad0\\1c&H" .. text_color .. "&}")
ass:pos(text_x, text_y)
ass:append(button_state.message)
-- Draw keyboard hint (second line)
local hint_y = text_y + font_size / 2 + line_spacing + hint_font_size / 2
ass:new_event()
ass:append("{\\an5\\fs" .. hint_font_size .. "\\b0\\bord0\\shad0\\1c&H" .. text_color .. "&\\alpha&H80&}")
ass:pos(text_x, hint_y)
ass:append(hint_text)
local ass_text = ass.text
-- Set overlay resolution and data
button_state.overlay.res_x = screen_width
button_state.overlay.res_y = screen_height
button_state.overlay.data = ass_text
button_state.overlay:update()
end
-- Bind/unbind button click
bind_button_click = function()
mp.add_forced_key_binding("MBTN_LEFT", "chapterskip-button-click", function()
local pos = mp.get_property_native("mouse-pos")
if not pos then return end
if button_state.mouse_hover then
-- Clicked on button
if button_state.action then
button_state.action()
end
hide_button()
else
-- Clicked outside - cancel
hide_button()
end
end)
end
unbind_button_click = function()
mp.remove_key_binding("chapterskip-button-click")
end
-- Mouse move handler
local function handle_button_mouse_move()
if button_state.visible then
render_button()
end
end
-- Hide button
hide_button = function()
if button_state.countdown_timer then
button_state.countdown_timer:kill()
button_state.countdown_timer = nil
end
button_state.visible = false
button_state.message = ""
button_state.action = nil
button_state.skip_obj = nil
button_state.countdown_remaining = 0
button_state.countdown_total = 0
if button_state.overlay then
button_state.overlay:remove()
end
unbind_button_click()
-- Remove keyboard shortcuts
mp.remove_key_binding("chapterskip-confirm")
mp.remove_key_binding("chapterskip-cancel")
end
-- Show button with countdown
local function show_button(message, action, skip_obj)
hide_button() -- Clear any existing button
button_state.visible = true
button_state.message = message
button_state.action = action
button_state.skip_obj = skip_obj
button_state.countdown_remaining = o.timeout
button_state.countdown_total = o.timeout
render_button()
bind_button_click()
-- Add keyboard shortcuts for confirm/cancel
mp.add_forced_key_binding("y", "chapterskip-confirm", function()
if button_state.action then
button_state.action()
end
hide_button()
end)
mp.add_forced_key_binding("n", "chapterskip-cancel", function()
if button_state.skip_obj then
button_state.skip_obj.cancelled = true
end
hide_button()
end)
if o.timeout > 0 then
button_state.countdown_timer = mp.add_periodic_timer(1, function()
button_state.countdown_remaining = button_state.countdown_remaining - 1
if button_state.countdown_remaining <= 0 then
if skip_obj then skip_obj.cancelled = true end
hide_button()
else
render_button()
end
end)
end
end
-- Register mouse move observer
mp.observe_property("mouse-pos", "native", handle_button_mouse_move)
-- Check if chapter matches skip pattern (title-based or position-based)
local function matches(i, title, chapter_time, chapter_duration, total_chapters, duration)
-- First, try title-based matching
for category in string.gmatch(o.skip, " *([^;]*[^; ]) *") do
if categories[category:lower()] then
if string.find(category:lower(), "^idx%-") == nil then
if title then
for pattern in string.gmatch(categories[category:lower()], "([^/]+)") do
if string.match(title, pattern) then
return true, "title", category:lower()
end
end
end
else
for pattern in string.gmatch(categories[category:lower()], "([^/]+)") do
if tonumber(pattern) == i then
return true, "index", category:lower()
end
end
end
end
end
-- If no title match and position inference is enabled, check position
if o.enable_position_inference and chapter_time and chapter_duration and total_chapters and duration then
-- Check chapter duration constraints (80-100 seconds)
if chapter_duration >= 80 and chapter_duration <= 100 then
-- Only consider chapters at the beginning or end
if i <= 2 or i >= total_chapters - 1 then
-- Check if chapter time is within the intro/outro windows
if i <= math.ceil(total_chapters / 2) then
-- First half: check for opening
if chapter_time < o.intro_time_window then
-- Check if opening category is in skip list
for category in string.gmatch(o.skip, " *([^;]*[^; ]) *") do
if category:lower() == "opening" then
return true, "position-opening", "opening"
end
end
end
else
-- Second half: check for ending
if duration > 0 and chapter_time >= (duration - o.outro_time_window) then
-- Check if ending category is in skip list
for category in string.gmatch(o.skip, " *([^;]*[^; ]) *") do
if category:lower() == "ending" then
return true, "position-ending", "ending"
end
end
end
end
end
end
end
return false, nil, nil
end
local function add_chapter_skip(s)
for _, exist in ipairs(chapter_skip) do
if math.abs(exist.start - s.start) <= 0.5 and math.abs(exist.ended - s.ended) <= 0.5 then
return
end
end
table.insert(chapter_skip, s)
end
local function cache_skip()
local chapters = mp.get_property_native("chapter-list") or {}
local matched = false
for i, chapter in ipairs(chapters) do
local start_time = chapters[i - 1] and chapters[i - 1].time or 0
local duration = chapter.time - start_time
if math.abs(chapter.time - state.ended) <= 10 and duration <= 120 then
matched = true
msg.verbose("Chapter skip found: " .. (chapter.title or ("Chapter "..i)))
add_chapter_skip({
start = start_time,
ended = chapter.time,
})
end
end
if not matched then
if state.start >= 90 or state.ended - state.start > 120 then
return
elseif state.start <= 30 then
state.start = 0
end
add_chapter_skip({
start = state.start,
ended = state.ended,
})
end
end
function cancel_skip_prompt()
hide_button()
if #skip_prompt_queue > 0 then
local next_prompt = table.remove(skip_prompt_queue, 1)
show_skip_prompt(next_prompt.action, next_prompt.skip_obj)
end
end
function confirm_skip_prompt(action)
cancel_skip_prompt()
if action then action() end
end
function show_skip_prompt(action, skip_obj)
if button_state.visible then
table.insert(skip_prompt_queue, {action = action, skip_obj = skip_obj})
return
end
-- Generate message based on category
local message = texts.skip_detected
if skip_obj and skip_obj.category then
if o.language == "chs" then
-- Chinese category names with Chinese "跳过" prefix
local category_names = {
opening = "片头",
ending = "片尾",
credits = "Staff",
prologue = "序章",
preview = "预告"
}
local category_display = category_names[skip_obj.category] or skip_obj.category
message = "跳过" .. category_display
else
local category_display = skip_obj.category:gsub("^%l", string.upper)
message = "Skip " .. category_display
end
end
show_button(message, action, skip_obj)
end
local function start_skip_watcher()
if skip_timer then return end
skip_timer = mp.add_periodic_timer(0.5, function()
local t = mp.get_property_number("time-pos")
local paused = mp.get_property_native("pause")
if not t or o.mode == "none" or paused then return end
local i = 1
while i <= #active_skips do
local s = active_skips[i]
if s.cancelled then
table.remove(active_skips, i)
elseif t >= s.start - 0.5 and t <= s.ended then
if o.mode == "auto" then
info((texts.auto_skip):format(timestamp(s.start), timestamp(s.ended), s.title))
mp.set_property_number("time-pos", s.ended)
s.triggered = true
table.remove(active_skips, i)
elseif o.mode == "manual" and not s.triggered then
s.triggered = true
show_skip_prompt(function()
info((texts.auto_skip):format(timestamp(s.start), timestamp(s.ended), s.title))
mp.set_property_number("time-pos", s.ended)
for j = #active_skips, 1, -1 do
if active_skips[j] == s then
table.remove(active_skips, j)
break
end
end
end, s)
i = i + 1
else
i = i + 1
end
elseif t < s.start - 0.5 then
if s.triggered then
s.cancelled = true
table.remove(active_skips, i)
cancel_skip_prompt()
else
i = i + 1
end
else
table.remove(active_skips, i)
cancel_skip_prompt()
end
end
if #active_skips == 0 then
skip_timer:kill()
skip_timer = nil
end
end)
end
local function add_active_skip(s)
for _, exist in ipairs(active_skips) do
if math.abs(exist.start - s.start) <= 0.5 and math.abs(exist.ended - s.ended) <= 0.5 then
return
end
end
table.insert(active_skips, {
start = s.start,
ended = s.ended,
title = s.title,
category = s.category,
triggered = false
})
start_skip_watcher()
end
local function chapterskip(_, current)
if o.mode == "none" then return end
for category in string.gmatch(o.categories, "([^;]+)") do
local name, patterns = string.match(category, " *([^+>]*[^+> ]) *[+>](.*)")
if name then
categories[name:lower()] = patterns
elseif not parsed[category] then
msg.warn("Improper category definition: " .. category)
end
parsed[category] = true
end
local chapters = mp.get_property_native("chapter-list")
local duration = mp.get_property_number("duration") or 0
local total_chapters = #chapters or 0
if duration <= o.intro_time_window or total_chapters <= 1 then return end
for i, chapter in ipairs(chapters) do
-- Calculate chapter duration
local chapter_duration = 0
if chapters[i + 1] then
chapter_duration = chapters[i + 1].time - chapter.time
elseif duration > 0 then
chapter_duration = duration - chapter.time
end
local is_match, match_type, category = matches(i, chapter.title, chapter.time, chapter_duration, total_chapters, duration)
if not skipped[i] and is_match then
if i == current + 1 then
skipped[i] = true
local skip_time = chapters[i + 1] and chapters[i + 1].time or mp.get_property_native("duration")
add_active_skip({
start = chapter.time,
ended = skip_time,
title = chapter.title,
category = category, -- Store the category information
})
end
end
end
end
local function check_skip()
local path = mp.get_property("path")
if not path then return end
local chapters = mp.get_property_native("chapter-list") or {}
local history = read_config(history_path) or {}
local duration = mp.get_property_number("duration") or 0
local filename = mp.get_property("filename")
local file_ext = filename:lower():match("%.([^%.]+)$") or ""
local title = mp.get_property_native("media-title"):gsub("%.[^%.]+$", "")
local dir = get_parent_dir(path)
if duration <= o.intro_time_window then return end
if is_protocol(filename) then
title = url_decode(title)
filename = title
end
if not dir then
local media_title, season, episode = title:match("^(.-)%s*[sS](%d+).-[eE](%d+)")
if season then
dir = (media_title ~= "" and media_title or title) .. " S" .. string.format("%02d", tonumber(season))
else
dir = media_title ~= "" and media_title or title
end
end
local file_history = history[dir]
if not file_history or not file_history.chapterskip then return end
local skip_list = file_history.chapterskip
local fname = file_history.fname
local fname_ext = fname:lower():match("%.([^%.]+)$") or ""
-- Check if it's the same file or a different file in the same directory
local is_same_file = (fname == filename)
if (not is_protocol(path) and file_ext ~= fname_ext) or
(fname ~= filename and not compare_filenames(fname, filename)) then
return
end
table.sort(skip_list, function(a, b) return a.start < b.start end)
if next(skip_list) == nil then return end
if next(chapters) == nil then
-- No chapters: check if we should apply history
if not o.enable_history_position_inference and not is_same_file then
return -- Skip history for non-chapter files when disabled and not the same file
end
-- Apply history with category inference (if enabled or same file)
for _, s in ipairs(skip_list) do
local category = nil
if s.start < o.intro_time_window then
category = "opening"
elseif duration > 0 and s.start >= (duration - o.outro_time_window) then
category = "ending"
end
add_active_skip({
start = s.start,
ended = s.ended,
title = s.title,
category = category
})
end
return
end
local used_chapters = {}
for _, s in ipairs(skip_list) do
for i, chapter in ipairs(chapters) do
if not used_chapters[i] then
local start_time = chapter.time
local end_time = chapters[i + 1] and chapters[i + 1].time or duration
if math.abs((end_time - start_time) - (s.ended - s.start)) <= 0.05 then
used_chapters[i] = true
-- Infer category for chapter-matched skips
local category = nil
if start_time < o.intro_time_window then
category = "opening"
elseif duration > 0 and start_time >= (duration - o.outro_time_window) then
category = "ending"
end
add_active_skip({
start = start_time,
ended = end_time,
category = category
})
break
end
end
end
end
end
local function toggle_markskip()
local pos, err = mp.get_property_number("time-pos")
if not pos then
show_message(texts.failed_timestamp, 2)
msg.error("Failed to get timestamp: " .. err)
return
end
if mark_pos then
local shift, endpos = mark_pos, pos
if shift > endpos then
shift, endpos = endpos, shift
elseif shift == endpos then
show_message(texts.mark_fragment_empty, 2)
return
end
mark_pos = nil
state.ended = endpos
info(string.format(texts.mark_fragment, timestamp(shift), timestamp(endpos)))
cache_skip()
else
mark_pos = pos
state.start = pos
info(string.format(texts.mark_start_pos, timestamp(pos)))
end
end
local function switch_chapterskip()
if o.mode == "none" then
o.mode = "auto"
elseif o.mode == "auto" then
o.mode = "manual"
else
o.mode = "none"
end
info(texts.chapter_mode .. o.mode)
end
local function restoreProp(pause)
if not pause then pause = pause_state end
local fullscreen = mp.get_property("fullscreen")
mp.set_property("vid", vid_state)
if not fullscreen then
mp.set_property("geometry", geometry_state)