YouTube-Relay / relay.py
Reoo88's picture
replace the bench with the full TikTok->YouTube relay (identical to Tktktk/On)
bd5e65b verified
Raw History Blame Contribute Delete
67.9 kB
"""One FFmpeg push per live session. Multiple senders run concurrently, one per YouTube event.""" import fcntl, os, queue, re, select, threading, time, subprocess from collections import deque from curl_cffi import requests from flv_bridge import FLVBridge, FormatChanged # أخطاء FFmpeg ← وصف عربي. قائمة واحدة على مستوى الوحدة حتى تُختبر على سطور FFmpeg حقيقية # بدل أن تُدفن في إغلاق داخل send(): الإغلاق هو ما أخفى أن كلمة المفتاح كُتبت بالخطأ. FFMPEG_ERROR_LABELS = [ ('Application defined reason', 'يوتيوب أرسل سبب الإغلاق من خادمه (رسالة RTMP)'), ('NetStream.Publish', 'يوتيوب رفض النشر على هذا المفتاح (NetStream.Publish)'), ('Publish stream', 'رفض خادم الاستقبال أمر النشر'), ('Connection refused', 'رفض اتصال خادم الاستقبال'), ('Connection timed out', 'انتهت مهلة اتصال خادم الاستقبال'), ('Connection reset by peer', 'خادم الاستقبال قطع الاتصال أثناء الإرسال'), ('Broken pipe', 'انقطع أنبوب الإرسال إلى خادم الاستقبال'), ('End of file', 'خادم الاستقبال أغلق الاتصال'), ('Immediate exit requested', 'طُلب إنهاء FFmpeg قبل اكتمال الإرسال'), ('Packet mismatch', 'عدم تطابق حزم الفيديو — تغيّر مقاس المصدر داخل الجلسة'), ('Input/output error', 'خطأ إدخال/إخراج في الإرسال'), ('Publishing stream at bitrates', 'يوتيوب قَبِل النشر فعلًا — فالقطع لاحقًا ليس رفض مفتاح'), ('Server error, Publish', 'خادم يوتيوب رفض أمر النشر على هذا المفتاح'), ('Server error', 'خادم الاستقبال أعاد خطأ'), ('Invalid data found', 'بيانات المصدر غير صالحة للقراءة'), ('Video codec', 'عدم توافق ترميز الفيديو مع الحاوية'), ('Invalid argument', 'أحد إعدادات FFmpeg غير مقبول'), # FFmpeg يكتب Non-monotonous لا Non-monotonic؛ النمط الخاطئ كان يجعل «لم يظهر سبب مصنّف» # عبارة كاذبة، لأن مشكلة التوقيت كانت تُرمى بصمت. ('Non-monotono', 'توقيت الفيديو غير متزايد (DTS) في التدفق الخارج'), ('input buffer overflow', 'امتلأ مخزن FFmpeg: المصدر أسرع من الإرسال أو الاتصال أبطأ'), ('Error writing packet', 'تعذّرت كتابة حزمة على الاتصال'), ('Unknown encoder', 'مرمز غير متوفر'), ('Option not found', 'خيار FFmpeg غير مدعوم'), ] INFO_KEEP = ('publish', 'reason', 'handshak', 'connect', '_error', 'reject', 'closing', 'input/output', 'broken pipe', 'reset by peer', 'timed out', 'refused', 'server error', 'unable to open') def _error_interesting(text): """ما يستحق البقاء من سطور FFmpeg: كل خطأ أو تحذير، أو سطر اتصال مفيد أثناء التشخيص القائمة بيضاء عمدًا: مع `info` تفيض سطور FFmpeg بالترويسات والروابط، والسجل يجب أن يبقى مقروءًا. وكل ما يبقى يمرّ بـ redact_stderr أولًا (يُمحى الرابط والمفتاح). """ low = (text or '').lower() if 'error' in low or 'warning' in low: return True return any(w in low for w in INFO_KEEP) def classify_ffmpeg_error(text): """أول وصف ينطبق على سطر من stderr، أو None. تصنيف نصي خالص بلا أي روابط.""" low = (text or '').lower() for needle, label in FFMPEG_ERROR_LABELS: if needle.lower() in low: return label return None def redact_stderr(text): """يُبقي سبب الخطأ ويخفي كل ما لا يجوز قراءته في سجل عام: الروابط والمفاتيح والرموز.""" t = re.sub(r'\b(?:rtmps?|rtsp|srt|https?)://\S+', '«رابط-مخفي»', text or '') t = re.sub(r'(?i)([?&=]|^|\s)((?:key|token|auth|sessionid|sign)\s*=\s*)[^\s&]+', r'\1\2«مخفي»', t) return t.strip()[:240] class SourceStalled(RuntimeError): """المصدر صامت: لا بايت من تيك توك منذ مهلة الحارس، أو لم يتقدّم FFmpeg. يُرفع بدل التعليق إلى الأبد لأن FFmpeg الحيّ لا يعني بثًا حيًا: العملية تنتظر stdin ويوتيوب يبقى مستقبِلًا على آخر ما وصل. يلتقطه sender_loop فيعيد رصد LIVE ويبني جلسة جديدة من الصفر. """ class RelayStartError(RuntimeError): """لم تبدأ الجلسة أصلًا (FFmpeg لم يولد أو المصدر رفض قبل التدفق). تُميَّز عن SourceStalled لأن العلاج مختلف: هنا يجب أن تُجرَّب تندرة أخرى/وضع آخر بدل إعادة رصد نفس القائمة فورًا — وبكل حال لا تبقى عملية نصفية. """ class Sender: """Single YouTube RTMPS push for one session. Process and progress are instance-scoped, so several senders can run at the same time without sharing state.""" def __init__(self,ffmpeg,log,headers_for=None): self.ffmpeg=ffmpeg;self.log=log self.headers_for=headers_for or (lambda user:{}) self.lock=threading.RLock();self.process=None self.data={'status':'','source':'','output_seconds':0,'last_output_at':None} self.last_exit_code=None # آخر رمز خروج FFmpeg (من آخر جلسة)، يقرؤه المشرف self.last_errors=[] # آخر سطور stderr مصنّفة ومُخفًى منها المفتاح: لماذا أقفلت الوجهة؟ self.on_stable=None # مستقبِل المدير: أول ≥25 ث مُسلَّمة = العقاب انتهى self.last_diagnostics=[] # آخر الأوصاف العربية المصنَّفة، تُعرض في اللوحة كما في السجل self.last_source_gap=0.0 # صمت المصدر لحظة التفكيك: يفصل جوع المصدر عن رفض الوجهة # Timestamps of source resolution changes seen by this sender (anti-flap window). self.flap=deque() # Once the source proved to flap, stay on a constant canvas for the rest of the # event. Without this the flap window expires after 10 quiet minutes and the # sender silently drops back to copy mode, restarting the whole failure loop. self.sticky_mode=None self.sticky_since=0.0 self.copy_recovery_fails=0 self._recovering_copy=False self._last_light_output=0.0 self._gop_w=0 self._gop_h=0 self._no_copy_recovery=False # Candidate handed to send_mode() so the codec rule can judge the real source. self.current_candidate=None # Journal setting wins over the environment so the mode can be changed from the UI # without a factory rebuild (env vars cannot be written from inside the Space). self.mode_override=None # حالة الجلسة الجارية: يقرأها terminate() ليفرض إنهاءً فوريًا بدل انتظار مهلة، # ويقرأها snapshot() لتظهر «منذ كم ثانية وصل آخر بايت» في الواجهة. self.session=None self.data.update(source_bytes=0,last_source_at=None,stalled=False) def set(self,**kw): with self.lock:self.data.update(kw) def snapshot(self): with self.lock: d=dict(self.data) stamp=d.get('last_source_at') if stamp:d['source_age']=round(max(0.0,time.monotonic()-stamp),1) try: d['send_mode']=self.sticky_mode or self.mode_override or '' except Exception: d['send_mode']='' return d def wait_until(self,condition,stop,poll=1.0,timeout=None): """Block while `condition()` holds; returns as soon as it stops or a stop is requested.""" started=time.monotonic() while not stop.is_set(): try: if not condition():return True except Exception:return True if timeout is not None and time.monotonic()-started>timeout:return False time.sleep(poll) return True def alive(self): """True while a live FFmpeg process belongs to this sender.""" with self.lock:p=self.process return bool(p and p.poll() is None) def terminate(self): with self.lock: p=self.process;sess=self.session # إن كان هناك من معلّق على read من تيك توك فإنهاء FFmpeg وحده لا يوقظه: نغلق # الاستجابة ونُعلم الجلسة أن الإيقاف مقصود (لا إعادة محاولة داخل الخيط القارئ). if sess is not None:sess['force_stop']=True if p and p.poll() is None: try:p.terminate() except OSError:pass def send_mode(self): """Policy for what YouTube receives: auto -> copy when the source is provably H.264, otherwise a constant canvas. DEFAULT: TikTok serves this channel as HEVC 720x1280 at 3.1 Mbit/s (measured on @viggoo313: origin/hd5 = h265, hd = h264 720x1280@1M, and ffprobe cannot even decode the h265 payload). Forwarding h265 in FLV is exactly the "picture froze, viewers must leave the app and come back" symptom, because the player latches onto the first configuration. copy -> forward the source untouched (needs a proven H.264 source) fixed1080 -> constant 1080x1920 canvas, re-encodes fixed720 -> constant 720x1280 canvas, re-encodes (lighter on CPU) """ mode=(self.mode_override or os.getenv('YOUTUBE_SEND_MODE','auto')).strip().lower() if mode not in ('auto','copy','fixed1080','fixed720','matchgop'): raise ValueError('وضع الإرسال يجب أن يكون auto أو copy أو fixed1080 أو fixed720 أو matchgop') # Sticky transcode is for HEVC / layout flap only. Measured 2026-09-27 on cpu-basic: # two fixed720 publishers used 1.67–1.85 of 2.0 quota (peak 92.6%) with YouTube # health still good — no headroom for a third. If this candidate is H264, copy. if self.sticky_mode: # Do NOT drop LIGHT just because the next TikTok label says h264. # That path produced COPY with output_seconds=0 on the same ingest # (LIGHT healthy ~45s → copy restart → out=0). Recovery is gated. if self._may_attempt_copy_recovery(): self._recovering_copy=True return 'copy' return self.sticky_mode # Stream copy is only legal for H.264 in FLV. Before trusting TikTok's own codec label, # the caller may hand us the candidate it is about to send (see current_candidate). if mode in ('auto','copy') and self.current_candidate is not None: # Copy needs proof, not wishful thinking — see copy_is_safe(). fb=self.allow_codec_fallback() if fb:return fb if mode=='auto': # Proven H.264 and a stable source: forward it untouched. return 'copy' if not self.sticky_mode else self.sticky_mode # copy mode only: if the phone keeps flipping resolution, stop flapping the # YouTube session and absorb the changes on a constant canvas instead. if mode=='copy': flap=self.flap now=time.monotonic() while flap and now-flap[0]>600:flap.popleft() if len(flap)>=int(os.getenv('YOUTUBE_FLAP_LIMIT','4')): mode=os.getenv('YOUTUBE_FLAP_FALLBACK_MODE','matchgop').strip().lower() if mode not in ('fixed1080','fixed720','matchgop'):mode='matchgop' self.sticky_mode=mode self.sticky_since=time.monotonic() self._recovering_copy=False return mode def _may_attempt_copy_recovery(self): """LIGHT→COPY only after a stable light run and a verified H.264 source. Isolated-handoff harness (SIMULATED): start copy, require bytes>0, then kill light — PASS. Naive sticky-clear on h264 label — the production bug. """ # Default OFF: going COPY again after matchgop sends a new SPS on the same # YouTube event. The mobile app then flashes/freezes until the viewer force-closes # it — measured on Prayer-Time-Bot / On. Opt in with YOUTUBE_COPY_RECOVERY=1. if str(os.getenv('YOUTUBE_COPY_RECOVERY','0')).strip().lower() in ('0','false','off','no',''): return False if self.copy_recovery_fails>=int(os.getenv('YOUTUBE_COPY_RECOVERY_MAX_FAILS','2')): return False need=max(45.0, float(os.getenv('YOUTUBE_COPY_RECOVERY_SECONDS','90'))) if not self.sticky_since or (time.monotonic()-self.sticky_since)<need: return False if float(self._last_light_output or 0)<20: return False if getattr(self,'_no_copy_recovery', False): return False cand=self.current_candidate or {} blob=(str(cand.get('codec') or '')+' '+str(cand.get('label') or '')+' '+str(cand.get('brief') or '')).lower() if any(k in blob for k in ('hevc','h265','hvc1')): return False return any(k in blob for k in ('h264','avc')) def request_sticky(self, mode, user, reason): """Per-broadcaster: stick LIGHT/matchgop and end this FFmpeg only — not the Space.""" mode=(mode or 'matchgop').strip().lower() if mode not in ('matchgop','fixed720','fixed1080'): mode='matchgop' if self.sticky_mode==mode and self.session: return False if not self.sticky_mode: try: from ingest import hub if not hub.light_available(): self.log(user, '[HEALTH] skip sticky %s — transcode slots full (%s)'%(mode, reason[:120])) return False except Exception: pass self.sticky_mode=mode self.sticky_since=time.monotonic() self._recovering_copy=False self._no_copy_recovery=True self.log(user, '[HEALTH] %s — sticky %s (this publisher only)'%(reason[:160], mode)) sess=self.session if isinstance(sess, dict): sess['force_stop']=True p=self.process if p is not None and p.stdin: try: p.stdin.close() except (OSError, ValueError): pass return True def note_format_change(self): self.flap.append(time.monotonic()) if len(self.flap)>=int(os.getenv('YOUTUBE_FLAP_LIMIT','4')): self.log('system','تغيّرت أبعاد المصدر عدة مرات خلال 10 دقائق؛ التحول تلقائيًا إلى كانفس ثابت (%s) لمنع تكرار الانقطاع'%os.getenv('YOUTUBE_FLAP_FALLBACK_MODE','matchgop')) @staticmethod def copy_is_safe(declared,probed): """Stream copy is allowed only on positive proof of H.264, never on absence of evidence. Why absence matters here: this rule decides whether the audience gets a live picture or a frozen one. TikTok advertises the rendition codec (verified live on @viggoo313: origin/hd5 = h265, hd = h264), while ffprobe sees only what the first bytes actually decoded — and an empty answer from an h265 FLV is normal, not a clean bill of health (measured here: origin/hd5 → probe returns no video stream at all, hd → h264 720x1280). A needless re-encode costs CPU; a wrong copy costs every viewer their picture until they leave the YouTube app and come back. """ def norm(x): x=str(x or '').strip().lower() return 'h264' if any(c in x for c in ('h264','avc')) else ('other' if x else '') d,q=norm(declared),norm(probed) if q=='h264':return d in ('','h264') # measurement wins, but not against a h265 label if q=='other':return False # measured as something else: never copy if d=='h264':return True # no measurement available, declaration is clean return False # h265 / unknown / unreadable → re-encode def allow_codec_fallback(self): """Decide from evidence once, then stick to it for the whole event.""" if str(os.getenv('YOUTUBE_AUTO_TRANSCODE','1')).strip().lower() in ('0','false','off','no'):return None cand=self.current_candidate if cand is None:return None found=self.live_probe(cand) probed=(found or {}).get('video') declared=str(cand.get('codec') or '') if self.copy_is_safe(declared,probed):return None label=str(cand.get('label') or cand.get('brief') or '') if any(k in str(declared).lower() for k in ('h264','avc')) or any(k in label.lower() for k in ('h264','avc')): return None try: from ingest import hub if not hub.light_available(): self.log('system','المصدر يحتاج ترميز لكن خانات CPU ممتلئة — نترك هذا المرشّح') return None except Exception: pass mode=os.getenv('YOUTUBE_CODEC_FALLBACK_MODE','matchgop').strip().lower() if mode not in ('fixed1080','fixed720','matchgop'):mode='matchgop' self.sticky_mode=mode self.sticky_since=time.monotonic() self._recovering_copy=False why=('ffprobe: '+str(probed)) if probed else (('مُعلَن: '+declared) if declared else 'ترميز مجهول والفحص لم يأتِ بنتيجة') self.log('system','لا يمكن نسخ المصدر كما هو ('+why+') — تحويل تلقائي إلى '+mode+ '؛ هذا يمنع تجمّد الصورة عند المشاهدين عند تغيّر المقاس أو في جولات PK') return mode def set_probe(self,probe): """Injected by the manager: probe(candidate) -> {'video':..,'audio':..} or None.""" self.probe_source=probe def live_probe(self,candidate): """FFmpeg's own view of the source, not the label TikTok sent us. None means "no opinion" (ffprobe unavailable, network dead): the caller must then trust the declared codec rather than treat an unknown as a mismatch and burn CPU needlessly. """ probe=getattr(self,'probe_source',None) if not probe:return None try:return probe(candidate) except Exception:return None def lock_gold(self, candidate=None, w=0, h=0): """Pin the YouTube output size to the first picture the player already latched. A later TikTok PK/layout hop must pad into this canvas. Changing width/height on an already-open live event is exactly the flash that only a YouTube-app restart clears for existing viewers. """ if int(getattr(self, '_gop_w', 0) or 0) >= 16: return (self._gop_w, self._gop_h) if candidate and not (w and h): try: w = int(candidate.get('width') or 0) h = int(candidate.get('height') or 0) except (TypeError, ValueError): w = h = 0 try: w, h = int(w or 0), int(h or 0) except (TypeError, ValueError): w = h = 0 w, h = w - w % 2, h - h % 2 if w >= 16 and h >= 16: w, h = self.youtube_safe_size(w, h) self._gop_w, self._gop_h = w, h return (int(getattr(self, '_gop_w', 0) or 0), int(getattr(self, '_gop_h', 0) or 0)) @staticmethod def youtube_safe_size(w, h): """Map 720-class sizes to a YouTube-healthy 720×1280 canvas. 720×1440 is 720-class (~1 Mbps) but YouTube treats height 1440 as 1440p and then reports videoIngestionStarved (measured a3dam_111). 640×1280 copy/matchgop was Studio black. True 1080 (short side ≥1080) is kept. """ try: w, h = int(w or 0), int(h or 0) except (TypeError, ValueError): return 0, 0 if w < 16 or h < 16: return w, h short, long_ = min(w, h), max(w, h) portrait = h >= w if short <= 720 and long_ >= 1280: return (720, 1280) if portrait else (1280, 720) return w - w % 2, h - h % 2 @staticmethod def canvas(width,height): # eval=frame: when TikTok hops size mid-session the filter keeps the *output* # WxH (and therefore the x264 SPS) unchanged. Default eval=init would reinit # the encoder → new SPS → YouTube app flash until reopen. return ('scale=w=%d:h=%d:force_original_aspect_ratio=decrease:flags=lanczos:eval=frame,' 'pad=%d:%d:(ow-iw)/2:(oh-ih)/2:color=black:eval=frame,setsar=1,format=yuv420p'%(width,height,width,height)) def input_args(self,candidate): """How FFmpeg *reads* the source — two transports, one sender. An FLV rendition is pushed through our stdin (FLVBridge validates and rewrites the header), while an HLS rendition is opened by FFmpeg itself, which is what makes the .m3u8 sources that rank_sources() used to throw away actually sendable: a playlist is text, so piping its bytes into `-i pipe:0` could only ever fail. FFmpeg's hls demuxer also fetches each segment on its own, so a CDN edge hiccup no longer kills the encoder. """ # Drop corrupt packets and regenerate PTS at the demuxer instead of feeding the decoder # broken frames: a viewer that hits a source hiccup recovers on its own instead of # freezing until they reconnect. (Checked on the image's FFmpeg 7.1.5: `-resync` is NOT # available — "Unrecognized option 'resync'" — so it must not be used; `discardcorrupt` # is the supported equivalent and is verified working in verify.sh step 17.) resync=['-fflags','+genpts+discardcorrupt'] if str(os.getenv('YOUTUBE_INPUT_RECOVERY','1')).strip().lower() in ('1','on','true','yes') else [] if (candidate or {}).get('media')=='hls': url=(candidate or {}).get('url') or '' # -reconnect belongs to the HTTP protocol layer: FFmpeg refuses it outright on a # non-network input ("Option reconnect not found"), so it is applied only where it # is both legal and wanted. net=['-reconnect','1','-reconnect_streamed','1','-reconnect_delay_max','5'] if url.startswith(('http://','https://')) else [] return {'stdin':None,'input':[ *net,*resync,'-live_start_index',os.getenv('HLS_START_INDEX','-3'), *(('-headers',self.headers_blob(candidate)) if candidate.get('user') else ()), '-i',url]} return {'stdin':subprocess.PIPE,'input':['-rw_timeout','20000000', '-fflags','+genpts','-i','pipe:0']} def headers_blob(self,candidate): """FFmpeg wants CRLF-terminated headers as one blob; our token store yields a dict.""" items=self.headers_for(candidate.get('user')) if candidate else {} return ''.join('%s: %s\r\n'%(k,v) for k,v in items.items() if v) @staticmethod def codec_unusable(candidate): """True when the declared video codec cannot be stream-copied into FLV. The copy path never re-encodes video, so anything other than H.264 (HEVC-only renditions, or a source whose codec we cannot read) is pushed to YouTube still wrapped in FLV and rejected there. Better to transcode than to fail forever. """ codec=str((candidate or {}).get('codec') or '').strip().lower() if not codec:return False return not any(c in codec for c in ('h264','avc','264')) @staticmethod def hevc_payload(candidate): """هل ما سيدفعه FFmpeg فعلًا HEVC؟ الإعلان عن Enhanced-RTMP يُقاس على هذا لا على الوضع.""" codec = str((candidate or {}).get('codec') or '').strip().lower() label = str((candidate or {}).get('label') or '').strip().lower() return any(k in codec for k in ('hevc', 'h265', 'hvc1')) or any(k in label for k in ('hevc', 'h265')) def enhanced_advertisement(self, mode, candidate): """قائمة خيارات FFmpeg لإعلان fourCcLive (Enhanced RTMP) — فارغة على تدفق H.264. الوثيقة: `rtmp_enhanced_codecs` هو «ما يعلن العميل دعمه» في خاصية fourCcLive لرسالة connect. سياسة هذه الشجرة لا تنسخ HEVC أصلًا (copy_is_safe يُعيد ترميز h265)، فإعلان hvc1 مع `-c:v copy` لمرشّح h264 كان كذبًا على حافة الاستقبال. YOUTUBE_ENHANCED_RTMP=off يطفئه كليًا لمن يشكّ في أن الإعلان نفسه ما يُغلق الاتصال. """ switch = os.getenv('YOUTUBE_ENHANCED_RTMP', 'auto').strip().lower() if switch in ('0', 'off', 'no', 'legacy'): return [] if mode != 'copy': return [] # إعادة ترميز إلى h264 دائمًا: لا شيء معزّز لنُعلنه if os.getenv('YOUTUBE_VIDEO_MODE', 'original').strip().lower() != 'original': return [] return ['-rtmp_enhanced_codecs', 'hvc1'] if self.hevc_payload(candidate) else [] def command(self,destination,candidate=None): # إعلان Enhanced-RTMP يُقاس على الترميز المدفوع فعلًا؛ ملفات الاختبار المحلية لا بروتوكول لها. mode=self.send_mode() network=destination.startswith(('rtmp://','rtmps://')) enhanced=self.enhanced_advertisement(mode,candidate) if network else [] if mode=='copy': video=['-c:v','copy'] else: if mode=='matchgop': w=int((candidate or {}).get('width') or 0); h=int((candidate or {}).get('height') or 0) w,h=w-w%2,h-h%2 if not getattr(self,'_gop_w',0) and w>=16 and h>=16: self._gop_w,self._gop_h=w,h cw,ch=int(getattr(self,'_gop_w',0) or w), int(getattr(self,'_gop_h',0) or h) if cw>=16 and ch>=16: vf=self.canvas(cw,ch) else: vf='scale=trunc(iw/2)*2:trunc(ih/2)*2,setsar=1,format=yuv420p' bitrate=os.getenv('VIDEO_BITRATE','').strip() or '4500k' else: width,height,bitrate=(1080,1920,'6000k') if mode=='fixed1080' else (720,1280,'4000k') vf=self.canvas(width,height) bitrate=os.getenv('VIDEO_BITRATE','').strip() or bitrate bufsize=str(int(int(str(bitrate).rstrip('kK'))*1.5))+'k' video=['-vf',vf,'-c:v','libx264','-preset',os.getenv('YOUTUBE_X264_PRESET','veryfast'), '-tune','zerolatency','-profile:v','high','-crf',os.getenv('YOUTUBE_CRF','22'), # -b:v is what makes VIDEO_BITRATE real: -crf alone lets x264 roam and # -maxrate only clamps the peaks, so a "4000k" promise to YouTube was not kept. '-b:v',bitrate,'-maxrate',bitrate,'-bufsize',bufsize, # IDR at least every 2 s: a viewer who stalls (or joins) re-syncs on the next # keyframe instead of waiting for the source's own GOP, which is what made # people leave the YouTube app and come back to get a picture again. '-force_key_frames','expr:gte(t,n_forced*2)', '-g',os.getenv('YOUTUBE_GOP','60'),'-keyint_min','30','-sc_threshold','0','-bf','0', '-x264-params','open-gop=0:scenecut=0:keyint=%s:min-keyint=30'%os.getenv('YOUTUBE_GOP','60'), '-pix_fmt','yuv420p','-fps_mode','cfr', '-colorspace','bt709','-color_primaries','bt709','-color_trc','bt709'] # Network output goes through the fifo pseudo-muxer instead of straight to flv. # fifo separates encoding from the RTMPS connection and reconnects transparently # when YouTube drops it, rather than killing the whole FFmpeg process. That is # exactly why the local recording kept running while the broadcast died: writing # to disk never fails, a network blip does, and with -f flv it was fatal. # Documented: https://ffmpeg.org/ffmpeg-formats.html#fifo # recover_any_error is deliberately NOT set, so permanent faults (bad stream key, # rejected codec) still fail fast and stay visible in the log instead of retrying # forever in silence. if network: # timeshift يؤخّر كل شيء عن الوجهة بمقدار ثابت. فائدته: سكّات المصدر تُبتلع بدل أن # تُجيع حافة يوتيوب، والحزم تبقى محفوظة عبر إعادة الاتصال. كلفته — وهي ما لم يكن # موثّقًا: أول بايت لا يصل قبل انقضاء المهلة كلها. مقيسٌ على أمر الشبكة نفسه بوجهة # ملف وتغذية 1 ميجابايت/ث: ts=10 ⇒ أول نمو للمخرج عند 10.0 ث، وts=0 ⇒ عند 1.4 ث. # وفي الإنتاج الحافة تقفل بعد 13-20 ث، فلا تبقى نافذة صالحة تكفي لتقول «good». # الافتراضي 0 إذًا. وتاريخًا (N26): كنّا نغلف الخرج بـfifo حتى مع ts=0 اعتمادًا على # استعادة الاتصال الشفافة — لكن ffmpeg 7.1 (صورة trixie الإنتاجية) غيّر دلالة # attempt_recovery: فشل فتح الوجهة (مفتاح فاسد/رفض/انقطاع DNS) صار يُعاد محاولته # إلى ما لا نهاية ⇒ عملية زومبي تلتهم المصدر وتُبلغ out_time وهميًا من المخزن # (مقيس: 84ث «مُسلَّمة» إلى rtmps://example.invalid في 40ث — ولا CLEANUP أبدًا). # لذا مع ts=0 خرج مباشر ‎-f flv‎: يفشل بصدق فورًا على كل الإصدارات، والمدير يعيد # بناء الجلسة بدورة [RESTART] المجرَّبة. من يريد الدرع ضد سكّات المصدر يرفع # YOUTUBE_FIFO_TIMESHIFT=10 ويعرف أنه يدفعه تأخيرًا ويبقى معه الـfifo بكل أدواته. ts=int(os.getenv('YOUTUBE_FIFO_TIMESHIFT','0')) if ts>0: # queue_size MUST grow with timeshift. Its default is 60 packets, which holds # under a second at ~77 pkt/s (30 fps video + ~47 fps AAC); once timeshift # delays the output the queue fills and, with drop_pkts_on_overflow=1, the # stream is destroyed rather than delayed. Measured: ts=3 with the default # queue yields 1 frame out of 480; ts=3 with 5000 and ts=10 with 20000 both # yield byte-identical output to the no-fifo case. q=max(500,int(os.getenv('YOUTUBE_FIFO_QUEUE','0')) or (ts*250+500)) output=['-f','fifo','-fifo_format','flv','-format_opts','flvflags=no_duration_filesize', # الإسقاط عند الامتلاء يبقى مفعّلًا: البث حيّ، وإعادة إرسال مخزن قديم أسوأ # من فجوة صغيرة — والاحتباس هنا يرتدّ إلى stdin فيتوقف ضخّ المصدر ويصمت # مؤقّت الحارس، فتُتهم تيك توك بجرم الشبكة. '-drop_pkts_on_overflow','1','-attempt_recovery','1', '-restart_with_keyframe','1', '-recovery_wait_time',os.getenv('YOUTUBE_RECOVERY_WAIT','1'), '-queue_size',str(q),'-timeshift',str(ts)] else: # N26: خرج مباشر بلا مخزن يكذب على الحارس — تقدم out_time هنا يعني تسليمًا فعليًا. output=['-flvflags','no_duration_filesize','-f','flv'] else: output=['-flvflags','no_duration_filesize','-f','flv'] ta=self.input_args(candidate) return [self.ffmpeg,'-hide_banner','-loglevel',os.getenv('YOUTUBE_FFMPEG_LOGLEVEL','error'), '-nostats','-progress','pipe:1', *ta['input'],'-map','0:v:0','-map','0:a:0?', # TikTok streams HE-AAC (SBR) at 64 kbit/s — measured on the live source. Copied # into FLV it is what players "recover" from by reconnecting, and YouTube's # transcoder re-uses whatever AAC config the first packet declared. Re-encoding audio # costs ~nothing and removes the whole class of stalls; video stays untouched in copy. *video,'-c:a','aac','-profile:a',os.getenv('YOUTUBE_AUDIO_PROFILE','aac_low'), '-b:a',os.getenv('YOUTUBE_AUDIO_BITRATE','128k'),'-ar','48000','-ac',os.getenv('YOUTUBE_AUDIO_CHANNELS','2'), '-af','aresample=async=1:first_pts=0','-avoid_negative_ts','make_zero', *enhanced,'-rw_timeout','20000000',*output,destination] # ------- مهل المصدر (كلها من البيئة؛ القيم الافتراضية مبرَّرة أدناه) ------- @property def stall_limit(self): """حدّ صمت المصدر بالثواني (0 = الحارس مطفأ) — تُعرض في اللوحة مع عمر آخر بايت.""" return self._stall_seconds() def _stall_seconds(self): """كم ثانية بلا بايت واحد من المصدر = المصدر متوقف (يوتيوب يبقى موصولًا واهمًا). 12ث: حافة يوتيوب تقفل بعد ~14-20ث صمت؛ عتبة 45 كانت تستيقظ بعد أن يتجمّد المشاهد. سكّات PK أقصر من هذا. 0 = بلا حارس. """ # 20 ث لا 45: مقيسٌ أن حافة يوتيوب تقفل النشر بعد 14-20 ث من الصمت، فعتبة أعلى تعني # أن نستيقظ بعد أن يكون هو قطع الجلسة (ونحصل على 187 بدل سبب حقيقي). أدنى من هذا تبدأ # إعادة اتصال كل سكّة صغيرة، وصمت تيك توك حول جولة PK يقيس ثوانٍ لا عشرات الثواني. raw = os.getenv('SOURCE_STALL_TIMEOUT') if raw is None or raw == '': raw = os.getenv('YOUTUBE_SOURCE_STALL_SECONDS', '12') return max(0.0, float(raw)) def _stream_tuning(self): """ما يعادله في هذه الشجرة لخيارات Streamlink (المشروع لا يستعمل Streamlink أصلًا): --stream-timeout → read_timeout (curl_cffi يرمي ReadTimeout بدل التعليق) --stream-segment-attempts → retries (محاولات لكل قراءة قبل إعلان التوقف) --stream-segment-timeout → total_timeout (سقف الجلسة كاملة: لا تعليق بلا نهاية) لا تُمرَّر أي خيار لبرنامج غير مثبت؛ لا streamlink في requirements.txt ولا في الصورة. """ return (max(5.0, float(os.getenv('YOUTUBE_SOURCE_READ_TIMEOUT', '15'))), max(1, int(os.getenv('YOUTUBE_SOURCE_READ_ATTEMPTS', '3'))), max(30.0, float(os.getenv('YOUTUBE_SESSION_MAX_SECONDS', '21600')))) @staticmethod def _write_deadline(stdin, buf, deadline): """write على stdin مع مهلة: أنبوب ممتلئ يجب ألّا يُعلّق الخيط إلى الأبد. الوضع المحجوز وحده يجعل «المصدر صامت + FFmpeg لا يقرأ» حالة لا تنتهي: الخيط يبقى داخل write، والحارس لا يرى جديدًا لأن آخر بايت سُجِّل قبل الانسداد. هنا نكتب بقدر ما يقبل الأنبوب، وننتظر بفارغ الصبر حتى deadline، ثم نعلن التوقف فيستيقظ الحارس. """ fd = stdin.fileno() flags = fcntl.fcntl(fd, fcntl.F_GETFL) try: fcntl.fcntl(fd, fcntl.F_SETFL, flags | os.O_NONBLOCK) view = memoryview(buf) while view: try: n = stdin.write(view) except BlockingIOError: n = 0 if n: view = view[n:] continue left = deadline - time.monotonic() if left <= 0: raise SourceStalled('أنبوب FFmpeg ممتلئ ولا يقرأ منذ %.0f ث' % max(0.0, -left)) select.select([], [fd], [], min(0.5, left)) finally: try: fcntl.fcntl(fd, fcntl.F_SETFL, flags) # نُنظّف: نُبقي الوضع محجوزًا كسابق عهده except OSError: pass @staticmethod def _is_timeout(e): n = type(e).__name__.lower() return 'timeout' in n or 'timed out' in str(e).lower() def _chunk_reader(self, it, out): """يقرأ قطعة واحدة من الاستجابة في خيط منفصل ويضعها في طابور بحجم 1. الضرورة: `next()` على مقبس صامت ينام حتى read_timeout (15ث افتراضيًا)، وقد تكون أطول من مهلة الحارس نفسها، فيبقى خيط الضخّ حيًا بعد teardown وتُترك العملية وحيدة. """ try: out.put(next(it)) except StopIteration: out.put(None) except BaseException as e: # تُعاد رفعها في خيط الضخّ لتُصنَّف هناك out.put(e) def _pump_source(self, response, p, bridge, stop, sess, read_timeout, retries): """نقل بايتات تيك توك إلى FFmpeg في خيط مستقل، مع تسجيل زمن آخر وصول فعلي. القراءة هنا هي مصدر الحقيقة: `poll()` الخاص بـ FFmpeg يبقى ناجحًا وهو جالس ينتظر stdin، ويوتيوب يبقى مستقبِلًا على آخر ما وصل — لذا يُقاس تدفق البيانات لا حالة العملية. """ it = response.iter_content(None).__iter__() deadline = time.monotonic() + sess['max_seconds'] chunk_wait = min(read_timeout, max(1.0, self._stall_seconds() / 3.0)) if self._stall_seconds() else read_timeout pending = None reader = None while not stop.is_set() and not sess['force_stop'] and not sess.get('swap_source'): if time.monotonic() > deadline: sess['error'] = 'انتهت مهلة الجلسة القصوى (%ds)' % int(sess['max_seconds']) return if pending is None: if reader is not None and reader.is_alive(): # لا قراءتين متوازيتين على نفس المولّد (ليس خيط-آمن): ننتظر دوره قليلًا time.sleep(0.2) continue box = queue.Queue(1) reader = threading.Thread(target=self._chunk_reader, args=(it, box), daemon=True) reader.start() pending = box try: got = pending.get(timeout=chunk_wait) except queue.Empty: silent = time.monotonic() - sess['last'] if self._stall_seconds() and silent > self._stall_seconds(): sess['error'] = 'صمت من تيك توك (%.0f ث بلا بايت)' % silent return continue pending = None if isinstance(got, BaseException): e = got if self._is_timeout(e) and not sess['force_stop']: if retries and sess['timeouts'] < retries: sess['timeouts'] += 1 continue # timeout قصير: نعيد المحاولة بدل قتل بثٍّ يعمل sess['error'] = 'انتهت مهلة قراءة المصدر (%ds × %d)' % (int(read_timeout), retries) return sess['error'] = 'خطأ قراءة من تيك توك (%s: %s)' % (type(e).__name__, str(e)[:120]) return if got is None: sess['ended'] = True # المصدر أغلق الاستجابة = انتهى البث/تجدد الرابط return chunk = got sess['timeouts'] = 0 if not chunk: continue sess['last'] = time.monotonic() with self.lock: self.data['source_bytes'] += len(chunk) self.data['last_source_at'] = sess['last'] if p.stdin is None: continue # لا أنبوب (HLS يقرأ بنفسه): الزمن وحده هو ما يُسجَّل stall_limit = self._stall_seconds() try: buf = bridge.feed(chunk) if not buf: continue if stall_limit: self._write_deadline(p.stdin, buf, sess['last'] + stall_limit) else: view = memoryview(buf) while view and not stop.is_set() and not sess['force_stop']: n = p.stdin.write(view) if not n: raise BrokenPipeError() view = view[n:] except SourceStalled as e: # الانسداد توقفُ مصدر مثلُه تمامًا: نسمّيه ونخرج ليقوم الحارس بالترتيب. sess['error'] = str(e) return except (BrokenPipeError, OSError, ValueError): return # FFmpeg هو من مات؛ الحلقة الرئيسية تتصرف except FormatChanged: sess['format_changed'] = True return def _try_reattach(self, user, p, bridge, sess, stop, refresh, read_timeout, retries, response, pump): """Close only the TikTok HTTP; keep FFmpeg stdin so YouTube does not see a new ingest. Returns (new_response, new_pump) or None. Viewer cuts come from killing FFmpeg, not from a 1–2 s TikTok URL refresh into the same process. """ if not refresh or p is None or p.stdin is None or p.poll() is not None: return None if int(sess.get('reattaches') or 0) >= 24: return None sess['swapping'] = True sess['swap_source'] = True sess['swap_started'] = time.monotonic() try: if response: try: response.close() except (OSError, ValueError): pass if pump is not None: pump.join(timeout=float(os.getenv('YOUTUBE_PUMP_JOIN_SECONDS', '2'))) try: cand = refresh() except Exception as e: self.log(user, '[RELAY] تعذر رصد مصدر بديل دون قطع يوتيوب (%s)' % type(e).__name__) return None if not cand or cand.get('media') == 'hls' or not cand.get('url'): return None try: new_resp = requests.get(cand['url'], headers={'Referer': 'https://www.tiktok.com/', **self.headers_for(user)}, impersonate='chrome', stream=True, timeout=(5, min(8, read_timeout or 8))) new_resp.raise_for_status() except Exception as e: self.log(user, '[RELAY] فشل فتح مصدر تيك توك البديل (%s)' % type(e).__name__) return None bridge.reconnect() sess['ended'] = False sess['error'] = '' sess['stall_reason'] = '' sess['force_stop'] = False sess['timeouts'] = 0 # Do not bump sess['last'] here: that hid 40–57s of silence from the # 12s stall watchdog (measured @vimtoo.2: out frozen, age 42–57, yh still good). sess['reattaches'] = int(sess.get('reattaches') or 0) + 1 self.current_candidate = cand self.set(source=cand.get('label') or cand.get('brief') or '', stalled=False) new_pump = threading.Thread(target=self._pump_source, args=(new_resp, p, bridge, stop, sess, read_timeout, retries), daemon=True) new_pump.start() self.log(user, '[RELAY] أُعيد توصيل تيك توك على نفس جلسة يوتيوب — بلا قتل FFmpeg') return new_resp, new_pump finally: sess['swap_source'] = False sess['swapping'] = False def _teardown(self, user, p, response, sess, stop, reason): """إنهاء مرتب — FFmpeg أولًا ثم الأنبوب ثم المصدر، مع wait محدود ثم kill. الترتيب مقصود: إغلاق stdin يخبر FFmpeg أن الإدخال انتهى فيتوقف بلطف ويُنهي ما في مخزنه؛ لو قتلنا FFmpeg أولًا وبقيت الاستجابة مفتوحة بقي الخيط القارئ معلقًا (وهو بالضبط ما كان يُبقي جلسة ميتة محتلةً لمكان الحدث). """ sess['force_stop'] = True # Do NOT set the supervisor `stop` Event here. That Event means "end the # whole account thread" (user stop / finish_event). Setting it on every # stall/format-change made sender_loop return, occupy a new FFmpeg, and # flash the YouTube spinner (measured on On @aboodi1994: age≈12s → rst++). # The pump watches sess['force_stop'] + stdin close. if p is not None: try: if p.stdin: p.stdin.close() except (OSError, ValueError): pass try: if response: response.close() # يفكّ التعليق داخل iter_content/read except (OSError, ValueError): pass codes = [] if p is not None: try: if p.poll() is None: p.terminate() except OSError: pass # عند صمت المصدر لا فائدة من انتظار «إنهاء لطيف» طويل: stdin مغلق ولا بيانات تُدفَّق. grace = float(os.getenv('YOUTUBE_KILL_GRACE_SECONDS', '10')) if sess.get('stall_reason') or sess.get('ended'): grace = min(grace, 2.0) try: codes.append(p.wait(timeout=grace)) except subprocess.TimeoutExpired: try: p.kill() except OSError: pass try: # SIGKILL لا يُقاوَم إلا في IO غير قابل للإيقاف؛ 3 ث تكفي والحارس يوثّق ما بعدها. codes.append(p.wait(timeout=3)) except subprocess.TimeoutExpired: sess['orphan'] = True # عملية لم تُقْبَر: لا يجوز أن تُنسى بصمت self.log(user, '[CLEANUP] ⚠ FFmpeg لم ينتهِ بعد kill؛ ستُراجع العملية في الدورة التالية (%s)' % reason) with self.lock: self.process = None # الرمز يبقى في الحالة بعد انتهاء الجلسة: المشرف يحتاجه ليميز «يوتيوب رفض الاستقبال» # (187/قطع من الخادم) عن صمت المصدر — الأول يستحق إبطاء الوتيرة لا تسريعها. self.last_exit_code = codes[0] if codes else None # الأخطاء تُنسخ في قارئ stderr أثناء الجلسة لا هنا: raw_tail/diagnostics محليّان داخل # send()، وأي إشارة لهما من _teardown ترفع NameError تُسقط بقية التفكيك والـset(). # كم كان المصدر صامتًا لحظة النهاية؟ بلا هذا القياس يُحسب كل قفل ذنبًا للوجهة، بينما # أكثر ما يحدث أن يوتيوب أقفل لأنه لم يعد تصله بايتات (مقيس: 13-14 ث بعد صمت المصدر). # لا معنى للقياس في HLS (لا استجابة عندنا يقرأها الحارس) فيبقى صفرا. if self.sticky_mode and not self._recovering_copy: try: self._last_light_output=max(float(self._last_light_output or 0), float(self.data.get('output_seconds') or 0)) except Exception: pass self.last_source_gap = round(max(0.0, time.monotonic() - sess['last']), 1) \ if (sess.get('src_metered') and sess.get('last')) else 0.0 self.set(status='', stalled=bool(sess.get('stall_reason') or sess.get('error')), note=reason, source_gap=self.last_source_gap, ffmpeg_errors=list(self.last_errors), ffmpeg_diagnostics=list(self.last_diagnostics)[-3:]) codes = [c for c in codes if c] self.log(user, '[CLEANUP] أُوقف FFmpeg (%s%s)' % (reason, '؛ رمز الخروج ' + ','.join(map(str, codes)) if codes else '')) def send(self, user, candidate, destination, stop, refresh=None): """Push one rendition until it dies, the source stalls, or `stop` is set. الإشراف هنا على **البيانات** لا على العمليات: FFmpeg يبقى حيًا ومسرورًا وهو جالس ينتظر stdin، ويوتيوب يبقى مستقبِلًا على آخر ثانية وصلته، فيبدو البث «معلقًا» للأبد. لذا: خيط قراءة يسجّل آخر بايت، وحارس يقارن الزمن، وteardown مرتب، ثم رجوع إلى حلقة الإشراف في `sender_loop` التي تُعيد رصد LIVE وتبني جلسة جديدة من الصفر. """ self.current_candidate = candidate self.lock_gold(candidate) if self.hevc_payload(candidate) and self.sticky_mode not in ('matchgop','fixed720','fixed1080'): ok=True try: from ingest import hub ok=hub.light_available() except Exception: ok=True if not ok: raise RelayStartError('HEVC يحتاج ترميز وخيارات CPU ممتلئة') self.sticky_mode='matchgop' self.sticky_since=time.monotonic() self._recovering_copy=False guard = os.getenv('YOUTUBE_FORMAT_GUARD', 'on').lower() in ('1', 'on', 'true', 'yes') hls = (candidate or {}).get('media') == 'hls' bridge = FLVBridge(detect_format_change=(self.send_mode() == 'copy' and guard and not hls)) response = None p = None error_reader = None done = threading.Event() progress = {'last': time.monotonic(), 'seconds': -1} pump = None diagnostics = [] raw_tail = [] # آخر سطور stderr بعد الإخفاء: تُطبع عند الخروج، لا تُخزَّن خامًا read_timeout, retries, max_seconds = self._stream_tuning() sess = {'last': time.monotonic(), 'ended': False, 'error': '', 'format_changed': False, 'src_metered': False, 'force_stop': False, 'timeouts': 0, 'orphan': False, 'stable_notified': False, 'max_seconds': max_seconds, 'stall_reason': '', 'spawned': False, 'spawn_error': '', 'ff_last': time.monotonic()} self.set(status='الاتصال بيوتيوب', source=candidate['label'], output_seconds=0, last_output_at=None, stalled=False, last_source_at=sess['last'], source_bytes=0) with self.lock: self.session = sess try: sess['src_metered'] = not hls # HLS: FFmpeg يقرأ القائمة، فلا عدّاد مصدر لنا args = self.command(destination, candidate) if hls: # noqa: E999 — HLS: بلا أنبوب stdin # FFmpeg يفتح القائمة بنفسه: لا HTTP عندنا ولا ضخّ على stdin ⇒ الحارس هنا # هو تقدّم FFmpeg نفسه (out_time)، لأن لا مصدر بايتات ثانٍ نقيسه. p = subprocess.Popen(args, stdin=None, stdout=subprocess.PIPE, stderr=subprocess.PIPE) else: response = requests.get(candidate['url'], headers={'Referer': 'https://www.tiktok.com/', **self.headers_for(user)}, impersonate='chrome', stream=True, timeout=(10, read_timeout)) response.raise_for_status() p = subprocess.Popen(args, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, bufsize=0) sess['spawned'] = True sess['spawned_at'] = time.monotonic() with self.lock: self.process = p self.log(user, '[RELAY] بدء FFmpeg ← %s (%s)' % (candidate['label'], 'إعلان Enhanced-RTMP: hvc1' if '-rtmp_enhanced_codecs' in ' '.join(args) else 'FLV تقليدي: لا إعلان hvc1')) # لا إعادة ترميز في هذا الوضع: انقطاع copy لا يترك عملية ورائها def read_errors(): # يصنّف أخطاء FFmpeg المختارة؛ لا يُسرّب stderr خامًا ولا روابط البث — الذيل # يُخفى مفتاحه ورابطه قبل أي تخزين أو طباعة. try: for line in iter(p.stderr.readline, b''): text = line.decode('utf-8', 'replace') label = classify_ffmpeg_error(text) if label and label not in diagnostics: diagnostics.append(label) self.last_diagnostics = list(diagnostics) if label or _error_interesting(text): safe = redact_stderr(text) if safe: raw_tail.append(safe) self.last_errors = list(raw_tail)[-4:] if len(raw_tail) > 60: # جلسة طويلة بإعادة اتصال متكرر: الذيل لا ينمو بلا سقف، وما # يهمّ المشرف هو آخر الرسائل لا أقدمها. del raw_tail[:40] except (OSError, ValueError): pass error_reader = threading.Thread(target=read_errors, daemon=True) error_reader.start() def read_progress(): try: for line in iter(p.stdout.readline, b''): if line.startswith(b'out_time_us='): try: seconds = int(line.split(b'=', 1)[1]) / 1000000 except ValueError: continue if seconds > progress['seconds']: progress['seconds'] = seconds progress['last'] = time.monotonic() sess['ff_last'] = time.monotonic() # ليس دليلاً على المصدر إلا في HLS sess['reattaches'] = 0 self.set(status='FFmpeg يرسل — تحقق من معاينة YouTube Studio', output_seconds=round(seconds, 1), last_output_at=time.time(), stalled=False) # «استقرار» مرة واحدة لكل جلسة: ثوانٍ من التدفق المقبول تعني أن الحافة لم تعد ترفضنا، # فلا معنى لبقاء نافذة العقاب ولا لملاحظتها على اللوحة حتى تموت الجلسة (وهو ما كان يحدث). if not sess.get('stable_notified') and seconds >= float(os.getenv('YOUTUBE_STABLE_SECONDS', '25')): sess['stable_notified'] = True cb = getattr(self, 'on_stable', None) if cb: try: cb(user) except Exception as e: # قرار المشرف لا يجوز أن يقتل بثًا يعمل self.log(user, '[WATCHDOG] فشل مُبلِّغ الاستقرار: ' + str(e)[:80]) except (OSError, ValueError): pass threading.Thread(target=read_progress, daemon=True).start() pump = None if response is not None: pump = threading.Thread(target=self._pump_source, args=(response, p, bridge, stop, sess, read_timeout, retries), daemon=True) pump.start() # ---- الحارس: لا تعتمد على poll() ولا على رمز الخروج ---- stall_limit = self._stall_seconds() progress_limit = max(30.0, float(os.getenv('YOUTUBE_PROGRESS_STALL_SECONDS', '60'))) next_report = 0.0 while not stop.is_set(): now = time.monotonic() # الدليل على أن المصدر لم يصمت هو بايتات تيك توك نفسها. تقدّم FFmpeg وحده لا # يكفي: في وضع النسخ يفرّغ المخزن الداخلي لدقائق بعد صمت المصدر، فيبدو البث # حيًا ويوتيوب يبقى على آخر ثانية — وهذا هو التعليق الذي شكا منه المستخدم. # في HLS يستحيل القياس إلا على FFmpeg (هو من يفتح القائمة)، فنقبل تقدّمه. _fresh = (sess['ff_last'] if response is None else sess['last']) swap_for = (now - float(sess.get('swap_started') or 0)) if sess.get('swapping') else 0.0 # swapping must not disable the stall watchdog for longer than the stall # limit: refresh()+HTTP open was measured at 40–57s of frozen viewers. if self._recovering_copy: ran=now-float(sess.get('spawned_at') or now) if ran>12 and progress['seconds']<0.5: self.copy_recovery_fails+=1 self._recovering_copy=False self.log(user,'[RECOVERY] COPY produced no output in %.0fs; staying on %s (fail %d)'%( ran, self.sticky_mode or 'light', self.copy_recovery_fails)) raise SourceStalled('COPY recovery produced no output; reverting to light') if progress['seconds']>=5: self.log(user,'[RECOVERY] COPY output verified (%.1fs); leaving light sticky'%progress['seconds']) self.sticky_mode=None self.sticky_since=0.0 self._recovering_copy=False if stall_limit and now - _fresh > 3 and not sess.get('swapping') and not sess.get('swap_source'): attached = self._try_reattach(user, p, bridge, sess, stop, refresh, read_timeout, retries, response, pump) if attached: response, pump = attached continue if stall_limit and now - _fresh > stall_limit and (not sess.get('swapping') or swap_for > stall_limit): attached = self._try_reattach(user, p, bridge, sess, stop, refresh, read_timeout, retries, response, pump) if attached: response, pump = attached continue # نُفيق الخيط أولًا (قد يكون محبوسًا في write على أنبوب ممتلئ)، ثم نرفع: # إغلاق stdin يجعل FFmpeg يرى EOF ويتوقف بلطف بدل SIGKILL. sess['force_stop'] = True if p.stdin: try: p.stdin.close() except (OSError, ValueError): pass raise SourceStalled('انقطع تدفق المصدر منذ %.0f ث (FFmpeg ما زال حيًا، ' 'ويوتيوب يبقى على آخر ثانية وصلته)' % (now - _fresh)) rc = p.poll() if rc is not None: if sess['format_changed']: raise FormatChanged() if not sess['ended'] and not stop.is_set() and rc: gap = max(0.0, time.monotonic() - sess['last']) if sess.get('src_metered') else 0.0 suspect = float(os.getenv('YOUTUBE_SOURCE_GAP_SUSPECT_SECONDS', '8')) blame = ('؛ المصدر كان صامتًا %.0f ث قبل القفل — المرجّح جوع التغذية لا رفض المستقبِل' % gap) if gap >= suspect else '' # «لم يظهر سبب مصنّف» لا يعني أن FFmpeg سكت: قد يكون قال شيئًا ليس في القائمة، # لذا تُطبع آخر رسالة بعد الإخفاء دائمًا إن وُجدت — هي وحدها ما يفرّق بين # «يوتيوب رفض المفتاح» و«توقيتنا فاسد» و«انتهت الصورة قبل الإرسال». tail = (' | آخر رسالة FFmpeg: ' + raw_tail[-1]) if raw_tail else '' self.log(user, 'FFmpeg خرج برمز %s%s%s%s' % ( rc, ' — ' + '؛ '.join(diagnostics[-3:]) if diagnostics else '؛ لم يظهر سبب مصنّف', blame, tail)) break if now - progress['last'] > progress_limit: raise SourceStalled('لم يتقدّم FFmpeg منذ %.0f ث' % (now - progress['last'])) if sess['ended'] and not sess['error']: self.log(user, '[MONITOR] أغلق تيك توك الاستجابة؛ الجلسة تُعاد من جديد') break if sess['error']: raise SourceStalled(sess['error']) if response is not None and now >= next_report: # بمعدل مضبوط: لا logging لكل بايت (كان سيملأ السجل في دقائق). next_report = now + max(15, int(os.getenv('YOUTUBE_WATCHDOG_REPORT_SECONDS', '60'))) self.log(user, '[WATCHDOG] المصدر يعمل؛ آخر بايت قبل %.0f ث، خرج %.1f ث' % (now - sess['last'], max(0, progress['seconds']))) if pump is not None and not pump.is_alive() and response is not None and not stop.is_set(): if sess['force_stop'] or sess['error'] or sess['ended']: break time.sleep(1) except (OSError, ValueError) as e: if p is None: sess['spawn_error'] = 'تعذر بدء FFmpeg/المصدر (%s)' % type(e).__name__ self.log(user, '[RELAY] فشل بدء الإرسال: %s' % sess['spawn_error']) raise except FormatChanged: sess['format_changed'] = True raise except SourceStalled as e: sess['stall_reason'] = str(e) self.log(user, '[WATCHDOG] توقف المصدر: %s' % e) raise finally: done.set() if p is None: # لا شيء لنُنهيّه: إما أن FFmpeg لم يولد أو أن الاستجابة رفضت قبل ذلك. try: if response: response.close() except (OSError, ValueError): pass with self.lock: self.session = None self.set(status='', stalled=False, note='لم يبدأ FFmpeg أصلًا') raise RelayStartError(sess.get('spawn_error') or 'تعذر بدء جلسة الإرسال') _why = sess.get('stall_reason') or sess.get('error') or ('تغيّر إعداد المصدر' if sess['format_changed'] else 'إيقاف عادي') self._teardown(user, p, response, sess, stop, _why) if error_reader: error_reader.join(timeout=1) if pump: # مهلة قصيرة عمدًا: الخيط قد يكون محبوسًا في next() على مقبس مُغلق؛ لا معنى # لتعليق الإشراف كله لأجله — FFmpeg أُقرِت والطرف القارئ أُغلق. pump.join(timeout=float(os.getenv('YOUTUBE_PUMP_JOIN_SECONDS', '2'))) if pump.is_alive(): sess['orphan'] = True self.log(user, '[CLEANUP] ⚠ خيط القراءة ما زال يعمل؛ سيُترك كـ daemon ويُعاد الرصد') with self.lock: self.session = None if sess['orphan']: raise RuntimeError('بقيت عملية/خيط من جلسة سابقة؛ تُراجع قبل جلسة جديدة') return progress['seconds'] > 0
"""One FFmpeg push per live session. Multiple senders run concurrently, one per YouTube event."""
import fcntl, os, queue, re, select, threading, time, subprocess
from collections import deque
from curl_cffi import requests
from flv_bridge import FLVBridge, FormatChanged
# أخطاء FFmpeg ← وصف عربي. قائمة واحدة على مستوى الوحدة حتى تُختبر على سطور FFmpeg حقيقية
# بدل أن تُدفن في إغلاق داخل send(): الإغلاق هو ما أخفى أن كلمة المفتاح كُتبت بالخطأ.
FFMPEG_ERROR_LABELS = [
('Application defined reason', 'يوتيوب أرسل سبب الإغلاق من خادمه (رسالة RTMP)'),
('NetStream.Publish', 'يوتيوب رفض النشر على هذا المفتاح (NetStream.Publish)'),
('Publish stream', 'رفض خادم الاستقبال أمر النشر'),
('Connection refused', 'رفض اتصال خادم الاستقبال'),
('Connection timed out', 'انتهت مهلة اتصال خادم الاستقبال'),
('Connection reset by peer', 'خادم الاستقبال قطع الاتصال أثناء الإرسال'),
('Broken pipe', 'انقطع أنبوب الإرسال إلى خادم الاستقبال'),
('End of file', 'خادم الاستقبال أغلق الاتصال'),
('Immediate exit requested', 'طُلب إنهاء FFmpeg قبل اكتمال الإرسال'),
('Packet mismatch', 'عدم تطابق حزم الفيديو — تغيّر مقاس المصدر داخل الجلسة'),
('Input/output error', 'خطأ إدخال/إخراج في الإرسال'),
('Publishing stream at bitrates', 'يوتيوب قَبِل النشر فعلًا — فالقطع لاحقًا ليس رفض مفتاح'),
('Server error, Publish', 'خادم يوتيوب رفض أمر النشر على هذا المفتاح'),
('Server error', 'خادم الاستقبال أعاد خطأ'),
('Invalid data found', 'بيانات المصدر غير صالحة للقراءة'),
('Video codec', 'عدم توافق ترميز الفيديو مع الحاوية'),
('Invalid argument', 'أحد إعدادات FFmpeg غير مقبول'),
# FFmpeg يكتب Non-monotonous لا Non-monotonic؛ النمط الخاطئ كان يجعل «لم يظهر سبب مصنّف»
# عبارة كاذبة، لأن مشكلة التوقيت كانت تُرمى بصمت.
('Non-monotono', 'توقيت الفيديو غير متزايد (DTS) في التدفق الخارج'),
('input buffer overflow', 'امتلأ مخزن FFmpeg: المصدر أسرع من الإرسال أو الاتصال أبطأ'),
('Error writing packet', 'تعذّرت كتابة حزمة على الاتصال'),
('Unknown encoder', 'مرمز غير متوفر'),
('Option not found', 'خيار FFmpeg غير مدعوم'),
]
INFO_KEEP = ('publish', 'reason', 'handshak', 'connect', '_error', 'reject', 'closing',
'input/output', 'broken pipe', 'reset by peer', 'timed out', 'refused', 'server error',
'unable to open')
def _error_interesting(text):
"""ما يستحق البقاء من سطور FFmpeg: كل خطأ أو تحذير، أو سطر اتصال مفيد أثناء التشخيص
القائمة بيضاء عمدًا: مع `info` تفيض سطور FFmpeg بالترويسات والروابط، والسجل يجب أن يبقى
مقروءًا. وكل ما يبقى يمرّ بـ redact_stderr أولًا (يُمحى الرابط والمفتاح).
"""
low = (text or '').lower()
if 'error' in low or 'warning' in low:
return True
return any(w in low for w in INFO_KEEP)
def classify_ffmpeg_error(text):
"""أول وصف ينطبق على سطر من stderr، أو None. تصنيف نصي خالص بلا أي روابط."""
low = (text or '').lower()
for needle, label in FFMPEG_ERROR_LABELS:
if needle.lower() in low:
return label
return None
def redact_stderr(text):
"""يُبقي سبب الخطأ ويخفي كل ما لا يجوز قراءته في سجل عام: الروابط والمفاتيح والرموز."""
t = re.sub(r'\b(?:rtmps?|rtsp|srt|https?)://\S+', '«رابط-مخفي»', text or '')
t = re.sub(r'(?i)([?&=]|^|\s)((?:key|token|auth|sessionid|sign)\s*=\s*)[^\s&]+', r'\1\2«مخفي»', t)
return t.strip()[:240]
class SourceStalled(RuntimeError):
"""المصدر صامت: لا بايت من تيك توك منذ مهلة الحارس، أو لم يتقدّم FFmpeg.
يُرفع بدل التعليق إلى الأبد لأن FFmpeg الحيّ لا يعني بثًا حيًا: العملية تنتظر stdin
ويوتيوب يبقى مستقبِلًا على آخر ما وصل. يلتقطه sender_loop فيعيد رصد LIVE ويبني جلسة
جديدة من الصفر.
"""
class RelayStartError(RuntimeError):
"""لم تبدأ الجلسة أصلًا (FFmpeg لم يولد أو المصدر رفض قبل التدفق).
تُميَّز عن SourceStalled لأن العلاج مختلف: هنا يجب أن تُجرَّب تندرة أخرى/وضع آخر
بدل إعادة رصد نفس القائمة فورًا — وبكل حال لا تبقى عملية نصفية.
"""
class Sender:
"""Single YouTube RTMPS push for one session. Process and progress are instance-scoped,
so several senders can run at the same time without sharing state."""
def __init__(self,ffmpeg,log,headers_for=None):
self.ffmpeg=ffmpeg;self.log=log
self.headers_for=headers_for or (lambda user:{})
self.lock=threading.RLock();self.process=None
self.data={'status':'','source':'','output_seconds':0,'last_output_at':None}
self.last_exit_code=None # آخر رمز خروج FFmpeg (من آخر جلسة)، يقرؤه المشرف
self.last_errors=[] # آخر سطور stderr مصنّفة ومُخفًى منها المفتاح: لماذا أقفلت الوجهة؟
self.on_stable=None # مستقبِل المدير: أول ≥25 ث مُسلَّمة = العقاب انتهى
self.last_diagnostics=[] # آخر الأوصاف العربية المصنَّفة، تُعرض في اللوحة كما في السجل
self.last_source_gap=0.0 # صمت المصدر لحظة التفكيك: يفصل جوع المصدر عن رفض الوجهة
# Timestamps of source resolution changes seen by this sender (anti-flap window).
self.flap=deque()
# Once the source proved to flap, stay on a constant canvas for the rest of the
# event. Without this the flap window expires after 10 quiet minutes and the