fix(kick/live): unbuffered CR/LF stream reader, live FFmpeg & HLS progress, and automatic MP4 remux on stop

This commit is contained in:
LilDosto 2026-11-04 01:30:58 +03:00
parent 80b0bf4fd2
commit 9ee7d42a8b
6 changed files with 224 additions and 24 deletions

3
bağlan.bat Normal file
View file

@ -0,0 +1,3 @@
@echo off
ssh -i "%USERPROFILE%\.ssh\id_ed25519" root@116.202.14.171
pause

View file

@ -8,12 +8,18 @@ from core.diagnostics import diagnose
class DownloadEngine: class DownloadEngine:
_PROGRESS_RE = re.compile( _PROGRESS_RE = re.compile(
r"\[PROGRESS\]\s*(?P<pct>[\d.]+)(?:%\s*)?\|\s*(?P<speed>.*?)\s*\|\s*(?P<total>.*?)\s*\|\s*(?P<eta>.*)" r"\[PROGRESS\]\s*(?P<pct>[\d.]+)(?:%\s*)?\|\s*(?P<speed>.*?)\s*\|\s*(?P<total>.*?)\s*\|\s*(?P<eta>[^|]*)"
r"(?:\|\s*(?P<dl>.*?)\s*\|\s*(?P<est>.*))?"
) )
_DL_RE = re.compile( _DL_RE = re.compile(
r"\[download\]\s+(?P<pct>[\d.]+)%\s+of\s+~?(?P<total>\S+)\s+" r"\[download\]\s+(?P<pct>[\d.]+)%\s+of\s+~?(?P<total>\S+)\s+"
r"at\s+(?P<speed>.*?)\s+ETA\s+(?P<eta>\S+)" r"at\s+(?P<speed>.*?)\s+ETA\s+(?P<eta>\S+)"
) )
_FFMPEG_PROGRESS_RE = re.compile(
r"size=\s*(?P<size>\d+)\s*(?P<unit>[kKmMgG]?i?[bB])\s+"
r"time=\s*(?P<time>[\d:.]+)\s+"
r"bitrate=\s*(?P<bitrate>[\d.]+)\s*(?P<br_unit>[kKmMgG]?bits/s)"
)
_DEST_RE = re.compile( _DEST_RE = re.compile(
r"\[(?:download|Merger|ExtractAudio|FixupM3u8|VideoRemuxer|VideoConvertor)\]\s+" r"\[(?:download|Merger|ExtractAudio|FixupM3u8|VideoRemuxer|VideoConvertor)\]\s+"
r"(?:Destination:\s+|Merging formats into\s+\"|Writing video subtitles to:\s+|Remuxing video from \S+ to\s+\"?)(?P<path>[^\"]+)" r"(?:Destination:\s+|Merging formats into\s+\"|Writing video subtitles to:\s+|Remuxing video from \S+ to\s+\"?)(?P<path>[^\"]+)"
@ -28,6 +34,7 @@ class DownloadEngine:
self._running = False self._running = False
self._cancelled = False self._cancelled = False
self._current_file = None self._current_file = None
self._is_live_session = False
self._lock = threading.Lock() self._lock = threading.Lock()
@property @property
@ -90,11 +97,103 @@ class DownloadEngine:
self._running = True self._running = True
self._cancelled = False self._cancelled = False
self._current_file = None self._current_file = None
self._is_live_session = ("--hls-use-mpegts" in cmd_args)
thread = threading.Thread(target=self._worker, args=(cmd_args, callbacks), daemon=True) thread = threading.Thread(target=self._worker, args=(cmd_args, callbacks), daemon=True)
thread.start() thread.start()
return True return True
@staticmethod
def _iter_unbuffered_lines(pipe):
"""
Subprocess stdout borusundan 8KB tampon (buffer) beklemeden anlık okuma yapar.
Hem '\\n' (yt-dlp) hem de '\\r' (ffmpeg canlı yayın / kesit ilerlemesi) karakterlerinde
satırı anında (0ms gecikmeyle) döndürür.
"""
fd = None
try:
fd = pipe.fileno()
except Exception:
fd = None
buf = ""
while True:
try:
if fd is not None:
chunk = os.read(fd, 1024)
else:
chunk = pipe.read(256)
except OSError:
break
if not chunk:
break
if isinstance(chunk, bytes):
text = chunk.decode("utf-8", errors="replace")
else:
text = chunk
buf += text
while True:
idx_r = buf.find("\r")
idx_n = buf.find("\n")
if idx_r == -1 and idx_n == -1:
break
if idx_r != -1 and (idx_n == -1 or idx_r < idx_n):
split_at = idx_r
# Eğer \r\n yan yanaysa ikisini birden atla
next_start = split_at + 2 if (split_at + 1 < len(buf) and buf[split_at + 1] == "\n") else split_at + 1
else:
split_at = idx_n
next_start = split_at + 1
line = buf[:split_at].strip()
buf = buf[next_start:]
if line:
yield line
if buf.strip():
yield buf.strip()
def _remux_live_file_if_needed(self, file_path, cb):
"""
Canlı yayın (--hls-use-mpegts) kaydı durdurulduğunda MPEG-TS akışını
standart MP4 kapsayıcısına (moov atom + süre bilgisi ile) kayıpsız dönüştürür.
"""
if not file_path or not os.path.isfile(file_path):
return file_path
try:
if os.path.getsize(file_path) < 32 * 1024:
return file_path
if not file_path.lower().endswith(".mp4"):
return file_path
ffmpeg_exe = find_executable("ffmpeg")
if not ffmpeg_exe:
return file_path
if cb.get("on_status"):
cb["on_status"]("Canlı yayın MP4 olarak kaydediliyor...")
temp_ts = file_path + ".remux_tmp.ts"
os.replace(file_path, temp_ts)
flags = subprocess.CREATE_NO_WINDOW if sys.platform == "win32" else 0
res = subprocess.run(
[ffmpeg_exe, "-y", "-hide_banner", "-loglevel", "error", "-i", temp_ts, "-c", "copy", "-bsf:a", "aac_adtstoasc", "-movflags", "+faststart", file_path],
creationflags=flags,
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
timeout=30
)
if res.returncode == 0 and os.path.isfile(file_path) and os.path.getsize(file_path) > 0:
try:
os.remove(temp_ts)
except OSError:
pass
else:
# Geri al
if os.path.isfile(temp_ts):
os.replace(temp_ts, file_path)
except Exception:
pass
return file_path
def _worker(self, cmd_args, cb): def _worker(self, cmd_args, cb):
rc = -1 rc = -1
error_message = None error_message = None
@ -114,20 +213,13 @@ class DownloadEngine:
cmd_args, cmd_args,
stdout=subprocess.PIPE, stdout=subprocess.PIPE,
stderr=subprocess.STDOUT, stderr=subprocess.STDOUT,
text=True, bufsize=0,
encoding="utf-8",
errors="replace",
creationflags=flags, creationflags=flags,
bufsize=1,
env=env env=env
) )
if self._proc and self._proc.stdout: if self._proc and self._proc.stdout:
for line in iter(self._proc.stdout.readline, ''): for line in self._iter_unbuffered_lines(self._proc.stdout):
line = line.rstrip()
if not line:
continue
if line.startswith(self._FINAL_PATH_PREFIX): if line.startswith(self._FINAL_PATH_PREFIX):
final_p = line[len(self._FINAL_PATH_PREFIX):].strip().strip('"') final_p = line[len(self._FINAL_PATH_PREFIX):].strip().strip('"')
if final_p and final_p != "NA": if final_p and final_p != "NA":
@ -135,6 +227,9 @@ class DownloadEngine:
self._current_file = final_p self._current_file = final_p
continue continue
if line.startswith("[kick:live]") or "live_status" in line:
self._is_live_session = True
# 1. Dosya yolu yakalama # 1. Dosya yolu yakalama
m_dest = self._DEST_RE.search(line) or self._ALREADY_RE.search(line) m_dest = self._DEST_RE.search(line) or self._ALREADY_RE.search(line)
if m_dest: if m_dest:
@ -161,10 +256,10 @@ class DownloadEngine:
cb["on_status"]("Sponsorlu bölümler kesiliyor...") cb["on_status"]("Sponsorlu bölümler kesiliyor...")
elif line.startswith("[download] Destination:"): elif line.startswith("[download] Destination:"):
if cb.get("on_status"): if cb.get("on_status"):
cb["on_status"]("İndiriliyor...") cb["on_status"]("Canlı Yayın Kaydediliyor..." if self._is_live_session else "İndiriliyor...")
# 2. İlerleme ayrıştırma # 2. İlerleme ayrıştırma (yt-dlp + FFmpeg canlı yayın/kesit ilerlemesi)
parsed = self._parse_progress(line, cb.get("on_progress")) parsed = self._parse_progress(line, cb.get("on_progress"), cb.get("on_status"))
# 3. Akıllı Hata Teşhisi # 3. Akıllı Hata Teşhisi
diag = diagnose(line) diag = diagnose(line)
@ -182,7 +277,10 @@ class DownloadEngine:
elif "[download] 100%" in line or "100% of" in line: elif "[download] 100%" in line or "100% of" in line:
tag = "success" tag = "success"
is_progress_line = line.startswith("[PROGRESS]") or (parsed and bool(self._DL_RE.search(line))) is_progress_line = (
line.startswith("[PROGRESS]")
or (parsed and bool(self._DL_RE.search(line) or self._FFMPEG_PROGRESS_RE.search(line)))
)
if cb.get("on_log") and not is_progress_line: if cb.get("on_log") and not is_progress_line:
cb["on_log"](line, tag) cb["on_log"](line, tag)
@ -206,6 +304,7 @@ class DownloadEngine:
with self._lock: with self._lock:
self._running = False self._running = False
cancelled = self._cancelled cancelled = self._cancelled
is_live_session = self._is_live_session
if self._proc and self._proc.stdout: if self._proc and self._proc.stdout:
try: try:
self._proc.stdout.close() self._proc.stdout.close()
@ -213,15 +312,27 @@ class DownloadEngine:
pass pass
self._proc = None self._proc = None
target_file = last_destination or self._current_file
# Eğer canlı yayın kaydı kullanıcı tarafından durdurulduysa ve diske veri kaydedildiyse,
# bunu iptal değil başarılı canlı yayın kaydı olarak tamamla ve MP4 kapsayıcısını onar!
if is_live_session and target_file and os.path.isfile(target_file):
try:
if os.path.getsize(target_file) > 32 * 1024:
target_file = self._remux_live_file_if_needed(target_file, cb)
cancelled = False
rc = 0
except Exception:
pass
success = (rc == 0 and not cancelled) success = (rc == 0 and not cancelled)
if cb.get("on_complete"): if cb.get("on_complete"):
cb["on_complete"](success, last_destination or self._current_file, error_message, cancelled) cb["on_complete"](success, target_file, error_message, cancelled)
def _parse_progress(self, line, on_progress): def _parse_progress(self, line, on_progress, on_status=None):
if not on_progress: if not on_progress:
return False return False
# Özel template kontrolü # 1. Özel [PROGRESS] template kontrolü (Normal + HLS/m3u8 yayınlar)
m = self._PROGRESS_RE.search(line) m = self._PROGRESS_RE.search(line)
if m: if m:
try: try:
@ -229,17 +340,63 @@ class DownloadEngine:
speed = m.group("speed").strip() speed = m.group("speed").strip()
total = m.group("total").strip() total = m.group("total").strip()
eta = m.group("eta").strip() eta = m.group("eta").strip()
dl = (m.group("dl") or "").strip()
est = (m.group("est") or "").strip()
speed = "—" if not speed or any(x in speed.lower() for x in ["unknown", "na", "—"]) else speed def _is_na(val):
total = "—" if not total or any(x in total.lower() for x in ["unknown", "na", "—"]) else total return not val or any(x in val.lower() for x in ["unknown", "na", "n/a", "—", "~0.00"])
eta = "—" if not eta or any(x in eta.lower() for x in ["unknown", "na", "—"]) or "" in eta else eta
speed = "—" if _is_na(speed) else speed
if _is_na(total):
if not _is_na(dl) and not _is_na(est):
total = f"{dl} / ~{est}"
elif not _is_na(dl):
total = dl
elif not _is_na(est):
total = f"~{est}"
else:
total = "—"
eta = "—" if _is_na(eta) else eta
on_progress(pct, speed, total, eta) on_progress(pct, speed, total, eta)
return True return True
except Exception: except Exception:
pass pass
# Standart yt-dlp ilerleme satırı # 2. FFmpeg canlı yayın ve kesit (--download-sections) ilerleme satırı
m_ff = self._FFMPEG_PROGRESS_RE.search(line)
if m_ff:
try:
raw_size = int(m_ff.group("size"))
unit = m_ff.group("unit").lower()
if unit.startswith("k"):
bytes_val = raw_size * 1024
elif unit.startswith("m"):
bytes_val = raw_size * 1024 * 1024
elif unit.startswith("g"):
bytes_val = raw_size * 1024 * 1024 * 1024
else:
bytes_val = raw_size
if bytes_val >= 1024 * 1024 * 1024:
size_str = f"{bytes_val / (1024 * 1024 * 1024):.2f} GB"
else:
size_str = f"{bytes_val / (1024 * 1024):.1f} MB"
br_val = float(m_ff.group("bitrate"))
mb_s = (br_val / 8.0) / 1024.0
speed_str = f"{mb_s:.2f} MB/s" if mb_s >= 0.05 else f"{br_val:.0f} kbps"
time_str = m_ff.group("time").split(".")[0]
# pct = -1.0 -> Canlı kayıt / FFmpeg akış modu
on_progress(-1.0, speed_str, size_str, f"Kayıt: {time_str}")
if on_status and self._is_live_session:
on_status(f"🔴 Canlı Yayın Kaydediliyor ({size_str} · {time_str})")
return True
except Exception:
pass
# 3. Standart yt-dlp ilerleme satırı
m = self._DL_RE.search(line) m = self._DL_RE.search(line)
if m: if m:
try: try:
@ -414,7 +571,7 @@ def build_command(url, output_dir, options):
"--progress-delta", "--progress-delta",
"0.15", "0.15",
"--progress-template", "--progress-template",
"download:[PROGRESS] %(progress._percent_str)s | %(progress._speed_str)s | %(progress._total_bytes_str)s | %(progress._eta_str)s" "download:[PROGRESS] %(progress._percent_str)s | %(progress._speed_str)s | %(progress._total_bytes_str)s | %(progress._eta_str)s | %(progress._downloaded_bytes_str)s | %(progress._total_bytes_estimate_str)s"
] ]
cmd.append(url) cmd.append(url)

View file

@ -213,6 +213,30 @@ class KickSupportTests(unittest.TestCase):
self.assertIn("--wait-for-video", cmd) self.assertIn("--wait-for-video", cmd)
self.assertIn("--live-from-start", cmd) self.assertIn("--live-from-start", cmd)
def test_ffmpeg_live_and_hls_progress_parsing(self):
from core.downloader import DownloadEngine
eng = DownloadEngine()
captured = []
# 1. FFmpeg live recording progress line
ok_ff = eng._parse_progress(
"frame= 1842 fps= 60 q=-1.0 size= 15360KiB time=00:00:30.70 bitrate=4098.2kbits/s speed=1.01x",
lambda p, s, t, e: captured.append((p, s, t, e))
)
self.assertTrue(ok_ff)
self.assertEqual(captured[-1][0], -1.0)
self.assertEqual(captured[-1][2], "15.0 MB")
self.assertEqual(captured[-1][3], "Kayıt: 00:00:30")
# 2. HLS m3u8_native progress line where total_bytes is N/A
ok_hls = eng._parse_progress(
"[PROGRESS] 24.5% | 4.12MiB/s | N/A | 00:18 | 12.40MiB | 50.60MiB",
lambda p, s, t, e: captured.append((p, s, t, e))
)
self.assertTrue(ok_hls)
self.assertEqual(captured[-1][0], 24.5)
self.assertEqual(captured[-1][2], "12.40MiB / ~50.60MiB")
if __name__ == "__main__": if __name__ == "__main__":
unittest.main() unittest.main()

