-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathvideo1.py
1098 lines (941 loc) · 47.3 KB
/
video1.py
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
import tkinter as tk
from tkinter import filedialog, messagebox
import vlc
import os
import sys
import logging
from screeninfo import get_monitors
import re
from datetime import timedelta
import json
import time
from openai import OpenAI
# Configure logging
logging.basicConfig(
level=logging.DEBUG,
format='%(asctime)s - %(levelname)s - %(message)s',
handlers=[
logging.FileHandler("video_player.log"),
logging.StreamHandler()
]
)
DATA_FILE = "video_player_data.json"
class VideoPlayer:
def __init__(self, master):
self.last_user_seek_time = 0
self.last_update_time = 0
self.last_position = 0
self.slider_update_in_progress = False
self.master = master
self.master.title("Main Video Window")
self.master.geometry("800x600")
# Initialize VLC player
self.instance = vlc.Instance()
self.player = self.instance.media_player_new()
# Video frame in main window
self.video_frame = tk.Frame(self.master, bg="black")
self.video_frame.pack(fill=tk.BOTH, expand=1)
# Bind single right-click event for play/pause
# self.video_frame.bind("<Button-3>", self.toggle_play_pause)
# self.video_frame.config(cursor="right_ptr") # Optional: Change cursor to indicate right-click functionality
# Initialize subtitle variables
self.left_subtitles = []
self.right_subtitles = []
self.left_subtitle_index = 0
self.right_subtitle_index = 0
self.is_closed = False # Flag to handle closure
# Initialize persistent data
self.persistent_data = {}
self.load_persisted_data()
# Create Controls Window
self.create_controls_window()
# Embed VLC Video
self.embed_video()
# Bind the close event
self.master.protocol("WM_DELETE_WINDOW", self.on_close)
self.controls_window.protocol("WM_DELETE_WINDOW", self.on_close)
# Update the slider periodically
self.update_slider()
# Initialize playback flags
self.is_fullscreen = False
# Bind keyboard shortcuts
self.master.bind('<space>', self.toggle_play_pause)
self.master.bind('<Left>', lambda event: self.seek_relative(-5))
self.master.bind('1', lambda event: self.seek_relative(-1))
self.master.bind('2', lambda event: self.seek_relative(-2))
self.master.bind('3', lambda event: self.seek_relative(-3))
self.master.bind('4', lambda event: self.seek_relative(-4))
self.master.bind('5', lambda event: self.seek_relative(-5))
self.master.bind('6', lambda event: self.seek_relative(-6))
self.master.bind('7', lambda event: self.seek_relative(-7))
self.master.bind('8', lambda event: self.seek_relative(-8))
self.master.bind('9', lambda event: self.seek_relative(-9))
self.master.bind('<Right>', lambda event: self.seek_relative(5))
self.master.bind('<plus>', self.jump_to_next_subtitle)
self.master.bind('*', self.cycle_audio_track) # Add binding for * key
# Add bindings for numeric keys 1-9
# Initialize audio and subtitle stream variables
self.current_audio_track = -1
self.current_subtitle_track = -1
def load_persisted_data(self):
"""
Load persisted data from the JSON file.
"""
if os.path.exists(DATA_FILE):
try:
with open(DATA_FILE, 'r', encoding='utf-8') as f:
self.persistent_data = json.load(f)
logging.info("Persisted data loaded successfully.")
except Exception as e:
logging.error(f"Error loading persisted data: {e}")
self.persistent_data = {}
else:
self.persistent_data = {}
def save_persisted_data(self):
"""
Save current video state to the JSON file.
"""
try:
with open(DATA_FILE, 'w', encoding='utf-8') as f:
json.dump(self.persistent_data, f, indent=4)
logging.info("Persisted data saved successfully.")
except Exception as e:
logging.error(f"Error saving persisted data: {e}")
def load_video(self):
"""
Load a video file and start playback. Automatically loads associated subtitles
and resumes playback if the video was opened previously.
"""
file_path = filedialog.askopenfilename(
filetypes=[("Video Files", "*.mp4 *.mkv *.avi *.mov")]
)
if file_path:
try:
# Reset subtitle paths
self.left_subtitle_path = None
self.right_subtitle_path = None
media = self.instance.media_new(file_path)
self.player.set_media(media)
self.player.play()
self.play_pause_btn.config(text="Pause")
logging.info(f"Playing video: {file_path}")
# Initialize video length retrieval
self.length = 0
self.get_video_length() # This will handle loading subtitles and seeking
# After some delay, load audio and subtitle tracks
self.master.after(1000, self.load_audio_tracks)
self.master.after(1500, self.load_subtitle_tracks)
except Exception as e:
logging.error(f"Error loading video: {e}")
messagebox.showerror("Error", f"Failed to load video.\n{str(e)}")
def get_video_length(self):
"""
Retrieve the length of the currently loaded video.
This method schedules itself to run repeatedly until a valid length is obtained.
Once the length is obtained, it proceeds to load subtitles and seek playback.
"""
try:
length_ms = self.player.get_length() # Length in milliseconds
if length_ms > 0:
self.length = length_ms / 1000 # Convert to seconds
logging.info(f"Video length: {self.length} seconds.")
# Proceed to load subtitles and seek playback
self.load_persisted_subtitles_and_seek()
else:
# Retry after 100 milliseconds if length is not yet available
self.master.after(100, self.get_video_length)
except Exception as e:
logging.error(f"Error getting video length: {e}")
self.length = 0
def load_persisted_subtitles_and_seek(self):
"""
Load associated subtitles and seek to the last playback position if available.
Also restore audio and subtitle stream selections.
"""
try:
# Get the current video path in absolute form
media = self.player.get_media()
if not media:
logging.warning("No media is currently loaded.")
return
video_path = media.get_mrl()
if video_path.startswith("file://"):
video_path = video_path[7:] # Remove 'file://' prefix
video_path = os.path.abspath(video_path)
# Check if there's persisted data for this video
video_data = self.persistent_data.get(video_path)
if video_data:
left_sub_path = video_data.get('left_subtitle')
right_sub_path = video_data.get('right_subtitle')
#additional_text_path = video_data.get('additional_text')
last_time = video_data.get('last_playback_time', 0)
self.current_audio_track = video_data.get('audio_track', -1)
self.current_subtitle_track = video_data.get('subtitle_track', -1)
# Restore volume if available
saved_volume = video_data.get('volume')
if saved_volume is not None:
self.player.audio_set_volume(saved_volume)
self.volume_slider.set(saved_volume)
logging.info(f"Restored volume to: {saved_volume}")
# Load additional text if path exists
# if additional_text_path and os.path.exists(additional_text_path):
# try:
# with open(additional_text_path, 'r', encoding='utf-8') as f:
# content = f.read()
# self.additional_text_text.config(state=tk.NORMAL)
# self.additional_text_text.delete(1.0, tk.END)
# self.additional_text_text.insert(tk.END, content)
# self.additional_text_text.config(state=tk.DISABLED)
# self.additional_text_path = additional_text_path
# logging.info(f"Loaded persisted additional text from {additional_text_path}")
# except Exception as e:
# logging.error(f"Error loading persisted additional text: {e}")
# messagebox.showwarning("Warning", f"Failed to load additional text file: {additional_text_path}")
# Automatically load subtitles if paths exist
if left_sub_path and os.path.exists(left_sub_path):
self.left_subtitles = self.load_subtitle_file(left_sub_path)
self.left_subtitle_text.config(state=tk.NORMAL)
self.left_subtitle_text.delete(1.0, tk.END)
self.left_subtitle_text.insert(tk.END, "\n\n".join([s['content'] for s in self.left_subtitles]))
self.left_subtitle_text.config(state=tk.DISABLED)
self.left_subtitle_path = os.path.abspath(left_sub_path)
logging.info(f"Left subtitles loaded from {left_sub_path}")
else:
if left_sub_path:
logging.warning(f"Left subtitle file not found: {left_sub_path}")
messagebox.showwarning("Warning", f"Left subtitle file not found: {left_sub_path}")
if right_sub_path and os.path.exists(right_sub_path):
self.right_subtitles = self.load_subtitle_file(right_sub_path)
self.right_subtitle_text.config(state=tk.NORMAL)
self.right_subtitle_text.delete(1.0, tk.END)
self.right_subtitle_text.insert(tk.END, "\n\n".join([s['content'] for s in self.right_subtitles]))
self.right_subtitle_text.config(state=tk.DISABLED)
self.right_subtitle_path = os.path.abspath(right_sub_path)
logging.info(f"Right subtitles loaded from {right_sub_path}")
else:
if right_sub_path:
logging.warning(f"Right subtitle file not found: {right_sub_path}")
messagebox.showwarning("Warning", f"Right subtitle file not found: {right_sub_path}")
# Resume playback from last saved time
if last_time > 0:
# Ensure that seeking happens after a short delay to allow playback to stabilize
self.master.after(500, lambda: self.seek_to_time(last_time))
# Restore audio and subtitle tracks after a delay
self.master.after(1000, self.restore_audio_and_subtitle_tracks)
except Exception as e:
logging.error(f"Error loading persisted subtitles and seeking playback: {e}")
def restore_audio_and_subtitle_tracks(self):
"""
Restore the saved audio and subtitle track selections.
"""
try:
if self.current_audio_track != -1:
self.player.audio_set_track(self.current_audio_track)
self.audio_var.set(self.current_audio_track)
logging.info(f"Restored audio track: {self.current_audio_track}")
if self.current_subtitle_track != -1:
self.player.video_set_spu(self.current_subtitle_track)
self.subtitle_var.set(self.current_subtitle_track)
logging.info(f"Restored subtitle track: {self.current_subtitle_track}")
except Exception as e:
logging.error(f"Error restoring audio and subtitle tracks: {e}")
def seek_to_time(self, seconds):
"""
Seek the video to the specified time in seconds.
"""
try:
# VLC expects time in milliseconds
self.player.set_time(int(seconds * 1000))
logging.info(f"Resumed playback from {seconds} seconds.")
except Exception as e:
logging.error(f"Error seeking to time {seconds}: {e}")
messagebox.showerror("Error", f"Failed to seek to the last playback time.\n{str(e)}")
def load_subtitle_file(self, file_path):
"""
Load subtitles from a given SRT file.
"""
try:
with open(file_path, 'r', encoding='utf-8') as f:
content = f.read()
subtitles = self.parse_srt(content)
return subtitles
except Exception as e:
logging.error(f"Error loading subtitle file {file_path}: {e}")
messagebox.showerror("Error", f"Failed to load subtitle file.\n{str(e)}")
return []
def create_controls_window(self):
"""
Create the Controls window with playback controls and audio stream options.
"""
self.controls_window = tk.Toplevel(self.master)
self.controls_window.title("Controls")
self.controls_window.geometry("1100x550")
self.controls_window.resizable(True, True)
self.controls_window.bind("<Button-3>", self.toggle_play_pause)
self.controls_window.bind('<space>', self.toggle_play_pause)
self.controls_window.bind('<Left>', lambda event: self.seek_relative(-5))
self.controls_window.bind('<Right>', lambda event: self.seek_relative(5))
self.controls_window.bind('1', lambda event: self.seek_relative(-1))
self.controls_window.bind('2', lambda event: self.seek_relative(-2))
self.controls_window.bind('3', lambda event: self.seek_relative(-3))
self.controls_window.bind('4', lambda event: self.seek_relative(-4))
self.controls_window.bind('5', lambda event: self.seek_relative(-5))
self.controls_window.bind('6', lambda event: self.seek_relative(-6))
self.controls_window.bind('7', lambda event: self.seek_relative(-7))
self.controls_window.bind('8', lambda event: self.seek_relative(-8))
self.controls_window.bind('9', lambda event: self.seek_relative(-9))
self.controls_window.bind('<plus>', self.jump_to_next_subtitle)
self.controls_window.bind('*', self.cycle_audio_track)
# Subtitle Sections Frame
subtitle_frame = tk.Frame(self.controls_window)
subtitle_frame.grid(row=0, column=0, columnspan=3, padx=10, pady=10, sticky="ew")
# Left Subtitle Section
left_subtitle_frame = tk.LabelFrame(subtitle_frame, text="Subtitles 1")
left_subtitle_frame.grid(row=0, column=0, padx=5, pady=5, sticky="nsew")
self.left_subtitle_text = tk.Text(left_subtitle_frame, height=15, width=40, wrap=tk.WORD, font=("Arial", 14))
self.left_subtitle_text.pack(padx=5, pady=5, fill=tk.BOTH, expand=True)
self.left_subtitle_btn = tk.Button(left_subtitle_frame, text="Select SRT File", command=lambda: self.load_subtitles('left'))
self.left_subtitle_btn.pack(pady=5)
# Right Subtitle Section
right_subtitle_frame = tk.LabelFrame(subtitle_frame, text="Subtitles 2")
right_subtitle_frame.grid(row=0, column=1, padx=5, pady=5, sticky="nsew")
self.right_subtitle_text = tk.Text(right_subtitle_frame, height=15, width=40, wrap=tk.WORD, font=("Arial", 14))
self.right_subtitle_text.pack(padx=5, pady=5, fill=tk.BOTH, expand=True)
self.right_subtitle_btn = tk.Button(right_subtitle_frame, text="Select SRT File", command=lambda: self.load_subtitles('right'))
self.right_subtitle_btn.pack(pady=5)
# AI explanation section
ai_frame = tk.LabelFrame(subtitle_frame, text="AI Explanation")
ai_frame.grid(row=0, column=2, padx=5, pady=5, sticky="nsew")
text_scroll_frame = tk.Frame(ai_frame)
text_scroll_frame.pack(padx=5, pady=5, fill=tk.BOTH, expand=True)
self.ai_text = tk.Text(text_scroll_frame, height=15, width=40, wrap=tk.WORD, font=("Arial", 14))
self.ai_text.pack(padx=5, pady=5, fill=tk.BOTH, expand=True)
self.ai_text_btn = tk.Button(ai_frame, text="Get AI Explanation", command=self.get_selected_text_explanation)
self.ai_text_btn.pack(pady=5)
# Additional text section
# additional_text_frame = tk.LabelFrame(subtitle_frame, text="Additional Text")
# additional_text_frame.grid(row=0, column=2, padx=5, pady=5, sticky="nsew")
# # Create a frame to hold the text widget and scrollbar
# text_scroll_frame = tk.Frame(additional_text_frame)
# text_scroll_frame.pack(padx=5, pady=5, fill=tk.BOTH, expand=True)
# # Add scrollbar
# text_scrollbar = tk.Scrollbar(text_scroll_frame)
# text_scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
# self.additional_text_text = tk.Text(text_scroll_frame, height=15, width=40, wrap=tk.WORD, font=("Arial", 14), yscrollcommand=text_scrollbar.set)
# self.additional_text_text.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
# text_scrollbar.config(command=self.additional_text_text.yview)
# self.additional_text_btn = tk.Button(additional_text_frame, text="Select Text", command=lambda: self.load_additional_text())
# self.additional_text_btn.pack(pady=5)
subtitle_frame.columnconfigure(0, weight=1)
subtitle_frame.columnconfigure(1, weight=1)
subtitle_frame.columnconfigure(2, weight=1)
# Control Buttons Frame
buttons_frame = tk.Frame(self.controls_window)
buttons_frame.grid(row=1, column=0, padx=10, pady=10, sticky="w")
# Play/Pause Button
self.play_pause_btn = tk.Button(buttons_frame, text="Play", command=self.play_pause)
self.play_pause_btn.grid(row=0, column=0, padx=5)
# Load Video Button
load_btn = tk.Button(buttons_frame, text="Load Video", command=self.load_video)
load_btn.grid(row=0, column=1, padx=5)
# Fullscreen Button
self.fullscreen_btn = tk.Button(buttons_frame, text="Fullscreen", command=self.toggle_fullscreen)
self.fullscreen_btn.grid(row=0, column=2, padx=5)
# Audio Streams Frame
audio_frame = tk.LabelFrame(self.controls_window, text="Audio Streams")
audio_frame.grid(row=1, column=0, padx=10, pady=10, sticky="e")
self.audio_var = tk.IntVar()
self.audio_var.set(-1) # Default to 'Disable' if applicable
# Arrange audio stream radio buttons horizontally
self.audio_frame_inner = tk.Frame(audio_frame)
self.audio_frame_inner.pack(anchor=tk.W)
# ---- New Subtitle Streams Section ----
subtitle_stream_frame = tk.LabelFrame(self.controls_window, text="Subtitle Streams")
subtitle_stream_frame.grid(row=2, column=0, padx=10, pady=10, sticky="w")
self.subtitle_var = tk.IntVar()
self.subtitle_var.set(-1) # Default to 'Disable' if applicable
# Arrange subtitle stream radio buttons horizontally
self.subtitle_frame_inner = tk.Frame(subtitle_stream_frame)
self.subtitle_frame_inner.pack(anchor=tk.W)
# Load Subtitle Streams Button
self.load_subtitle_streams_btn = tk.Button(subtitle_stream_frame, text="Refresh Subtitle Streams", command=self.load_subtitle_tracks)
self.load_subtitle_streams_btn.pack(pady=5)
# Seek and Volume Sliders Frame
middle_frame = tk.Frame(self.controls_window)
middle_frame.grid(row=3, column=0, columnspan=2, padx=10, pady=10)
# Time Slider
self.seek_var = tk.StringVar()
self.time_slider = tk.Scale(
middle_frame,
from_=0,
to=1000,
orient=tk.HORIZONTAL,
length=400,
command=self.seek,
variable=self.seek_var
)
self.time_slider.grid(row=0, column=0, sticky="ew", padx=5)
# Volume Slider
self.volume_var = tk.StringVar()
self.volume_slider = tk.Scale(
middle_frame,
from_=0,
to=200,
orient=tk.HORIZONTAL,
command=self.set_volume,
variable=self.volume_var
)
self.volume_slider.set(95)
self.volume_slider.grid(row=0, column=1, sticky="w", padx=5)
# Playback Time Label
self.time_label = tk.Label(self.controls_window, text="00:00:00 / 00:00:00")
self.time_label.grid(row=4, column=0, columnspan=2, pady=5)
def embed_video(self):
"""
Embed the VLC video in the Tkinter frame.
"""
try:
if sys.platform.startswith('linux'): # for Linux using the X Server
self.player.set_xwindow(self.video_frame.winfo_id())
elif sys.platform == "win32": # for Windows
self.player.set_hwnd(self.video_frame.winfo_id())
elif sys.platform == "darwin": # for MacOS
try:
from ctypes import c_void_p
self.player.set_nsobject(c_void_p(self.video_frame.winfo_id()))
except Exception as e:
logging.error(f"Error embedding video on MacOS: {e}")
messagebox.showerror("Error", f"Failed to embed video on MacOS.\n{str(e)}")
else:
messagebox.showerror("Error", "Unsupported OS.")
except Exception as e:
logging.error(f"Error embedding video: {e}")
messagebox.showerror("Error", f"Failed to embed video.\n{str(e)}")
def load_audio_tracks(self):
"""
Load available audio tracks and create radio buttons for selection.
"""
try:
descs = self.player.audio_get_track_description()
if descs:
# Clear existing radio buttons
for widget in self.audio_frame_inner.winfo_children():
widget.destroy()
# Add 'Disable' option if applicable
# Uncomment the following lines if 'Disable' is supported
# tk.Radiobutton(self.audio_frame_inner, text="Disable", variable=self.audio_var, value=-1, command=self.set_audio_track).pack(side=tk.LEFT, padx=5)
# Dynamically create radio buttons based on available audio tracks
for track in descs:
impl, name = track
tk.Radiobutton(self.audio_frame_inner, text=name, variable=self.audio_var, value=impl, command=self.set_audio_track).pack(side=tk.LEFT, padx=5)
logging.info("Audio tracks loaded.")
else:
logging.info("No audio tracks available.")
messagebox.showinfo("Info", "No audio tracks available.")
except Exception as e:
logging.error(f"Error loading audio tracks: {e}")
messagebox.showerror("Error", f"Failed to load audio tracks.\n{str(e)}")
def set_audio_track(self):
"""
Set the VLC player to use the selected audio track.
"""
try:
selected_track = self.audio_var.get()
if selected_track == -1:
self.player.audio_set_track(-1) # Disable audio
logging.info("Audio disabled.")
else:
self.player.audio_set_track(selected_track)
logging.info(f"Audio track set to: {selected_track}")
self.current_audio_track = selected_track # Update the current audio track
except Exception as e:
logging.error(f"Error setting audio track: {e}")
messagebox.showerror("Error", f"Failed to set audio track.\n{str(e)}")
def toggle_fullscreen(self):
"""
Toggle fullscreen mode via Tkinter's window attributes.
"""
try:
if not self.is_fullscreen:
self.move_to_same_screen()
self.is_fullscreen = not self.is_fullscreen
self.master.attributes("-fullscreen", self.is_fullscreen)
# Update the button text accordingly
self.fullscreen_btn.config(text="Windowed" if self.is_fullscreen else "Fullscreen")
logging.info(f"Fullscreen {'enabled' if self.is_fullscreen else 'disabled'}.")
except Exception as e:
logging.error(f"Error toggling fullscreen: {e}")
messagebox.showerror("Error", f"Failed to toggle fullscreen.\n{str(e)}")
def move_to_same_screen(self):
"""
Ensure the main window is on the same screen as the controls window before fullscreen.
"""
try:
# Get the position of the controls window
controls_x = self.controls_window.winfo_x()
controls_y = self.controls_window.winfo_y()
# Get monitor info
monitors = get_monitors()
target_monitor = None
for monitor in monitors:
if (monitor.x <= controls_x <= monitor.x + monitor.width) and \
(monitor.y <= controls_y <= monitor.y + monitor.height):
target_monitor = monitor
break
if target_monitor:
# Move main window to the same monitor
self.master.geometry(f"+{target_monitor.x}+{target_monitor.y}")
logging.info(f"Moved main window to monitor at ({target_monitor.x}, {target_monitor.y}).")
else:
logging.warning("Controls window is not on any detected monitor.")
except Exception as e:
logging.error(f"Error moving window to the same screen: {e}")
def toggle_play_pause(self, event=None):
"""
Toggle between play and pause states.
Can be called by the space bar or the play/pause button.
"""
if self.player.is_playing():
self.player.pause()
self.play_pause_btn.config(text="Play")
logging.info("Playback paused.")
else:
self.player.play()
self.play_pause_btn.config(text="Pause")
logging.info("Playback started.")
def play_pause(self):
"""
Existing play/pause method for the button.
Now just calls toggle_play_pause for consistency.
"""
self.toggle_play_pause()
def seek_relative(self, offset):
"""
Seek relative to the current position.
"""
try:
current_time = time.time()
# Only process seek if it's been at least 0.5 seconds since the last seek
if current_time - self.last_user_seek_time > 0.5:
self.slider_update_in_progress = True
current_time_ms = self.player.get_time()
new_time = max(0, current_time_ms + (offset * 1000)) # Convert to milliseconds
self.player.set_time(int(new_time))
self.last_user_seek_time = current_time
self.slider_update_in_progress = False
logging.info(f"Seeked {'forward' if offset > 0 else 'backward'} by {abs(offset)} seconds.")
except Exception as e:
logging.error(f"Error seeking relative: {e}")
messagebox.showerror("Error", f"Failed to seek relative.\n{str(e)}")
def seek(self, value):
"""
Seek to a specific position in the video based on the slider.
"""
try:
current_time = time.time()
# Only process seek if it's been at least 0.5 seconds since the last seek
# and if it's a user-initiated seek (not an automatic update)
if (not self.slider_update_in_progress and
current_time - self.last_user_seek_time > 0.5):
length = self.player.get_length()
seek_time = (float(value) / 1000.0) * length
# Only seek if the change is significant (more than 1 second)
current_position = self.player.get_time()
if abs(current_position - seek_time) > 1000: # 1000ms = 1 second
self.player.set_time(int(seek_time))
self.last_user_seek_time = current_time
logging.info(f"User seeking to: {seek_time} ms")
except Exception as e:
logging.error(f"Error seeking video: {e}")
messagebox.showerror("Error", f"Failed to seek video.\n{str(e)}")
def set_volume(self, volume):
"""
Set the player's volume based on the slider.
"""
try:
volume = int(volume)
self.player.audio_set_volume(volume)
logging.info(f"Volume set to: {volume}")
except Exception as e:
logging.error(f"Error setting volume: {e}")
messagebox.showerror("Error", f"Failed to set volume.\n{str(e)}")
def update_slider(self):
"""
Update the time slider based on the current playback position.
"""
if self.is_closed:
return
try:
current_time = time.time()
if self.player.is_playing() and current_time - self.last_update_time >= 0.5:
position_ms = self.player.get_time()
length = self.player.get_length()
if length > 0:
position = (position_ms / length) * 1000
current_pos = float(self.time_slider.get())
# Only update if position has changed significantly (more than 1%)
if abs(current_pos - position) > 10: # 1% of 1000
self.slider_update_in_progress = True
self.time_slider.set(int(position))
self.last_position = position
self.last_update_time = current_time
self.slider_update_in_progress = False
self.update_time_label()
except Exception as e:
logging.error(f"Error updating slider: {e}")
# Schedule the next update with a longer interval
if not self.is_closed:
self.master.after(500, self.update_slider)
self.update_subtitles()
def update_time_label(self):
"""
Update the playback time label.
"""
try:
if self.length > 0:
current_time = self.player.get_time() # in milliseconds
length = self.length
current_sec = int(current_time / 1000)
total_sec = int(length)
current_str = self.seconds_to_time(current_sec)
total_str = self.seconds_to_time(total_sec)
self.time_label.config(text=f"{current_str} / {total_str}")
else:
self.time_label.config(text="00:00:00 / 00:00:00")
except Exception as e:
logging.error(f"Error updating time label: {e}")
@staticmethod
def seconds_to_time(seconds):
"""
Convert seconds to HH:MM:SS format.
"""
hrs = seconds // 3600
mins = (seconds % 3600) // 60
secs = seconds % 60
return f"{int(hrs):02}:{int(mins):02}:{int(secs):02}"
def on_close(self):
"""
Handle closing of the application. Persist current video state.
"""
self.is_closed = True # Set the flag to True when closing
try:
if self.player:
media = self.player.get_media()
if not media:
logging.warning("No media is currently loaded.")
else:
video_path = media.get_mrl()
if video_path.startswith("file://"):
video_path = video_path[7:] # Remove 'file://' prefix
video_path = os.path.abspath(video_path)
# Get current playback time in seconds
current_time = self.player.get_time() / 1000 if self.player.get_time() > 0 else 0
# Get subtitle file paths and additional text path
left_sub_path = getattr(self, 'left_subtitle_path', None)
right_sub_path = getattr(self, 'right_subtitle_path', None)
#additional_text_path = getattr(self, 'additional_text_path', None)
# Update persistent data
self.persistent_data[video_path] = {
'left_subtitle': left_sub_path,
'right_subtitle': right_sub_path,
#'additional_text': additional_text_path,
'last_playback_time': current_time,
'audio_track': self.current_audio_track,
'subtitle_track': self.current_subtitle_track,
'volume': self.player.audio_get_volume() # Save current volume
}
self.save_persisted_data()
logging.info(f"Persisted state for {video_path} saved at {current_time} seconds.")
self.player.stop()
logging.info("Video player stopped.")
except Exception as e:
logging.error(f"Error during on_close: {e}")
self.master.destroy()
def load_subtitles(self, section):
file_path = filedialog.askopenfilename(filetypes=[("SRT Files", "*.srt")])
if file_path:
try:
subtitles = self.load_subtitle_file(file_path)
if section == 'left':
self.left_subtitles = subtitles
self.left_subtitle_index = 0
self.left_subtitle_path = os.path.abspath(file_path) # Track left subtitle path
else:
self.right_subtitles = subtitles
self.right_subtitle_index = 0
self.right_subtitle_path = os.path.abspath(file_path) # Track right subtitle path
logging.info(f"Loaded subtitles for {section} section: {file_path}")
self.update_subtitles()
except Exception as e:
logging.error(f"Error loading subtitles: {e}")
messagebox.showerror("Error", f"Failed to load subtitles.\n{str(e)}")
@staticmethod
def parse_srt(content):
pattern = re.compile(r'(\d+)\n(\d{2}:\d{2}:\d{2},\d{3}) --> (\d{2}:\d{2}:\d{2},\d{3})\n((?:.*\n)*?)(?:\n|$)')
subtitles = []
for match in pattern.finditer(content):
start = VideoPlayer.parse_time(match.group(2))
end = VideoPlayer.parse_time(match.group(3))
text = match.group(4).strip()
subtitles.append({'start': start, 'end': end, 'content': text})
return subtitles
@staticmethod
def parse_time(time_str):
h, m, s = time_str.replace(',', '.').split(':')
return timedelta(hours=int(h), minutes=int(m), seconds=float(s)).total_seconds()
def update_subtitles(self):
if self.is_closed or not self.player.is_playing():
return # Exit if the window has been closed or video is not playing
try:
current_time = self.player.get_time() / 1000 # Convert to seconds
self.update_subtitle_section(current_time, self.left_subtitles, self.left_subtitle_text, 'left')
self.update_subtitle_section(current_time, self.right_subtitles, self.right_subtitle_text, 'right')
except Exception as e:
logging.error(f"Error updating subtitles: {e}")
# Schedule the next update
if not self.is_closed:
self.master.after(100, self.update_subtitles)
def update_subtitle_section(self, current_time, subtitles, text_widget, section):
if not subtitles:
return
try:
current_subtitle = None
current_index = 0
for i, subtitle in enumerate(subtitles):
if subtitle['start'] <= current_time <= subtitle['end']:
current_subtitle = subtitle
current_index = i
break
if current_subtitle:
prev_subtitles = subtitles[max(0, current_index - 3):current_index]
next_subtitles = subtitles[current_index + 1:current_index + 3]
text_widget.config(state=tk.NORMAL) # Enable editing
text_widget.delete(1.0, tk.END)
# Insert previous subtitles
for s in prev_subtitles:
text_widget.insert(tk.END, s['content'] + "\n\n")
# Insert current subtitle (will be underlined later)
current_start = text_widget.index(tk.END)
text_widget.insert(tk.END, current_subtitle['content'] + "\n\n")
current_end = text_widget.index(tk.END + "-1c") # End of the current subtitle
# Insert next subtitles
for s in next_subtitles:
text_widget.insert(tk.END, s['content'] + "\n\n")
# Apply underline to current subtitle
text_widget.tag_remove("underline", "1.0", tk.END) # Remove previous underlines
text_widget.tag_add("underline", current_start, current_end)
text_widget.tag_configure("underline", underline=True)
# Ensure the current subtitle is visible
text_widget.see(current_start)
text_widget.config(state=tk.DISABLED) # Disable editing
if section == 'left':
self.left_subtitle_index = current_index
else:
self.right_subtitle_index = current_index
except Exception as e:
logging.error(f"Error updating {section} subtitle section: {e}")
# ---- New Methods for Subtitle Stream Selection ----
def load_subtitle_tracks(self):
"""
Load available subtitle tracks from the currently opened video and create radio buttons for selection.
"""
try:
descs = self.player.video_get_spu_description()
if descs:
# Clear existing subtitle radio buttons
for widget in self.subtitle_frame_inner.winfo_children():
widget.destroy()
# Add 'Disable' option
tk.Radiobutton(
self.subtitle_frame_inner,
text="Disable",
variable=self.subtitle_var,
value=-1,
command=self.set_subtitle_track
).pack(side=tk.LEFT, padx=5)
# Dynamically create radio buttons based on available subtitle tracks
for spu in descs:
id_, description = spu
tk.Radiobutton(
self.subtitle_frame_inner,
text=description if description else f"Subtitle {id_}",
variable=self.subtitle_var,
value=id_,
command=self.set_subtitle_track
).pack(side=tk.LEFT, padx=5)
logging.info("Subtitle streams loaded.")
else:
logging.info("No subtitle streams available.")
messagebox.showinfo("Info", "No subtitle streams available.")
except Exception as e:
logging.error(f"Error loading subtitle streams: {e}")
messagebox.showerror("Error", f"Failed to load subtitle streams.\n{str(e)}")
def set_subtitle_track(self):
"""
Set the VLC player to use the selected subtitle track.
"""
try:
selected_spu = self.subtitle_var.get()
if selected_spu == -1:
self.player.video_set_spu(-1) # Disable subtitles
logging.info("Subtitles disabled.")
else:
self.player.video_set_spu(selected_spu)
logging.info(f"Subtitle track set to: {selected_spu}")
self.current_subtitle_track = selected_spu # Update the current subtitle track
except Exception as e:
logging.error(f"Error setting subtitle track: {e}")
messagebox.showerror("Error", f"Failed to set subtitle track.\n{str(e)}")
def update_subtitle_tracks_ui(self):
"""
Refresh the subtitle tracks UI elements if needed.
"""
self.load_subtitle_tracks()
def rewind_seconds(self, seconds):
"""
Rewind the video by the specified number of seconds.
Args:
seconds (int): Number of seconds to rewind
"""
try:
current_time = self.player.get_time() # Current time in milliseconds
new_time = max(0, current_time - (seconds * 1000)) # Ensure we don't go below 0
self.player.set_time(int(new_time))
logging.info(f"Rewound video by {seconds} seconds")
except Exception as e:
logging.error(f"Error rewinding video: {e}")
messagebox.showerror("Error", f"Failed to rewind video.\n{str(e)}")
def jump_to_next_subtitle(self, event=None):
"""
Jump to the beginning of the next subtitle fragment in left_subtitles.
"""
try:
if not self.left_subtitles:
logging.info("No left subtitles loaded to jump to")
return
current_time = self.player.get_time() / 1000 # Convert to seconds
next_subtitle = None
# Find the next subtitle that starts after current time
for subtitle in self.left_subtitles[self.left_subtitle_index:]:
if subtitle['start'] > current_time:
next_subtitle = subtitle
break
if next_subtitle:
# Jump to the start time of the next subtitle
self.player.set_time(int(next_subtitle['start'] * 1000)-500)
logging.info(f"Jumped to next subtitle at {next_subtitle['start']} seconds")
else:
logging.info("No next subtitle found")
except Exception as e:
logging.error(f"Error jumping to next subtitle: {e}")
messagebox.showerror("Error", f"Failed to jump to next subtitle.\n{str(e)}")
def cycle_audio_track(self, event=None):
"""
Cycle through available audio tracks when * key is pressed.
Skips the disabled (-1) track.
"""
try:
descs = self.player.audio_get_track_description()
if not descs:
logging.info("No audio tracks available to cycle through")
return
# Get list of valid track IDs (excluding -1/disabled)
valid_tracks = [track[0] for track in descs if track[0] >= 0]
if not valid_tracks:
logging.info("No valid audio tracks to cycle through")
return
# Find current track index
current_track = self.audio_var.get()
try:
current_index = valid_tracks.index(current_track)
except ValueError:
# If current track is not in valid tracks (e.g., -1), start from beginning
current_index = -1
# Get next track (cycle back to beginning if at end)
next_index = (current_index + 1) % len(valid_tracks)