-
Notifications
You must be signed in to change notification settings - Fork 17
Expand file tree
/
Copy pathIPTV_checker.py
More file actions
1869 lines (1667 loc) · 79.6 KB
/
IPTV_checker.py
File metadata and controls
1869 lines (1667 loc) · 79.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import requests
import argparse
import signal
import os
import sys
import time
import subprocess
import logging
import shutil
import random
import json
import codecs
import csv
import re
import threading
from concurrent.futures import ThreadPoolExecutor, as_completed
import hashlib
from urllib.parse import urljoin, urlparse, parse_qs, urlencode, urlunparse
from dataclasses import dataclass
from requests.adapters import HTTPAdapter
@dataclass
class ScanConfig:
"""Configuration for an IPTV playlist scan."""
group_title: str | None = None
timeout: int = 15
extended_timeout: int | None = None
split: bool = False
rename: bool = False
skip_screenshots: bool = False
output_file: str | None = None
channel_search: str | None = None
channel_pattern: object | None = None
proxy_list: list | None = None
test_geoblock: bool = False
profile_bitrate: bool = False
ffmpeg_available: bool = True
ffprobe_available: bool = True
backoff: str = 'linear'
retries: int = 6
workers: int = 4
insecure: bool = False
ACTIVE_SUBPROCESSES = set()
_subprocess_lock = threading.Lock()
cancel_event = threading.Event()
def print_header():
header_text = """
\033[96m██╗██████╗ ████████╗██╗ ██╗ ██████╗██╗ ██╗███████╗ ██████╗██╗ ██╗███████╗██████╗
██║██╔══██╗╚══██╔══╝██║ ██║ ██╔════╝██║ ██║██╔════╝██╔════╝██║ ██╔╝██╔════╝██╔══██╗
██║██████╔╝ ██║ ██║ ██║ ██║ ███████║█████╗ ██║ █████╔╝ █████╗ ██████╔╝
██║██╔═══╝ ██║ ╚██╗ ██╔╝ ██║ ██╔══██║██╔══╝ ██║ ██╔═██╗ ██╔══╝ ██╔══██╗
██║██║ ██║ ╚████╔╝ ╚██████╗██║ ██║███████╗╚██████╗██║ ██╗███████╗██║ ██║
╚═╝╚═╝ ╚═╝ ╚═══╝ ╚═════╝╚═╝ ╚═╝╚══════╝ ╚═════╝╚═╝ ╚═╝╚══════╝╚═╝ ╚═╝
\033[0m
"""
print(header_text)
print("\033[93mWelcome to the IPTV Stream Checker!\n\033[0m")
print("\033[93mUse -h for help on how to use this tool.\033[0m")
def setup_logging(verbose_level):
if verbose_level == 1:
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
elif verbose_level >= 2:
logging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s')
else:
logging.basicConfig(level=logging.ERROR, format='%(asctime)s - %(levelname)s - %(message)s')
def terminate_process(process):
if process is None:
return
if process.poll() is not None:
return
try:
if os.name == 'nt':
process.terminate()
else:
os.killpg(os.getpgid(process.pid), signal.SIGTERM)
except Exception:
pass
try:
process.wait(timeout=3)
except subprocess.TimeoutExpired:
try:
if os.name == 'nt':
process.kill()
else:
os.killpg(os.getpgid(process.pid), signal.SIGKILL)
except Exception:
pass
def cleanup_active_subprocesses():
with _subprocess_lock:
procs = list(ACTIVE_SUBPROCESSES)
for process in procs:
terminate_process(process)
with _subprocess_lock:
ACTIVE_SUBPROCESSES.clear()
def run_managed_subprocess(command, timeout):
popen_kwargs = {
'stdout': subprocess.PIPE,
'stderr': subprocess.PIPE
}
if os.name == 'nt':
creation_flag = getattr(subprocess, 'CREATE_NEW_PROCESS_GROUP', 0)
if creation_flag:
popen_kwargs['creationflags'] = creation_flag
else:
popen_kwargs['preexec_fn'] = os.setsid
process = None
try:
process = subprocess.Popen(command, **popen_kwargs)
with _subprocess_lock:
ACTIVE_SUBPROCESSES.add(process)
stdout, stderr = process.communicate(timeout=timeout)
return subprocess.CompletedProcess(command, process.returncode, stdout, stderr)
except subprocess.TimeoutExpired:
if process is not None:
terminate_process(process)
raise
finally:
if process is not None:
with _subprocess_lock:
ACTIVE_SUBPROCESSES.discard(process)
def handle_sigint(signum, frame):
logging.info("Interrupt received, stopping...")
cancel_event.set()
cleanup_active_subprocesses()
signal.signal(signal.SIGINT, handle_sigint)
def get_video_bitrate(url):
"""
Measure approximate video bitrate by sampling the stream for 10 seconds.
"""
command = [
'ffmpeg',
'-v',
'debug',
'-user_agent',
'VLC/3.0.14',
'-i',
url,
'-t',
'10',
'-f',
'null',
'-'
]
try:
result = run_managed_subprocess(command, timeout=20)
output = result.stderr.decode(errors='ignore')
total_bytes = 0
for line in output.splitlines():
if "Statistics:" in line and "bytes read" in line:
parts = line.split("bytes read")
try:
size_str = parts[0].strip().split()[-1]
total_bytes = int(size_str)
break
except (IndexError, ValueError):
continue
if total_bytes <= 0:
return "N/A"
bitrate_kbps = (total_bytes * 8) / 1000 / 10
return f"{round(bitrate_kbps)} kbps"
except FileNotFoundError:
logging.warning("ffmpeg not found when attempting to measure video bitrate.")
return "Unknown"
except subprocess.TimeoutExpired:
logging.error(f"Timeout when trying to get video bitrate for {url}")
return "Unknown"
except Exception as exc:
logging.error(f"Error when attempting to retrieve video bitrate: {exc}")
return "N/A"
def check_ffmpeg_availability():
"""Check whether ffmpeg and ffprobe are available in the system PATH."""
tool_status = {}
for tool in ['ffmpeg', 'ffprobe']:
available = False
try:
result = run_managed_subprocess([tool, '-version'], timeout=5)
if result.returncode == 0:
logging.debug(f"{tool} is available")
available = True
else:
logging.error(f"{tool} is installed but not working properly")
except FileNotFoundError:
logging.error(f"{tool} is not found in system PATH. Please install {tool} to use this tool.")
except subprocess.TimeoutExpired:
logging.error(f"{tool} check timed out")
except Exception as e:
logging.exception(f"Unexpected error checking {tool}: {e}")
tool_status[tool] = available
return tool_status
def test_with_proxy(url, proxy, timeout, retries=3):
"""
Test stream access through a specific proxy
"""
headers = {
'User-Agent': 'VLC/3.0.14 LibVLC/3.0.14'
}
proxies = {'http': proxy, 'https': proxy}
stream_extensions = ('.ts', '.m2ts', '.m4s', '.mp4', '.aac', '.m3u8')
for attempt in range(max(1, retries)):
try:
with requests.get(url, stream=True, timeout=(5, timeout), headers=headers, proxies=proxies) as resp:
if resp.status_code != 200:
continue
content_type = resp.headers.get('Content-Type', '')
lowered_type = content_type.lower()
stream_path = urlparse(resp.url).path.lower()
if (
lowered_type.startswith('video/')
or lowered_type.startswith('audio/')
or 'application/vnd.apple.mpegurl' in lowered_type
or 'application/x-mpegurl' in lowered_type
or 'application/octet-stream' in lowered_type
or 'application/mp4' in lowered_type
or stream_path.endswith(stream_extensions)
):
# Read some data to verify stream
for chunk in resp.iter_content(1024 * 500): # 500KB
if chunk:
return True
except requests.RequestException as e:
logging.debug(f"Proxy test failed with {proxy} (attempt {attempt + 1}/{max(1, retries)}): {summarize_error(e)}")
if attempt + 1 < max(1, retries):
time.sleep(0.5 * (attempt + 1))
return False
def load_proxy_list(proxy_file):
"""
Load proxy list from file. Supports formats:
- ip:port
- protocol://ip:port
- JSON format with proxy objects (supports both 'protocol' and 'protocols' fields)
"""
proxies = []
valid_proxies = []
def validate_proxy_entry(proxy_value):
if not proxy_value:
return None, "entry is empty"
candidate = proxy_value.strip()
if not candidate:
return None, "entry is empty"
if '://' not in candidate:
candidate = f"http://{candidate}"
parsed = urlparse(candidate)
scheme = parsed.scheme.lower()
if scheme not in {'http', 'https', 'socks4', 'socks4a', 'socks5', 'socks5h'}:
return None, f"unsupported proxy scheme '{parsed.scheme}'"
if not parsed.hostname:
return None, "missing proxy host"
try:
port = parsed.port
except ValueError:
return None, "invalid proxy port"
if port is None:
return None, "missing proxy port"
if port < 1 or port > 65535:
return None, f"proxy port {port} is out of range (1-65535)"
if parsed.path not in ('', '/'):
return None, "proxy URL must not include a path"
if parsed.params or parsed.query or parsed.fragment:
return None, "proxy URL must not include params, query, or fragment"
return f"{scheme}://{parsed.netloc}", None
try:
with open(proxy_file, 'r', encoding='utf-8', errors='replace') as f:
content = f.read().strip()
# Try JSON format first
try:
proxy_data = json.loads(content)
if isinstance(proxy_data, list):
for proxy in proxy_data:
if isinstance(proxy, dict):
ip = proxy.get('ip')
port = proxy.get('port')
if ip and port:
# Check for protocols array (new format)
if 'protocols' in proxy and isinstance(proxy['protocols'], list):
for protocol in proxy['protocols']:
proxies.append(f"{protocol}://{ip}:{port}")
# Fall back to single protocol (legacy format)
elif 'protocol' in proxy:
protocol = proxy.get('protocol', 'http')
proxies.append(f"{protocol}://{ip}:{port}")
# Default to http if no protocol specified
else:
proxies.append(f"http://{ip}:{port}")
elif isinstance(proxy, str):
proxies.append(proxy)
except json.JSONDecodeError:
# Fall through to plain text format parsing.
pass
if not proxies:
# Plain text format
lines = content.split('\n')
for line in lines:
line = line.strip()
if line and not line.startswith('#'):
proxies.append(line)
except FileNotFoundError:
logging.error(f"Proxy file not found: {proxy_file}")
except Exception as e:
logging.error(f"Error loading proxy file: {str(e)}")
skipped = 0
for idx, proxy in enumerate(proxies, 1):
validated_proxy, error_message = validate_proxy_entry(proxy)
if error_message:
logging.warning(f"Proxy entry #{idx} '{proxy}': {error_message}")
skipped += 1
continue
valid_proxies.append(validated_proxy)
if proxies:
if valid_proxies:
logging.info(f"Loaded {len(valid_proxies)} of {len(proxies)} proxies ({skipped} skipped)")
else:
logging.error("No valid proxy entries remain after validation.")
return valid_proxies
def summarize_error(exc):
msg = str(exc).lower()
if isinstance(exc, requests.Timeout):
return "Connection timed out"
if isinstance(exc, requests.ConnectionError):
if any(kw in msg for kw in ['dns', 'name or service not known', 'nodename nor servname', 'no such host', 'getaddrinfo failed']):
return "DNS resolution failed"
if 'ssl' in msg or 'tls' in msg or 'certificate' in msg or 'handshake' in msg:
return "SSL/TLS error"
if 'connection refused' in msg:
return "Connection refused"
return "Connection error"
if isinstance(exc, requests.TooManyRedirects):
return "Redirect loop"
return str(exc)[:80]
def check_channel_status(url, timeout, retries=6, extended_timeout=None, proxy_list=None, test_geoblock=False, ffmpeg_available=True, backoff='linear', session=None):
headers = {
'User-Agent': 'VLC/3.0.14 LibVLC/3.0.14'
}
min_data_threshold = 1024 * 500 # 500KB minimum threshold for direct streams
playlist_segment_threshold = 1024 * 128 # Smaller threshold for HLS media segments
max_playlist_depth = 4
initial_timeout = 5
retryable_http_statuses = {408, 425, 429, 500, 502, 503, 504}
geoblock_statuses = {403, 451, 426}
secondary_geoblock_statuses = {401, 423, 451}
backoff_mode = (backoff or 'linear').strip().lower()
if backoff_mode not in {'none', 'linear', 'exponential'}:
logging.warning(f"Unknown backoff mode '{backoff_mode}', defaulting to linear.")
backoff_mode = 'linear'
def is_playlist(content_type, target_url):
lowered_type = content_type.lower()
lowered_url = target_url.lower()
lowered_path = urlparse(lowered_url).path
return (
'application/vnd.apple.mpegurl' in lowered_type
or 'application/x-mpegurl' in lowered_type
or lowered_path.endswith('.m3u8')
)
def is_direct_stream(content_type, target_url):
lowered_type = content_type.lower()
lowered_path = urlparse(target_url).path.lower()
stream_extensions = ('.ts', '.m2ts', '.m4s', '.mp4', '.aac')
return (
lowered_type.startswith('video/')
or lowered_type.startswith('audio/')
or 'application/octet-stream' in lowered_type
or 'application/mp4' in lowered_type
or lowered_path.endswith(stream_extensions)
)
def extract_next_url(base_url, playlist_body):
def parse_tag_attributes(tag_line):
attributes = {}
_, _, payload = tag_line.partition(':')
if not payload:
return attributes
index = 0
payload_length = len(payload)
while index < payload_length:
while index < payload_length and payload[index] in ' \t,':
index += 1
if index >= payload_length:
break
key_start = index
while index < payload_length and payload[index] not in '=,':
index += 1
key = payload[key_start:index].strip().upper()
if not key:
index += 1
continue
if index >= payload_length or payload[index] != '=':
while index < payload_length and payload[index] != ',':
index += 1
continue
index += 1
if index < payload_length and payload[index] == '"':
index += 1
value_chars = []
while index < payload_length:
char = payload[index]
if char == '\\' and index + 1 < payload_length:
value_chars.append(payload[index + 1])
index += 2
continue
if char == '"':
index += 1
break
value_chars.append(char)
index += 1
value = ''.join(value_chars)
else:
value_start = index
while index < payload_length and payload[index] != ',':
index += 1
value = payload[value_start:index].strip()
attributes[key] = value
if index < payload_length and payload[index] == ',':
index += 1
return attributes
def parse_resolution_pixels(resolution_value):
if not resolution_value:
return 0
match = re.match(r'^\s*(\d+)\s*x\s*(\d+)\s*$', resolution_value, flags=re.IGNORECASE)
if not match:
return 0
width = int(match.group(1))
height = int(match.group(2))
if width <= 0 or height <= 0:
return 0
return width * height
def parse_int(value):
if not value:
return 0
try:
parsed = int(value.strip())
return parsed if parsed > 0 else 0
except (TypeError, ValueError):
return 0
saw_stream_inf = False
pending_variant_attrs = None
best_variant_url = None
best_variant_score = None
fallback_url = None
for raw_line in playlist_body.splitlines():
line = raw_line.strip()
if not line:
continue
if line.startswith('#'):
if line.upper().startswith('#EXT-X-STREAM-INF'):
saw_stream_inf = True
pending_variant_attrs = parse_tag_attributes(line)
continue
resolved_url = urljoin(base_url, line)
if not saw_stream_inf:
return resolved_url
if pending_variant_attrs is not None:
resolution_pixels = parse_resolution_pixels(pending_variant_attrs.get('RESOLUTION'))
average_bandwidth = parse_int(pending_variant_attrs.get('AVERAGE-BANDWIDTH'))
bandwidth = parse_int(pending_variant_attrs.get('BANDWIDTH'))
quality_score = (
1 if resolution_pixels else 0,
resolution_pixels,
average_bandwidth,
bandwidth
)
if best_variant_score is None or quality_score > best_variant_score:
best_variant_score = quality_score
best_variant_url = resolved_url
pending_variant_attrs = None
elif fallback_url is None:
fallback_url = resolved_url
if best_variant_url:
return best_variant_url
return fallback_url
def read_stream(response, min_bytes):
bytes_read = 0
for chunk in response.iter_content(1024 * 128): # 128KB chunks
if not chunk:
continue
bytes_read += len(chunk)
if bytes_read >= min_bytes:
logging.debug(f"Data received: {bytes_read} bytes")
return 'Alive', response.url, None
logging.debug(f"Data received: {bytes_read} bytes")
if min_bytes >= min_data_threshold:
fallback_threshold = min_bytes
else:
fallback_threshold = max(32768, min_bytes // 2) # Allow smaller segments to pass
if bytes_read >= fallback_threshold:
return 'Alive', response.url, None
return 'Dead', None, 'Insufficient data received'
def verify(target_url, current_timeout, depth, visited):
if depth > max_playlist_depth:
logging.debug("Maximum playlist nesting depth reached")
return 'Dead', None, 'Max playlist depth exceeded'
normalized_url = target_url.split('#')[0]
if normalized_url in visited:
logging.debug(f"Detected playlist loop at {target_url}")
return 'Dead', None, 'Playlist loop detected'
visited.add(normalized_url)
playlist_text = None
final_url = target_url
http = session or requests
try:
with http.get(
target_url,
stream=True,
timeout=(initial_timeout, current_timeout),
headers=headers
) as resp:
if resp.status_code in retryable_http_statuses:
logging.debug(f"Retryable HTTP status {resp.status_code} for {target_url}, retrying...")
return 'Retry', None, f'HTTP {resp.status_code}'
if resp.status_code in geoblock_statuses:
logging.debug(f"Potential geoblock detected: HTTP {resp.status_code}")
return 'Geoblocked', None, None
if resp.status_code != 200:
logging.debug(f"HTTP status code not OK: {resp.status_code}")
if resp.status_code in secondary_geoblock_statuses:
return 'Geoblocked', None, None
return 'Dead', None, f'HTTP {resp.status_code}'
content_type = resp.headers.get('Content-Type', '')
logging.debug(f"Content-Type: {content_type}")
final_url = resp.url
if is_playlist(content_type, final_url):
playlist_text = resp.text
elif is_direct_stream(content_type, final_url):
min_bytes = min_data_threshold if depth == 0 else playlist_segment_threshold
return read_stream(resp, min_bytes)
else:
if content_type.lower().startswith('text/'):
logging.debug(f"Content-Type not recognized as stream: {content_type}")
return 'Dead', None, f'Unrecognized content type: {content_type}'
logging.debug(f"Unrecognized Content-Type '{content_type}'. Attempting fallback stream read.")
min_bytes = min_data_threshold if depth == 0 else playlist_segment_threshold
return read_stream(resp, min_bytes)
except requests.ConnectionError as exc:
logging.warning(f"{summarize_error(exc)} for {target_url}")
return 'Retry', None, summarize_error(exc)
except requests.Timeout as exc:
logging.warning(f"{summarize_error(exc)} for {target_url}")
return 'Retry', None, summarize_error(exc)
except requests.RequestException as e:
logging.error(f"Request failed for {target_url}: {summarize_error(e)}")
return 'Dead', None, summarize_error(e)
if not playlist_text:
logging.debug("Playlist response was empty")
return 'Dead', None, 'Empty playlist response'
next_url = extract_next_url(final_url, playlist_text)
if not next_url:
logging.debug("No media segments found in playlist")
return 'Dead', None, 'No media segments in playlist'
logging.debug(f"Following playlist entry: {next_url}")
return verify(next_url, current_timeout, depth + 1, visited)
def get_retry_delay(attempt_index):
if backoff_mode == 'none':
return 0
if backoff_mode == 'exponential':
return min(2 ** attempt_index, 30)
return min(attempt_index + 1, 10)
def attempt_check(current_timeout):
total_attempts = max(1, retries)
last_reason = None
for attempt in range(total_attempts):
if cancel_event.is_set():
return 'Dead', None, 'Cancelled'
visited = set()
status, stream_url, reason = verify(url, current_timeout, 0, visited)
if status == 'Retry':
last_reason = reason
logging.debug(f"Retrying stream check for {url} ({attempt + 1}/{total_attempts})")
if attempt + 1 < total_attempts:
delay_seconds = get_retry_delay(attempt)
if delay_seconds > 0:
logging.debug(f"Applying {backoff_mode} backoff delay of {delay_seconds}s")
time.sleep(delay_seconds)
continue
return status, stream_url, reason
logging.error("Maximum retries exceeded for checking channel status")
return 'Dead', None, last_reason or 'Max retries exceeded'
# First attempt with the initial timeout
status, stream_url, error_reason = attempt_check(timeout)
# If the channel is detected as dead and extended_timeout is specified, retry with extended timeout
if status == 'Dead' and extended_timeout:
logging.info(f"Channel initially detected as dead. Retrying with an extended timeout of {extended_timeout} seconds.")
status, stream_url, error_reason = attempt_check(extended_timeout)
# If geoblocked and proxy testing is enabled, test with proxies
if status == 'Geoblocked' and test_geoblock and proxy_list:
logging.info(f"Testing geoblocked stream with {len(proxy_list)} proxies...")
for proxy in random.sample(proxy_list, min(3, len(proxy_list))): # Test up to 3 random proxies
if test_with_proxy(url, proxy, timeout):
logging.info(f"Stream accessible via proxy {proxy} - confirming geoblock")
return 'Geoblocked (Confirmed)', None, None
logging.info("Stream not accessible via tested proxies")
return 'Geoblocked (Unconfirmed)', None, None
# Final Verification using ffmpeg/ffprobe for streams marked alive
if status == 'Alive' and ffmpeg_available:
verification_url = stream_url or url
try:
command = [
'ffmpeg', '-user_agent', headers['User-Agent'], '-i', verification_url, '-t', '5', '-f', 'null', '-'
]
ffmpeg_result = run_managed_subprocess(command, timeout=15)
if ffmpeg_result.returncode != 0:
logging.warning(f"ffmpeg failed to read stream ({verification_url}); continuing with HTTP validation result")
except FileNotFoundError:
logging.warning(f"ffmpeg not found for stream verification, skipping ffmpeg check")
# Keep status as 'Alive' since we already verified via HTTP
except subprocess.TimeoutExpired:
logging.warning(f"Timeout when trying to verify stream with ffmpeg for {verification_url}; continuing with HTTP validation result")
except Exception as e:
logging.warning(f"Error verifying stream with ffmpeg ({verification_url}): {str(e)}; continuing with HTTP validation result")
return status, stream_url, error_reason
def build_screenshot_filename(output_path, channel_index, channel_name, max_length=200):
illegal_chars_pattern = r'[\\/:*?"<>|]'
windows_reserved_names = {
'CON', 'PRN', 'AUX', 'NUL',
'COM1', 'COM2', 'COM3', 'COM4', 'COM5', 'COM6', 'COM7', 'COM8', 'COM9',
'LPT1', 'LPT2', 'LPT3', 'LPT4', 'LPT5', 'LPT6', 'LPT7', 'LPT8', 'LPT9'
}
normalized_name = channel_name if channel_name else "channel"
normalized_name = re.sub(illegal_chars_pattern, '-', normalized_name)
normalized_name = normalized_name.strip().strip('.')
normalized_name = re.sub(r'\s+', ' ', normalized_name)
if not normalized_name:
normalized_name = "channel"
if normalized_name.upper() in windows_reserved_names:
normalized_name = f"{normalized_name}_channel"
base_prefix = f"{channel_index}-"
remaining_length = max(1, max_length - len(base_prefix))
base_name = normalized_name[:remaining_length]
candidate = f"{base_prefix}{base_name}"
suffix_index = 1
while os.path.exists(os.path.join(output_path, f"{candidate}.png")):
suffix = f"_{suffix_index}"
allowed_length = max(1, remaining_length - len(suffix))
candidate = f"{base_prefix}{base_name[:allowed_length]}{suffix}"
suffix_index += 1
return candidate
def capture_frame(url, output_path, file_name):
command = [
'ffmpeg', '-y', '-i', url, '-frames:v', '1',
os.path.join(output_path, f"{file_name}.png")
]
try:
run_managed_subprocess(command, timeout=30)
logging.debug(f"Screenshot saved for {file_name}")
return True
except FileNotFoundError:
logging.error(f"ffmpeg not found. Please install ffmpeg to capture screenshots.")
return False
except subprocess.TimeoutExpired:
logging.error(f"Timeout when trying to capture frame for {file_name}")
return False
except Exception as e:
logging.error(f"Error capturing frame for {file_name}: {str(e)}")
return False
def get_detailed_stream_info(url, profile_bitrate=False):
command = [
'ffprobe', '-v', 'error',
'-analyzeduration', '15000000', '-probesize', '15000000',
'-select_streams', 'v', '-show_entries',
'stream=codec_name,width,height,r_frame_rate', '-of', 'json', url
]
try:
result = run_managed_subprocess(command, timeout=10)
output = result.stdout.decode(errors='ignore')
codec_name = "Unknown"
width = height = 0
fps = None
probe_data = json.loads(output) if output else {}
streams = probe_data.get('streams', []) if isinstance(probe_data, dict) else []
selected_stream = None
selected_pixels = -1
for stream in streams:
if not isinstance(stream, dict):
continue
stream_width = int(stream.get('width') or 0)
stream_height = int(stream.get('height') or 0)
pixel_count = stream_width * stream_height
if pixel_count > selected_pixels:
selected_pixels = pixel_count
selected_stream = stream
if selected_stream:
codec_name = (selected_stream.get('codec_name') or "Unknown").upper()
width = int(selected_stream.get('width') or 0)
height = int(selected_stream.get('height') or 0)
fps_data = selected_stream.get('r_frame_rate')
if fps_data:
try:
if '/' in fps_data:
numerator_str, denominator_str = fps_data.split('/', 1)
numerator = float(numerator_str)
denominator = float(denominator_str)
if denominator > 0:
fps = round(numerator / denominator)
else:
fps = round(float(fps_data))
except ValueError:
logging.debug(f"Unable to parse frame rate '{fps_data}' for {url}")
else:
# No video streams found — check if audio-only
try:
audio_probe_cmd = [
'ffprobe', '-v', 'error',
'-analyzeduration', '15000000', '-probesize', '15000000',
'-select_streams', 'a', '-show_entries', 'stream=codec_type',
'-of', 'json', url
]
audio_result = run_managed_subprocess(audio_probe_cmd, timeout=10)
audio_output = audio_result.stdout.decode(errors='ignore')
audio_data = json.loads(audio_output) if audio_output else {}
audio_streams = audio_data.get('streams', []) if isinstance(audio_data, dict) else []
if audio_streams:
return "Audio Only", "N/A", "Audio Only", None
except Exception:
pass
if fps is not None and fps <= 0:
fps = None
# Determine resolution string with FPS
resolution = "Unknown"
if width > 0 and height > 0:
if width >= 3840 and height >= 2160:
resolution = "4K"
elif width >= 1920 and height >= 1080:
resolution = "1080p"
elif width >= 1280 and height >= 720:
resolution = "720p"
else:
resolution = "SD"
video_bitrate = get_video_bitrate(url) if profile_bitrate else "N/A"
return codec_name, video_bitrate, resolution, fps
except FileNotFoundError:
logging.error(f"ffprobe not found. Please install ffprobe to get stream info.")
return "Unknown", "Unknown", "Unknown", None
except subprocess.TimeoutExpired:
logging.error(f"Timeout when trying to get stream info for {url}")
return "Unknown", "Unknown", "Unknown", None
except Exception as e:
logging.error(f"Error getting stream info: {str(e)}")
return "Unknown", "Unknown", "Unknown", None
def format_stream_info(codec_name, video_bitrate, resolution, fps):
if resolution != "Unknown" and fps:
resolution_display = f"{resolution}{fps}"
else:
resolution_display = resolution
components = []
if resolution_display != "Unknown":
components.append(resolution_display)
if codec_name and codec_name != "Unknown":
components.append(codec_name)
base_info = " ".join(components) if components else "Unknown"
if video_bitrate and isinstance(video_bitrate, str) and video_bitrate not in ("Unknown", "N/A"):
return f"{base_info} ({video_bitrate})"
return base_info
def get_audio_bitrate(url):
command = [
'ffprobe', '-v', 'error',
'-analyzeduration', '15000000', '-probesize', '15000000',
'-select_streams', 'a:0', '-show_entries',
'stream=codec_name,bit_rate', '-of', 'default=noprint_wrappers=1', url
]
try:
result = run_managed_subprocess(command, timeout=10)
output = result.stdout.decode()
audio_bitrate = None
codec_name = None
for line in output.splitlines():
if line.startswith("bit_rate="):
bitrate_value = line.split('=')[1]
if bitrate_value.isdigit():
audio_bitrate = int(bitrate_value) // 1000 # Convert to kbps
else:
audio_bitrate = 'N/A'
elif line.startswith("codec_name="):
codec_name = line.split('=')[1].upper()
return f"{audio_bitrate} kbps {codec_name}" if codec_name and audio_bitrate else "Unknown"
except FileNotFoundError:
logging.error(f"ffprobe not found. Please install ffprobe to get audio bitrate.")
return "Unknown"
except subprocess.TimeoutExpired:
logging.error(f"Timeout when trying to get audio bitrate for {url}")
return "Unknown"
except Exception as e:
logging.error(f"Error getting audio bitrate: {str(e)}")
return "Unknown"
def check_label_mismatch(channel_name, resolution):
channel_name_lower = channel_name.lower()
mismatches = []
# Compare resolution ignoring the framerate part (word-boundary matching)
if re.search(r'\b4k\b', channel_name_lower) or re.search(r'\buhd\b', channel_name_lower):
if resolution != "4K":
mismatches.append(f"\033[91mExpected 4K, got {resolution}\033[0m")
elif re.search(r'\b1080p\b', channel_name_lower) or re.search(r'\bfhd\b', channel_name_lower):
if resolution != "1080p":
mismatches.append(f"\033[91mExpected 1080p, got {resolution}\033[0m")
elif re.search(r'\bhd\b', channel_name_lower):
if resolution not in ["1080p", "720p"]:
mismatches.append(f"\033[91mExpected 720p or 1080p, got {resolution}\033[0m")
elif resolution == "4K":
mismatches.append(f"\033[91m4K channel not labeled as such\033[0m")
return mismatches
def parse_extinf_metadata(extinf_line):
"""
Parse an EXTINF line into attributes and channel name while handling quoted values.
"""
if not extinf_line.startswith('#EXTINF'):
return {}, "Unknown Channel"
_, _, payload = extinf_line.partition(':')
if not payload:
return {}, "Unknown Channel"
in_quotes = False
escape_next = False
split_index = -1
for idx, char in enumerate(payload):
if escape_next:
escape_next = False
continue
if char == '\\':
escape_next = True
continue
if char == '"':
in_quotes = not in_quotes
continue
if char == ',' and not in_quotes:
split_index = idx
break
if split_index >= 0:
metadata_payload = payload[:split_index]
channel_name = payload[split_index + 1:].strip() or "Unknown Channel"
else:
metadata_payload = payload
channel_name = "Unknown Channel"
attributes = {}
metadata = metadata_payload.strip()
index = 0
metadata_length = len(metadata)
while index < metadata_length:
while index < metadata_length and metadata[index].isspace():
index += 1
if index >= metadata_length:
break
key_start = index
while index < metadata_length and not metadata[index].isspace() and metadata[index] != '=':
index += 1
key = metadata[key_start:index].strip().lower()
if not key:
if index < metadata_length:
index += 1
continue
equals_index = index
while equals_index < metadata_length and metadata[equals_index].isspace():
equals_index += 1
if equals_index >= metadata_length or metadata[equals_index] != '=':
# Token without '=' (e.g., duration) is ignored.
index = equals_index
continue
index = equals_index + 1
while index < metadata_length and metadata[index].isspace():
index += 1
if index < metadata_length and metadata[index] == '"':
index += 1
value_chars = []
while index < metadata_length:
char = metadata[index]
if char == '\\' and index + 1 < metadata_length:
value_chars.append(metadata[index + 1])
index += 2
continue
if char == '"':
index += 1
break
value_chars.append(char)
index += 1
value = ''.join(value_chars)
else:
value_start = index
while index < metadata_length and not metadata[index].isspace():
index += 1
value = metadata[value_start:index].strip()
if key:
attributes[key] = value
return attributes, channel_name
def get_channel_name(extinf_line):
_, channel_name = parse_extinf_metadata(extinf_line)
return channel_name
def get_group_name(extinf_line):
attributes, _ = parse_extinf_metadata(extinf_line)
group_name = attributes.get('group-title')
if group_name:
return group_name
return "Unknown Group"
def get_channel_id(url):
if not url:
return "Unknown"
segment = url.rsplit('/', 1)[-1]
if segment: