On deploy commited on
Commit
d6fd944
·
1 Parent(s): ecb535b

Use Tktktk engine as-is (copy-first, PK matchgop on first canvas).

Browse files
Files changed (6) hide show
  1. Dockerfile +5 -5
  2. README.md +73 -11
  3. app.py +7 -1
  4. relay.py +44 -35
  5. requirements.txt +1 -1
  6. youtube_manager.py +73 -37
Dockerfile CHANGED
@@ -4,7 +4,7 @@ RUN apt-get update && apt-get install -y --no-install-recommends ffmpeg ca-certi
4
  RUN ffmpeg -hide_banner -h protocol=rtmps 2>&1 | grep -q rtmp_enhanced_codecs
5
  WORKDIR /app
6
  COPY requirements.txt .
7
- RUN pip install --no-cache-dir -r requirements.txt
8
  COPY app.py relay.py youtube_api.py youtube_manager.py flv_bridge.py tiktok_auth.py ingest.py index.html ./
9
  COPY verify.sh verify_tokens.py probe_live.py test_watchdog.py test_lifecycle.py test_relay.py test_concurrency.py ./
10
 
@@ -24,17 +24,17 @@ ENV TZ=Asia/Baghdad \
24
  YOUTUBE_GOP=60 \
25
  YOUTUBE_INPUT_RECOVERY=1 \
26
  YOUTUBE_PREFER_H264=1 \
27
- YOUTUBE_CODEC_FALLBACK_MODE=fixed720 \
28
  YOUTUBE_RETRY_MIN=1 \
29
  YOUTUBE_RETRY_MAX=60 \
30
  YOUTUBE_SOURCE_LIMIT=6 \
31
  YOUTUBE_FORMAT_GUARD=on \
32
  YOUTUBE_FLAP_LIMIT=4 \
33
- YOUTUBE_FLAP_FALLBACK_MODE=fixed720 \
34
  YOUTUBE_X264_PRESET=veryfast \
35
  YOUTUBE_CRF=22 \
36
  YOUTUBE_FIFO_TIMESHIFT=0 \
37
- YOUTUBE_HEALTH_INTERVAL=180 \
38
  YOUTUBE_OBS_HOLD_SECONDS=900 \
39
  YOUTUBE_SOURCE_RETRY=15 \
40
  YOUTUBE_FORCE_GAP=5 \
@@ -49,7 +49,7 @@ ENV TZ=Asia/Baghdad \
49
  YOUTUBE_PUMP_JOIN_SECONDS=2 \
50
  YOUTUBE_AUTH_PAUSE_SECONDS=90 \
51
  YOUTUBE_SESSION_MAX_SECONDS=21600 \
52
- YOUTUBE_ENHANCED_RTMP=auto \
53
  YOUTUBE_SOURCE_GAP_SUSPECT_SECONDS=8 \
54
  TIKTOK_TT_TARGET_IDC=useast1a \
55
  STORAGE_WAIT_SECONDS=30 \
 
4
  RUN ffmpeg -hide_banner -h protocol=rtmps 2>&1 | grep -q rtmp_enhanced_codecs
5
  WORKDIR /app
6
  COPY requirements.txt .
7
+ RUN pip install --no-cache-dir -U -r requirements.txt
8
  COPY app.py relay.py youtube_api.py youtube_manager.py flv_bridge.py tiktok_auth.py ingest.py index.html ./
9
  COPY verify.sh verify_tokens.py probe_live.py test_watchdog.py test_lifecycle.py test_relay.py test_concurrency.py ./
10
 
 
24
  YOUTUBE_GOP=60 \
25
  YOUTUBE_INPUT_RECOVERY=1 \
26
  YOUTUBE_PREFER_H264=1 \
27
+ YOUTUBE_CODEC_FALLBACK_MODE=matchgop \
28
  YOUTUBE_RETRY_MIN=1 \
29
  YOUTUBE_RETRY_MAX=60 \
30
  YOUTUBE_SOURCE_LIMIT=6 \
31
  YOUTUBE_FORMAT_GUARD=on \
32
  YOUTUBE_FLAP_LIMIT=4 \
33
+ YOUTUBE_FLAP_FALLBACK_MODE=matchgop \
34
  YOUTUBE_X264_PRESET=veryfast \
35
  YOUTUBE_CRF=22 \
36
  YOUTUBE_FIFO_TIMESHIFT=0 \
37
+ YOUTUBE_HEALTH_INTERVAL=60 \
38
  YOUTUBE_OBS_HOLD_SECONDS=900 \
39
  YOUTUBE_SOURCE_RETRY=15 \
40
  YOUTUBE_FORCE_GAP=5 \
 
49
  YOUTUBE_PUMP_JOIN_SECONDS=2 \
50
  YOUTUBE_AUTH_PAUSE_SECONDS=90 \
51
  YOUTUBE_SESSION_MAX_SECONDS=21600 \
52
+ YOUTUBE_ENHANCED_RTMP=off \
53
  YOUTUBE_SOURCE_GAP_SUSPECT_SECONDS=8 \
54
  TIKTOK_TT_TARGET_IDC=useast1a \
55
  STORAGE_WAIT_SECONDS=30 \
README.md CHANGED
@@ -8,28 +8,90 @@ pinned: false
8
  app_port: 7860
9
  ---
10
 
11
- # Reoo88/On — نفس محرك Tktktk (relay-v2.9-confirm)
 
 
 
12
 
13
- سبيس ثانٍ لنفس المشروع: رصد تيك توك → FFmpeg → YouTube RTMPS.
14
  **لا تسجيل. لا أرشيف. لا ملفات فيديو على القرص.**
15
 
16
  ```
17
  TikTok LIVE
18
  → اكتشاف الحساب
19
- → مصدر مستقل لكل مذيع (H264/FLV أولاً)
20
  → FFmpeg (stream copy إن أمكن)
21
- → YouTube RTMPS (OAuth لكل حساب، أو مفتاح بيئة واحد فقط)
 
 
 
 
 
 
 
 
 
 
 
22
  ```
23
 
24
- ## سقف التزامن
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
25
 
26
- `MAX_CONCURRENT_RELAYS=5` و `YOUTUBE_MAX_EVENTS=5` في الصورة.
27
- عطل مذيع لا يوقف الباقين. مفتاح RTMPS البيئي واحد = ناشر واحد.
28
 
29
- ## تنبيه التشغيل جنبًا إلى جنب مع Tktktk
30
 
