-
Notifications
You must be signed in to change notification settings - Fork 10
/
subtitle_word_search.lua
executable file
·1098 lines (919 loc) · 40.3 KB
/
subtitle_word_search.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
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
--[[
Program: Subtitle Word Search
Purpose: Search words from the current subtitle file in a search engine
Author: Tomás Crespo
License: GNU GENERAL PUBLIC LICENSE
]]
function descriptor()
return {
title = "Subtitle Word Search",
version = "1.3",
author = "Tomás Crespo",
url = "https://github.com/tcrespog/vlc-subtitle-word-search",
shortdesc = "Subtitle Word Search",
description = "Search words from the current subtitle in a search engine",
capabilities = {}
}
end
-- Add your favourite search engines here, just add another entry of the type {name = "<Your name>", url = "<Your URL>"}
-- Make sure the search engine has the %s text in place of the text to search
search_engines = {
{ name = "Wikitionary", url = "http://en.wiktionary.org/wiki/%s" },
{ name = "WordReference EN-ES", url = "http://www.wordreference.com/enes/%s" },
{ name = "Wikipedia", url = "https://en.wikipedia.org/wiki/%s" },
{ name = "Cambridge", url = "https://dictionary.cambridge.org/search/direct/?datasetsearch=english&q=%s" },
{ name = "Collins", url = "https://www.collinsdictionary.com/search/?dictCode=english&q=%s" },
{ name = "Merriam-Webster", url = "https://www.merriam-webster.com/dictionary/%s" },
{ name = "Vocabulary", url = "https://www.vocabulary.com/dictionary/%s" },
{ name = "Urban Dictionary", url = "https://www.urbandictionary.com/define.php?term=%s" },
}
---------- Module declaration ----------
-- Declare module so as to be able to unit test some components
local M = {};
---------- VLC entrypoints ----------
function activate()
initialize_gui()
initialize_subtitle_files()
initialize_search_engines()
load_subtitle_file()
end
function deactivate()
vlc.deactivate()
end
function close()
deactivate()
end
---------- Initialization functions ----------
-- gui {Gui} The Graphical User Interface.
gui = nil
-- subtitle_files {array<SubtitleFile>} Contains the candidate subtitle files.
subtitle_files = nil
-- current_subtitle_file {SubtitleFile} Contains the currently selected subtitle file.
current_subtitle_file = nil
function initialize_gui()
gui = Gui.new()
gui:render()
end
-- Look for the candidate subtitle files and adds them to the GUI dropdown.
function initialize_subtitle_files()
local file_discoverer = SubtitleFileDiscoverer.new("srt")
subtitle_files = file_discoverer:discover_files()
for index, subtitle_file in ipairs(subtitle_files) do
gui:inject_subtitle_file(subtitle_file:get_name(), index)
end
end
-- Inject the search engine names in the corresponding dropdown widget.
function initialize_search_engines()
for index, search_engine in ipairs(search_engines) do
gui:inject_search_engine(search_engine.name, index)
end
end
---------- GUI callback functions ----------
-- Load a subtitle file.
-- Then shows the subtitle words corresponding to the current time, or displays an error message if something went wrong.
function load_subtitle_file()
if (current_subtitle_file) then
current_subtitle_file:clear()
end
local subtitle_file_index = gui:get_selected_subtitle_file_index()
current_subtitle_file = subtitle_files[subtitle_file_index]
if (current_subtitle_file) then
local subtitle_delay = vlc.var.get(vlc.object.input(), "spu-delay")
local video_length = vlc.var.get(vlc.object.input(), "length")
local srt_reader = SrtReader.new(current_subtitle_file:get_path(), subtitle_delay, video_length)
local subtitle_lines, error_message = srt_reader:read()
if (error_message) then
gui:print_error_message(error_message)
else
current_subtitle_file:set_subtitle_lines(subtitle_lines)
capture_words_at_now()
end
else
local video_directory, video_filename = get_video_file_location()
if (video_directory) then
gui:print_error_message("No subtitle files found at '" .. video_directory .. "' for the file '" .. video_filename .. "'")
else
gui:print_error_message("No item playing")
end
end
end
-- Show the words of the subtitle appearing at the current timestamp in the corresponding list widget.
-- Displays an error message if something goes wrong.
function capture_words_at_now()
if (not current_subtitle_file) then
return
end
local current_playing_timestamp = Timestamp.now()
local subtitle_line = current_subtitle_file:search_line_at(current_playing_timestamp)
show_subtitle_and_timestamp(subtitle_line, current_playing_timestamp)
end
-- Show the words in the list widget corresponding to the current subtitle.
function navigate_still()
navigate(0)
end
-- Show the words in the list widget corresponding to the subtitle that goes before the current one.
function navigate_backward()
navigate(-1)
end
-- Show the words in the list widget corresponding to the subtitle that goes after the current one.
function navigate_forward()
navigate(1)
end
-- Show the words in the list widget corresponding to the subtitle shifted `n` lines.
-- @param n {number} The number of lines to shift.
function navigate(n)
if (not current_subtitle_file) then
return
end
local subtitle_line = current_subtitle_file:shift_lines(n)
if (subtitle_line) then
show_subtitle_and_timestamp(subtitle_line, subtitle_line:get_start())
end
end
-- Show the words of a subtitle along with the associated timestamp in the corresponding list widget.
-- @param subtitle_line {SubtitleLine} The subtitle line to show split.
-- @param timestamp {Timestamp} The associated appearance timestamp.
function show_subtitle_and_timestamp(subtitle_line, timestamp)
if (subtitle_line) then
gui:inject_subtitle_words(subtitle_line:get_content())
else
gui:inject_subtitle_words("")
end
gui:print_timestamp(timestamp)
end
-- Read the timestamp corresponding to the current subtitle line and visits that time in the video.
function go_to_subtitle_timestamp()
if (not current_subtitle_file) then
return
end
local current_subtitle_line = current_subtitle_file:shift_lines(0)
if (current_subtitle_line) then
vlc.var.set(vlc.object.input(), "time", current_subtitle_line:get_start():truncate_to_seconds():to_microseconds())
end
end
-- Look up a word in a search engine.
function search_word()
local selected_word = gui:get_first_selected_word()
local selected_search_engine_index = gui:get_selected_search_engine_index()
local selected_search_engine_url = search_engines[selected_search_engine_index].url
if (not selected_word) then
return
end
local is_remove_head = gui:get_remove_head_flag()
local online_search = OnlineSearch.new(selected_search_engine_url, selected_word, is_remove_head)
local hyperlink = online_search:generate_html_hyperlink()
gui:print_html(hyperlink .. "<p><em>Searching...</em></p>")
gui:update()
local content, error_message = online_search:request()
if (content) then
gui:print_html(hyperlink .. content)
else
gui:print_error_message(hyperlink .. error_message)
end
end
---------- Classes ----------
-- class Gui
-- Renders the GUI (Graphical User Interface).
Gui = {}
Gui.__index = Gui
-- Constructor method. Create the GUI instance.
function Gui.new()
local self = setmetatable({}, Gui)
-- dialog {vlc.dialog} The VLC dialog.
self.dialog = nil
-- files_dropdown {vlc.dropdown} The subtitle files dropdown.
self.files_dropdown = nil
-- lower_checkbox {vlc.checkbox} The text to lower case checkbox flag.
self.lower_checkbox = nil
-- symbol_checkbox {vlc.checkbox} The text to punctuation strip checkbox flag.
self.symbol_checkbox = nil
-- timestamp_label {vlc.label} The current timestamp label.
self.timestamp_label = nil
-- words_list {vlc.list} The words list widget.
self.words_list = nil
-- search_engines_dropdown {vlc.dropdown} The search engines dropdown.
self.search_engines_dropdown = nil
-- remove_head_checkbox {vlc.checkbox} The HTML remove head checkbox flag.
self.remove_head_checkbox = nil
-- html_text_box {vlc.html} The text box to render the web HTML.
self.html_text_box = nil
-- last_row {number} The last row in the grid being constructed (starts at 0: no row).
self.last_row = 0
return self
end
-- Render the VLC extension grid dialog.
function Gui:render()
self.dialog = vlc.dialog("Subtitle Word Search")
self:draw_file_section()
self:draw_subtitle_section()
self:draw_online_search_section()
self.dialog:show()
end
-- Increment the index of the last row in the GUI and return it.
-- Equivalent to the typical construct `++n` of other programming languages.
-- @return {number} The last row number after the increment.
function Gui:increment_row()
self.last_row = self.last_row + 1
return self.last_row
end
-- Draw the subtitle files selector section.
function Gui:draw_file_section()
self.dialog:add_label("<b>Subtitles file</b>", 1, self:increment_row(), 5, 1)
self.files_dropdown = self.dialog:add_dropdown(1, self:increment_row(), 4, 1)
self.dialog:add_button("Load", load_subtitle_file, 5, self.last_row, 1, 1)
end
-- Draw the subtitle navigation and word selection section.
function Gui:draw_subtitle_section()
self.dialog:add_label("<b>Subtitle words</b>", 1, self:increment_row(), 5, 1)
self.dialog:add_button("Transform", navigate_still, 1, self:increment_row(), 3, 1)
self.lower_checkbox = self.dialog:add_check_box("Lower", true, 4, self.last_row, 1, 1)
self.symbol_checkbox = self.dialog:add_check_box("Symbols", false, 5, self.last_row, 1, 1)
self.dialog:add_button("Refresh", capture_words_at_now, 1, self:increment_row(), 1, 1)
self.dialog:add_button("<<", navigate_backward, 2, self.last_row, 1, 1)
self.timestamp_label = self.dialog:add_label("00:00:00", 3, self.last_row, 1, 1)
self.dialog:add_button(">>", navigate_forward, 4, self.last_row, 1, 1)
self.dialog:add_button("Go", go_to_subtitle_timestamp, 5, self.last_row, 1, 1)
self.words_list = self.dialog:add_list(1, self:increment_row(), 5, 1)
end
-- Draw the search section.
function Gui:draw_online_search_section()
self.dialog:add_label("<b>Word Search</b>", 1, self:increment_row(), 5, 1)
self.search_engines_dropdown = self.dialog:add_dropdown(1, self:increment_row(), 3, 1)
self.remove_head_checkbox = self.dialog:add_check_box("Remove style", false, 4, self.last_row, 1 ,1)
self.dialog:add_button("Search", search_word, 5, self.last_row, 1, 1)
self.html_text_box = self.dialog:add_html("", 1, self:increment_row(), 5, 1)
self:print_html("<p><em>Search result goes here.</em></p>")
end
-- Add a file name to the corresponding dropdown widget.
-- @param name {string} The subtitle file name.
-- @param index {number} The search engine index in the global array of subtitle files.
function Gui:inject_subtitle_file(name, index)
self.files_dropdown:add_value(name, index)
end
-- Add a search engine to the corresponding dropdown widget.
-- @param name {string} The search engine name.
-- @param index {number} The search engine index in the global array of engines.
function Gui:inject_search_engine(name, index)
self.search_engines_dropdown:add_value(name, index)
end
-- Show the split words from a subtitle in the list widget.
-- @param subtitle {string} the subtitle to show.
function Gui:inject_subtitle_words(text)
self.words_list:clear()
local to_lower = self.lower_checkbox:get_checked()
local strip_punctuation = not self.symbol_checkbox:get_checked()
local words = split_words(text, to_lower, strip_punctuation)
for index, word in ipairs(words) do
self.words_list:add_value(word, index)
end
end
-- Get the index of the selected subtitle file in the corresponding dropdown widget.
-- @return {number} The index of the selected file.
function Gui:get_selected_subtitle_file_index()
return self.files_dropdown:get_value()
end
-- Get the selected search engine index in the corresponding dropdown widget.
-- @return {number} The selected search engine index.
function Gui:get_selected_search_engine_index()
return self.search_engines_dropdown:get_value()
end
-- Get the first selected word in the corresponding list widget.
-- @return {string} The first selected word, `nil` if nothing was selected
function Gui:get_first_selected_word()
local selection = self.words_list:get_selection()
if (selection) then
for index, selected_word in pairs(selection) do
return selected_word
end
else
return nil
end
end
-- Gets the value of the remove HTML head checkbox flag.
-- @return {boolean} `true` if the checkbox is checked, `false` otherwise.
function Gui:get_remove_head_flag()
return self.remove_head_checkbox:get_checked()
end
-- Print a timestamp in the specific label.
-- @param timestamp {Timestamp} The timestamp to print.
function Gui:print_timestamp(timestamp)
self.timestamp_label:set_text(timestamp:to_string())
end
-- Print a HTML text in the corresponding widget.
-- @param html {string} The HTML text content.
function Gui:print_html(html)
self.html_text_box:set_text(html)
end
-- Print a red-colored HTML error message.
-- @param error_message {string} The error message to print.
function Gui:print_error_message(error_message)
local html_error_message = "<p><font color='red'>" .. error_message .. "</font></p>"
self:print_html(html_error_message)
end
-- Update the GUI. Useful to render partial updates before a method returns.
function Gui:update()
self.dialog:update()
end
-- class Gui end
-- Class: OnlineSearch.
-- Represents a search in a search engine.
OnlineSearch = {}
OnlineSearch.__index = OnlineSearch
-- Constructor method. Create an online search.
-- @param search_engine_url {string} The search engine URL.
-- @return {OnlineSearch} The search engine instance.
function OnlineSearch.new(search_engine_url, word, is_remove_head)
local self = setmetatable({}, OnlineSearch)
-- search_engine_url {string} The search engine URL with a placeholder.
self.search_engine_url = search_engine_url
-- is_remove_head {boolean} If `true`, removes the HTML <head> tag from the downloaded content.
self.is_remove_head = is_remove_head
-- query_url {string} The constructed URL composed of engine URL and word.
self.prepared_url = nil
self:prepare_url(word)
return self
end
-- Request the query result.
-- @return {string} The query result content, `nil` if some error occurs.
-- @return {string} An error message, `nil` if everything was good.
function OnlineSearch:request()
local downloaded_content = download_content(self.prepared_url)
if (self.is_remove_head) then
return remove_html_head(downloaded_content)
else
return downloaded_content
end
end
-- Build the URL query to look up a word in a search engine.
-- @param word {string} The word to look up.
function OnlineSearch:prepare_url(word)
local query_place_regex = "%%s"
local encoded_term = M.encode_uri_component(word)
self.prepared_url = self.search_engine_url:gsub(query_place_regex, encoded_term)
end
-- Generates an HTML hyperlink to the query URL.
-- @return {string} The HTML hyperlink.
function OnlineSearch:generate_html_hyperlink()
return "<p><a href=\"" .. self.prepared_url .. "\" target=\"_blank\"><strong>Open in browser</strong></a></p>"
end
-- Class: SubtitleFileDiscoverer.
-- Discovers the candidate subtitle files in the filesystem.
SubtitleFileDiscoverer = {}
SubtitleFileDiscoverer.__index = SubtitleFileDiscoverer
-- Constructor method. Create a subtitle file discoverer.
-- @param extension {string} The extension of the file to discover. Ex. "srt".
-- @return {SubtitleFileDiscoverer} The subtitle discoverer instance.
function SubtitleFileDiscoverer.new(extension)
local self = setmetatable({}, SubtitleFileDiscoverer)
-- extension {string} The file extension to discover
self.extension = extension
return self
end
-- Get the file system's paths to the found subtitles of the playing video
-- @return {array<SubtitleFile>} The array of discovered files.
function SubtitleFileDiscoverer:discover_files()
local subtitle_files = {}
local video_dir_path, video_filename = get_video_file_location()
if (not video_dir_path) then
return subtitle_files
end
local video_filename_no_ext = video_filename:match("^(.+)%..+$")
if (is_unix_os()) then
video_dir_path = "/" .. video_dir_path
end
local filenames_in_directory = list_directory(video_dir_path)
local subtitle_filenames = self:find_matching_filenames(video_filename_no_ext, filenames_in_directory)
if (subtitle_filenames) then
for index, subtitle_filename in ipairs(subtitle_filenames) do
local absolute_path = video_dir_path .. subtitle_filename
subtitle_files[#subtitle_files + 1] = SubtitleFile.new(absolute_path, subtitle_filename)
end
else
vlc.msg.warn("The list of filenames in the directory couldn't be retrieved: trying the default subtitle name")
local filename = video_filename_no_ext .. "." .. self.extension
local absolute_path = video_dir_path .. filename
subtitle_files[1] = SubtitleFile.new(absolute_path, filename)
end
return subtitle_files
end
-- Get an array of filenames that have the same name as the given filename but differ in extension.
-- @param target_filename {string} The filename to match (without the extension). Ex. "video".
-- @param filename_listing {array<string>} The array of filenames to compare.
-- @param extension {string} The extension to match. Ex. ".srt".
-- @return {array<string>} The array of matching filenames. Ex. { "video.srt", "video.eng.srt", ... }.
function SubtitleFileDiscoverer:find_matching_filenames(target_filename, filename_listing)
local matching_filenames = {}
for index, candidate_filename in ipairs(filename_listing) do
local has_name = candidate_filename:find(target_filename, 1, true)
local has_extension = candidate_filename:find("%." .. self.extension .. "$")
if (has_name and has_extension) then
matching_filenames[#matching_filenames + 1] = candidate_filename
end
end
return matching_filenames
end
-- Class: SubtitleFile.
-- Represents a subtitle file.
SubtitleFile = {}
SubtitleFile.__index = SubtitleFile
-- Constructor method. Create a subtitle file.
-- @param path {string} The absolute path of the file.
-- @param name {string} The name of the file.
-- @return {SubtitleFile} The subtitle file instance.
function SubtitleFile.new(path, name)
local self = setmetatable({}, SubtitleFile)
-- path {string} The path of the subtitle file.
self.path = path
-- name {string} The name of the subtitle file.
self.name = name
-- subtitle_lines {array<SubtitleLine>} The subtitle lines in the file.
self.subtitle_lines = nil
-- current_line_index {number} The index of the current subtitle.
self.current_line_index = nil
return self
end
-- Set the subtitle lines read from the file.
-- @param {array<SubtitleLine>} The array of subtitle lines in order of appearance.
function SubtitleFile:set_subtitle_lines(subtitle_lines)
self.subtitle_lines = subtitle_lines
end
-- Get the name of the subtitle file.
-- @return {string} The name of the subtitle file.
function SubtitleFile:get_name()
return self.name
end
-- Get the path of the subtitle file.
-- @return {string} The path of the subtitle file.
function SubtitleFile:get_path()
return self.path
end
-- Search the subtitle line at the given timestamp.
-- Performs a binary search over the ordered subtitle lines.
-- Updates the value of the current line index, which would point to an index with fractional part if nothing was found.
-- @param {Timestamp} The timestamp to search the subtitle at.
-- @return {SubtitleLine} The found line, `nil` if no line was found for the timestamp.
function SubtitleFile:search_line_at(timestamp)
local lower_bound, upper_bound = 1, #self.subtitle_lines
local found_line, middle_index
repeat
local half_distance = math.floor((upper_bound - lower_bound) / 2)
middle_index = lower_bound + half_distance
local current_line = self.subtitle_lines[middle_index]
local is_in_interval = current_line:is_in_interval(timestamp)
if (is_in_interval) then
found_line = current_line
self.current_line_index = middle_index
break
else
local comparison = timestamp:compare_to(current_line:get_start())
if (comparison > 0) then
lower_bound = middle_index
else
upper_bound = middle_index
end
end
until (half_distance == 0)
if (not found_line) then
self:set_invalid_line_index(lower_bound, upper_bound, timestamp)
end
return found_line
end
-- Set an index with fractional part, indicating the place near two consecutive indices where a value not found should be.
-- @param lower_bound {number} The lower bound index of the value proximity.
-- @param upper_bound {number} The upper bound index of the value proximity.
-- @param timestamp {Timestamp} The not found value timestamp.
function SubtitleFile:set_invalid_line_index(lower_bound, upper_bound, timestamp)
local lower_line_timestamp = self.subtitle_lines[lower_bound]:get_start()
local upper_line_timestamp = self.subtitle_lines[upper_bound]:get_start()
if (timestamp:compare_to(lower_line_timestamp) < 0) then
self.current_line_index = lower_bound - 0.5
elseif (timestamp:compare_to(upper_line_timestamp) > 0) then
self.current_line_index = upper_bound + 0.5
else
self.current_line_index = lower_bound + 0.5
end
end
-- Check if the current index is pointing to an actual subtitle, or rather to a middle ground.
-- @return {boolean} `true` if the current line index points to a valid line, `false` otherwise.
function SubtitleFile:is_valid_line_index()
return (self.current_line_index == math.floor(self.current_line_index))
end
-- Get the subtitle line shifting `n` lines from the current line.
-- The lines to shift must be between -1, 0 and +1. A value of 0 returns the current line, or `nil` if not pointing to a valid line.
-- @param n {number} The number of lines to shift.
-- @return The shifted line, `nil` if the shift exceeds the array bounds or doesn't point to anything.
function SubtitleFile:shift_lines(n)
local is_valid_line_index = self:is_valid_line_index()
if (not is_valid_line_index and (n == 0)) then
return nil
end
local new_line_index
if (is_valid_line_index) then
new_line_index = self.current_line_index + n
else
new_line_index = self.current_line_index + 0.5 * n
end
if ((new_line_index < 1) or (new_line_index > #self.subtitle_lines)) then
return nil
end
self.current_line_index = new_line_index
return self.subtitle_lines[new_line_index]
end
-- Clear the subtitle lines of the file.
-- Note the current line index is not cleared.
function SubtitleFile:clear()
self.subtitle_lines = nil
end
-- Class: SrtReader.
-- Reads an SRT file.
SrtReader = {}
SrtReader.__index = SrtReader
-- Reader state machine values
SrtReader.READING_NUMBER = 0
SrtReader.READING_INTERVAL = 1
SrtReader.READING_CONTENT = 2
-- Constructor method. Creates a reader.
-- @param filepath {string} The path of the file to read.
-- @param subtitle_delay_microseconds {number} The subtitle delay in microseconds. Can be negative.
-- @return {SrtReader} The SRT reader instance.
function SrtReader.new(filepath, subtitle_delay_microseconds, video_length_microseconds)
local self = setmetatable({}, SrtReader)
-- filepath {string} The path of the file to read.
self.filepath = filepath
-- subtitle_delay_microseconds {number} The subtitle delay in microseconds.
self.subtitle_delay_microseconds = subtitle_delay_microseconds
-- video_length_microseconds {number} The length of the video in microseconds.
self.video_length_microseconds = video_length_microseconds
-- current_line_number {number} The line number of the text file being read.
self.current_line_number = 1
-- subtitle_lines {array<SubtitleLine>} The subtitle lines in the file.
self.subtitle_lines = {}
-- current_index {number} The index corresponding to the current subtitle line being read.
self.current_index = 1
-- current_number {number} The number of the subtitle line being read.
self.current_number = 1
-- current_subtitle_line {SubtitleLine} The subtitle line being constructed.
self.current_subtitle_line = nil
-- state {number} The current state in the reader's state machine
self.current_state = SrtReader.READING_NUMBER
return self
end
-- Read the file extracting all subtitle lines.
-- @return {array<SubtitleLine>} The resulting subtitle lines.
-- @return {string} An error message if some I/O error or processing occurs, nil if everything goes well
function SrtReader:read()
local file, error_message = io.open(self.filepath, "r")
if (not file) then
return nil, error_message
end
self.current_subtitle_line = SubtitleLine.new()
for line in file:lines() do
error_message = self:process_line(line)
if (error_message) then
file:close()
return nil, error_message
end
end
file:close()
return self.subtitle_lines
end
-- Process a file line depending on the state machine status.
-- @param line {string} The file line to read.
-- @return {string} An error message if something goes wrong, `nil` if everything goes well
function SrtReader:process_line(line)
if (self.current_line_number == 1) then
line = filter_utf8_bom(line)
end
local error_message
if (self.current_state == SrtReader.READING_NUMBER) then
error_message = self:process_number(line)
elseif (self.current_state == SrtReader.READING_INTERVAL) then
error_message = self:process_interval(line)
elseif (self.current_state == SrtReader.READING_CONTENT) then
self:process_content(line)
end
self.current_line_number = self.current_line_number + 1
return error_message
end
-- Process a file line looking for a subtitle number.
-- @param line {string} The file line to read.
-- @return {string} An error message if something goes wrong, `nil` if everything goes well.
function SrtReader:process_number(line)
if (is_blank(line)) then return end
local error_message = self:read_number(line)
self.current_state = SrtReader.READING_INTERVAL
return error_message
end
-- Process a file line looking for a subtitle appearance interval.
-- @param line {string} The file line to read.
-- @return {string} An error message if something goes wrong, `nil` if everything goes well.
function SrtReader:process_interval(line)
if (is_blank(line)) then return end
local error_message = self:read_interval(line)
self.current_state = SrtReader.READING_CONTENT
return error_message
end
-- Process a file line looking for subtitle content.
-- @param line {string} The file line to read.
function SrtReader:process_content(line)
if (is_blank(line)) then
if (self.current_subtitle_line.start:is_in_video_bounds(self.video_length_microseconds)) then
-- Save the subtitle line only if the start timestamp is within the video bounds
self.subtitle_lines[self.current_index] = self.current_subtitle_line
self.current_index = self.current_index + 1
end
self.current_state = SrtReader.READING_NUMBER
self.current_subtitle_line = SubtitleLine.new()
return
end
self:read_content(line)
end
-- Read the line containing the number of the current subtitle.
-- Checks if the number is expected.
-- @param line {string} The file line to read.
-- @return {string} The error message if something goes wrong, `nil` if everything goes well
function SrtReader:read_number(line)
local number = line:match("^%s*(%d+)%s*$")
if (not number) then
return "Malformed subtitle number on line " .. self.current_line_number .. "."
end
local number_as_number = tonumber(number)
if (number_as_number ~= self.current_number) then
return "Out of place subtitle found on line " .. self.current_line_number .. "."
end
self.current_number = self.current_number + 1
end
-- Read the line containing the interval appearance time of the current subtitle.
-- Set the state in the current subtitle line under construction.
-- @param line {string} The file line to read.
-- @return {string} The error message if something goes wrong, `nil` if everything goes well
function SrtReader:read_interval(line)
local start_text, finish_text = line:match("^%s*(%d+:%d+:%d+,%d+)%s*-->%s*(%d+:%d+:%d+,%d+)%s*$")
if (not start_text or not finish_text) then
return "Malformed subtitle interval on line " .. self.current_line_number .. "."
end
local start = Timestamp.of_text(start_text):add_microseconds(self.subtitle_delay_microseconds)
local finish = Timestamp.of_text(finish_text):add_microseconds(self.subtitle_delay_microseconds)
self.current_subtitle_line:set_start(start)
self.current_subtitle_line:set_finish(finish)
end
-- Read the line containing the current subtitle text content.
-- Appends the content to the overall subtitle under construction.
-- @param line {string} The file line to read.
function SrtReader:read_content(line)
self.current_subtitle_line:append_content(line)
end
-- Class: SubtitleLine.
-- Class representing a subtitle line with its content and appearance timestamp interval.
SubtitleLine = {}
SubtitleLine.__index = SubtitleLine
-- Constructor method. Create an empty subtitle line to be filled.
-- @return {SubtitleLine} The subtitle line instance.
function SubtitleLine.new()
local self = setmetatable({}, SubtitleLine)
-- start {Timestamp} The start timestamp of the appearance interval.
self.start = nil
-- finish {Timestamp} The finish timestamp of the appearance interval.
self.finish = nil
-- content {string} The text content of the subtitle.
self.content = ""
return self
end
-- Set the start timestamp of the appearance interval.
-- @param start {Timestamp} The start timestamp of the appearance interval.
function SubtitleLine:set_start(start)
self.start = start
end
-- Set the finish timestamp of the appearance interval.
-- @param finish {Timestamp} The finish timestamp of the appearance interval.
function SubtitleLine:set_finish(finish)
self.finish = finish
end
-- Append content to the subtitle line.
-- @param content {string} The text content to append.
function SubtitleLine:append_content(content)
self.content = self.content .. " " .. content
end
-- Get the start timestamp of the appearance interval.
-- @return {Timestamp} The start timestamp of the appearance interval.
function SubtitleLine:get_start()
return self.start
end
-- Get the content of the subtitle line.
-- @return {string} The content of the subtitle.
function SubtitleLine:get_content()
return self.content
end
-- Check whether a timestamp is contained in the subtitle appearance interval (both inclusive).
-- @param timestamp {Timestamp} The timestamp to check.
-- @return {boolean} True if the timestamp is in the interval, false otherwise.
function SubtitleLine:is_in_interval(timestamp)
return (timestamp:compare_to(self.start) >= 0) and (timestamp:compare_to(self.finish) <= 0)
end
-- Class: Timestamp.
-- Class representing a player timestamp.
Timestamp = {}
Timestamp.__index = Timestamp
-- Constructor method. Creates an empty timestamp instance.
-- @return {Timestamp} The timestamp instance.
function Timestamp.new()
local self = setmetatable({}, Timestamp)
-- text {string} The timestamp in <hh:mm:ss,fff> format.
self.text = nil
-- microseconds {number} The timestamp in microseconds.
self.microseconds = nil
return self
end
-- Factory method. Create a new timestamp from text in <hh:mm:ss,fff format>.
-- Computes the equivalent microseconds.
-- @param text {string} The timestamp in <hh:mm:ss,fff> format.
-- @return {Timestamp} The timestamp instance.
function Timestamp.of_text(text)
local instance = Timestamp.new()
instance.text = text
local hours, minutes, seconds, millis = text:match("(%d+):(%d+):(%d+),(%d+)")
instance.microseconds = (tonumber(hours) * 3600 + tonumber(minutes) * 60 + tonumber(seconds) + tonumber(millis) / 1000) * 1000000
return instance
end
-- Factory method. Create a new timestamp from microseconds.
-- Computes the text representation in <hh:mm:ss,fff> format.
-- @param total_microseconds {number} The number of microseconds.
-- @return {Timestamp} The timestamp instance.
function Timestamp.of_microseconds(total_microseconds)
local instance = Timestamp.new()
instance.microseconds = total_microseconds
local milliseconds = math.floor((total_microseconds % 1000000) / 1000)
local hours = math.floor(total_microseconds / 3600000000)
local minutes = math.floor((total_microseconds % 3600000000) / 60000000)
local seconds = math.floor((total_microseconds % 60000000) / 1000000)
instance.text = string.format("%02d:%02d:%02d,%03d", hours, minutes, seconds, milliseconds)
return instance
end
-- Factory method. Create a new timestamp from the playing time of the video.
-- @return {Timestamp} The timestamp instance.
function Timestamp.now()
local playing_time_microseconds = vlc.var.get(vlc.object.input(), "time")
return Timestamp.of_microseconds(playing_time_microseconds)
end
-- Get a representation of the timestamp in <hh:mm:ss> format.
-- @return {string} The timestamp in <hh:mm:ss> format.
function Timestamp:to_string()
return self.text:sub(1, -5)
end
-- Get a representation of the timestamp in microseconds.
-- @return {number} The timestamp in microseconds.
function Timestamp:to_microseconds()
return self.microseconds
end
-- Add a number of microseconds to a timestamp. Returns a new instance.
-- @param microseconds {number} The number of microseconds to add; can be negative.
-- @return {Timestamp} The resulting new timestamp instance.
function Timestamp:add_microseconds(microseconds)
local result_microseconds = self.microseconds + microseconds
return Timestamp.of_microseconds(result_microseconds)
end
-- Compares this timestamp to the given timestamp.
-- @param t {Timestamp} The timestamp to compare to.
-- @return {number} A negative number if this is lower than `t`, a positive number if this is greater than `t`, zero if both are equal.
function Timestamp:compare_to(t)
if (self.microseconds < t.microseconds) then
return -1
elseif (self.microseconds > t.microseconds) then
return 1
else
return 0
end
end
-- Truncates the timestamp to second precision (ignoring milliseconds).
-- @return {Timestamp} A new instance of timestamp truncated to second precision.
function Timestamp:truncate_to_seconds()
local text_without_milliseconds = self:to_string() .. ",000"
return Timestamp.of_text(text_without_milliseconds)
end
-- Checks whether a timestamp is within the bounds of the video length or not.
-- @return {boolean} `true` if is greater than 0 and lower than the video length, `false` otherwise.
function Timestamp:is_in_video_bounds(video_length_microseconds)
return ((self.microseconds >= 0) and (self.microseconds <= video_length_microseconds))
end
---------- Utility functions ----------
-- Check if a string is a blank string (empty or only blanks).
-- @param s {string} The string to check.
-- @return {boolean} `true` if the string is a blank string, `false` otherwise.
function is_blank(s)
if (s:find("^%s*$")) then
return true
end
return false
end
-- Remove the UTF-8 BOM initial mark from a string if present.
-- @param s {string} The string to process.
-- @return {string} The string without the mark if present; the string itself otherwise.
function filter_utf8_bom(s)
local bom_mark = '^' .. string.char(239) .. string.char(187) .. string.char(191)
local start, finish = s:find(bom_mark)
if (start) then
return s:sub(finish + 1, -1)
end
return s
end
-- Check if the current operating system is Unix-like.
-- @return {boolean} `true` if the operating system is Unix-like, `false` otherwise.
function is_unix_os()
if (vlc.config.homedir():find("^/")) then
return true
end
return false
end
-- Get the list of filenames inside a given directory.
-- @param path {string} The directory path separated by slashes. Ex. "directory1/directory2/".
-- @return {array} The array of file names inside the directory, `nil` if the files listing could not be retrieved.
function list_directory(directory)
local filenames = {}
local listing_command
if (is_unix_os()) then
listing_command = 'ls -p "' .. directory .. '" | grep -v /'
else
listing_command = 'dir "' .. directory .. '" /b /a-d'
end