View file

@ -729,6 +729,7 @@ class ContextualDownloadDrawer(tk.Frame):
self.log_text.config(state="disabled") self.log_text.config(state="disabled")
self.btn_open.pack_forget() self.btn_open.pack_forget()
self.btn_close.pack_forget() self.btn_close.pack_forget()
self.btn_cancel.config(text="⛔ İptal")
self.btn_cancel.pack(side="left", padx=(0, 6), before=self.btn_console_toggle) self.btn_cancel.pack(side="left", padx=(0, 6), before=self.btn_console_toggle)
parent_container = getattr(self.master, "content_container", None) parent_container = getattr(self.master, "content_container", None)
if parent_container and parent_container.winfo_ismapped(): if parent_container and parent_container.winfo_ismapped():
@ -750,8 +751,8 @@ class ContextualDownloadDrawer(tk.Frame):
self._toggle_console() self._toggle_console()
def update_stats(self, pct, speed, total, eta): def update_stats(self, pct, speed, total, eta):
# 0% ve 100% gibi kritik sınırları hemen göster # 0% ve 100% gibi kritik sınırları hemen göster (pct < 0 canlı yayın modudur, 50ms throttle kullanır)
if pct <= 0 or pct >= 100: if pct == 0 or pct >= 100:
if self._stats_after_id: if self._stats_after_id:
try: try:
self.after_cancel(self._stats_after_id) self.after_cancel(self._stats_after_id)
@ -786,6 +787,14 @@ class ContextualDownloadDrawer(tk.Frame):
def _apply_stats(self, pct, speed, total, eta): def _apply_stats(self, pct, speed, total, eta):
if not self.winfo_exists(): if not self.winfo_exists():
return return
if pct < 0:
self.pbar["value"] = 100
self.pct_var.set("🔴 CANLI")
self.speed_var.set(f"⚡ {speed}")
self.dl_var.set(f"📥 {total}")
self.eta_var.set(f"⏱ {eta}")
self.btn_cancel.config(text="⏹ Kaydı Bitir & Kaydet")
return
self.pbar["value"] = pct self.pbar["value"] = pct
self.pct_var.set(f"{pct:.1f}%") self.pct_var.set(f"{pct:.1f}%")
self.speed_var.set(f"⚡ {speed}") self.speed_var.set(f"⚡ {speed}")