31
- هذه نسخة ثانية من المحرك. إذا فُعّلت أتمتة OAuth هنا **وعلى** `Reoo88/Tktktk` بنفس قناة يوتيوب، قد يُفتح حدثان لنفس المذيع على نفس الحساب. شغّل الأتمتة في سبيس واحد لكل قناة، أو استخدم قناة/مفاتيح مختلفة.
32
 
33
- المطلوب للتشغيل: `PASSWORD` (HTTP Basic، المستخدم `admin`). OAuth اختياري للعنوان؛ الفيديو يعمل بـ RTMPS.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
34
 
35
- `GET /health` عام. لا تضع توكنات في Git.
 
8
  app_port: 7860
9
  ---
10
 
11
+ # TikTok Live Monitor → Direct Relay → YouTube
12
+
13
+ رصد مستمر لحسابات تيك توك. عند LIVE يُفتح Relay عبر FFmpeg إلى YouTube RTMPS.
14
+ عند انتهاء البث يُغلق Relay فعليًا ويعود الرصد.
15
 
 
16
  **لا تسجيل. لا أرشيف. لا ملفات فيديو على القرص.**
17
 
18
  ```
19
  TikTok LIVE
20
  → اكتشاف الحساب
21
+ → اختيار مصدر مستقر (H264/FLV أولاً، الباقي احتياط)
22
  → FFmpeg (stream copy إن أمكن)
23
+ → YouTube RTMPS
24
+ ```
25
+
26
+ المسار: TikTok → ذاكرة/أنبوب/شبكة → FFmpeg → YouTube.
27
+
28
+ ## التشغيل
29
+
30
+ مطلوب متغير `PASSWORD` (حماية HTTP Basic، المستخدم ثابت: `admin`).
31
+
32
+ ```bash
33
+ export PASSWORD=...
34
+ uvicorn app:app --host 0.0.0.0 --port 7860
35
  ```
36
 
37
+ أو عبر Docker / Hugging Face Space (sdk: docker).
38
+
39
+ ## ماذا يفعل النظام
40
+
41
+ 1. **Monitor** مستقل لكل حساب: `OFFLINE → LIVE candidate → confirmation → START RELAY`.
42
+ 2. **Source selection** لكل مذيع على حدة: كل المصادر تُستخرج (codec / دقة / bitrate / نوع النقل). الأولوية: مصدر قابل للـrelay، ثم codec متوافق مع يوتيوب (H264)، ثم الجودة. HEVC لا يُحذف — يُستخدم كاحتياط.
43
+ 3. **Watchdog** على تدفق البيانات لا على `poll()` فقط. إذا صمت المصدر `SOURCE_STALL_TIMEOUT` ثانية يُعتبر stalled، يُنظَّف FFmpeg، ويُجرَّب المصدر التالي أو يُعاد الرصد.
44
+ 4. **Cleanup إلزامي**: إيقاف المصدر، إغلاق الأنبوب، terminate ثم kill، بلا orphan.
45
+ 5. **YouTube** يفتح مع LIVE ويُغلق بعد تأكيد Offline. كل جلسة LIVE جديدة تحصل على عنوان بتاريخ/وقت بغداد للبداية الفعلية.
46
+ 6. حساب واحد لا يشغّل أكثر من Relay. عطل مذيع لا يوقف الباقين.
47
+
48
+ ## متغيرات البيئة
49
+
50
+ | المتغير | الافتراضي | المعنى |
51
+ |---|---|---|
52
+ | `PASSWORD` | *(إلزامي)* | كلمة مرور الواجهة (المستخدم `admin`) |
53
+ | `CHECK_INTERVAL` | `20` | ثانية بين دورات الرصد للحسابات غير المباشرة |
54
+ | `SOURCE_STALL_TIMEOUT` | `45` | ثانية بلا بايت من المصدر = stalled |
55
+ | `YOUTUBE_RTMP_URL` | — | عنوان ingest (مثال `rtmps://a.rtmps.youtube.com:443/live2`) — مسار الفيديو لا يحتاج OAuth |
56
+ | `YOUTUBE_STREAM_KEY` | — | مفتاح البث. مفتاح واحد = ناشر واحد في نفس الوقت |
57
+ | `YOUTUBE_TITLE_TEMPLATE` | `{broadcaster} \| {date} {time}` | عنوان يوتيوب؛ `{date}`=`YYYY-MM-DD`، `{time}`=`HH:mm` بتوقيت `Asia/Baghdad` لحظة بدء جلسة تيك توك. التحديث عبر OAuth فقط؛ فشل العنوان لا يوقف الفيديو |
58
+ | `DATA_DIR` | `/data/tiktok-relay` | مجلد الحالة (حسابات، توكنات، دفتر يوتيوب) — ليس فيديو |
59
+ | `MAX_ACCOUNTS` | بلا حد | سقف الحسابات |
60
+ | `YOUTUBE_SEND_MODE` | `auto` | `auto` / `copy` / `fixed720` / `fixed1080` |
61
+ | `YOUTUBE_VIDEO_MODE` | `original` | `original` يبقي HEVC كاحتياط؛ `h264` يصفّي |
62
+ | `YOUTUBE_PREFER_H264` | `1` | تقديم H264 على HEVC لنفس الجلسة |
63
+ | `YOUTUBE_END_GRACE` | `40` | تأكيد Offline قبل إغلاق حدث يوتيوب |
64
+ | `YOUTUBE_RETRY_MIN` / `YOUTUBE_RETRY_MAX` | `1` / `60` | backoff |
65
+ | `YOUTUBE_SOURCE_READ_TIMEOUT` | `15` | مهلة قراءة المصدر (لا تعليق أبدي على `iter_content`) |
66
+ | `TIKTOK_SESSIONID` | — | كوكيز جلسة لفتح غرف 18+ |
67
+ | `GOOGLE_CLIENT_ID` / `GOOGLE_CLIENT_SECRET` / `YOUTUBE_REFRESH_TOKEN` | — | OAuth يوتيوب |
68
 
69
+ لا تضع كلمة المرور أو التوكنات داخل الكود أو Git.
 
70
 
71
+ ## الواجهة
72
 
73
+ ثلاثة أقسام فقط:
74
 
75
+ - **Accounts** — الاسم، الحالة، LIVE منذ، المصدر، الجودة، codec
76
+ - **YouTube** — الاتصال، حالة البث، العنوان الحالي، وقت البدء
77
+ - **System** — Monitoring، عدد الحسابات، Relay active، آخر خطأ، سجل حي (آخر ~100 حدث في الذاكرة)
78
+
79
+ لا يوجد سجل بثوث محفوظ ولا تنزيل ملفات.
80
+
81
+ ## الصحة
82
+
83
+ `GET /health` بدون مصادقة:
84
+
85
+ ```json
86
+ {"application":"running","monitor":"running","accounts":N,"active_relays":N,"last_monitor_cycle":...}
87
+ ```
88
+
89
+ `GET /api/health` خلف Basic Auth ويضيف `last_error` لكل مذيع.
90
+
91
+ ## الاختبار
92
+
93
+ ```bash
94
+ python3 test_relay.py
95
+ ```
96
 
