-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathevmp.py
More file actions
845 lines (743 loc) · 40.3 KB
/
evmp.py
File metadata and controls
845 lines (743 loc) · 40.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
#!/usr/bin/env python3
import sys
import os
import threading
import time
import tempfile
import shutil
import argparse
from PIL import Image
import numpy as np
import cv2
import sounddevice as sd
import soundfile as sf
import subprocess
import signal
import ssl # <--- IMPORT SSL MODULE
# --- Conditional Import for PytubeFix ---
try:
import pytubefix
except ImportError:
pytubefix = None
# --- Platform specific input ---
# ... (rest of the get_key_non_blocking function remains the same) ...
def get_key_non_blocking():
try: # Unix-like systems
import tty
import termios
import select
fd = sys.stdin.fileno()
old_settings = termios.tcgetattr(fd)
try:
tty.setraw(sys.stdin.fileno())
if select.select([sys.stdin], [], [], 0) == ([sys.stdin], [], []):
ch = sys.stdin.read(1)
if ch == '\x1b': # ESC sequence
next1 = None
if select.select([sys.stdin], [], [], 0) == ([sys.stdin], [], []):
next1 = sys.stdin.read(1)
next2 = None
if next1 and select.select([sys.stdin], [], [], 0) == ([sys.stdin], [], []):
next2 = sys.stdin.read(1)
if next1 == '[':
if next2 == 'A': return "UP"
if next2 == 'B': return "DOWN"
if next2 == 'C': return "RIGHT"
if next2 == 'D': return "LEFT"
full_sequence = ch + (next1 or '') + (next2 or '')
return full_sequence
elif ch == '\x03': return "CTRL_C"
else: return ch
finally:
termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
except ImportError: # Windows
import msvcrt
if msvcrt.kbhit():
ch_bytes = msvcrt.getch()
if ch_bytes == b'\xe0' or ch_bytes == b'\x00':
ch2_bytes = msvcrt.getch()
if ch_bytes == b'\xe0':
if ch2_bytes == b'H': return "UP"
if ch2_bytes == b'P': return "DOWN"
if ch2_bytes == b'M': return "RIGHT"
if ch2_bytes == b'K': return "LEFT"
else:
try:
decoded_ch = ch_bytes.decode('utf-8')
if decoded_ch == '\x1b': return "ESC"
if ch_bytes == b'\x03': return "CTRL_C"
return decoded_ch
except UnicodeDecodeError: return ch_bytes
except Exception: pass
return None
# --- Constants ---
UPPER_HALF_BLOCK = '▀'
CSI = '\x1b['
FG_TRUECOLOR = '38;2;'
BG_TRUECOLOR = '48;2;'
END_CODE = 'm'
RESET_ALL = f'{CSI}0{END_CODE}'
CLEAR_SCREEN = f'{CSI}2J'
CURSOR_HOME = f'{CSI}H'
HIDE_CURSOR = f'{CSI}?25l'
SHOW_CURSOR = f'{CSI}?25h'
CURSOR_UP_N = lambda n: f'{CSI}{n}A'
CURSOR_COL_1 = f'{CSI}1G'
SEEK_TIME_SECONDS = 5
AUDIO_LATENCY_SUGGESTION = 'high'
PROGRESS_BAR_FILLED_CHAR = '█'
PROGRESS_BAR_EMPTY_CHAR = '─'
PROGRESS_BAR_COLOR_FG = f'{CSI}{FG_TRUECOLOR}220;50;50{END_CODE}'
PROGRESS_BAR_COLOR_BG_ANSI = f'{CSI}{BG_TRUECOLOR}50;50;50{END_CODE}'
TIMESTAMP_COLOR_FG_ANSI = f'{CSI}{FG_TRUECOLOR}200;200;200{END_CODE}'
# --- Helper Functions ---
def rgb_to_ansi_fg(r, g, b):
return f'{CSI}{FG_TRUECOLOR}{int(r)};{int(g)};{int(b)}{END_CODE}'
def rgb_to_ansi_bg(r, g, b):
return f'{CSI}{BG_TRUECOLOR}{int(r)};{int(g)};{int(b)}{END_CODE}'
def clear_terminal():
sys.stdout.write(CLEAR_SCREEN + CURSOR_HOME)
sys.stdout.flush()
def format_time(seconds):
seconds = int(seconds)
hours = seconds // 3600
minutes = (seconds % 3600) // 60
secs = seconds % 60
if hours > 0: return f"{hours:02d}:{minutes:02d}:{secs:02d}"
else: return f"{minutes:02d}:{secs:02d}"
class TerminalPlayer:
def __init__(self, source_path, is_youtube=False, repeat=False, speed=1.0, no_audio=False):
self.source_path = source_path
self.is_youtube = is_youtube
self.repeat = repeat
self.speed = max(0.1, speed)
self.force_no_audio = no_audio
self.temp_dir = None
self.video_file_to_play = None
self.audio_file_to_play = None
self.cap = None
self.fps = 30.0
self.effective_fps = 30.0
self.video_frame_count = 0
self.duration = 0.1
self.render_width = 80
self.video_render_height_pixels = 48
self.num_video_lines = 24
self.playing = False
self.paused = False
self.exit_flag = threading.Event()
self.state_lock = threading.Lock() # For shared state like paused, current_audio_frame, seek_request
self.audio_data = None
self.audio_samplerate = None
self.audio_stream = None
self.current_audio_frame = 0
self.audio_channels = 1
self.audio_total_frames = 0
self.has_audio = False
self.first_frame_rendered = False
self.last_term_size = (0, 0)
self.original_termios_settings = None
self.original_sigint_handler = None
self.show_progress_bar = True
self.seek_request_time_sec = -1.0
def _setup_signal_handler(self):
try:
self.original_sigint_handler = signal.getsignal(signal.SIGINT)
signal.signal(signal.SIGINT, self._handle_sigint)
except Exception as e:
print(f"Warning: Error setting up SIGINT handler: {e}", file=sys.stderr)
def _handle_sigint(self, signum, frame):
print("\nCtrl+C detected by signal handler! Signaling exit...", end='', flush=True)
self.exit_flag.set()
def _update_render_dimensions(self):
try:
cols, lines = os.get_terminal_size()
self.render_width = cols
if lines > 1:
self.num_video_lines = lines - 1
self.show_progress_bar = True
else:
self.num_video_lines = lines
self.show_progress_bar = False
self.video_render_height_pixels = self.num_video_lines * 2
self.last_term_size = (cols, lines)
return True
except OSError:
# print("Warning: Could not get terminal size. Using default dimensions.", file=sys.stderr)
self.render_width = 80
self.num_video_lines = 23
self.show_progress_bar = True
self.video_render_height_pixels = self.num_video_lines * 2
self.last_term_size = (self.render_width, self.num_video_lines + 1)
return False
def _setup_terminal(self):
self._update_render_dimensions()
if 'termios' in sys.modules:
try: self.original_termios_settings = termios.tcgetattr(sys.stdin.fileno())
except Exception: self.original_termios_settings = None
print(HIDE_CURSOR, end='')
sys.stdout.flush()
def _prepare_media_files(self):
if self.is_youtube:
if pytubefix is None:
print("ERROR: pytubefix module is not installed. Cannot play YouTube videos.", file=sys.stderr)
return False
self.temp_dir = tempfile.mkdtemp(prefix="term_player_yt_")
print("Connecting to YouTube using pytubefix...")
try:
yt = pytubefix.YouTube(self.source_path, on_progress_callback=self._download_progress)
print(f"Fetching streams for: {yt.title}")
video_stream = yt.streams.filter(progressive=True, file_extension='mp4').get_highest_resolution()
if not video_stream:
print("No progressive MP4 found, trying adaptive video stream...")
video_stream = yt.streams.filter(adaptive=True, file_extension='mp4', only_video=True).order_by('resolution').desc().first()
if not video_stream:
print("Error: No suitable MP4 video stream found.", file=sys.stderr)
return False
print(f"Selected Video: {video_stream.resolution}, Type: {video_stream.mime_type}")
print("\nDownloading Video...")
self.video_file_to_play = video_stream.download(output_path=self.temp_dir, filename_prefix="video_")
print(f"\nVideo saved to: {self.video_file_to_play}")
if not self.force_no_audio:
print("Selecting Audio Stream...")
audio_stream = yt.streams.filter(only_audio=True, mime_type="audio/webm").order_by('abr').desc().first()
if not audio_stream:
audio_stream = yt.streams.filter(only_audio=True, mime_type="audio/mp4").order_by('abr').desc().first()
if not audio_stream:
audio_stream = yt.streams.filter(only_audio=True).order_by('abr').desc().first()
if audio_stream:
print(f"Selected Audio: {audio_stream.abr}, Type: {audio_stream.mime_type}")
print("\nDownloading Audio...")
self.audio_file_to_play = audio_stream.download(output_path=self.temp_dir, filename_prefix="audio_")
print(f"\nAudio saved to: {self.audio_file_to_play}")
else:
print("Warning: No separate YouTube audio stream found.", file=sys.stderr)
else:
print("Skipping YouTube audio download (--no-audio specified).")
return True
except Exception as e:
print(f"YouTube download process failed: {e} ({type(e).__name__})", file=sys.stderr)
return False
else:
if not os.path.isfile(self.source_path):
print(f"Error: Local video file not found: {self.source_path}", file=sys.stderr)
return False
self.video_file_to_play = self.source_path
print(f"Playing local video file: {self.video_file_to_play}")
if self.force_no_audio:
print("Audio explicitly disabled by user (--no-audio).")
return True
def _download_progress(self, stream, chunk, bytes_remaining):
total_size = stream.filesize
bytes_downloaded = total_size - bytes_remaining
percentage = (bytes_downloaded / total_size) * 100
bar_filled = int(percentage / 10)
bar_empty = 10 - bar_filled
progress_display = f"\rDownloading {stream.mime_type.split('/')[0]}: [{'#' * bar_filled}{'-' * bar_empty}] {percentage:.1f}% "
sys.stdout.write(progress_display)
sys.stdout.flush()
def _init_playback(self):
print("\nInitializing playback systems...")
if not self.video_file_to_play:
print("Error: Video file path has not been set.", file=sys.stderr)
return False
self.cap = cv2.VideoCapture(self.video_file_to_play)
if not self.cap.isOpened():
print(f"Error: Could not open video source: {self.video_file_to_play}", file=sys.stderr)
return False
self.fps = self.cap.get(cv2.CAP_PROP_FPS)
if self.fps <= 0:
print("Warning: Video FPS not readable or zero, defaulting to 30 FPS.", file=sys.stderr)
self.fps = 30.0
self.effective_fps = self.fps * self.speed
self.video_frame_count = int(self.cap.get(cv2.CAP_PROP_FRAME_COUNT))
if self.video_frame_count <= 0:
print("Warning: Video frame count not available or zero. Duration may be inaccurate.", file=sys.stderr)
self.duration = float('inf') # Indicate unknown but long duration for progress display
else:
self.duration = (self.video_frame_count / self.fps) if self.fps > 0 else 0.1
if self.duration <= 0.1 and self.video_frame_count <=0 :
print("Warning: Could not determine video duration. Progress bar and seeking might not work as expected.")
self.duration = float('inf')
actual_width = int(self.cap.get(cv2.CAP_PROP_FRAME_WIDTH))
actual_height = int(self.cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
print(f"Video Info: {actual_width}x{actual_height} @ {self.fps:.2f} FPS (Effective: {self.effective_fps:.2f} FPS)")
if self.duration != float('inf'):
print(f"Frames: {self.video_frame_count}, Duration: {format_time(self.duration)}")
else:
print(f"Frames: {self.video_frame_count} (may be inaccurate), Duration: Unknown")
self.has_audio = False
audio_source_for_processing = self.audio_file_to_play if self.is_youtube and self.audio_file_to_play else self.video_file_to_play
if self.force_no_audio:
print("Audio explicitly disabled by user command.")
elif not audio_source_for_processing:
print("VIDEO ONLY mode: No audio source file specified or found.")
else:
try:
print(f"Attempting to load/extract audio directly from: {audio_source_for_processing}")
info = sf.info(audio_source_for_processing)
self.audio_data, self.audio_samplerate = sf.read(audio_source_for_processing, dtype='float32', always_2d=True)
self.audio_channels = self.audio_data.shape[1]
self.audio_total_frames = len(self.audio_data)
if self.audio_total_frames == 0:
print("[AUDIO] Warning: Loaded audio data is empty (0 frames). Playback will be silent.")
self.has_audio = False
else:
print(f"[AUDIO] Loaded from source: Rate={self.audio_samplerate}, Channels={self.audio_channels}, Frames={self.audio_total_frames}")
self.has_audio = True
except Exception as e_direct_load:
print(f"Direct audio load/extraction failed ({type(e_direct_load).__name__}: {e_direct_load}).")
print("Attempting audio extraction/conversion using FFmpeg as a fallback...")
try:
if not self.temp_dir:
self.temp_dir = tempfile.mkdtemp(prefix="term_player_local_audio_")
base_name = os.path.splitext(os.path.basename(audio_source_for_processing))[0]
converted_audio_output_path = os.path.join(self.temp_dir, f"{base_name}_extracted_audio.wav")
ffmpeg_command = ['ffmpeg', '-y', '-i', audio_source_for_processing, '-vn', '-acodec', 'pcm_s16le', converted_audio_output_path]
print(f"Running FFmpeg command: {' '.join(ffmpeg_command)}")
ffmpeg_process_result = subprocess.run(ffmpeg_command, capture_output=True, text=True, check=False)
if ffmpeg_process_result.returncode != 0:
print("--- FFmpeg Audio Processing Error ---", file=sys.stderr)
print(f"FFmpeg Stderr:\n{ffmpeg_process_result.stderr}", file=sys.stderr)
raise RuntimeError("FFmpeg audio extraction/conversion process failed.")
else: print("FFmpeg audio processing successful.")
print(f"Loading FFmpeg processed audio from: {converted_audio_output_path}")
info = sf.info(converted_audio_output_path)
self.audio_data, self.audio_samplerate = sf.read(converted_audio_output_path, dtype='float32', always_2d=True)
self.audio_channels = self.audio_data.shape[1]
self.audio_total_frames = len(self.audio_data)
if self.audio_total_frames == 0:
print("[AUDIO] Warning: FFmpeg processed audio data is empty (0 frames). Playback will be silent.")
self.has_audio = False
else:
print(f"[AUDIO] Loaded FFmpeg processed: Rate={self.audio_samplerate}, Channels={self.audio_channels}, Frames={self.audio_total_frames}")
self.has_audio = True
except Exception as e_ffmpeg_processing:
print(f"--- AUDIO ERROR (Post-FFmpeg Attempt) ---", file=sys.stderr)
print(f"Error during FFmpeg processing or loading: {e_ffmpeg_processing} ({type(e_ffmpeg_processing).__name__})", file=sys.stderr)
self.has_audio = False
if self.has_audio:
try:
if self.audio_channels > 2:
print("Warning: Audio source has >2 channels. Using first two.")
self.audio_data = self.audio_data[:, :2]
self.audio_channels = 2
elif self.audio_channels == 1 and len(self.audio_data.shape) == 1:
self.audio_data = self.audio_data.reshape(-1, 1)
effective_audio_samplerate = int(self.audio_samplerate * self.speed)
if self.speed != 1.0:
print(f"[AUDIO] Applying speed {self.speed}x. Original SR: {self.audio_samplerate} -> Effective SR: {effective_audio_samplerate}. Pitch will change.")
self.audio_stream = sd.OutputStream(
samplerate=effective_audio_samplerate, channels=self.audio_channels,
callback=self._audio_callback, finished_callback=self._audio_finished_callback,
latency=AUDIO_LATENCY_SUGGESTION
)
print(f"[AUDIO] Sounddevice stream created with latency: '{AUDIO_LATENCY_SUGGESTION}'.")
except Exception as e_audio_stream_creation:
print(f"Error creating sounddevice audio stream: {e_audio_stream_creation}", file=sys.stderr)
self.has_audio = False
if not self.has_audio:
print("---> Playback will continue with VIDEO ONLY. <---")
self.playing = True
self.current_audio_frame = 0
return True
def _audio_callback(self, outdata, frames, time_info, status):
if status.output_underflow: print("[AUDIO] Warning: Sounddevice output underflow!", file=sys.stderr)
if status.output_overflow: print("[AUDIO] Warning: Sounddevice output overflow!", file=sys.stderr)
with self.state_lock:
if not self.has_audio or self.audio_data is None or self.audio_total_frames == 0:
outdata.fill(0)
return
remaining_frames = self.audio_total_frames - self.current_audio_frame
frames_to_provide = min(frames, remaining_frames)
if frames_to_provide > 0:
data_chunk = self.audio_data[self.current_audio_frame : self.current_audio_frame + frames_to_provide]
outdata[:frames_to_provide] = data_chunk
self.current_audio_frame += frames_to_provide
if frames_to_provide < frames:
outdata[frames_to_provide:] = 0
if remaining_frames <= 0 and not self.repeat:
raise sd.CallbackStop
def _audio_finished_callback(self):
pass
def _get_current_playback_time_unsafe(self):
if self.has_audio and self.audio_samplerate and self.audio_samplerate > 0 and self.audio_total_frames > 0:
return self.current_audio_frame / self.audio_samplerate
elif self.cap and self.cap.isOpened():
pos_msec = self.cap.get(cv2.CAP_PROP_POS_MSEC)
if pos_msec > 0 : return pos_msec / 1000.0
pos_frames = self.cap.get(cv2.CAP_PROP_POS_FRAMES)
if self.fps > 0: return pos_frames / self.fps
return 0.0
def _get_current_playback_time(self):
with self.state_lock:
return self._get_current_playback_time_unsafe()
def _render_progress_bar(self, current_time_sec):
if not self.show_progress_bar or self.duration == float('inf') or self.duration <= 0:
if self.duration == float('inf'):
time_display_str = f"{TIMESTAMP_COLOR_FG_ANSI}[{format_time(current_time_sec)} / --:--]{RESET_ALL}"
return f"{CURSOR_COL_1}{time_display_str}{CSI}K"
return ""
time_display_str = (
f"{TIMESTAMP_COLOR_FG_ANSI}"
f"[{format_time(current_time_sec)} / {format_time(self.duration)}]"
f"{RESET_ALL}"
)
non_visible_chars_in_time_str = (len(TIMESTAMP_COLOR_FG_ANSI) + len(RESET_ALL))
visible_time_str_len = len(time_display_str) - non_visible_chars_in_time_str
bar_area_width = max(10, self.render_width - visible_time_str_len - 3)
progress_ratio = min(1.0, max(0.0, current_time_sec / self.duration))
filled_bar_width = int(progress_ratio * bar_area_width)
empty_bar_width = bar_area_width - filled_bar_width
progress_bar_itself = (
f"{PROGRESS_BAR_COLOR_FG}{PROGRESS_BAR_FILLED_CHAR * filled_bar_width}"
f"{PROGRESS_BAR_COLOR_BG_ANSI}{PROGRESS_BAR_EMPTY_CHAR * empty_bar_width}{RESET_ALL}"
)
full_bar_line = f"{CURSOR_COL_1}{time_display_str} {progress_bar_itself}{CSI}K"
return full_bar_line
def _render_frame(self, frame_bgr, current_playback_time_sec_for_progress_bar):
try:
frame_rgb = cv2.cvtColor(frame_bgr, cv2.COLOR_BGR2RGB)
pil_image = Image.fromarray(frame_rgb)
resized_pil_image = pil_image.resize(
(self.render_width, self.video_render_height_pixels), Image.Resampling.LANCZOS
)
pixels_np_array = np.array(resized_pil_image)
video_output_lines = []
effective_video_pixel_height = (
self.video_render_height_pixels if self.video_render_height_pixels % 2 == 0
else self.video_render_height_pixels - 1
)
for y_coord in range(0, effective_video_pixel_height, 2):
current_line_chars = []
for x_coord in range(self.render_width):
top_pixel = pixels_np_array[y_coord, x_coord]
bottom_pixel = pixels_np_array[y_coord + 1, x_coord]
fg_color_ansi = rgb_to_ansi_fg(top_pixel[0], top_pixel[1], top_pixel[2])
bg_color_ansi = rgb_to_ansi_bg(bottom_pixel[0], bottom_pixel[1], bottom_pixel[2])
current_line_chars.append(f'{bg_color_ansi}{fg_color_ansi}{UPPER_HALF_BLOCK}')
video_output_lines.append("".join(current_line_chars) + RESET_ALL)
video_frame_as_string = "\n".join(video_output_lines)
progress_bar_as_string = self._render_progress_bar(current_playback_time_sec_for_progress_bar)
total_lines_to_overwrite = self.num_video_lines
if self.show_progress_bar and progress_bar_as_string: total_lines_to_overwrite += 1
final_output = video_frame_as_string
if self.show_progress_bar and progress_bar_as_string: final_output += "\n" + progress_bar_as_string
with self.state_lock:
if not self.first_frame_rendered:
sys.stdout.write(CURSOR_HOME)
sys.stdout.write(final_output)
self.first_frame_rendered = True
else:
sys.stdout.write(CURSOR_COL_1 + CURSOR_UP_N(total_lines_to_overwrite))
sys.stdout.write(final_output)
sys.stdout.flush()
except Exception as e:
print(f"\nError during frame rendering: {e} ({type(e).__name__})", file=sys.stderr)
time.sleep(0.1)
def _video_playback_loop(self):
if not self.playing: return
if self.has_audio and self.audio_stream and not self.paused:
try:
# print("[AUDIO] Starting initial audio stream...")
self.audio_stream.start()
except Exception as e:
print(f"[AUDIO] Error starting initial audio stream: {e}", file=sys.stderr)
while not self.exit_flag.is_set():
loop_iteration_start_time = time.time()
try:
current_terminal_size = os.get_terminal_size()
if current_terminal_size != self.last_term_size:
with self.state_lock:
self._update_render_dimensions()
clear_terminal()
self.first_frame_rendered = False
time.sleep(0.05)
except OSError: pass
requested_seek_target_sec_for_video = -1.0
with self.state_lock:
if self.seek_request_time_sec >= 0:
requested_seek_target_sec_for_video = self.seek_request_time_sec
self.seek_request_time_sec = -1.0
if requested_seek_target_sec_for_video >= 0:
if self.cap and self.cap.isOpened():
new_video_frame_target = int(requested_seek_target_sec_for_video * self.fps)
if not self.cap.set(cv2.CAP_PROP_POS_FRAMES, new_video_frame_target):
print(f"Warning: cv2.VideoCapture.set() failed for seek to frame {new_video_frame_target}.", file=sys.stderr)
else:
print("Warning: self.cap not available for seek.", file=sys.stderr)
is_currently_paused_local = False
with self.state_lock:
is_currently_paused_local = self.paused
if is_currently_paused_local:
if self.has_audio and self.audio_stream and self.audio_stream.active:
try: self.audio_stream.stop(ignore_errors=True)
except Exception: pass
time.sleep(0.05)
continue
if self.has_audio and self.audio_stream and not self.audio_stream.active:
if not self.exit_flag.is_set():
try: self.audio_stream.start()
except Exception as e:
print(f"[AUDIO] Warning: Error restarting inactive audio stream: {e}", file=sys.stderr)
time.sleep(0.1)
current_playback_time_seconds = self._get_current_playback_time()
target_video_frame_index = int(current_playback_time_seconds * self.effective_fps)
if not (self.cap and self.cap.isOpened()):
if not self.exit_flag.is_set():
print("Error: Video capture became unavailable.", file=sys.stderr)
self.exit_flag.set()
break
current_opencv_frame_position = int(self.cap.get(cv2.CAP_PROP_POS_FRAMES))
frame_difference_from_target = target_video_frame_index - current_opencv_frame_position
sync_tolerance_frames = int(self.effective_fps * 0.7)
needs_to_read_new_frame = False
if frame_difference_from_target > 1:
if frame_difference_from_target > sync_tolerance_frames:
if self.cap.set(cv2.CAP_PROP_POS_FRAMES, target_video_frame_index):
needs_to_read_new_frame = True
# else: print(f"Video sync: set frame failed") # Optional debug
else:
for _ in range(frame_difference_from_target - 1):
if not self.cap.grab():
current_opencv_frame_position = self.video_frame_count
break
needs_to_read_new_frame = True
elif frame_difference_from_target < -sync_tolerance_frames:
if self.cap.set(cv2.CAP_PROP_POS_FRAMES, target_video_frame_index):
needs_to_read_new_frame = True
# else: print(f"Video sync: set frame failed") # Optional debug
else:
needs_to_read_new_frame = True
frame_was_read_successfully = False
actual_frame_position_after_read = -1
video_frame_bgr = None
# For unknown duration, video_frame_count might be 0 or small, rely on read success.
# Allow reading if needs_to_read_new_frame is true, and either not at end OR duration is unknown.
can_try_read = needs_to_read_new_frame and \
( (self.duration != float('inf') and current_opencv_frame_position < self.video_frame_count) or \
(self.duration == float('inf')) )
if can_try_read:
if self.cap and self.cap.isOpened():
frame_was_read_successfully, video_frame_bgr = self.cap.read()
if frame_was_read_successfully:
actual_frame_position_after_read = int(self.cap.get(cv2.CAP_PROP_POS_FRAMES))
else:
frame_was_read_successfully = False
if frame_was_read_successfully and video_frame_bgr is not None:
if not self.exit_flag.is_set():
self._render_frame(video_frame_bgr, current_playback_time_seconds)
else:
if self.duration != float('inf') and current_opencv_frame_position < self.video_frame_count and needs_to_read_new_frame:
# print(f"Debug: Frame read failed at {current_opencv_frame_position}/{self.video_frame_count}")
pass
current_effective_pos_for_repeat = (
actual_frame_position_after_read if actual_frame_position_after_read != -1
else current_opencv_frame_position
)
is_at_end = False
if self.duration != float('inf'):
is_at_end = current_effective_pos_for_repeat >= self.video_frame_count and self.video_frame_count > 0
elif not frame_was_read_successfully and needs_to_read_new_frame and not (video_frame_bgr is not None): # For unknown duration, end is when read fails
is_at_end = True
if is_at_end:
if self.repeat and not self.exit_flag.is_set():
if self.cap and self.cap.isOpened(): self.cap.set(cv2.CAP_PROP_POS_FRAMES, 0)
with self.state_lock:
self.current_audio_frame = 0
self.first_frame_rendered = False
if self.has_audio and self.audio_stream:
try:
self.audio_stream.stop(ignore_errors=True)
time.sleep(0.02)
self.audio_stream.start()
except Exception as e_audio_repeat:
print(f"[AUDIO] Error restarting audio on repeat: {e_audio_repeat}", file=sys.stderr)
time.sleep(0.05)
continue
else:
# print("[PLAYER] End of video reached.")
self.exit_flag.set()
break
time_spent_in_loop = time.time() - loop_iteration_start_time
desired_time_per_frame = 1.0 / self.effective_fps if self.effective_fps > 0 else 0.033
sleep_duration = desired_time_per_frame - time_spent_in_loop
if sleep_duration > 0:
time.sleep(sleep_duration)
self.playing = False
if self.has_audio and self.audio_stream:
try: self.audio_stream.stop(ignore_errors=True)
except Exception: pass
def _handle_input(self):
last_pause_toggle_time = 0
pause_debounce_interval = 0.3
last_seek_time = 0
seek_debounce_interval = 0.1 # Reduced for responsiveness
while not self.exit_flag.is_set():
key_pressed = get_key_non_blocking()
current_time_monotonic = time.monotonic()
if key_pressed:
if key_pressed == "ESC" or key_pressed == "CTRL_C" or key_pressed == 'q':
print("\nExit key pressed! Signaling exit...", end='', flush=True)
self.exit_flag.set()
break
elif key_pressed == ' ':
if current_time_monotonic - last_pause_toggle_time > pause_debounce_interval:
with self.state_lock: self.paused = not self.paused
status_message = f"{'Paused' if self.paused else 'Resumed'}"
sys.stdout.write(CURSOR_COL_1 + " " * (self.render_width -1) + "\r") # Clear line
sys.stdout.write(CURSOR_COL_1 + status_message + "\r")
sys.stdout.flush()
last_pause_toggle_time = current_time_monotonic
elif key_pressed == "LEFT" or key_pressed == "RIGHT":
if current_time_monotonic - last_seek_time > seek_debounce_interval:
if self.duration != float('inf') and self.duration > 0.1 :
seek_direction = -1 if key_pressed == "LEFT" else 1
self._seek(seek_direction * SEEK_TIME_SECONDS)
last_seek_time = current_time_monotonic
else:
status_message = "Seek unavailable (unknown/short duration)"
sys.stdout.write(CURSOR_COL_1 + " " * (self.render_width -1) + "\r")
sys.stdout.write(CURSOR_COL_1 + status_message + "\r")
sys.stdout.flush()
time.sleep(0.01)
def _seek(self, time_delta_seconds):
if self.duration == float('inf') or self.duration <= 0.1:
return
temp_current_time_for_msg = self._get_current_playback_time()
temp_new_target_time_for_msg = max(0.0, min(self.duration - 0.1, temp_current_time_for_msg + time_delta_seconds))
seek_status_msg = f"Seeking to ~{format_time(temp_new_target_time_for_msg)}..."
sys.stdout.write(CURSOR_COL_1 + " " * (self.render_width -1) + "\r") # Clear line
sys.stdout.write(CURSOR_COL_1 + seek_status_msg + "\r")
sys.stdout.flush()
with self.state_lock:
current_playback_pos_sec = self._get_current_playback_time_unsafe()
new_target_time_sec = max(
0.0,
min(self.duration - 0.1, current_playback_pos_sec + time_delta_seconds)
)
audio_needs_restart_after_seek = False
if self.has_audio and self.audio_stream:
if self.audio_stream.active:
audio_needs_restart_after_seek = True
try: self.audio_stream.stop(ignore_errors=True)
except Exception as e: print(f"[AUDIO] Error stopping stream for seek: {e}", file=sys.stderr)
if self.audio_samplerate and self.audio_samplerate > 0:
new_audio_frame_target = int(new_target_time_sec * self.audio_samplerate)
if self.audio_total_frames > 0:
self.current_audio_frame = max(0, min(self.audio_total_frames - 1, new_audio_frame_target))
else:
self.current_audio_frame = 0
else:
self.current_audio_frame = 0
self.seek_request_time_sec = new_target_time_sec
if audio_needs_restart_after_seek and not self.paused:
if self.has_audio and self.audio_stream:
try: self.audio_stream.start()
except Exception as e: print(f"[AUDIO] Error restarting stream after seek: {e}", file=sys.stderr)
self.first_frame_rendered = False
def run(self):
self._setup_signal_handler()
try:
self._setup_terminal()
if not self._prepare_media_files(): return
if not self._init_playback():
if not self.video_file_to_play or not self.cap or not self.cap.isOpened():
print("Critical error: Video source could not be initialized. Exiting.", file=sys.stderr)
return
print("\nWarning: Playback initialization had issues, attempting video only...")
self.has_audio = False
clear_terminal()
self.first_frame_rendered = False
video_playback_thread = threading.Thread(target=self._video_playback_loop, daemon=True)
video_playback_thread.start()
self._handle_input()
if video_playback_thread.is_alive():
video_playback_thread.join(timeout=0.5)
except KeyboardInterrupt:
# print("\nKeyboardInterrupt caught in run(). Signaling exit.") # Already handled by sigint
self.exit_flag.set()
except Exception as e:
print(f"\nFATAL UNHANDLED ERROR in player run loop: {e} ({type(e).__name__})", file=sys.stderr)
import traceback
traceback.print_exc()
self.exit_flag.set()
finally:
self._cleanup()
def _cleanup(self):
print("\nCleaning up resources...")
self.exit_flag.set()
if self.has_audio and self.audio_stream:
try:
self.audio_stream.stop(ignore_errors=True)
self.audio_stream.close(ignore_errors=True)
except Exception: pass
if self.cap:
self.cap.release()
if 'termios' in sys.modules and self.original_termios_settings:
try: termios.tcsetattr(sys.stdin.fileno(), termios.TCSADRAIN, self.original_termios_settings)
except Exception: pass
if self.original_sigint_handler:
try: signal.signal(signal.SIGINT, self.original_sigint_handler)
except Exception: pass
if self.temp_dir and os.path.exists(self.temp_dir):
try: shutil.rmtree(self.temp_dir)
except Exception as e_rm_temp: print(f"Warning: Could not remove temp dir {self.temp_dir}: {e_rm_temp}", file=sys.stderr)
sys.stdout.write(f"\n{RESET_ALL}{SHOW_CURSOR}")
sys.stdout.flush()
print("Exiting.")
def main():
parser = argparse.ArgumentParser(
description="Play video (local or YouTube) in terminal.",
epilog="Keys: [Space]=Pause/Play, [Left/Right Arrow]=Seek, [Esc/q/Ctrl+C]=Exit\n"
"FFmpeg (installed and in PATH) is recommended for reliable audio.",
formatter_class=argparse.RawTextHelpFormatter
)
source_group = parser.add_mutually_exclusive_group(required=True)
source_group.add_argument("local_file", nargs='?', help="Path to local video file.")
source_group.add_argument("--youtube", metavar="URL", help="YouTube video URL (requires 'pytubefix').")
parser.add_argument("--repeat", action="store_true", help="Repeat video.")
parser.add_argument("--speed", type=float, default=1.0, help="Playback speed (e.g., 0.5, 2.0). Min 0.1.")
parser.add_argument("--no-audio", action="store_true", help="Disable audio.")
args = parser.parse_args()
playback_source_path = None
is_youtube_video = False
if args.youtube:
if pytubefix is None:
print("ERROR: The '--youtube' option was used, but the 'pytubefix' module is not installed.", file=sys.stderr)
print("Please install it, for example using: pip install pytubefix", file=sys.stderr)
sys.exit(1)
playback_source_path = args.youtube
is_youtube_video = True
# --- SSL Workaround for YouTube ---
print("\nINFO: Applying SSL workaround for YouTube downloads.")
print(" This disables SSL certificate verification for pytubefix.")
print(" WARNING: This is a potential security risk. Use with caution, especially on untrusted networks.\n")
try:
_create_unverified_https_context = ssl._create_unverified_context
except AttributeError:
# Legacy Python versions (older than 2.7.9 and 3.4.3) might not have this
print(" Warning: Your Python version might be too old for the standard SSL workaround method.")
pass
else:
# ssl._create_default_https_context is the function that urllib.request.urlopen()
# calls to create the SSLContext object when it opens an https:// URL.
# By overriding it, we change the default SSL behavior for all https requests made by urllib
# in this script session *after* this point.
ssl._create_default_https_context = _create_unverified_https_context
print(" SSL certificate verification has been (attempted to be) disabled globally for urllib.")
elif args.local_file:
playback_source_path = args.local_file
is_youtube_video = False
player = TerminalPlayer(
source_path=playback_source_path,
is_youtube=is_youtube_video,
repeat=args.repeat,
speed=args.speed,
no_audio=args.no_audio
)
player.run()
if __name__ == "__main__":
main()
sys.stdout.write(SHOW_CURSOR)
sys.stdout.flush()