View file

@ -540,6 +540,12 @@ class KickTab(tk.Frame):
values=(f"✂️ {cat}", c.get("title", "—"), c.get("duration", "—"), views_str, c.get("date", "—")) values=(f"✂️ {cat}", c.get("title", "—"), c.get("duration", "—"), views_str, c.get("date", "—"))
) )
children = self.tree.get_children()
if children:
self.tree.selection_set(children[0])
self.tree.focus(children[0])
self._on_tree_selected()
def _on_tree_selected(self, event=None): def _on_tree_selected(self, event=None):
sel = self.tree.selection() sel = self.tree.selection()
if not sel: if not sel:

View file

@ -351,6 +351,7 @@ class SingleTab(tk.Frame):
"use_download_archive": config.get("use_download_archive", False), "use_download_archive": config.get("use_download_archive", False),
"clip_start": self.clip_start_entry.get_clean_text(), "clip_start": self.clip_start_entry.get_clean_text(),
"clip_end": self.clip_end_entry.get_clean_text(), "clip_end": self.clip_end_entry.get_clean_text(),
"is_live": bool(self.current_metadata.get("is_live")) if self.current_metadata else False,
"title": self.current_metadata.get("title") if self.current_metadata else None "title": self.current_metadata.get("title") if self.current_metadata else None
} }