97
+ اختبارات FFmpeg الحقيقية تحتاج `ffmpeg` محليًا أو داخل صورة Docker.
app.py CHANGED
@@ -369,7 +369,13 @@ def rank_sources(source):
369
  compat=2 if h264 else (1 if not hevc else 0)
370
  # Extreme bitrates often stall FFmpeg/YouTube on small hosts.
371
  rate_score=rate if rate<=6500 else max(0,13000-rate)
372
- score=(flv, compat, quality, pixels, rate_score, not assumed)
 
 
 
 
 
 
373
  item={'url':url,'media':media,'codec':codec,'quality_name':str(label),
374
  'resolution':res,'width':width,'height':height,'bitrate':rate,
375
  'label':str(label)+((' · '+res) if res else '')+' · '+(codec or 'غير محدد')+((' · '+media.upper()) if media!='flv' else ''),
 
369
  compat=2 if h264 else (1 if not hevc else 0)
370
  # Extreme bitrates often stall FFmpeg/YouTube on small hosts.
371
  rate_score=rate if rate<=6500 else max(0,13000-rate)
372
+ # Recorder idea (tiktoklive_monitor / TikTokLive origin): the file looks
373
+ # sharp because it pulls `origin`. Live YouTube cannot copy HEVC, so:
374
+ # decent H264 (≥720 short side) still wins for copy; origin beats 640p H264.
375
+ origin=1 if str(label).lower() in ('origin','original','origion','uhd','uhd_60') else 0
376
+ short=min(width,height) if (width and height) else 0
377
+ decent_h264=1 if h264 and short>=720 else 0
378
+ score=(decent_h264, origin, pixels, flv, quality, rate_score, not assumed)
379
  item={'url':url,'media':media,'codec':codec,'quality_name':str(label),
380
  'resolution':res,'width':width,'height':height,'bitrate':rate,
381
  'label':str(label)+((' · '+res) if res else '')+' · '+(codec or 'غير محدد')+((' · '+media.upper()) if media!='flv' else ''),
relay.py CHANGED
@@ -104,9 +104,6 @@ class Sender:
104
  self.copy_recovery_fails=0
105
  self._recovering_copy=False
106
  self._last_light_output=0.0
107
- self._gop_w=0
108
- self._gop_h=0
109
- self._no_copy_recovery=False
110
  # Candidate handed to send_mode() so the codec rule can judge the real source.
111
  self.current_candidate=None
112
  # Journal setting wins over the environment so the mode can be changed from the UI
@@ -194,7 +191,7 @@ class Sender:
194
  now=time.monotonic()
195
  while flap and now-flap[0]>600:flap.popleft()
196
  if len(flap)>=int(os.getenv('YOUTUBE_FLAP_LIMIT','4')):
197
- mode=os.getenv('YOUTUBE_FLAP_FALLBACK_MODE','fixed720').strip().lower()
198
  if mode not in ('fixed1080','fixed720'):mode='fixed720'
199
  self.sticky_mode=mode
200
  self.sticky_since=time.monotonic()
@@ -206,9 +203,7 @@ class Sender:
206
  Isolated-handoff harness (SIMULATED): start copy, require bytes>0, then
207
  kill light — PASS. Naive sticky-clear on h264 label — the production bug.
208
  """
209
- # Default OFF: COPY after matchgop sends a new SPS on the same YouTube event.
210
- # The mobile app then flashes until the viewer force-closes it.
211
- if str(os.getenv('YOUTUBE_COPY_RECOVERY','0')).strip().lower() in ('0','false','off','no',''):
212
  return False
213
  if self.copy_recovery_fails>=int(os.getenv('YOUTUBE_COPY_RECOVERY_MAX_FAILS','2')):
214
  return False
@@ -234,6 +229,8 @@ class Sender:
234
  self.sticky_since=time.monotonic()
235
  self._recovering_copy=False
236
  self._no_copy_recovery=True
 
 
237
  self.log(user, '[HEALTH] %s — sticky %s (this publisher only)'%(reason[:160], mode))
238
  sess=self.session
239
  if isinstance(sess, dict):
@@ -246,7 +243,7 @@ class Sender:
246
  def note_format_change(self):
247
  self.flap.append(time.monotonic())
248
  if len(self.flap)>=int(os.getenv('YOUTUBE_FLAP_LIMIT','4')):
249
- self.log('system','تغيّرت أبعاد المصدر عدة مرات خلال 10 دقائق؛ التحول تلقائيًا إلى كانفس ثابت (%s) لمنع تكرار الانقطاع'%os.getenv('YOUTUBE_FLAP_FALLBACK_MODE','fixed720'))
250
  @staticmethod
251
  def copy_is_safe(declared,probed):
252
  """Stream copy is allowed only on positive proof of H.264, never on absence of evidence.
@@ -304,29 +301,10 @@ class Sender:
304
  if not probe:return None
305
  try:return probe(candidate)
306
  except Exception:return None
307
- def lock_gold(self, candidate=None, w=0, h=0):
308
- """Pin YouTube output to the first size the player already latched."""
309
- if int(getattr(self, '_gop_w', 0) or 0) >= 16:
310
- return (self._gop_w, self._gop_h)
311
- if candidate and not (w and h):
312
- try:
313
- w = int(candidate.get('width') or 0)
314
- h = int(candidate.get('height') or 0)
315
- except (TypeError, ValueError):
316
- w = h = 0
317
- try:
318
- w, h = int(w or 0), int(h or 0)
319
- except (TypeError, ValueError):
320
- w = h = 0
321
- w, h = w - w % 2, h - h % 2
322
- if w >= 16 and h >= 16:
323
- self._gop_w, self._gop_h = w, h
324
- return (int(getattr(self, '_gop_w', 0) or 0), int(getattr(self, '_gop_h', 0) or 0))
325
-
326
  @staticmethod
327
  def canvas(width,height):
328
- return ('scale=w=%d:h=%d:force_original_aspect_ratio=decrease:flags=lanczos:eval=frame,'
329
- 'pad=%d:%d:(ow-iw)/2:(oh-ih)/2:color=black:eval=frame,setsar=1,format=yuv420p'%(width,height,width,height))
330
  def input_args(self,candidate):
331
  """How FFmpeg *reads* the source — two transports, one sender.
332
 
@@ -402,8 +380,9 @@ class Sender:
402
  video=['-c:v','copy']
403
  else:
404
  if mode=='matchgop':
405
- # Same-size closed GOP ~2s. Pin first canvas so PK hops pad instead of
406
- # changing YouTube SPS (app flash until force-close).
 
407
  w=int((candidate or {}).get('width') or 0); h=int((candidate or {}).get('height') or 0)
408
  w,h=w-w%2,h-h%2
409
  if not getattr(self,'_gop_w',0) and w>=16 and h>=16:
@@ -428,7 +407,8 @@ class Sender:
428
  # keyframe instead of waiting for the source's own GOP, which is what made
429
  # people leave the YouTube app and come back to get a picture again.
430
  '-force_key_frames','expr:gte(t,n_forced*2)',
431
- '-g',os.getenv('YOUTUBE_GOP','60'),'-keyint_min','30','-sc_threshold','0','-bf','0',
 
432
  '-pix_fmt','yuv420p','-fps_mode','cfr',
433
  '-colorspace','bt709','-color_primaries','bt709','-color_trc','bt709']
434
  # Network output goes through the fifo pseudo-muxer instead of straight to flv.
@@ -657,7 +637,7 @@ class Sender:
657
  """
658
  if not refresh or p is None or p.stdin is None or p.poll() is not None:
659
  return None
660
- if int(sess.get('reattaches') or 0) >= 8:
661
  return None
662
  sess['swapping'] = True
663
  sess['swap_source'] = True
@@ -681,7 +661,7 @@ class Sender:
681
  new_resp = requests.get(cand['url'],
682
  headers={'Referer': 'https://www.tiktok.com/', **self.headers_for(user)},
683
  impersonate='chrome', stream=True,
684
- timeout=(10, read_timeout))
685
  new_resp.raise_for_status()
686
  except Exception as e:
687
  self.log(user, '[RELAY] فشل فتح مصدر تيك توك البديل (%s)' % type(e).__name__)
@@ -788,7 +768,8 @@ class Sender:
788
  الإشراف في `sender_loop` التي تُعيد رصد LIVE وتبني جلسة جديدة من الصفر.
789
  """
790
  self.current_candidate = candidate
791
- self.lock_gold(candidate)
 
792
  if self.hevc_payload(candidate) and self.sticky_mode not in ('matchgop','fixed720','fixed1080'):
793
  self.sticky_mode='matchgop'
794
  self.sticky_since=time.monotonic()
@@ -923,6 +904,14 @@ class Sender:
923
  self.sticky_mode=None
924
  self.sticky_since=0.0
925
  self._recovering_copy=False
 
 
 
 
 
 
 
 
926
  if stall_limit and now - _fresh > stall_limit and (not sess.get('swapping') or swap_for > stall_limit):
927
  attached = self._try_reattach(user, p, bridge, sess, stop, refresh,
928
  read_timeout, retries, response, pump)
@@ -955,6 +944,26 @@ class Sender:
955
  self.log(user, 'FFmpeg خرج برمز %s%s%s%s' % (
956
  rc, ' — ' + '؛ '.join(diagnostics[-3:]) if diagnostics else '؛ لم يظهر سبب مصنّف', blame, tail))
957
  break
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
958
  if now - progress['last'] > progress_limit:
959
  raise SourceStalled('لم يتقدّم FFmpeg منذ %.0f ث' % (now - progress['last']))
960
  if sess['ended'] and not sess['error']:
 
104
  self.copy_recovery_fails=0
105
  self._recovering_copy=False
106
  self._last_light_output=0.0
 
 
 
107
  # Candidate handed to send_mode() so the codec rule can judge the real source.
108
  self.current_candidate=None
109
  # Journal setting wins over the environment so the mode can be changed from the UI
 
191
  now=time.monotonic()
192
  while flap and now-flap[0]>600:flap.popleft()
193
  if len(flap)>=int(os.getenv('YOUTUBE_FLAP_LIMIT','4')):
194
+ mode=os.getenv('YOUTUBE_FLAP_FALLBACK_MODE','matchgop').strip().lower()
195
  if mode not in ('fixed1080','fixed720'):mode='fixed720'
196
  self.sticky_mode=mode
197
  self.sticky_since=time.monotonic()
 
203
  Isolated-handoff harness (SIMULATED): start copy, require bytes>0, then
204
  kill light — PASS. Naive sticky-clear on h264 label — the production bug.
205
  """
206
+ if str(os.getenv('YOUTUBE_COPY_RECOVERY','1')).strip().lower() in ('0','false','off','no'):
 
 
207
  return False
208
  if self.copy_recovery_fails>=int(os.getenv('YOUTUBE_COPY_RECOVERY_MAX_FAILS','2')):
209
  return False
 
229
  self.sticky_since=time.monotonic()
230
  self._recovering_copy=False
231
  self._no_copy_recovery=True
232
+ # Do not reset _gop_w: PK restick must keep the first YouTube canvas
233
+ # (copy 1280 then 4-player 640 must pad into 1280, not lock 640).
234
  self.log(user, '[HEALTH] %s — sticky %s (this publisher only)'%(reason[:160], mode))
235
  sess=self.session
236
  if isinstance(sess, dict):
 
243
  def note_format_change(self):
244
  self.flap.append(time.monotonic())
245
  if len(self.flap)>=int(os.getenv('YOUTUBE_FLAP_LIMIT','4')):
246
+ self.log('system','تغيّرت أبعاد المصدر عدة مرات خلال 10 دقائق؛ التحول تلقائيًا إلى كانفس ثابت (%s) لمنع تكرار الانقطاع'%os.getenv('YOUTUBE_FLAP_FALLBACK_MODE','matchgop'))
247
  @staticmethod
248
  def copy_is_safe(declared,probed):
249
  """Stream copy is allowed only on positive proof of H.264, never on absence of evidence.
 
301
  if not probe:return None
302
  try:return probe(candidate)
303
  except Exception:return None
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
304
  @staticmethod
305
  def canvas(width,height):
306
+ return ('scale=w=%d:h=%d:force_original_aspect_ratio=decrease:flags=lanczos,'
307
+ 'pad=%d:%d:(ow-iw)/2:(oh-ih)/2:color=black,setsar=1,format=yuv420p'%(width,height,width,height))
308
  def input_args(self,candidate):
309
  """How FFmpeg *reads* the source — two transports, one sender.
310
 
 
380
  video=['-c:v','copy']
381
  else:
382
  if mode=='matchgop':
383
+ # Closed GOP 2s. Keep the FIRST origin size as the YouTube canvas so PK
384
+ # rounds (640↔1280) pad into the same ingest — no new SPS, no viewer cut.
385
+ # Not a 720 squash: canvas is this session's origin, not fixed720.
386
  w=int((candidate or {}).get('width') or 0); h=int((candidate or {}).get('height') or 0)
387
  w,h=w-w%2,h-h%2
388
  if not getattr(self,'_gop_w',0) and w>=16 and h>=16:
 
407
  # keyframe instead of waiting for the source's own GOP, which is what made
408
  # people leave the YouTube app and come back to get a picture again.
409
  '-force_key_frames','expr:gte(t,n_forced*2)',
410
+ '-g',os.getenv('YOUTUBE_GOP','60'),'-keyint_min','30','-sc_threshold','0',
411
+ '-x264-params','open-gop=0:scenecut=0:keyint=%s:min-keyint=30'%os.getenv('YOUTUBE_GOP','60'),
412
  '-pix_fmt','yuv420p','-fps_mode','cfr',
413
  '-colorspace','bt709','-color_primaries','bt709','-color_trc','bt709']
414
  # Network output goes through the fifo pseudo-muxer instead of straight to flv.
 
637
  """
638
  if not refresh or p is None or p.stdin is None or p.poll() is not None:
639
  return None
640
+ if int(sess.get('reattaches') or 0) >= 24:
641
  return None
642
  sess['swapping'] = True
643
  sess['swap_source'] = True
 
661
  new_resp = requests.get(cand['url'],
662
  headers={'Referer': 'https://www.tiktok.com/', **self.headers_for(user)},
663
  impersonate='chrome', stream=True,
664
+ timeout=(5, min(8, read_timeout or 8)))
665
  new_resp.raise_for_status()
666
  except Exception as e:
667
  self.log(user, '[RELAY] فشل فتح مصدر تيك توك البديل (%s)' % type(e).__name__)
 
768
  الإشراف في `sender_loop` التي تُعيد رصد LIVE وتبني جلسة جديدة من الصفر.
769
  """
770
  self.current_candidate = candidate
771
+ # Never let YouTube see HEVC even for one packet — the player latches the first
772
+ # decoder config; viewers must kill the app to recover (measured production freeze).
773
  if self.hevc_payload(candidate) and self.sticky_mode not in ('matchgop','fixed720','fixed1080'):
774
  self.sticky_mode='matchgop'
775
  self.sticky_since=time.monotonic()
 
904
  self.sticky_mode=None
905
  self.sticky_since=0.0
906
  self._recovering_copy=False
907
+ if stall_limit and now - _fresh > 3 and not sess.get('swapping') and not sess.get('swap_source'):
908
+ # Re-splice TikTok into the SAME FFmpeg before the 12s kill.
909
+ # Killing FFmpeg is what repeats the last YouTube clip on every source drop.
910
+ attached = self._try_reattach(user, p, bridge, sess, stop, refresh,
911
+ read_timeout, retries, response, pump)
912
+ if attached:
913
+ response, pump = attached
914
+ continue
915
  if stall_limit and now - _fresh > stall_limit and (not sess.get('swapping') or swap_for > stall_limit):
916
  attached = self._try_reattach(user, p, bridge, sess, stop, refresh,
917
  read_timeout, retries, response, pump)
 
944
  self.log(user, 'FFmpeg خرج برمز %s%s%s%s' % (
945
  rc, ' — ' + '؛ '.join(diagnostics[-3:]) if diagnostics else '؛ لم يظهر سبب مصنّف', blame, tail))
946
  break
947
+ # Freeze detect without decoding. freezedetect needs a decoder — that
948
+ # is already transcode. Forums (SO RTSP freeze, 2026 YT GOP): copy can
949
+ # keep the last frame while the socket is alive; viewers see a still.
950
+ # If TikTok bytes still arrive and out_time does not, switch THIS
951
+ # publisher to same-size closed GOP 2s (matchgop), not default 720.
952
+ mode_now = ''
953
+ try:
954
+ mode_now = self.send_mode()
955
+ except Exception:
956
+ mode_now = self.sticky_mode or ''
957
+ src_fresh = (now - _fresh) < max(3.0, (stall_limit or 12) * 0.5)
958
+ ran = now - float(sess.get('spawned_at') or now)
959
+ if (mode_now in ('auto', 'copy', '') and not self.sticky_mode and src_fresh):
960
+ frozen_out = progress['seconds'] >= 0.5 and (now - progress['last']) >= 8
961
+ no_out = ran >= 12 and progress['seconds'] < 0.5
962
+ if frozen_out or no_out:
963
+ self.request_sticky('matchgop', user,
964
+ 'freeze: source flowing, ffmpeg out=%.1fs idle %.0fs' % (
965
+ max(0.0, progress['seconds']), now - progress['last']))
966
+ raise SourceStalled('frozen copy while source alive; switching matchgop')
967
  if now - progress['last'] > progress_limit:
968
  raise SourceStalled('لم يتقدّم FFmpeg منذ %.0f ث' % (now - progress['last']))
969
  if sess['ended'] and not sess['error']:
requirements.txt CHANGED
@@ -1,3 +1,3 @@
1
  fastapi>=0.115,<1
2
  uvicorn>=0.30,<1
3
- curl_cffi>=0.13,<1
 
1
  fastapi>=0.115,<1
2
  uvicorn>=0.30,<1
3
+ curl_cffi>=0.16.3,<1
youtube_manager.py CHANGED
@@ -35,6 +35,9 @@ class ManagedYouTube:
35
  self.end_grace=max(15,int(os.getenv('YOUTUBE_END_GRACE','40')))
36
  self._unstable={}
37
  self._live_confirm={}
 
 
 
38
  # Reuse one YouTube broadcast when TikTok moves the streamer to a new session. The stream
39
  # key is persistent (isReusable) and the broadcast is created with enableAutoStop=false,
40
  # so the broadcast stays resumable and the watch URL does not change. YOUTUBE_REUSE_IDLE
@@ -61,8 +64,6 @@ class ManagedYouTube:
61
  # السقف، و0 يطفئ الاحتفاظ.
62
  self.hold_seconds=max(0.0,float(os.getenv('YOUTUBE_OBS_HOLD_SECONDS','900')))
63
  self._held={};self._last_force_at={};self.hammer={};self.retry_at={};self._offline_logged=set();self._gate_note_at={};self.auth_pause={};self.starve={};self._hold_notes={};self.last_seen_status={};self._blocked403={};self._skip_probe_once={};self._skip_hold=set();self._loop_miss={}
64
- self._sender_sticky={}
65
- self._sender_gop={}
66
  # هل تقبل دالة الرصد المحقونة force=؟ (app.py يفعّلها؛ الاختبارات قد لا تفعل)
67
  try:self._observe_force='force' in inspect.signature(self.observe).parameters
68
  except (TypeError,ValueError):self._observe_force=False
@@ -158,12 +159,15 @@ class ManagedYouTube:
158
  prefer=str(os.getenv('YOUTUBE_PREFER_H264','1')).strip().lower() in ('1','on','true','yes')
159
  if prefer and os.getenv('YOUTUBE_SEND_MODE','auto').strip().lower() in ('auto','copy'):
160
  h264=[c for c in supported if any(k in _cod(c) for k in ('h264','avc'))]
161
- # Measured: falling through to origin HEVC then fixed720 pegged 2-core
162
- # quota at 99–101% (a3dam_111). H264 hd copy of the same room was ~few % CPU.
163
- if h264:
164
- supported=sorted(h264, key=lambda c: 0 if str(c.get('media') or '')=='flv' else 1)
165
- else:
166
- supported=sorted(supported, key=lambda c: 0 if str(c.get('media') or '')=='flv' else 1)
 
 
 
167
  out=supported
168
  else:
169
  raise RuntimeError('YOUTUBE_VIDEO_MODE يجب أن يكون original أو h264')
@@ -279,7 +283,7 @@ class ManagedYouTube:
279
  try:self.finish_event(_k)
280
  except Exception:self.archive_event(_k,'local_cancelled_'+str(reason))
281
  _rid=str(room_id or '')
282
- if _rid:self._blocked403[user+':'+_rid]=time.monotonic()
283
  self.log(user,'[MONITOR] يوتيوب رفض إنشاء الحدث (403/%s)؛ أُغلق حدثه ويُمنع تكرار المفتاح %d ث — يُعاد الاكتشاف بعد معالجة الصلاحية'%(reason,int(float(os.getenv('YOUTUBE_403_BLOCK_SECONDS','600')))))
284
 
285
  # ---------- channel / settings ----------
@@ -509,8 +513,11 @@ class ManagedYouTube:
509
  # قفل رفض 403 يُفحص أولًا: بعد الإغلاق يبقى المفتاح في history والفحص اللاحق كان
510
  # يسمح بلوغ الحدث مرة أخرى كل دورة رفض متكررة (الرفض حصل لأن المفتاح في history).
511
  block=self._blocked403.get(key)
512
- if block and time.monotonic()-block<float(os.getenv('YOUTUBE_403_BLOCK_SECONDS','600')):
513
- self._skip_note(user,'يوتيوب رفض إنشاء حدث لهذه الجلسة (403) مؤخرًا؛ ننتظر %d ث قبل المحاولة من جديد'%int(float(os.getenv('YOUTUBE_403_BLOCK_SECONDS','600'))-(time.monotonic()-block)))
 
 
 
514
  return False
515
  if key in d['events'] or any(h['session_key']==key for h in d['history']):return False
516
  dt=datetime.now(ZoneInfo('Asia/Baghdad'));settings=d['settings']
@@ -727,7 +734,6 @@ class ManagedYouTube:
727
  sender._no_copy_recovery=True
728
  gw,gh=self._sender_gop.get(u,(0,0))
729
  sender._gop_w,sender._gop_h=int(gw or 0),int(gh or 0)
730
- # Give the sender a real codec probe so "copy" is chosen from the payload, not a label.
731
  sender.set_probe(self.codec_probe)
732
  # حين تبدأ الحافة بقبولنا فعلًا يُمسح العقاب وأثره — لا يُتركان حتى أول انقطاع لاحق
733
  sender.on_stable=lambda u=ev['username']: self.mark_stream_stable(u)
@@ -765,7 +771,7 @@ class ManagedYouTube:
765
  if not since:
766
  entry['idle_since']=time.monotonic()
767
  continue
768
- if time.monotonic()-since<20:
769
  continue
770
  self.log(ev.get('username') or key,
771
  '[RELAY] @%s sender thread without FFmpeg; recycle'%ev.get('username'))
@@ -853,6 +859,22 @@ class ManagedYouTube:
853
  room_id=new_room
854
  session_started=time.monotonic()
855
  candidates=self._select_source(user,obs)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
856
  if not candidates:
857
  self.log(user,'لا مرشح فيديو صالح لهذه الدورة؛ سيُحدَّث المصدر تلقائيًا')
858
  stop.wait(self._backoff(user));continue
@@ -867,12 +889,10 @@ class ManagedYouTube:
867
  self.log(user,'[RELAY] @%s starting (%s)'%(user,self._source_brief(candidate)))
868
  if sender.send(user,candidate,destination,stop, refresh=lambda: self._refresh_flv(user)):
869
  sent=True
870
- sender.lock_gold(candidate)
871
- gw,gh=int(getattr(sender,'_gop_w',0) or 0), int(getattr(sender,'_gop_h',0) or 0)
872
- if gw>=16 and gh>=16:
873
- self._sender_gop[user]=(gw,gh)
874
  if sender.sticky_mode:
875
  self._sender_sticky[user]=sender.sticky_mode
 
876
  except RelayStartError as e:
877
  self.log(user,'[RELAY] @%s start failed; trying fallback (%s)'%(user,self.safe_error(e)[:90]))
878
  if candidate is not None:self.mark_unstable(user,candidate,'start failed')
@@ -885,27 +905,26 @@ class ManagedYouTube:
885
  self.starve[user]=int(self.starve.get(user) or 0)+1
886
  ran=time.monotonic()-session_started
887
  self.log(user,'[WATCHDOG] @%s data stalled (%s)'%(user,self.safe_error(e)[:100]))
888
- if candidate is not None:
889
- self.mark_unstable(user,candidate,'stalled after %.0fs'%ran)
890
- rest=candidates[candidates.index(candidate)+1:] if candidate in candidates else []
891
- nxt=next((c for c in rest if c.get('media')!='flv'), None) or (rest[0] if rest else None)
892
- if nxt:
893
- self.log(user,'[SOURCE] @%s trying fallback source %s'%(user,self._source_brief(nxt)))
894
- continue
895
  stalled=True
896
  self._skip_probe_once[user]=True
897
  self.retry[user]=self.retry_min
898
  break
899
  except FormatChanged:
 
 
900
  prev=sender.current_candidate or candidate or {}
901
  sender.note_format_change()
902
- sender.lock_gold(prev)
903
  sender.request_sticky('matchgop', user, 'PK/layout size change — keep YouTube canvas')
904
  self._sender_sticky[user]='matchgop'
905
- gw,gh=int(getattr(sender,'_gop_w',0) or 0), int(getattr(sender,'_gop_h',0) or 0)
906
- if gw>=16 and gh>=16:
907
- self._sender_gop[user]=(gw,gh)
908
- self.log(user,'تغيرت أبعاد المصدر؛ نثبت نفس مقاس يوتيوب (بدون وميض التطبيق)')
 
 
 
 
909
  restart_at=time.monotonic();sent=True;break
910
  except Exception as e:
911
  self.log(user,'تعثر إرسال الفيديو؛ نفس الحدث سيُستخدم — '+self.safe_error(e)[:160])
@@ -1099,7 +1118,17 @@ class ManagedYouTube:
1099
  return None
1100
  if (obs or {}).get('status')!='live':
1101
  return None
1102
- for c in self._select_source(user, obs) or []:
 
 
 
 
 
 
 
 
 
 
1103
  if c.get('media')!='hls' and c.get('url'):
1104
  return c
1105
  return None
@@ -1518,6 +1547,7 @@ class ManagedYouTube:
1518
  self.log(user,'[RELAY] @%s stopping (TikTok LIVE ended)'%user)
1519
  self._unstable.pop(user,None)
1520
  self._live_confirm.pop(user,None)
 
1521
  self._sender_sticky.pop(user,None)
1522
  self._sender_gop.pop(user,None)
1523
  self.finish_event(key)
@@ -1709,13 +1739,19 @@ class ManagedYouTube:
1709
  delay=self.scan
1710
  try:
1711
  now=time.monotonic()
1712
- with self.operations:
1713
- if not checked:self.check_channel();checked=True
1714
- if now-last_tick>=self.scan:
1715
- self.tick()
1716
- last_tick=now
1717
- else:
1718
- self.restart_dead_senders()
 
 
 
 
 
 
1719
  d=self.journal.read()
1720
  if not d['enabled'] and not d['events']:self.set_status('الأتمتة معطلة؛ لا إرسال ولا إنشاء أحداث')
1721
  dead=any(not (e.get('thread') and e['thread'].is_alive()) for e in list(self.senders.values()))
 
35
  self.end_grace=max(15,int(os.getenv('YOUTUBE_END_GRACE','40')))
36
  self._unstable={}
37
  self._live_confirm={}
38
+ self._rendition_pin={}
39
+ self._sender_sticky={}
40
+ self._sender_gop={}
41
  # Reuse one YouTube broadcast when TikTok moves the streamer to a new session. The stream
42
  # key is persistent (isReusable) and the broadcast is created with enableAutoStop=false,
43
  # so the broadcast stays resumable and the watch URL does not change. YOUTUBE_REUSE_IDLE
 
64
  # السقف، و0 يطفئ الاحتفاظ.
65
  self.hold_seconds=max(0.0,float(os.getenv('YOUTUBE_OBS_HOLD_SECONDS','900')))
66
  self._held={};self._last_force_at={};self.hammer={};self.retry_at={};self._offline_logged=set();self._gate_note_at={};self.auth_pause={};self.starve={};self._hold_notes={};self.last_seen_status={};self._blocked403={};self._skip_probe_once={};self._skip_hold=set();self._loop_miss={}
 
 
67
  # هل تقبل دالة الرصد المحقونة force=؟ (app.py يفعّلها؛ الاختبارات قد لا تفعل)
68
  try:self._observe_force='force' in inspect.signature(self.observe).parameters
69
  except (TypeError,ValueError):self._observe_force=False
 
159
  prefer=str(os.getenv('YOUTUBE_PREFER_H264','1')).strip().lower() in ('1','on','true','yes')
160
  if prefer and os.getenv('YOUTUBE_SEND_MODE','auto').strip().lower() in ('auto','copy'):
161
  h264=[c for c in supported if any(k in _cod(c) for k in ('h264','avc'))]
162
+ def _short(c):
163
+ try:w=int(c.get('width') or 0);h=int(c.get('height') or 0)
164
+ except (TypeError,ValueError):w=h=0
165
+ return min(w,h) if w and h else 0
166
+ # Copy 720-class+ H264 when it exists (low CPU). If the only H264 is
167
+ # 640p, keep origin (often HEVC) so matchgop can send recording-class size.
168
+ decent=[c for c in h264 if _short(c)>=720]
169
+ if decent:
170
+ supported=decent
171
  out=supported
172
  else:
173
  raise RuntimeError('YOUTUBE_VIDEO_MODE يجب أن يكون original أو h264')
 
283
  try:self.finish_event(_k)
284
  except Exception:self.archive_event(_k,'local_cancelled_'+str(reason))
285
  _rid=str(room_id or '')
286
+ if _rid:self._blocked403[user+':'+_rid]={'t':time.monotonic(),'reason':str(reason or '')}
287
  self.log(user,'[MONITOR] يوتيوب رفض إنشاء الحدث (403/%s)؛ أُغلق حدثه ويُمنع تكرار المفتاح %d ث — يُعاد الاكتشاف بعد معالجة الصلاحية'%(reason,int(float(os.getenv('YOUTUBE_403_BLOCK_SECONDS','600')))))
288
 
289
  # ---------- channel / settings ----------
 
513
  # قفل رفض 403 يُفحص أولًا: بعد الإغلاق يبقى المفتاح في history والفحص اللاحق كان
514
  # يسمح بلوغ الحدث مرة أخرى كل دورة رفض متكررة (الرفض حصل لأن المفتاح في history).
515
  block=self._blocked403.get(key)
516
+ bt=float((block or {}).get('t') or 0) if isinstance(block,dict) else float(block or 0)
517
+ if bt and time.monotonic()-bt<float(os.getenv('YOUTUBE_403_BLOCK_SECONDS','600')):
518
+ why=str((block or {}).get('reason') or '') if isinstance(block,dict) else ''
519
+ tag=('403/%s'%why) if why else '403'
520
+ self._skip_note(user,'يوتيوب رفض إنشاء حدث لهذه الجلسة (%s) مؤخرًا؛ ننتظر %d ث قبل المحاولة من جديد'%(tag,int(float(os.getenv('YOUTUBE_403_BLOCK_SECONDS','600'))-(time.monotonic()-bt))))
521
  return False
522
  if key in d['events'] or any(h['session_key']==key for h in d['history']):return False
523
  dt=datetime.now(ZoneInfo('Asia/Baghdad'));settings=d['settings']
 
734
  sender._no_copy_recovery=True
735
  gw,gh=self._sender_gop.get(u,(0,0))
736
  sender._gop_w,sender._gop_h=int(gw or 0),int(gh or 0)
 
737
  sender.set_probe(self.codec_probe)
738
  # حين تبدأ الحافة بقبولنا فعلًا يُمسح العقاب وأثره — لا يُتركان حتى أول انقطاع لاحق
739
  sender.on_stable=lambda u=ev['username']: self.mark_stream_stable(u)
 
771
  if not since:
772
  entry['idle_since']=time.monotonic()
773
  continue
774
+ if time.monotonic()-since<3:
775
  continue
776
  self.log(ev.get('username') or key,
777
  '[RELAY] @%s sender thread without FFmpeg; recycle'%ev.get('username'))
 
859
  room_id=new_room
860
  session_started=time.monotonic()
861
  candidates=self._select_source(user,obs)
862
+ # Pin THIS resolution, not just "hd": 1280→1440 same label killed pid 39
863
+ # (measured) and zeroed output — YouTube jumps/repeats the last clip.
864
+ prev=getattr(sender,'current_candidate',None) or {}
865
+ def _pin(c):
866
+ return '|'.join([str(c.get('quality_name') or c.get('label') or '').strip().lower(),
867
+ str(c.get('width') or ''), str(c.get('height') or ''),
868
+ str(c.get('media') or '')])
869
+ pin=_pin(prev) if any(_pin(prev).split('|')) else (self._rendition_pin.get(user) or '')
870
+ if pin.strip('|') and candidates:
871
+ same=[c for c in candidates if _pin(c)==pin]
872
+ if same:
873
+ rest=[c for c in candidates if c not in same]
874
+ candidates=same+rest
875
+ else:
876
+ self.log(user,'[SOURCE] نُبقي المقاس المقفول؛ لا قفز 1440 بعد فصل المصدر')
877
+ stop.wait(self._backoff(user));continue
878
  if not candidates:
879
  self.log(user,'لا مرشح فيديو صالح لهذه الدورة؛ سيُحدَّث المصدر تلقائيًا')
880
  stop.wait(self._backoff(user));continue
 
889
  self.log(user,'[RELAY] @%s starting (%s)'%(user,self._source_brief(candidate)))
890
  if sender.send(user,candidate,destination,stop, refresh=lambda: self._refresh_flv(user)):
891
  sent=True
892
+ self._rendition_pin[user]=_pin(candidate)
 
 
 
893
  if sender.sticky_mode:
894
  self._sender_sticky[user]=sender.sticky_mode
895
+ self._sender_gop[user]=(int(getattr(sender,'_gop_w',0) or 0), int(getattr(sender,'_gop_h',0) or 0))
896
  except RelayStartError as e:
897
  self.log(user,'[RELAY] @%s start failed; trying fallback (%s)'%(user,self.safe_error(e)[:90]))
898
  if candidate is not None:self.mark_unstable(user,candidate,'start failed')
 
905
  self.starve[user]=int(self.starve.get(user) or 0)+1
906
  ran=time.monotonic()-session_started
907
  self.log(user,'[WATCHDOG] @%s data stalled (%s)'%(user,self.safe_error(e)[:100]))
908
+ # Never mark the pinned size unstable: URL expiry is not a bad rendition.
 
 
 
 
 
 
909
  stalled=True
910
  self._skip_probe_once[user]=True
911
  self.retry[user]=self.retry_min
912
  break
913
  except FormatChanged:
914
+ # 4-player PK / layout. Copy cannot splice a new SPS. Stick matchgop
915
+ # on the FIRST canvas so YouTube does not jump or repeat a clip.
916
  prev=sender.current_candidate or candidate or {}
917
  sender.note_format_change()
 
918
  sender.request_sticky('matchgop', user, 'PK/layout size change — keep YouTube canvas')
919
  self._sender_sticky[user]='matchgop'
920
+ try:
921
+ w=int(prev.get('width') or 0); h=int(prev.get('height') or 0)
922
+ except (TypeError, ValueError):
923
+ w=h=0
924
+ w,h=w-w%2,h-h%2
925
+ if w>=16 and h>=16 and not getattr(sender,'_gop_w',0):
926
+ sender._gop_w,sender._gop_h=w,h
927
+ self.log(user,'تغيرت أبعاد المصدر (جولة PK رباعية)؛ نثبت matchgop على نفس حدث يوتيوب')
928
  restart_at=time.monotonic();sent=True;break
929
  except Exception as e:
930
  self.log(user,'تعثر إرسال الفيديو؛ نفس الحدث سيُستخدم — '+self.safe_error(e)[:160])
 
1118
  return None
1119
  if (obs or {}).get('status')!='live':
1120
  return None
1121
+ ordered=self._select_source(user, obs) or []
1122
+ def _pin(c):
1123
+ return '|'.join([str(c.get('quality_name') or c.get('label') or '').strip().lower(),
1124
+ str(c.get('width') or ''), str(c.get('height') or ''),
1125
+ str(c.get('media') or '')])
1126
+ pin=self._rendition_pin.get(user) or ''
1127
+ if pin.strip('|'):
1128
+ same=[c for c in ordered if _pin(c)==pin]
1129
+ if same:
1130
+ ordered=same
1131
+ for c in ordered:
1132
  if c.get('media')!='hls' and c.get('url'):
1133
  return c
1134
  return None
 
1547
  self.log(user,'[RELAY] @%s stopping (TikTok LIVE ended)'%user)
1548
  self._unstable.pop(user,None)
1549
  self._live_confirm.pop(user,None)
1550
+ self._rendition_pin.pop(user,None)
1551
  self._sender_sticky.pop(user,None)
1552
  self._sender_gop.pop(user,None)
1553
  self.finish_event(key)
 
1739
  delay=self.scan
1740
  try:
1741
  now=time.monotonic()
1742
+ # Network (TikTok observe, YouTube liveStreams/liveBroadcasts) must
1743
+ # not run under `operations`. That lock serializes HTTP enable/disable/
1744
+ # settings with the manager; holding it across tick() starved those
1745
+ # callers for every account's round-trip (harness A/B analog).
1746
+ # Journal has its own lock. start_sender still gates via hub.occupy.
1747
+ if not checked:
1748
+ self.check_channel()
1749
+ checked=True
1750
+ if now-last_tick>=self.scan:
1751
+ self.tick()
1752
+ last_tick=now
1753
+ else:
1754
+ self.restart_dead_senders()
1755
  d=self.journal.read()
1756
  if not d['enabled'] and not d['events']:self.set_status('الأتمتة معطلة؛ لا إرسال ولا إنشاء أحداث')
1757
  dead=any(not (e.get('thread') and e['thread'].is_alive()) for e in list(self.senders.values()))