Spaces:
Running
Running
Exact copy of Reoo88/On @ 826bfe0 (relay-v2.32-gap-filler)
Browse files- AUDIT_AR.md +341 -0
- Dockerfile +13 -13
- README.md +138 -161
- app.py +84 -117
- flv_bridge.py +133 -52
- index.html +105 -26
- ingest.py +48 -28
- kick_source.py +0 -371
- relay.py +619 -176
- requirements.txt +5 -3
- stream_monitor.py +220 -0
- telemetry.py +589 -0
- test_adaptive_format.py +335 -0
- test_channel_switch.py +236 -0
- test_completion.py +2 -2
- test_dashboard.js +138 -0
- test_flv_bridge.py +244 -0
- test_ingest_routes.py +190 -0
- test_kick.py +0 -346
- test_lifecycle.py +69 -144
- test_regressions.py +146 -0
- test_relay.py +51 -9
- test_smart_mode.py +213 -0
- test_source_reconnect.py +295 -0
- test_telemetry.py +134 -0
- test_transition_ingest.py +68 -0
- test_watchdog.py +19 -3
- tiktok_auth.py +39 -4
- verify.sh +15 -0
- youtube_manager.py +657 -173
AUDIT_AR.md
ADDED
|
@@ -0,0 +1,341 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# تقرير تدقيق وإصلاح Space `Reoo88/On`
|
| 2 |
+
|
| 3 |
+
**التاريخ:** 2026-10-07 — **النسخة المنشورة قبل هذا التغيير:** `fa14eaf` — **النسخة الجديدة المرشحة:** `relay-v2.21-adaptive-source`
|
| 4 |
+
|
| 5 |
+
> هذا تقرير تقني وتشغيلي، وليس وعدًا بمنع كل عطل مستقبلي. TikTok وYouTube وHugging Face خدمات خارجية تتغير دون تحكم المشروع؛ الهدف هو منع الأعطال المعروفة، كشف الأعطال الجديدة بسرعة، والتعافي الآمن دون إنشاء أحداث مكررة.
|
| 6 |
+
|
| 7 |
+
## 1. الخلاصة التنفيذية
|
| 8 |
+
|
| 9 |
+
كان الـSpace يبني ويعمل، لكن وُجد عطل إنتاج حقيقي: حدث YouTube بقي `live/noData` بينما خيط الإشراف حي وعملية FFmpeg ميتة. ظل الحساب المتأثر بلا PID وبلا خرج أكثر من 14 دقيقة، ولم يظهر السبب في Container Logs لأن سجل التطبيق كان داخل الذاكرة فقط، بينما access log كان يملأ السجل بطلبات اللوحة كل خمس ثوانٍ.
|
| 10 |
+
|
| 11 |
+
السبب الجذري كان في جدولة مدير YouTube: `restart_dead_senders()` كانت داخل فرع `else`. نوم المدير كان ينتهي غالبًا عند موعد الفحص الكامل تمامًا، فيدخل فرع `tick()` في كل دورة ولا ينفذ حارس المرسل الميت. لذلك لم يكن «خيط حي + FFmpeg ميت» يُعاد تدويره.
|
| 12 |
+
|
| 13 |
+
كما ظهر أن رسالة `401 Unauthorized` عند فتح رابط الـSpace ليست فشل بناء؛ كانت نتيجة حماية HTTP Basic على `/` داخل iframe. المتصفح لا يعرض تجربة دخول مناسبة هناك، فبدت الواجهة معطلة.
|
| 14 |
+
|
| 15 |
+
تم إصلاح المشكلتين، وإصلاح عطل JavaScript كان يوقف تحديث اللوحة بسبب غياب العنصرين `#ncpu` و`#nram`، وتشديد الخصوصية والسجلات والتبعيات والاختبارات.
|
| 16 |
+
|
| 17 |
+
## 2. الأدلة المقاسة من التشغيل الحقيقي
|
| 18 |
+
|
| 19 |
+
### حالة المنصة والبناء
|
| 20 |
+
|
| 21 |
+
- Hugging Face API: الحالة `RUNNING`، العتاد `cpu-basic`، والمنفذ `7860` جاهز.
|
| 22 |
+
- Build logs: اكتمل بناء commit `9f1a134` بنجاح ولم يوجد Build Error.
|
| 23 |
+
- Container logs التي سُحبت عبر API: 632 سطرًا تقريبًا؛ معظمها طلبات لوحة دورية، بلا traceback أو exception ظاهر.
|
| 24 |
+
- `/` و`/?logs=container` أعادا `401` لأن middleware كان يحمي الصفحة نفسها.
|
| 25 |
+
|
| 26 |
+
### عطل البث الحقيقي
|
| 27 |
+
|
| 28 |
+
أُخذت ثلاث عينات متباعدة 20 ثانية من `/health` قبل الإصلاح:
|
| 29 |
+
|
| 30 |
+
- حدثان YouTube مفتوحان، لكن Relay فعلي واحد فقط.
|
| 31 |
+
- الحساب السليم: PID موجود، `source_age≈0`، والخرج يتقدم.
|
| 32 |
+
- الحساب المتعطل: `youtube_health=noData`، لا PID، `output_seconds=0`، وعمر آخر مصدر ارتفع من نحو 804 إلى 844 ثانية دون تعافٍ.
|
| 33 |
+
- CPU كان منخفضًا؛ لذلك لم يكن العطل اختناق CPU أو OOM.
|
| 34 |
+
|
| 35 |
+
هذه الحالة طابقت مسارًا برمجيًا محددًا: thread حي، FFmpeg ميت، و`restart_dead_senders()` لا تُستدعى بسبب نمط نوم الحلقة.
|
| 36 |
+
|
| 37 |
+
## 3. الإصلاحات المطبقة
|
| 38 |
+
|
| 39 |
+
### 3.1 إصلاح noData الدائم
|
| 40 |
+
|
| 41 |
+
في `youtube_manager.py`:
|
| 42 |
+
|
| 43 |
+
1. تشغيل `restart_dead_senders()` بعد **كل** مرور للمدير، سواء نُفذ `tick()` أم لا.
|
| 44 |
+
2. اعتبار الحالة «غير سليمة» إذا مات FFmpeg حتى لو بقي thread حيًا؛ عندها يستيقظ المدير كل ثانيتين بدل انتظار scan كامل.
|
| 45 |
+
3. التفريق بين:
|
| 46 |
+
- مشرف جديد ما زال يفحص المصادر: مهلة آمنة افتراضيًا 120 ثانية.
|
| 47 |
+
- مشرف سبق أن استقبل وسائط ثم فقد FFmpeg: إعادة تدوير بعد 5 ثوانٍ.
|
| 48 |
+
4. إذا لم يخرج thread خلال 3 ثوانٍ بعد وضع stop وإنهاء FFmpeg، يُفصل قيده الميت من `senders` و`RelayHub`. stop flag يمنع الخيط القديم من بدء إرسال جديد عند رجوع القراءة الشبكية.
|
| 49 |
+
|
| 50 |
+
متغيرات الضبط الاختيارية:
|
| 51 |
+
|
| 52 |
+
- `YOUTUBE_DEAD_FFMPEG_RECYCLE_SECONDS=5`
|
| 53 |
+
- `YOUTUBE_SUPERVISOR_START_SECONDS=120`
|
| 54 |
+
|
| 55 |
+
### 3.2 حل 401 داخل واجهة Hugging Face
|
| 56 |
+
|
| 57 |
+
- أصبحت `/` تعرض shell دخول آمنًا بدل JSON خام `Unauthorized`.
|
| 58 |
+
- يُدخل المشغّل قيمة Secret `PASSWORD` في النموذج؛ اسم المستخدم الداخلي `admin`.
|
| 59 |
+
- النموذج يرسل Basic Authorization إلى `/api/*`، ولا يضع السر في URL أو Git.
|
| 60 |
+
- بيانات التشغيل وعمليات التعديل تبقى محمية؛ الصفحة العامة لا تحمل بي��نات حساسة.
|
| 61 |
+
- التخزين في `sessionStorage` خاص بعمر التبويب، مع زر خروج.
|
| 62 |
+
|
| 63 |
+
### 3.3 إصلاح اللوحة
|
| 64 |
+
|
| 65 |
+
- إضافة العنصرين المفقودين `#ncpu` و`#nram`؛ غيابهما كان يرمي JavaScript TypeError بعد كل refresh.
|
| 66 |
+
- عرض السقف المفتوح `0` كـ `∞` بدل `?`.
|
| 67 |
+
- إيقاف polling عندما تكون الصفحة مخفية، وتخفيفه من 5 إلى 10 ثوانٍ.
|
| 68 |
+
|
| 69 |
+
### 3.4 الخصوصية والأمان
|
| 70 |
+
|
| 71 |
+
- `/health` أصبح لiveness محدودًا: status/application/monitor/version فقط.
|
| 72 |
+
- أسماء الحسابات، room IDs، أخطاء البث، وحالة YouTube تبقى في `/api/health` و`/api/state` المحميين.
|
| 73 |
+
- `Cache-Control: no-store` وCSP و`nosniff` و`Referrer-Policy: no-referrer` وPermissions Policy.
|
| 74 |
+
- ملف التوافق القديم `tokens.json` يكتب بصلاحية `0600` بعد كل استبدال.
|
| 75 |
+
- لم تُعثر على أسرار hard-coded في الملفات المتتبعة.
|
| 76 |
+
|
| 77 |
+
### 3.5 سجلات قابلة للتشخيص
|
| 78 |
+
|
| 79 |
+
- أحداث التطبيق المهمة تُرسل إلى stdout بعد إخفاء URLs والحقول الشبيهة بالتوكنات.
|
| 80 |
+
- access log الدوري لـUvicorn معطل؛ لا يعود السجل ممتلئًا بطلبين كل خمس ثوانٍ.
|
| 81 |
+
- تبقى رسائل FFmpeg المصنفة مخفية الروابط والمفاتيح.
|
| 82 |
+
|
| 83 |
+
### 3.6 قابلية إعادة البناء
|
| 84 |
+
|
| 85 |
+
تم تثبيت التبعيات المباشرة بدل نطاقات مفتوحة:
|
| 86 |
+
|
| 87 |
+
- `fastapi==0.142.2`
|
| 88 |
+
- `uvicorn==0.54.0`
|
| 89 |
+
- `curl_cffi==0.16.3`
|
| 90 |
+
- `pydantic==2.13.5`
|
| 91 |
+
|
| 92 |
+
هذا يمنع Factory Rebuild مستقبليًا من جلب إصدار جديد تلقائيًا وتغيير السلوك دون commit.
|
| 93 |
+
|
| 94 |
+
### 3.7 حدّ أمان كوكي TikTok عند مصادر CDN
|
| 95 |
+
|
| 96 |
+
أظهر التحقق الحي بعد نشر الإصلاح الأساسي أن `@ahmadbarbooka22` استمر أكثر من 120 ثانية، بينما كان مصدر `@strongarmor` يصمت بعد 10–13 ثانية ثم يتعافى بالحارس. أثبت فحص مستقل أن الحساب مباشر وأن أول FLV عام سلّم بيانات أكثر من 12 ثانية؛ لذلك لم يكن التفسير البسيط «الحساب غير مباشر» كافيًا.
|
| 97 |
+
|
| 98 |
+
كشف تتبع طلبات الوسائط أن التطبيق كان يضيف كوكي `sessionid` يدويًا إلى روابط CDN موقعة خارج نطاق TikTok، مثل `tiktokcdn-us.com`. المتصفح لا يرسل كوكي نطاق `tiktok.com` إلى تلك المضيفات. هذا تسريب صلاحية غير لازم، وقد يغير تعامل حافة CDN مع رابط عام؛ لكنه **فرضية سببية** لمشكلة الصمت إلى أن يؤكدها رصد النسخة المنشورة.
|
| 99 |
+
|
| 100 |
+
أضيفت سياسة مركزية صغيرة:
|
| 101 |
+
|
| 102 |
+
- مضيف `tiktok.com` الحقيقي أو نطاقه الفرعي فقط يمكنه استلام ترويسات الحساب.
|
| 103 |
+
- روابط CDN لا تستلم إلا `Referer` العام، ولا تستدعي أصلًا دالة تحميل الكوكي.
|
| 104 |
+
- السياسة نفسها مطبقة على فتح FLV الأول، وإعادة إرفاق المصدر، وHLS/FFmpeg، وفحوص المدير و`ffprobe`.
|
| 105 |
+
- أسماء شبيهة مثل `tiktok.com.attacker.example` لا تتجاوز فحص حدود النطاق، ولا يسمح للمصدر بفرض ترويسة `Host`.
|
| 106 |
+
|
| 107 |
+
### 3.8 فصل عطل المصدر عن انسداد خرج YouTube
|
| 108 |
+
|
| 109 |
+
بعد نشر `6536328` تحسن `@strongarmor` إلى **540.6 ثانية** متصلة على الأقل بعد التعافي، لكن `@ahmadbarbooka22` عمل **300 ثانية** ثم عاد إلى دورات 10–13 ثانية. أظهر stderr الحقيقي السطر `Error opening output files: End of file`. وفي المقابل سلّم أول FLV للحسابين بيانات متصلة 90 ثانية في اختبارات مستقلة متكررة، ومنها HTTP/1.1. هذا الدليل غيّر التشخيص: عندما يتعطل فتح/كتابة RTMPS يتوقف FFmpeg عن قراءة `stdin`، فيمتلئ الأنبوب ويكبر عمر عداد المصدر **كنتيجة**؛ الاعتماد على العمر وحده كان يتهم TikTok خطأً، يقفز إلى HLS غير صالح، ولا يصل إلى علاج جهة YouTube.
|
| 110 |
+
|
| 111 |
+
الإصلاح النهائي يتبع تسلسلًا محدودًا بدل إعادة التشغيل العمياء:
|
| 112 |
+
|
| 113 |
+
1. يميز stderr وانسداد أنبوب FFmpeg عطل **output** عن صمت **source**.
|
| 114 |
+
2. لا يمسح روابط TikTok ولا ينتقل إلى HLS إذا كان الدليل من خرج RTMPS.
|
| 115 |
+
3. عند أول رفض خرج مؤكد يعيد قراءة عنوان الاستقبال والمفتاح الحاليين من YouTube API.
|
| 116 |
+
4. عند الرفض الثاني، ومع ثبوت وصول بايتات المصدر، يحوّل ذلك المذيع وحده إلى `matchgop`: H.264/AAC�� كانفس ثابت، CFR، GOP مغلق وIDR كل ثانيتين؛ وهي صيغة YouTube الموثقة بدل تكرار `copy` الذي ترفضه الحافة.
|
| 117 |
+
5. يمكن فرض هذا الوضع منذ أول إطار لحساب معروف الحساسية عبر `YOUTUBE_FORCE_TRANSCODE_USERS`، مع احترام `YOUTUBE_LIGHT_MAX` حتى لا يتحول علاج مذيع إلى اختناق كل المذيعين.
|
| 118 |
+
6. عولج أيضًا شكل TikTok الحالي الذي يعيد `hls_pull_url` كسلسلة واحدة؛ كان استدعاء `.items()` عليها يسقط fallback كله.
|
| 119 |
+
|
| 120 |
+
هذه السياسة لا تدّعي منع انقطاع TikTok/YouTube/Hugging Face الخارجي بنسبة مطلقة، لكنها تمنع نمط الانقطاع الداخلي المقاس: إعادة `copy` كل 10 ثوانٍ مع تشخيص الطرف الخطأ.
|
| 121 |
+
|
| 122 |
+
### 3.9 CBR حقيقي بعد حكم YouTube المباشر
|
| 123 |
+
|
| 124 |
+
في تشغيل الإنتاج للنسخة `2211b63` استعاد الحسابان القبول واستمر `@strongarmor` **1380.4 ثانية** و`@ahmadbarbooka22` **1439.6 ثانية** على الأقل بلا إعادة تشغيل FFmpeg. لكن واجهة YouTube نفسها سجلت للحسابين `videoIngestionStarved [error] Video output low`، وهو حكم صريح بأن المشاهد قد يتعرض للتخزين المؤقت؛ لذلك لا تكفي عبارة «العملية ما زالت حية» للحكم بالنجاح.
|
| 125 |
+
|
| 126 |
+
كشف قياس محلي للأمر نفسه أن الجمع بين `-crf 22` و`-b:v 4500k -maxrate 4500k` لم يكن CBR: مشهد ساكن 720x1280/30 خرج عند **14.12 kbit/s** فقط، رغم أن رأس FFmpeg كان يطبع 4500 kbit/s. بعد إزالة CRF وإضافة `-minrate 4500k` و`nal-hrd=cbr:force-cfr=1` خرج القياس نفسه عند **4443.72 kbit/s**. هذه ليست زيادة اسمية للرقم، بل filler موثق داخل H.264 يحافظ على معدل النقل عند المشاهد الساكنة. يطابق ذلك توجيه YouTube الرسمي بأن ترميز البث الحي يكون CBR، ويبقي 4.5 Mbit/s فوق الحد الأدنى الرسمي لـH.264 720p/30.
|
| 127 |
+
|
| 128 |
+
لكن الرصد بعد نشر CBR لم يسمح باعتباره العلاج الكامل: عاد `videoIngestionStarved` للحسابين. كشف endpoint المقاييس الرسمي للـSpace أثناء عمل التحويلين **928 عينة**: وسيط CPU **99%**، وp95 **101%**، وقمة **104%**؛ أي أن حصتي CPU كانتا مشبعتين فعلًا، بينما بقيت الذاكرة بعيدة عن الحد. هذا دليل مباشر على أن مورد الترميز — لا قيمة bitrate الاسمية وحدها — كان يخنق التسليم.
|
| 129 |
+
|
| 130 |
+
جُرّب `superfast` لأنه خفض زمن قياس x264 المحلي نحو 25% (`4.40x` إلى `5.84x`)، لكن حكم الإنتاج كان أوضح: أول نافذة 15 دقيقة بقي وسيط CPU فيها **91%** وp95 **100%**، والنافذة التالية وسيطها **85%** وp95 **99%**، ثم عاد `videoIngestionStarved` لأحمد. لذلك لا يُسمى هذا headroom. انتقل الافتراضي إلى `ultrafast`، الذي بلغ **10.86x** محليًا (أسرع 46% من `superfast`) مع إبقاء CBR/GOP/المقاس ثابتة. هذا preset يخرج H.264 Constrained Baseline بدل High، وهو مدعوم لدى YouTube لكنه أقل كفاءة ضغطًا؛ المقايضة مقصودة لأن المصدرين المقاسين أصلهما نحو 1 Mbit/s بينما الخرج 4.5 Mbit/s، ولأن صورة أقل كفاءة أفضل من تخزين مؤقت وانقطاع. يجب أن يؤكد الرصد الحي بقاء CPU دون 85% واختفاء تشخيص YouTube؛ وإلا فالخيار الصادق هو عتاد CPU Upgrade أو تحويل واحد، لا مزيد من التعديلات التخمينية.
|
| 131 |
+
|
| 132 |
+
لم تُضف primary/backup أو `tee` في هذه المرحلة: لا يعالج مسار احتياطي نقص البيانات إذا كانت النسختان من المرمّز نفسه ناقصتين، كما أن نشره من دون تحقق metadata واختبار موارد سيزيد التعقيد والمخاطر بلا دليل سببي.
|
| 133 |
+
|
| 134 |
+
### 3.10 تمرير تغيير سجل المفكك بلا قطع جلسة RTMPS
|
| 135 |
+
|
| 136 |
+
#### سبب الانقطاع في الشيفرة السابقة
|
| 137 |
+
|
| 138 |
+
كان `FLVBridge` يلتقط كل `AVCDecoderConfigurationRecord` و`HEVCDecoderConfigurationRecord`، ثم يقارن البايتات بالسجل الأول. عند اختلاف SPS/PPS أو VPS/SPS/PPS كان يرمي `FormatChanged` **قبل** إخراج الوسم الجديد. يلتقط المدير الاستثناء، يغلق stdin وFFmpeg، ثم ينتقل إلى `matchgop/x264`. هذه ليست معالجة داخل الجلسة؛ إنها قطع ناشر RTMPS ظاهر للمشاهد، وهي تفسر الوميض/السواد عند PK أو عودة الهاتف من الخلفية.
|
| 139 |
+
|
| 140 |
+
الإصلاح المرشح يزيل هذا المسار كاملًا من `relay.py` و`youtube_manager.py`:
|
| 141 |
+
|
| 142 |
+
1. يسجل الجسر عدد تغييرات decoder config ونوع FourCC للمراقبة فقط.
|
| 143 |
+
2. يخرج سجل التهيئة الجديد كاملًا في ترتيبه الأصلي، ثم الإطار المشفر التالي، عبر stdin وFFmpeg وجلسة RTMPS المفتوحة نفسها.
|
| 144 |
+
3. لا يرمي `FormatChanged` حتى لو أنشأه مستدعٍ قديم بـ`detect_format_change=True`؛ بقي اسم الاستثناء للتوافق فقط ولا يوجد مستدعٍ إنتاجي له.
|
| 145 |
+
4. عند تجديد HTTP-FLV، يحذف رأس الملف الثاني وmetadata البدئية، ويحذف **فقط** نسخة startup المطابقة للسجل السابق. إذا اختلف السجل فلا يُحذف.
|
| 146 |
+
5. يحول HEVC القديم ذي CodecID=12 إلى Enhanced RTMP: `SequenceStart=0`، و`CodedFrames=1` مع CTS الموقّع نفسه، و`SequenceEnd=2`، وFourCC=`hvc1`. لا يلمس access unit أو keyframe flag أو DTS/CTS.
|
| 147 |
+
|
| 148 |
+
#### لماذا لا نجمع SPS/PPS قديمًا وجديدًا عشوائيًا؟
|
| 149 |
+
|
| 150 |
+
كل سجل `avcC` يسمح أصلًا بعدة SPS/PPS، وكل `hvcC` يسمح بمصفوفات متعددة من VPS/SPS/PPS. الجسر يحفظ **السجل الكامل** كما جاء، واختبار مخصص يثبت عدم إسقاط السجلات المتعددة. أما ضم سجلين تاريخيين فقد يضع نسختين مختلفتين تحملان parameter-set ID نفسه داخل config واحد؛ عندها لا يوجد اختيار حتمي للمفكك وقد نصنع المشكلة التي نحاول حلها. المراجع العملية (`rtmp-rs` وFFmpeg/GStreamer) تنقل config الجديد؛ لا تبني اتحادًا تراكميًا غير محدود. لذلك آخر سجل كامل هو المرجع، مع بقاء access units كما هي.
|
| 151 |
+
|
| 152 |
+
#### إثبات المسار عبر FFmpeg لا الجسر وحده
|
| 153 |
+
|
| 154 |
+
القول إن الجسر كتب SequenceStart لا يكفي لأن FFmpeg يقع بينه وبين YouTube. مصدر FFmpeg 7.1 يبين الآتي:
|
| 155 |
+
|
| 156 |
+
- `flvdec.c` يضع سجلًا لاحقًا في `AV_PKT_DATA_NEW_EXTRADATA` على الحزمة التالية.
|
| 157 |
+
- `flvenc.c` يقارن هذا side-data بـextradata الحالي، ثم يستدعي `flv_write_codec_header()` عند الاختلاف قبل كتابة الحزمة.
|
| 158 |
+
|
| 159 |
+
أضيف `test_flv_bridge.py` بfixtures حتمية لا تحتاج شبكة. اختباره الحقيقي مع FFmpeg 7 يمرر سجلين مختلفين لكل من AVC وHEVC عبر `-c:v copy`، ثم يفك وسوم FLV الناتجة ويتحقق من وجود السجلين بالبايت والترتيب. ويختبر أيضًا chunk boundaries، CTS سالبًا، HEVC القديم والمعزز، تعدد SPS/PPS داخل avcC، reconnect مع DTS متزايد، وسجلًا معززًا مبتورًا يفشل بشكل مضبوط.
|
| 160 |
+
|
| 161 |
+
#### حدود تبدل H.264 ↔ H.265
|
| 162 |
+
|
| 163 |
+
تبدل decoder config داخل codec واحد ليس كتبدل codec. fixture قسري AVC→HEVC أثبت:
|
| 164 |
+
|
| 165 |
+
- `FLVBridge` يستطيع تمثيل FourCC الجديد ولا يرمي استثناء ولا يقتطع الوسوم.
|
| 166 |
+
- FFmpeg 7 يرى HEVC اللاحق كـ`New video stream` جديد، بينما أمر النشر فتح خريطة `-map 0:v:0` ورأس خرج واحدًا قبل ظهور ذلك stream. لذلك لا ينتقل خرج الفيديو المفتوح إلى codec الجديد.
|
| 167 |
+
|
| 168 |
+
Enhanced RTMP v2 يعرّف multitrack، لكن ذلك لا يجعل track واحدًا يغير codec تلقائيًا، ولا يثبت أن YouTube سيختار track جديدًا في منتصف البث. كما أن `rtmp-rs 0.6.0` ليس دالة Python بديلة: parser فيه يثبت envelope `0x90 + hvc1 + config`، لكن `RtmpPublisher` العام في هذه النسخة يرسل الصوت فقط. دمجه يحتاج ناشرًا جديدًا واختبارات RTMPS/YouTube، وهو تغيير معماري أكبر لا يجوز إخفاؤه داخل «إصلاح صغير».
|
| 169 |
+
|
| 170 |
+
لذلك إعادة توصيل URL تثبت codec family نفسه، لكنها تسمح بتبدل المقاس/profile/config داخله. إذا لم يعد TikTok يقدم codec نفسه، لا تُغذى خريطة FFmpeg ببايتات ستُسقط بصمت. دعم switch كامل مستقبلًا يتطلب واحدًا من:
|
| 171 |
+
|
| 172 |
+
- ناشر RTMP tag-level يحافظ على الاتصال ويرسل audio/video messages مباشرة مع تفاوض Enhanced RTMP؛ أو
|
| 173 |
+
- FFmpeg حديثًا ومسار multitrack مُعلنًا منذ البداية، مع fixture وقياس قبول YouTube وانتقال المشغل.
|
| 174 |
+
|
| 175 |
+
لا يدّعي هذا الإصلاح أن أيًا منهما مثبت.
|
| 176 |
+
|
| 177 |
+
#### وضع التشغيل الافتراضي
|
| 178 |
+
|
| 179 |
+
أزيل فرض `matchgop` عن `ahmadbarbooka22,strongarmor`. أصبحت القيم الافتراضية:
|
| 180 |
+
|
| 181 |
+
- `YOUTUBE_LIGHT_MAX=0`
|
| 182 |
+
- `YOUTUBE_AUTO_TRANSCODE=0`
|
| 183 |
+
- `YOUTUBE_ENHANCED_RTMP=auto`
|
| 184 |
+
- لا `YOUTUBE_FORCE_TRANSCODE_USERS`
|
| 185 |
+
|
| 186 |
+
أي أن فيديو H.264 ينسخ، وفيديو H.265 ينسخ مع إعلان `hvc1`، ولا يوجد فك/scale/x264 في هذا الإصلاح. يبقى AAC normalization منفصلًا ولا يغيّر إطارات الفيديو. مسار x264 التاريخي ما زال في المصدر كخيار يدوي فقط؛ رفع `YOUTUBE_LIGHT_MAX` هو opt-in صريح.
|
| 187 |
+
|
| 188 |
+
#### سجل أحداث البث الدائم
|
| 189 |
+
|
| 190 |
+
أضيف `stream_monitor.py` ويكتب مصفوفة JSON محدودة افتراضيًا إلى `logs/stream_events.json` تحت `DATA_DIR`/Storage Bucket؛ يضيف كل حدث بكلفة ثابتة تقريبًا ويضغط الملف دوريًا عبر atomic replace بدل إعادة كتابة الملف كاملًا مع كل health poll. كل سجل يحوي `timestamp` بتوقيت UTC و`sequence` و`broadcaster` و`event` و`details`. لا تُكتب فيديوهات أو access units أو URLs أو stream keys أو cookies/tokens؛ المرشح يحذف هذه المفاتيح قبل الكتابة، والملف `0600` ويحتفظ بآخر 10,000 حدث فقط.
|
| 191 |
+
|
| 192 |
+
الأحداث المتصلة فعليًا بمصادرها:
|
| 193 |
+
|
| 194 |
+
- `CODEC_CHANGE`: من مقارنة FourCC في SequenceStart داخل `FLVBridge`.
|
| 195 |
+
- `RESOLUTION_CHANGE`: من parsing بايتي لـSPS داخل avcC/hvcC، من دون فك إطار.
|
| 196 |
+
- `BITRATE_CHANGE`: نافذة أربع ثوانٍ من أحجام video tags وDTS، بعتبة نسبة 35% وفارق 50 kbit/s لتجنب ضجيج VBR العادي.
|
| 197 |
+
- `KEYFRAME_CHANGE`: من keyframe flag وفرق DTS بين الإطارات المفتاحية، مع rate limit.
|
| 198 |
+
- `SOURCE_CHANGE`: يسجل هبوط rendition صامت إلى جودة أقل أو استعادة الجودة المفضلة لاحقًا، مع الأبعاد والسبب ومن دون URL.
|
| 199 |
+
- `RECONNECT`: يميز `scope=tiktok_http` مع `outbound_rtmp_reused=true` عن `scope=youtube_rtmp` عند فتح ناشر خرج ثانٍ فعليًا.
|
| 200 |
+
- `CONNECTION_ERROR`: من فشل الفتح أو حارس source/output أو خروج FFmpeg على جهة YouTube.
|
| 201 |
+
- `YOUTUBE_HEALTH`: من `status.healthStatus` وقائمة configuration issues كل 20 ثانية (الحد الأدنى 15 ثانية).
|
| 202 |
+
|
| 203 |
+
يمكن للمشغل قراءة السجل من endpoint محمي بالمصادقة: `GET /api/stream-events?limit=200&broadcaster=user`. هذا السجل هو دليل اختبار PK والخلفية والإشعارات؛ لكنه لا يستبدل مشاهدة عميل YouTube فعلية لأن العطل الأصلي كان player-side بينما VOD سليم.
|
| 204 |
+
|
| 205 |
+
#### fallback جودة المصدر بلا ترميز أو قطع RTMP
|
| 206 |
+
|
| 207 |
+
كان اختيار `YOUTUBE_PREFER_H264` يحتفظ فقط بمرشحات H.264 ذات الضلع القصير 720 أو أكثر عند وجودها، فيسقط SD/LD من قائمة النجاة رغم أن `rank_sources` اكتشفها. كذلك كان المشرف ينتظر إذا اختفى rendition المثبت بدل تجربة مصدر أقل. عُدّل ذلك بأقل نطاق ممكن:
|
| 208 |
+
|
| 209 |
+
1. تبقى الجودة H.264/720+ أولًا، لكن لا تُحذف renditions الأقل ولا HEVC الاحتياطية.
|
| 210 |
+
2. عند صمت FLV، يُرصد رابط طازج للجودة نفسها أولًا.
|
| 211 |
+
3. إذا أعاد TikTok الرابط الصامت نفسه، يُختار أقرب FLV أصغر من **عائلة الترميز نفسها** ويُدخل عبر `FLVBridge.reconnect()` في FFmpeg والناشر RTMP المفتوحين؛ لا x264 ولا إعادة فتح YouTube.
|
| 212 |
+
4. لا يُقطع مصدر منخفض يعمل لمجرد رفع الدقة. عند تجديد طبيعي لاحق فقط، وبعد 300 ثانية مستقرة افتراضيًا، يمكن استعادة الـrendition المفضل. هذا يمنع quality flapping المتعمد.
|
| 213 |
+
5. HLS أو تبدل H.264↔H.265 لا يُحقن في خريطة FFmpeg المفتوحة؛ تبقى القيود السابقة صريحة.
|
| 214 |
+
|
| 215 |
+
#### المراجع التي حُكم بها
|
| 216 |
+
|
| 217 |
+
- Enhanced RTMP v2 الرسمي: <https://veovera.org/docs/enhanced/enhanced-rtmp-v2.pdf>
|
| 218 |
+
- FFmpeg 7.1 FLV demux/mux: <https://github.com/FFmpeg/FFmpeg/blob/n7.1.1/libavformat/flvdec.c> و<https://github.com/FFmpeg/FFmpeg/blob/n7.1.1/libavformat/flvenc.c>
|
| 219 |
+
- GStreamer 797255 (اقتراح إعادة stream headers، أُغلق obsolete) و797256 (التغيير المدمج الذي يسمح بتغير codec-data بعد بدء streamable FLV): <https://bugzilla.gnome.org/show_bug.cgi?id=797255> و<https://bugzilla.gnome.org/show_bug.cgi?id=797256>
|
| 220 |
+
- `rtmp-rs 0.6.0`: <https://docs.rs/crate/rtmp-rs/latest/source/src/media/enhanced_video.rs> وpublisher: <https://docs.rs/crate/rtmp-rs/latest/source/src/client/publisher.rs>
|
| 221 |
+
- إعدادات YouTube الحالية تسرد H.264 وH.265 وAV1 مع RTMP/RTMPS: <https://support.google.com/youtube/answer/2853702?hl=en>
|
| 222 |
+
- صفحة `py-restream` تعلن bypass/stream-copy، لكن مستودع GitLab المشار إليه صار يطلب تسجيل دخول؛ لذلك لم يُستعمل كمصدر لسلوك تغيير config: <https://hub.docker.com/r/nqdev/py-restream>
|
| 223 |
+
|
| 224 |
+
## 4. سياسة أقل ترميز ممكن
|
| 225 |
+
|
| 226 |
+
سياسة هذه النسخة هي منع **إعادة ترميز الفيديو** افتراضيًا:
|
| 227 |
+
|
| 228 |
+
1. H.264/FLV → `copy`، مع تمرير avcC الجديد في الجلسة نفسها.
|
| 229 |
+
2. HEVC/FLV → تحويل غلاف CodecID=12 عند الحاجة إلى Enhanced RTMP `hvc1` ثم `copy`، مع تمرير hvcC الجديد.
|
| 230 |
+
3. لا يُستخدم تغير المقاس/PK سببًا لـx264 أو لإغلاق الناشر.
|
| 231 |
+
4. `YOUTUBE_LIGHT_MAX=0` و`YOUTUBE_AUTO_TRANSCODE=0` يمنعان كل fallback فيديو تلقائي. رفع الحد خيار مشغل صريح لمسار تاريخي خارج هذا الإصلاح.
|
| 232 |
+
5. `MAX_CONCURRENT_RELAYS=4` و`YOUTUBE_MAX_EVENTS=4` يبقيان سقف أربعة ناشرين؛ يجب خفضهما إذا أثبتت الشبكة/ذاكرة الحافة عكس ذلك، لا بسبب x264 الذي لم يعد يعمل افتراضيًا.
|
| 233 |
+
|
| 234 |
+
YouTube يسرد H.265 ضمن codecs المقبولة حاليًا لـRTMP/RTMPS، لكن نجاح المواصفة لا يغني عن اختبار الحدث الحقيقي. لذلك لا يُنشر الادعاء النهائي «اختفى السواد» قبل اختبار PK والخلفية والإشعارات على `ahmadbarbooka22` ومراقبة YouTube health والمشاهد الفعلي.
|
| 235 |
+
|
| 236 |
+
## 5. اختبارات حقيقية ومحاكاة واقعية
|
| 237 |
+
|
| 238 |
+
نفذ `verify.sh` بعد إصلاح config passthrough وإضافة المراقبة وfallback الجودة، والنتيجة **328/328** فحصًا ناجحًا:
|
| 239 |
+
|
| 240 |
+
- فحص بنيوي واحد يؤكد غياب التسجيل وواجهة تنزيل الفيديو.
|
| 241 |
+
- 25 فحص تزامن وعزل حسابات.
|
| 242 |
+
- 29 regression للدخول والخصوصية وحدود الكوكي وفصل عطل RTMPS عن جوع المصدر، ومنها API سجل الأحداث المحمي.
|
| 243 |
+
- 86 فحص relay/API/UI، ومنها غياب أي runtime caller لـ`FormatChanged`، والاحتفاظ بمصادر الجودة الأقل، والهبوط/العودة المتحكمان بلا تبدل codec.
|
| 244 |
+
- 33 فحصًا خاصًا بـFLVBridge/StreamMonitor: AVC/HEVC، CTS/DTS، reconnect، multi-SPS/PPS، parsing دقة SPS، codec/resolution/bitrate/keyframe events، JSON وصلاحية `0600` وتنقية الأسرار، وتمرير FFmpeg الحقيقي للسجلين ولـaccess units بالبايت.
|
| 245 |
+
- 40 فحص completion، منها FFmpeg حقيقي ومقارنة مهلات الصمت 12/30/45 ثانية.
|
| 246 |
+
- 38 فحص watchdog بشبكة HTTP محلية وFFmpeg حقيقي، ومنها أن HEVC يستخدم `-c:v copy` ولا يدخل `libx264`.
|
| 247 |
+
- 76 فحص lifecycle، منها source stall → cleanup → re-observe → session جديدة، استئناف حدث YouTube نفسه، حدود التزامن، 403، offline، HLS fallback، وعدم تراكم العمليات.
|
| 248 |
+
|
| 249 |
+
فحوص إضافية:
|
| 250 |
+
|
| 251 |
+
- `compileall`: ناجح.
|
| 252 |
+
- Ruff للأخطاء الحرجة/الأسماء غير المعرفة: ناجح.
|
| 253 |
+
- `pip check`: ناجح.
|
| 254 |
+
- `pip-audit -r requirements.txt`: لا توجد ثغرات معروفة في تبعيات التطبيق المثبتة وقت التدقيق.
|
| 255 |
+
- فحص أسرار الملفات المتتبعة: لا توجد مطابقة لتوكن HF أو Google secret أو private key.
|
| 256 |
+
|
| 257 |
+
الاختبارات المحلية لا تدّعي أنها YouTube/TikTok حقيقيان؛ الدليل الحي المستخدم لتشخيص العطل جاء من الـSpace الجاري، بينما اختبارات FFmpeg/network محلية وحقيقية وليست mocks للعملية.
|
| 258 |
+
|
| 259 |
+
## 6. إعدادات Hugging Face الموصى بها
|
| 260 |
+
|
| 261 |
+
### Variables
|
| 262 |
+
|
| 263 |
+
| المفتاح | القيمة | السبب |
|
| 264 |
+
|---|---:|---|
|
| 265 |
+
| `MAX_CONCURRENT_RELAYS` | `4` | يمنع عدد عمليات غير محدود |
|
| 266 |
+
| `YOUTUBE_MAX_EVENTS` | `4` | يطابق سقف الناشرين |
|
| 267 |
+
| `YOUTUBE_LIGHT_MAX` | `0` | يعطل إعادة ترميز الفيديو؛ لا يرفع إلا كـopt-in خارج إصلاح config passthrough |
|
| 268 |
+
| `YOUTUBE_AUTO_TRANSCODE` | `0` | يمنع fallback تلقائيًا إلى x264 عند تغير المصدر |
|
| 269 |
+
| `YOUTUBE_FORCE_TRANSCODE_USERS` | احذف المتغير | لا يُجبر أحمد أو Strong على `matchgop` |
|
| 270 |
+
| `YOUTUBE_ENHANCED_RTMP` | `auto` | يعلن `hvc1` فقط عندما يكون payload المنسوخ HEVC، ولا يعلنه كذبًا على H.264 |
|
| 271 |
+
| `YOUTUBE_VIDEO_MODE` | `original` | يبقي H.264 وH.265 ضمن المرشحين؛ يفضل H.264 مفيدًا عند وجوده ويقبل HEVC عند غيابه |
|
| 272 |
+
| `YOUTUBE_SOURCE_UPGRADE_SECONDS` | `300` | لا يعيد الجودة الأعلى إلا عند تجديد طبيعي بعد خمس دقائق مستقرة على fallback |
|
| 273 |
+
| `YOUTUBE_HEALTH_INTERVAL` | `20` | يسجل healthStatus أثناء سيناريو الاختبار؛ راقب quota عند 3–5 أحداث متزامنة |
|
| 274 |
+
| `STREAM_EVENT_MAX` | `10000` | يمنع نمو `stream_events.json` بلا حد |
|
| 275 |
+
| `YOUTUBE_DAILY_BUDGET` | اترك القيمة الحالية المدروسة | منع استنزاف API |
|
| 276 |
+
|
| 277 |
+
في سقفي الناشرين/الأحداث تعني `0` بلا سقف، فلا تضعها بدل `4`. أما `YOUTUBE_LIGHT_MAX=0` فمعناه المقصود **صفر عمليات x264**. Variables في الـSpace تتقدم على Dockerfile، لذا يجب حذف القيم القديمة `2` وقائمة الحسابات المجبرة عند النشر.
|
| 278 |
+
|
| 279 |
+
### Secrets
|
| 280 |
+
|
| 281 |
+
المفاتيح المطلوبة الموجودة بالاسم الصحيح:
|
| 282 |
+
|
| 283 |
+
- `PASSWORD`
|
| 284 |
+
- `GOOGLE_CLIENT_ID`
|
| 285 |
+
- `GOOGLE_CLIENT_SECRET`
|
| 286 |
+
- `YOUTUBE_REFRESH_TOKEN`
|
| 287 |
+
- `TIKTOK_SESSIONID` أو `TIKTOK_COOKIES`
|
| 288 |
+
|
| 289 |
+
لا حاجة إلى `YOUTUBE_STREAM_KEY` إذا كانت أتمتة OAuth تنشئ stream مستقلًا لكل حساب. مفتاح RTMPS بيئي واحد لا يجوز استخدامه لعدة مذيعين متزامنين.
|
| 290 |
+
|
| 291 |
+
## 7. مراقبة وتشغيل يومي قليل التدخل
|
| 292 |
+
|
| 293 |
+
### إنذارات حرجة
|
| 294 |
+
|
| 295 |
+
- حدث YouTube `live` مع `relay_pid=null` لأكثر من 30 ثانية.
|
| 296 |
+
- `youtube_health=noData` لأكثر من 60 ثانية.
|
| 297 |
+
- `source_age>20s` بينما الحساب LIVE.
|
| 298 |
+
- `youtube_manager=stopped` أو monitor متوقف.
|
| 299 |
+
- انتهاء TikTok `sid_guard` خلال أقل من ساعة.
|
| 300 |
+
|
| 301 |
+
### إنذارات تحذيرية
|
| 302 |
+
|
| 303 |
+
- CPU فوق 85% من الحصة ثلاث دقائق.
|
| 304 |
+
- `videoIngestionStarved` أو `bitrateLow` مستمر أكثر من دقيقتين.
|
| 305 |
+
- ثلاث عمليات إغلاق مبكر متتالية من وجهة YouTube.
|
| 306 |
+
|
| 307 |
+
### Runbook
|
| 308 |
+
|
| 309 |
+
1. افحص Container Logs وابحث عن `[WATCHDOG]` و`[RESTART]` و`[CLEANUP]`.
|
| 310 |
+
2. من اللوحة، قارن `relay_alive/PID` مع `youtube_health` و`source_age`.
|
| 311 |
+
3. إذا التوكن 401/403: حدّث TikTok Secret؛ لا تعدّل الكود.
|
| 312 |
+
4. إذا YouTube 403 `concurrentBroadcastsExceedLimit`: أغلق الحدث الزائد في Studio؛ لا تكرر POST.
|
| 313 |
+
5. إذا CPU مرتفع: خفض `MAX_CONCURRENT_RELAYS` و`YOUTUBE_MAX_EVENTS` إلى 2، واترك `YOUTUBE_LIGHT_MAX=0`؛ لا تعالج الضغط بترميز فيديو جديد.
|
| 314 |
+
6. إذا build فشل بعد تحديث تبعية: ارجع إلى آخر commit ناجح؛ التبعيات الآن pinned لتقليل هذا الاحتمال.
|
| 315 |
+
|
| 316 |
+
## 8. ما لا يمكن ضمانه برمجيًا
|
| 317 |
+
|
| 318 |
+
- TikTok ليس API بث عامة مستقرة لهذا الاستخدام؛ قد يغير schema أو signatures أو يمنع IP مركز البيانات.
|
| 319 |
+
- كوكيز TikTok تنتهي وقد تحتاج تحققًا بشريًا.
|
| 320 |
+
- YouTube يفرض quota وصلاحيات وحدود بث متزامن؛ 403 دائم لا يعالج بإعادة المحاولة السريعة.
|
| 321 |
+
- انقطاع Hugging Face أو إعادة تشغيل الحاوية خارج سيطرة التطبيق.
|
| 322 |
+
- stream copy يعتمد على صحة codec/GOP/timestamps الواردة؛ المصدر الفاسد يجب أن يفشل بوضوح أو ينتظر rendition صالحًا، لا أن يتحول سرًا إلى x264.
|
| 323 |
+
|
| 324 |
+
التصميم بعد الإصلاح يعالج هذه الحالات بمبدأ: **fail visible، لا تكرار أحداث، لا تسريب أسرار، وتعافٍ تلقائي حين يكون التعافي آمنًا**.
|
| 325 |
+
|
| 326 |
+
## 9. مصادر رسمية وتجارب مطورين
|
| 327 |
+
|
| 328 |
+
- [Hugging Face — Docker Spaces: الأسرار، UID 1000، والمنفذ والتخزين](https://huggingface.co/docs/hub/spaces-sdks-docker)
|
| 329 |
+
- [Hugging Face — Spaces Overview: الموارد وSecrets/Variables](https://huggingface.co/docs/hub/spaces-overview)
|
| 330 |
+
- [Hugging Face — إدارة Space وقراءة build/run logs برمجيًا](https://huggingface.co/docs/huggingface_hub/main/en/guides/manage-spaces)
|
| 331 |
+
- [تجربة مطورين: سحب logs عبر JWT/SSE](https://github.com/huggingface/huggingface_hub/issues/2667)
|
| 332 |
+
- [تجربة مطورين: Container logs قد تعرض startup فقط رغم عمل التطبيق](https://discuss.huggingface.co/t/docker-space-runs-normally-but-run-logs-only-show-application-startup-banner-no-container-stdout-stderr/173988)
|
| 333 |
+
- [تجربة مطورين: مشاكل iframe/خصوصية المتصفح مع مصادقة Spaces](https://discuss.huggingface.co/t/persistent-404-on-docker-space-app-port-routing-seems-to-be-ignored-user-josejar/159665)
|
| 334 |
+
- [YouTube LiveStreams: streamStatus وhealthStatus وnoData](https://developers.google.com/youtube/v3/live/docs/liveStreams)
|
| 335 |
+
- [YouTube: أنواع مشاكل الصحة مثل gopSizeLong وvideoIngestionStarved وvideoCodec](https://developers.google.com/youtube/v3/live/docs/liveStreams/health_status_messages)
|
| 336 |
+
- [YouTube Help: RTMPS، CBR، H.264/AAC، وkeyframe كل ثانيتين وبحد أقصى 4](https://support.google.com/youtube/answer/2853702?hl=en)
|
| 337 |
+
- [تجارب مشغلي OBS: RTMP WriteN/قطع YouTube بعد دقائق ثم reconnect](https://obsproject.com/forum/threads/rtmp-errors-streaming-to-youtube.135130/)
|
| 338 |
+
- [YouTube: دورة البث وشرط streamStatus=active قبل transition](https://developers.google.com/youtube/v3/live/life-of-a-broadcast)
|
| 339 |
+
- [YouTube: أخطاء transition وحدود البث المتزامن](https://developers.google.com/youtube/v3/live/docs/liveBroadcasts/transition)
|
| 340 |
+
- [FFmpeg Protocols: rw_timeout وإعادة اتصال HTTP وRTMPS](https://ffmpeg.org/ffmpeg-protocols.html)
|
| 341 |
+
- [تجربة مستخدم FFmpeg: استخدام rw_timeout لحل input timeout](https://ffmpeg.org/pipermail/ffmpeg-user/2019-June/044682.html)
|
Dockerfile
CHANGED
|
@@ -5,8 +5,8 @@ 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
|
| 9 |
-
COPY verify.sh verify_tokens.py probe_live.py test_watchdog.py test_lifecycle.py test_relay.py test_concurrency.py
|
| 10 |
|
| 11 |
# TikTok Live Monitor → Direct Relay → YouTube. No local video files.
|
| 12 |
ENV TZ=Asia/Baghdad \
|
|
@@ -15,10 +15,10 @@ ENV TZ=Asia/Baghdad \
|
|
| 15 |
YOUTUBE_SOURCE_STALL_SECONDS=12 \
|
| 16 |
MAX_CONCURRENT_RELAYS=4 \
|
| 17 |
YOUTUBE_MAX_EVENTS=4 \
|
| 18 |
-
YOUTUBE_LIGHT_MAX=
|
| 19 |
YOUTUBE_TITLE_TEMPLATE="{broadcaster} | {date} {time}" \
|
| 20 |
YOUTUBE_SEND_MODE=auto \
|
| 21 |
-
YOUTUBE_AUTO_TRANSCODE=
|
| 22 |
YOUTUBE_AUDIO_PROFILE=aac_low \
|
| 23 |
YOUTUBE_AUDIO_BITRATE=128k \
|
| 24 |
YOUTUBE_AUDIO_CHANNELS=2 \
|
|
@@ -29,15 +29,17 @@ ENV TZ=Asia/Baghdad \
|
|
| 29 |
YOUTUBE_RETRY_MIN=1 \
|
| 30 |
YOUTUBE_RETRY_MAX=60 \
|
| 31 |
YOUTUBE_SOURCE_LIMIT=6 \
|
| 32 |
-
|
| 33 |
YOUTUBE_FLAP_LIMIT=4 \
|
| 34 |
YOUTUBE_FLAP_FALLBACK_MODE=matchgop \
|
| 35 |
YOUTUBE_COPY_RECOVERY=1 \
|
| 36 |
YOUTUBE_COPY_RECOVERY_SECONDS=60 \
|
| 37 |
-
YOUTUBE_X264_PRESET=
|
| 38 |
-
YOUTUBE_CRF=22 \
|
| 39 |
YOUTUBE_FIFO_TIMESHIFT=0 \
|
| 40 |
-
YOUTUBE_HEALTH_INTERVAL=
|
|
|
|
|
|
|
|
|
|
| 41 |
YOUTUBE_OBS_HOLD_SECONDS=900 \
|
| 42 |
YOUTUBE_SOURCE_RETRY=15 \
|
| 43 |
YOUTUBE_FORCE_GAP=5 \
|
|
@@ -47,22 +49,20 @@ ENV TZ=Asia/Baghdad \
|
|
| 47 |
YOUTUBE_FFMPEG_LOGLEVEL=info \
|
| 48 |
YOUTUBE_SOURCE_READ_TIMEOUT=15 \
|
| 49 |
YOUTUBE_SOURCE_READ_ATTEMPTS=3 \
|
|
|
|
| 50 |
YOUTUBE_PROGRESS_STALL_SECONDS=60 \
|
| 51 |
YOUTUBE_KILL_GRACE_SECONDS=10 \
|
| 52 |
YOUTUBE_PUMP_JOIN_SECONDS=2 \
|
| 53 |
YOUTUBE_AUTH_PAUSE_SECONDS=90 \
|
| 54 |
YOUTUBE_SESSION_MAX_SECONDS=21600 \
|
| 55 |
-
YOUTUBE_ENHANCED_RTMP=
|
| 56 |
YOUTUBE_SOURCE_GAP_SUSPECT_SECONDS=8 \
|
| 57 |
TIKTOK_TT_TARGET_IDC=useast1a \
|
| 58 |
STORAGE_WAIT_SECONDS=30 \
|
| 59 |
HLS_START_INDEX=-3 \
|
| 60 |
-
KICK_MAX_HEIGHT=1080 \
|
| 61 |
-
KICK_SEG_RETRY=2 \
|
| 62 |
-
KICK_TIMEOUT=20 \
|
| 63 |
PORT=7860 \
|
| 64 |
PYTHONUNBUFFERED=1 \
|
| 65 |
YOUTUBE_VIDEO_MODE=original
|
| 66 |
|
| 67 |
EXPOSE 7860
|
| 68 |
-
CMD ["sh", "-c", "exec uvicorn app:app --host 0.0.0.0 --port ${PORT:-7860} --timeout-graceful-shutdown 65"]
|
|
|
|
| 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 stream_monitor.py telemetry.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_source_reconnect.py test_ingest_routes.py test_transition_ingest.py test_concurrency.py test_flv_bridge.py test_adaptive_format.py test_regressions.py test_completion.py test_channel_switch.py test_dashboard.js test_telemetry.py test_smart_mode.py ./
|
| 10 |
|
| 11 |
# TikTok Live Monitor → Direct Relay → YouTube. No local video files.
|
| 12 |
ENV TZ=Asia/Baghdad \
|
|
|
|
| 15 |
YOUTUBE_SOURCE_STALL_SECONDS=12 \
|
| 16 |
MAX_CONCURRENT_RELAYS=4 \
|
| 17 |
YOUTUBE_MAX_EVENTS=4 \
|
| 18 |
+
YOUTUBE_LIGHT_MAX=0 \
|
| 19 |
YOUTUBE_TITLE_TEMPLATE="{broadcaster} | {date} {time}" \
|
| 20 |
YOUTUBE_SEND_MODE=auto \
|
| 21 |
+
YOUTUBE_AUTO_TRANSCODE=0 \
|
| 22 |
YOUTUBE_AUDIO_PROFILE=aac_low \
|
| 23 |
YOUTUBE_AUDIO_BITRATE=128k \
|
| 24 |
YOUTUBE_AUDIO_CHANNELS=2 \
|
|
|
|
| 29 |
YOUTUBE_RETRY_MIN=1 \
|
| 30 |
YOUTUBE_RETRY_MAX=60 \
|
| 31 |
YOUTUBE_SOURCE_LIMIT=6 \
|
| 32 |
+
YOUTUBE_SOURCE_UPGRADE_SECONDS=300 \
|
| 33 |
YOUTUBE_FLAP_LIMIT=4 \
|
| 34 |
YOUTUBE_FLAP_FALLBACK_MODE=matchgop \
|
| 35 |
YOUTUBE_COPY_RECOVERY=1 \
|
| 36 |
YOUTUBE_COPY_RECOVERY_SECONDS=60 \
|
| 37 |
+
YOUTUBE_X264_PRESET=ultrafast \
|
|
|
|
| 38 |
YOUTUBE_FIFO_TIMESHIFT=0 \
|
| 39 |
+
YOUTUBE_HEALTH_INTERVAL=20 \
|
| 40 |
+
TELEMETRY_ENABLED=1 \
|
| 41 |
+
YOUTUBE_IDLE_RESET_SECONDS=600 \
|
| 42 |
+
STREAM_EVENT_MAX=10000 \
|
| 43 |
YOUTUBE_OBS_HOLD_SECONDS=900 \
|
| 44 |
YOUTUBE_SOURCE_RETRY=15 \
|
| 45 |
YOUTUBE_FORCE_GAP=5 \
|
|
|
|
| 49 |
YOUTUBE_FFMPEG_LOGLEVEL=info \
|
| 50 |
YOUTUBE_SOURCE_READ_TIMEOUT=15 \
|
| 51 |
YOUTUBE_SOURCE_READ_ATTEMPTS=3 \
|
| 52 |
+
YOUTUBE_REATTACH_GRACE_SECONDS=2 \
|
| 53 |
YOUTUBE_PROGRESS_STALL_SECONDS=60 \
|
| 54 |
YOUTUBE_KILL_GRACE_SECONDS=10 \
|
| 55 |
YOUTUBE_PUMP_JOIN_SECONDS=2 \
|
| 56 |
YOUTUBE_AUTH_PAUSE_SECONDS=90 \
|
| 57 |
YOUTUBE_SESSION_MAX_SECONDS=21600 \
|
| 58 |
+
YOUTUBE_ENHANCED_RTMP=auto \
|
| 59 |
YOUTUBE_SOURCE_GAP_SUSPECT_SECONDS=8 \
|
| 60 |
TIKTOK_TT_TARGET_IDC=useast1a \
|
| 61 |
STORAGE_WAIT_SECONDS=30 \
|
| 62 |
HLS_START_INDEX=-3 \
|
|
|
|
|
|
|
|
|
|
| 63 |
PORT=7860 \
|
| 64 |
PYTHONUNBUFFERED=1 \
|
| 65 |
YOUTUBE_VIDEO_MODE=original
|
| 66 |
|
| 67 |
EXPOSE 7860
|
| 68 |
+
CMD ["sh", "-c", "exec uvicorn app:app --host 0.0.0.0 --port ${PORT:-7860} --timeout-graceful-shutdown 65 --no-access-log"]
|
README.md
CHANGED
|
@@ -8,190 +8,167 @@ pinned: false
|
|
| 8 |
app_port: 7860
|
| 9 |
---
|
| 10 |
|
| 11 |
-
# Reoo88/On —
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 12 |
|
| 13 |
-
|
| 14 |
-
**لا تسجيل. لا أرشيف. لا ملفات فيديو على القرص.**
|
| 15 |
|
| 16 |
-
```
|
| 17 |
-
|
| 18 |
-
→ اكتشاف الحساب
|
| 19 |
-
→ مصدر مستقل لكل مذيع (H264/FLV أولاً)
|
| 20 |
-
→ FFmpeg (stream copy إن أمكن)
|
| 21 |
-
→ YouTube RTMPS (OAuth لكل حساب، أو مفتاح بيئة واحد فقط)
|
| 22 |
-
```
|
| 23 |
|
| 24 |
-
|
| 25 |
|
| 26 |
-
|
| 27 |
-
`kick_source.py`، ونقطة التماس الوحيدة دالة رصد واحدة تُرجع نفس عقد تيك توك.
|
| 28 |
|
| 29 |
-
|
| 30 |
-
ف
|
|
|
|
| 31 |
|
| 32 |
-
``
|
| 33 |
-
kick:emadpes
|
| 34 |
-
https://kick.com/emadpes
|
| 35 |
-
```
|
| 36 |
|
| 37 |
-
تي
|
| 38 |
-
الحسابات تتعايش في نفس اللوحة، وكل حساب له حدث يوتيوب خاص به.
|
| 39 |
|
| 40 |
-
##
|
| 41 |
|
| 42 |
-
|
| 43 |
-
مُقاس حيًّا على القناة `absi`:
|
| 44 |
|
| 45 |
-
|
| 46 |
-
|---------|-----------|-----------------------|-----------|
|
| 47 |
-
| 1080p60 | 1920x1080 | avc1.64002A / mp4a.40.2 | ~9.0 Mbps |
|
| 48 |
-
| 720p60 | 1280x720 | avc1.4D401F / mp4a.40.2 | ~3.4 Mbps |
|
| 49 |
-
| 480p30 | 852x480 | avc1.4D401F / mp4a.40.2 | ~1.4 Mbps |
|
| 50 |
-
| 360p30 | 640x360 | avc1.4D401F / mp4a.40.2 | ~0.6 Mbps |
|
| 51 |
|
| 52 |
-
و
|
| 53 |
-
**صفر إعادة ترميز للصورة، صفر خسارة جودة، صفر حمل CPU.**
|
| 54 |
-
الصوت وحده يُعاد ترميزه إلى AAC 128k/48k — وهذه سياسة المشروع القائمة أصلًا
|
| 55 |
-
لكلا المنصتين (`relay.command`)، كلفتها لا تُذكر وتُزيل صنفًا كاملًا من التجمّد.
|
| 56 |
|
| 57 |
-
|
| 58 |
-
خرج 9.2 Mbps = معدل المصدر بالضبط، **بلا أي خطأ ولا تحذير `Non-monotonous DTS`**،
|
| 59 |
-
والخرج المفحوص: `h264 1920x1080 @59fps + aac 48000 stereo`.
|
| 60 |
|
| 61 |
-
|
|
|
|
|
|
|
| 62 |
|
| 63 |
-
|
| 64 |
-
لكن هذا قيد **في واجهة الموقع فقط**. مُقاس بمقارنة مباشرة على قناتين مباشرتين
|
| 65 |
-
(`absi` و`luchodku`): الـmaster playlist يُرجع السلّم نفسه حرفيًا بكوكيز وبدونها —
|
| 66 |
-
1080p60 أولًا. **فلا حاجة لتوكن Kick إطلاقًا**، ولا يُنصح بتخزين كوكيز جلسة شخصية
|
| 67 |
-
في أسرار السبيس واستعمالها من عنوان مركز بيانات.
|
| 68 |
|
| 69 |
-
|
| 70 |
-
واجهة Kick وحدها؛ روابط IVS موقّعة فلا تُرسل إليها أي كوكيز.)
|
| 71 |
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
ومر
|
| 80 |
-
|
|
|
|
|
|
|
|
|
|
| 81 |
|
| 82 |
-
|
| 83 |
|
| 84 |
-
|
| 85 |
|
| 86 |
-
``
|
| 87 |
-
BPP = البتريت ÷ (العرض × الارتفاع × الإطارات)
|
| 88 |
-
```
|
| 89 |
|
| 90 |
-
|
| 91 |
-
و**0.05 الحدّ الأدنى المقبول**. فطبقة 1080p بـ900 كيلوبت (BPP≈0.015) تبدو
|
| 92 |
-
أسوأ بوضوح من طبقة 720p بـ2400 كيلوبت (BPP≈0.086) لأن البتّات توزَّعت على
|
| 93 |
-
ضعف عدد البكسلات.
|
| 94 |
-
|
| 95 |
-
هذه ليست حالة نظرية — إنها سلّم @emadpes الحقيقي (VOD 2026-10-06):
|
| 96 |
-
|
| 97 |
-
| الطبقة | البتريت | BPP | الحكم |
|
| 98 |
-
|---|---|---|---|
|
| 99 |
-
| 1080p30 | 943k | 0.0152 | ضعيف ⛔ |
|
| 100 |
-
| **720p30** | **2379k** | **0.0860** | **جيد ✅** |
|
| 101 |
-
| 480p30 | 1434k | 0.1169 | ممتاز |
|
| 102 |
-
|
| 103 |
-
لذلك يَسِم `renditions()` كل طبقة **دقتها أعلى وبتريتها أقل من طبقة أدنى
|
| 104 |
-
منها** بأنها `starved`، ويُنزلها إلى ذيل السلّم بدل صدارته. القاعدة **نسبية
|
| 105 |
-
داخل السلّم نفسه** فلا تحتاج أي عتبة مُعايَرة، و**لا تتفعّل إطلاقًا على سلّم
|
| 106 |
-
سليم** يرتفع بتريته مع دقته — تحقَّق على @luchodku (1080p60 بـ4797k)
|
| 107 |
-
و@absi (1080p60 بـ9015k): كلاهما يبقى 1080p60 متصدّرًا.
|
| 108 |
-
|
| 109 |
-
الطبقة المجوّعة **لا تُحذف**، تبقى احتياطيًا إن فشل ما فوقها. وحين تغيب بيانات
|
| 110 |
-
البتريت من الـmanifest يعود الترتيب إلى الدقة وحدها كما كان حرفيًا.
|
| 111 |
-
|
| 112 |
-
كل مرشّح يحمل الآن `bpp` و`bpp_grade` (`excellent`/`good`/`fair`/`poor`)
|
| 113 |
-
و`starved` للتشخيص.
|
| 114 |
-
|
| 115 |
-
> ملاحظة لصاحب القناة: BPP منخفض سببه إعدادات البثّ عند المذيع لا المشروع.
|
| 116 |
-
> توصية Kick لـ1080p30 هي **4500–6000 kbps** (والحد الأقصى 8000).
|
| 117 |
-
|
| 118 |
-
### ضمانات ضد تجميد الصورة عند المشاهد
|
| 119 |
-
|
| 120 |
-
1. **رابط جودة ثابتة لا الـmaster.** نُسلّم FFmpeg رابط جودة واحدة بعينها، فلا يقفز
|
| 121 |
-
ABR بين 1080p و360p وسط الجلسة — وقفزة الدقة داخل جلسة RTMP هي أكثر ما يُجمّد
|
| 122 |
-
صورة يوتيوب. الـmaster لا يُسلَّم لـFFmpeg إطلاقًا.
|
| 123 |
-
2. **سلّم بديل كامل.** تُعاد كل الجودات مرتَّبة؛ إن تعثّرت 1080p60 ينزل المشرف إلى
|
| 124 |
-
720p60 في نفس الدورة بدل أن يقف ��لبث.
|
| 125 |
-
3. **روابط طازجة دائمًا.** روابط IVS موقّعة وتنتهي صلاحيتها؛ كل رصد يجلب
|
| 126 |
-
`playback_url` جديدًا، فإعادة الاتصال بعد أي صمت تبدأ برابط حيّ لا ميت.
|
| 127 |
-
4. **`-seg_max_retry 2`** (معلّق على `platform=='kick'` فقط). افتراضي FFmpeg صفر:
|
| 128 |
-
أول مقطع يفشل تنزيله (502 أو انقطاع CDN لحظي) يُنهي الإدخال فورًا ⇒ تموت
|
| 129 |
-
الجلسة ويرى المشاهد تجمّدًا ثم انقطاعًا. بإعادتين تُبتلع العثرة بصمت.
|
| 130 |
-
وهذا هو **الخيار الوحيد** المضاف لـFFmpeg؛ جُرّبت خيارات HLS أخرى على
|
| 131 |
-
ffmpeg 7.1.5 وحُذفت لأنها إمّا مطابقة للافتراضي (`http_persistent` أصلًا `true`
|
| 132 |
-
للمفكِّك) أو **أضعف** منه (`m3u8_hold_counters` الافتراضي 1000 لا 10).
|
| 133 |
-
5. **امتصاص عثرة API واحدة.** عطل مؤقت من Kick لا يقطع بثًا جاريًا: يُستعمل آخر
|
| 134 |
-
رصد ناجح خلال 90 ثانية (`kick_source.last_good`).
|
| 135 |
-
6. الحارس، سقف التزامن، إعادة التشغيل، وإدارة أحداث يوتيوب — كلها المنطق القائم
|
| 136 |
-
نفسه بلا تفرّع.
|
| 137 |
-
|
| 138 |
-
### متغيّرات Kick
|
| 139 |
-
|
| 140 |
-
| المتغيّر | الافتراضي | المعنى |
|
| 141 |
-
|----------|-----------|--------|
|
| 142 |
-
| `KICK_MAX_HEIGHT` | `1080` | أعلى ارتفاع يُسمح به. اضبطه `720` لتخفيف النطاق الصادر. |
|
| 143 |
-
| `KICK_SEG_RETRY` | `2` | إعادات تنزيل المقطع عند عثرة CDN (افتراضي FFmpeg صفر). |
|
| 144 |
-
| `KICK_TIMEOUT` | `20` | مهلة طلبات Kick بالثواني. |
|
| 145 |
-
| `KICK_COOKIE` | — | اختياري وغير لازم للجودة: 1080p متاح بلا تسجيل دخول. |
|
| 146 |
-
| `KICK_IMPERSONATE` | `chrome` | بصمة TLS المستعملة مع curl_cffi. |
|
| 147 |
-
|
| 148 |
-
### حجم الإضافة
|
| 149 |
-
|
| 150 |
-
ملف واحد جديد (`kick_source.py`) + ملف اختبارات، وفي الملفات القائمة:
|
| 151 |
-
|
| 152 |
-
| الملف | أسطر وظيفية مضافة |
|
| 153 |
-
|-------|-------------------|
|
| 154 |
-
| `relay.py` | 2 (كلاهما مشروط بـ`platform=='kick'`) |
|
| 155 |
-
| `app.py` | 3 (موجّه منصة في `clean_user` و`_observe_session` و`tiktok_headers`) |
|
| 156 |
-
| `youtube_manager.py` | Referer ووصف الحدث حسب المنصة |
|
| 157 |
-
|
| 158 |
-
لا دوال غير مستعملة، ولا خيارات FFmpeg بلا أثر، ولا حقول بيانات لا يقرأها أحد.
|
| 159 |
-
|
| 160 |
-
**وصف حدث يوتيوب:** قالب الوصف في هذا المشروع كُتب في زمن المنصة الواحدة ويثبّت
|
| 161 |
-
`https://www.tiktok.com/@{username}` يدويًا. و`{username}` لحساب كيك هو `kick:slug`،
|
| 162 |
-
فكان الناتج رابطًا مكسورًا يُنشر **علنًا** في وصف كل بث:
|
| 163 |
-
`https://www.tiktok.com/@kick:emadpes`. الإصلاح في `description_with_links`
|
| 164 |
-
يصحّح الناتج لحسابات كيك فقط، فيعمل مع القوالب القائمة بلا أن يضطر المشغّل
|
| 165 |
-
لتعطيل الأتمتة لتحرير القالب. وأُضيفت ثلاثة متغيّرات قالب واعية بالمنصة —
|
| 166 |
-
`{handle}` و`{profile_url}` و`{platform}` — تُغني مستقبلًا عن كتابة الرابط يدويًا
|
| 167 |
-
(ومعها قاموس التحقق عند الحفظ، وإلا رُفض كل قالب يستعملها).
|
| 168 |
-
|
| 169 |
-
**تسمية المنصة في السجل:** رسائل التشغيل في `youtube_manager` ورثت كلمة «تيك توك»
|
| 170 |
-
من زمن المنصة الواحدة، فكان حساب Kick يُسجَّل بـ«تيك توك يقول إن الحساب غير مباشر».
|
| 171 |
-
الإصلاح سطران في `app.log` يستبدلان الاسم في **النص المعروض فقط** لحسابات Kick.
|
| 172 |
-
لم تُلمس أي سلسلة حرفية في `youtube_manager`: بعضها مُطابَق في `is_fault_note`
|
| 173 |
-
وفي `test_lifecycle`، وتغييرها كان سيكسر منطق استرداد الأعطال.
|
| 174 |
-
آمن لأن `events` قائمة عرض محضة تُقرأ في `/api/state` ولا يُطابقها أي منطق.
|
| 175 |
-
|
| 176 |
-
### الاختبارات
|
| 177 |
|
| 178 |
```bash
|
| 179 |
-
|
| 180 |
-
KICK_LIVE=1 python3 test_kick.py absi # + اختبار حيّ كامل عبر FFmpeg
|
| 181 |
```
|
| 182 |
|
| 183 |
-
ي
|
| 184 |
-
ولا يرث أيًّا من خيارات Kick، ووصف يوتيوب لحسابات تيك توك بقي كما هو.
|
| 185 |
-
|
| 186 |
-
## سقف التزامن
|
| 187 |
-
|
| 188 |
-
`MAX_CONCURRENT_RELAYS=5` و `YOUTUBE_MAX_EVENTS=5` في الصورة.
|
| 189 |
-
عطل مذيع لا يوقف الباقين. مفتاح RTMPS البيئي واحد = ناشر واحد.
|
| 190 |
-
|
| 191 |
-
## تنبيه التشغيل جنبًا إلى جنب مع Tktktk
|
| 192 |
-
|
| 193 |
-
هذه نسخة ثانية من المحرك. إذا فُعّلت أتمتة OAuth هنا **وعلى** `Reoo88/Tktktk` بنفس قناة يوتيوب، قد يُفتح حدثان لنفس المذيع على نفس الحساب. شغّل الأتمتة في سبيس واحد لكل قناة، أو استخدم قناة/مفاتيح مختلفة.
|
| 194 |
|
| 195 |
-
|
| 196 |
|
| 197 |
-
|
|
|
|
|
|
|
|
|
| 8 |
app_port: 7860
|
| 9 |
---
|
| 10 |
|
| 11 |
+
# Reoo88/On — relay-v2.29-smart-mode
|
| 12 |
+
|
| 13 |
+
## تنظيف تلقائي عند غياب البث في v2.27
|
| 14 |
+
|
| 15 |
+
عند غياب أي بث بشكل كامل ومستمر لمدة `YOUTUBE_IDLE_RESET_SECONDS` (الافتراضي
|
| 16 |
+
600 ث = 10 دقائق) يصفّر المدير تلقائيًا — مرة واحدة في كل فترة خمول — بقايا حالة
|
| 17 |
+
التكيّف المتراكمة في الذاكرة: أوضاع الترميز اللاصقة (`matchgop`) ومقاساتها،
|
| 18 |
+
تثبيتات الجودة، قوائم المصادر غير المستقرة، الرصد المحفوظ، عدّادات التأجيل
|
| 19 |
+
والجوع، ووجهات RTMPS المحفوظة (لتُعاد قراءتها طازجة من YouTube API عند البث
|
| 20 |
+
التالي). الرصد نفسه لا يتوقف لحظة (24/7)، وعودة أي بث تعيد ضبط مؤقّت الخمول
|
| 21 |
+
من الصفر. **لا يُحذف أي ملف ولا تُمسّ بيانات دائمة**: ربط القناة ومصادر
|
| 22 |
+
الاستقبال القابلة لإعادة الاستخدام وإعدادات المشغّل والتوكنات كلها محفوظة —
|
| 23 |
+
حذف سجل الأحداث (`youtube-api-state.json`) كان سيضيّع الربط، وسجلّ أحداث
|
| 24 |
+
البث (`stream_events.json`) محدود أصلًا بسقف 10,000 سجل ويُقلَّم تلقائيًا.
|
| 25 |
+
القيمة `0` تعطّل الميزة. يُوثَّق كل تنظيف بحدث `IDLE_AUTOCLEAN` وسطر `[IDLE]`
|
| 26 |
+
في السجل.
|
| 27 |
+
|
| 28 |
+
## حاكم أوضاع ذكي في v2.29
|
| 29 |
+
|
| 30 |
+
سياسة اختيار `copy`/الترميز صارت قرارًا مبنيًا على نوع العطل لا على اللصق
|
| 31 |
+
الدائم:
|
| 32 |
+
|
| 33 |
+
- **النسخ هو الأصل** لأي مصدر AVC أو HEVC مُثبت (HEVC يُحمل Enhanced RTMP
|
| 34 |
+
`hvc1` كما هو)، والترميز علاج موجّه فقط.
|
| 35 |
+
- **يدخل الترميز** لأعطال تستطيع المعالجة إصلاحها: ترميز/مقاس/GOP لا يقبله
|
| 36 |
+
الاستقبال، `noData` بينما بايتات المصدر تتدفق فعلًا، رفرفة مقاس متكررة،
|
| 37 |
+
رفض خرج متكرر، أو نسخة مُعلنة أكبر بكثير من معدل بتّها. أما
|
| 38 |
+
`videoIngestionStarved` وحده فهو جوع بيانات — لا يفرض ترميزًا بعد الآن.
|
| 39 |
+
- **يعود إلى النسخ تلقائيًا:** بعد جولة ترميز مستقرة (افتراضيًا ≥60 ثانية
|
| 40 |
+
وخرج مُسلَّم ≥20 ثانية) يُفحَص النسخ لأي مصدر مدعوم AVC/HEVC؛ إن صمد
|
| 41 |
+
الخرج (افتراضيًا 15 ثانية) يُنسى وضع الترميز من الذاكرة **ومن سجل الحدث**
|
| 42 |
+
وتُحرَّر خانة المعالج، وإن فشل الفحص يُحسَب ويُمنع الرفرفة. وضع يفرضه
|
| 43 |
+
المشغّل صراحة لا يُفحَص ولا يُلغى.
|
| 44 |
+
- **كانفس الترميز مسقوف** عند فئة 720p افتراضيًا
|
| 45 |
+
(`YOUTUBE_TRANSCODE_MAX_SHORT/LONG`)، فلا يخنق المعالجَ فكُّ HEVC عالٍ
|
| 46 |
+
وإعادة ترميزه بحجمه الكامل؛ وضع `fixed1080` الصريح للمشغّل لا يُسقَف.
|
| 47 |
+
- **حاكم سرعة:** ترميز يبقى أبطأ من الزمن الحقيقي (افتراضيًا <0.90 لمدة
|
| 48 |
+
30 ثانية بعد 20 ثانية خرج) يُنهى ناشره ويُفحَص النسخ بدل حرق الحدث كله
|
| 49 |
+
خلف مرمّز متأخر (`TRANSCODE_TOO_SLOW`).
|
| 50 |
+
- كل انتقالات الحاكم تُسجَّل في سجل الأحداث والقياس الدائم
|
| 51 |
+
(`COPY_RECOVERY` و`TRANSCODE_TOO_SLOW`)، وضبطها من
|
| 52 |
+
`YOUTUBE_COPY_RECOVERY*` و`YOUTUBE_TRANSCODE_*`، وإلغاء العودة للنسخ
|
| 53 |
+
بـ`YOUTUBE_COPY_RECOVERY=0`.
|
| 54 |
+
|
| 55 |
+
## قياس تشخيصي دائم في v2.28
|
| 56 |
+
|
| 57 |
+
أضافت هذه النسخة **قياسًا للقراءة فقط**: لا يغيّر وضع الإرسال ولا الجودة ولا
|
| 58 |
+
المرمّز ولا مهلات الحارس ولا إعادة الاتصال، ولا تُقرأ نتائجه داخل أي قرار بث.
|
| 59 |
+
تُجمَّع عدّادات كل جلسة FFmpeg في الذاكرة (سرعة/إطارات FFmpeg، معدل بايتات
|
| 60 |
+
المصدر وعمر آخر بايت، تغيّرات المقاس/الترميز/معدل البت/GOP، أخطاء فتح المصدر
|
| 61 |
+
مع رمز HTTP، أحداث صحة YouTube، وحمل CPU العام)، ويكتبها خيط مستقل كل دقيقة
|
| 62 |
+
كنقاط تفتيش وعند نهاية الجلسة.
|
| 63 |
+
|
| 64 |
+
الكتابة **إلحاقية فقط** في `telemetry/telemetry.jsonl` داخل Storage Bucket
|
| 65 |
+
نفسه (`0600`)، من دون روابط موقّعة أو مفاتيح أو كوكيز أو وسائط. لا يوجد في
|
| 66 |
+
الكود أي سقف أو تدوير أو حذف أو تقليم لهذا الملف، والتنظيف الخامل لا يلمسه��
|
| 67 |
+
يبقى إلى أن يُراجَع ويُحذف يدويًا بقرار صريح خارج مسار التشغيل. إذا تعطّل
|
| 68 |
+
التخزين أو امتلأت قائمة القياس تُسقَط عيّنات القياس نفسها ولا يتأثر البث.
|
| 69 |
+
يمكن إيقاف القياس وحده بـ`TELEMETRY_ENABLED=0`، وقراءته من المسار المحمي
|
| 70 |
+
`GET /api/telemetry?limit=200&broadcaster=user`. الهدف جمع أدلة كافية أيامًا
|
| 71 |
+
قبل أي تعديل معالجة/ترميز لاحق مبني على قياس لا على افتراض.
|
| 72 |
+
|
| 73 |
+
## منع تعليق بدء البث في v2.25
|
| 74 |
+
|
| 75 |
+
`liveStarting` و`testStarting` ليستا رفضًا للاستقبال. بعد قبول طلب الانتقال يجب أن يبقى إرسال نفس الحدث والمصدر جاريًا حتى يؤكد يوتيوب الحالة النهائية. كان شرط الجاهزية يوقف المرسل في المرحلتين، فيبقى الحدث عالقًا بلا بيانات. الآن يُستأنف المرسل نفسه، مع فحص الصحة والملكية المعتاد، بلا تكرار transition أو إنشاء حدث جديد. مرحلتا created وcomplete/revoked تبقيان محميتين. الاختبار `test_transition_ingest.py` يغطي الرصد الجديد والحالة المخزنة والحالات النهائية.
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
## استعادة استقبال يوتيوب في v2.24
|
| 79 |
+
|
| 80 |
+
عند فشل خرج RTMPS المتكرر تُجرّب نقطة الاستقبال الاحتياطية الآمنة لنفس مصدر يوتيوب، لا قناة أو مفتاحًا أو حدثًا جديدًا. لا يُستعمل مسار محفوظ بعد تبديل القناة أو معرّف المصدر. تبقى query الخاصة بالاحتياطي بعد المفتاح في الرابط الصحيح، وتبقى عناوين الإرسال ومفاتيحها في الذاكرة فقط.
|
| 81 |
+
|
| 82 |
+
فشل بدء الخرج يفعّل تشخيص تفاوض RTMP للمحاولة التالية، مع إخفاء `playpath` من رسالة `Sending publish command` حتى إن لم يظهر كـURL. رسائل النجاح `NetStream.Publish.Start` و`FCPublish` لا تُعتبر رفضًا للنشر. التشخيص لا يُغيّر توكنات أو إعدادات نشر المستخدم.
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
## إصلاح انقطاع المصدر في v2.23
|
| 86 |
+
|
| 87 |
+
كان القارئ البديل يبدأ قبل مسح `swap_source`، فيخرج أحيانًا دون قراءة أي بايت، ثم يُعاد فتح المصدر مرارًا بينما يوتيوب يعرض `noData`. الآن يُوقف القارئ القديم أولًا، ولا يُعاد استعمال جسر FLV إذا بقي حيًا؛ تُمسح علامة التسليم قبل تشغيل القارئ الجديد. لكل قارئ إلغاء مستقل لمنع بايت متأخر من الجلسة السابقة.
|
| 88 |
+
|
| 89 |
+
- إغلاق CDN للاستجابة أو خطأ القراءة يجرّب مصدرًا بديلًا داخل **نفس FFmpeg ونفس حدث يوتيوب** قبل إعادة تشغيل الناشر.
|
| 90 |
+
- تُمنح الاستجابة الجديدة مهلة أول بايت قدرها ثانيتان (`YOUTUBE_REATTACH_GRACE_SECONDS`، حد أقصى 5 ث ونصف مهلة الصمت). لا يُحدّث عدّاد وصول البيانات وهميًا، ولا تُخفى أعطال خرج RTMP.
|
| 91 |
+
- أثناء إعادة التوصيل نجرّب رابطًا متوافق الترميز من رصد LIVE حديث (بحد أقصى 45 ث) بدل تجويع الناشر بانتظار طلبات بيانات تيك توك الطويلة. الرصد القديم أو غير المتوافق لا يُعتمد، وفحص انتهاء البث يبقى كما هو.
|
| 92 |
+
- ترويسة البداية `16×16` لا تثبّت كانفس التحويل الخفيف. عند غياب مقاس صالح يستعمل `matchgop` كانفس ثابتًا `720×1280`؛ أما مسار نسخ AVC/HEVC الأصلي فلا يُعاد ترميزه بسبب هذه الرقعة.
|
| 93 |
+
|
| 94 |
+
`test_source_reconnect.py` يشمل جدولة يبدأ فيها القارئ فورًا، وقارئًا قديمًا لم يتوقف، وإيقاف المستخدم، وعدم تزوير العمر، والترويسة الصغيرة، واختبار HTTP + FFmpeg حقيقيين: إغلاقات متكررة وتأخير أول بايت، مع استمرار الساعة بنفس عملية الإرسال في وضعي `copy` و`matchgop`. لا يستعمل الاختبار بثوثًا حقيقية.
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
رصد TikTok LIVE → FFmpeg → YouTube RTMPS.
|
| 98 |
+
**لا تسجيل محلي، لا أرشيف فيديو، ولا ملفات فيديو على القرص.**
|
| 99 |
+
|
| 100 |
+
```text
|
| 101 |
+
TikTok H.264 أو H.265/FLV
|
| 102 |
+
→ FLVBridge: تحويل HEVC القديم إلى Enhanced RTMP hvc1
|
| 103 |
+
→ تمرير سجل SPS/PPS أو VPS/SPS/PPS المحدّث في الجلسة نفسها
|
| 104 |
+
→ FFmpeg stream copy للفيديو (من دون فك/ترميز) + تطبيع AAC فقط
|
| 105 |
+
→ جلسة YouTube RTMPS نفسها
|
| 106 |
+
```
|
| 107 |
|
| 108 |
+
## الدخول
|
|
|
|
| 109 |
|
| 110 |
+
افتح واجهة الـSpace وأدخل قيمة Secret المسمى `PASSWORD`؛ اسم المستخدم الداخلي ثابت `admin`.
|
| 111 |
+
الواجهة العامة لا تعرض بيانات تشغيلية قبل الدخول. `GET /health` عام ومحدود بحالة الحياة والإصدار فقط، أما `/api/*` فمحمي.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 112 |
|
| 113 |
+
> لا تلصق توكن Hugging Face في الواجهة، ولا تضع أي توكن أو كوكي أو مفتاح بث داخل Git.
|
| 114 |
|
| 115 |
+
## تغيير قناة يوتيوب بعد تدوير Secrets
|
|
|
|
| 116 |
|
| 117 |
+
1. حدّث `GOOGLE_CLIENT_ID` و`GOOGLE_CLIENT_SECRET` و`YOUTUBE_REFRESH_TOKEN` للقناة المطلوبة.
|
| 118 |
+
2. اضغط **فحص OAuth والقناة**: تظهر القناة المفوضة الجديدة والقناة السابقة إن اختلفتا. الفحص لا يعتمد التبديل وحده.
|
| 119 |
+
3. اضغط **اعتماد القناة الجديدة فقط** وأكّد اسمها ومعرّفها، إن أردت تبديل الربط دون بدء بث؛ أو **تفعيل البث التلقائي** مع تأكيد القناة لبدء الأتمتة.
|
| 120 |
|
| 121 |
+
لا يحذف التبديل أحداث القناة السابقة ولا يعدّلها عبر YouTube API: يوقف مرسلاتها، يؤرشف قيودها محليًا مع معرّف قناتها، ويُسقط مصادرها ومفاتيح RTMPS المخزنة في الذاكرة. الاعتماد وحده يترك الأتمتة معطلة عند التبديل. تبقى الحماية من تغيّر القناة غير المؤكد مفعلة، ولا حاجة لحذف `youtube-api-state.json` أو تفريغ التخزين.
|
|
|
|
|
|
|
|
|
|
| 122 |
|
| 123 |
+
إصلاح الواجهة: نتيجة الفحص منفصلة الآن عن قناة السجل؛ التحديث الدوري لا يعيد اختيار القناة القديمة. يعاد فحص OAuth قبل الاعتماد/التفعيل، ويُرفض الطلب إذا لم يطابق التفويض معرّف القناة الذي أكّدته.
|
|
|
|
| 124 |
|
| 125 |
+
## كوكيز تيك توك
|
| 126 |
|
| 127 |
+
تُقبل قيمة `sessionid`، أو سطر `Cookie` كامل، أو تصدير الكوكيز بصيغة JSON. يستبعد محلل JSON الكوكيز المنتهية ونطاقات المواقع الأخرى ويختار كوكي `www.tiktok.com` الأكثر تخصيصًا عند تكرار الاسم. لا تُحفظ القيم في Git ولا تُعرض في الـAPI.
|
|
|
|
| 128 |
|
| 129 |
+
أسرار Hugging Face تتقدم على مخزن الواجهة: `TIKTOK_SESSIONID` يتقدم على `TIKTOK_COOKIES`. عند تدوير الجلسة، حدّث القيمتين إلى سطر الكوكيز الجديد نفسه، أو احذف السر القديم `TIKTOK_SESSIONID` واكتفِ بـ`TIKTOK_COOKIES`؛ لا تترك سرًا قديمًا يحجب الكوكيز الجديدة. تاريخ `sid_guard` تقديري، والقبول الفعلي تقرره تيك توك وقد تنتهي الجلسة قبل هذا التاريخ.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 130 |
|
| 131 |
+
## حدود الموارد الموصى بها لـ CPU Basic
|
|
|
|
|
|
|
|
|
|
| 132 |
|
| 133 |
+
الصورة تضبط:
|
|
|
|
|
|
|
| 134 |
|
| 135 |
+
- `MAX_CONCURRENT_RELAYS=4`: أربع عمليات نشر كحد أعلى.
|
| 136 |
+
- `YOUTUBE_MAX_EVENTS=4`: أربعة أحداث يوتيوب كحد أعلى.
|
| 137 |
+
- `YOUTUBE_LIGHT_MAX=0` و`YOUTUBE_AUTO_TRANSCODE=0`: لا تحويل فيديو في المسار الافتراضي. H.264 يُنسخ كما هو، وH.265 يُحمل بـEnhanced RTMP `hvc1`. يبقى كود x264 القديم خيار تشغيل يدويًا فقط ولا يدخل في إصلاح تبدل سجلات المفكك.
|
| 138 |
|
| 139 |
+
متغيرات إعدادات الـSpace تتقدم على Dockerfile. اترك سقفي الناشرين/الأحداث على `4`، وراقب الشبكة وحكم YouTube؛ كلفة stream copy وAAC أقل كثيرًا من تحويلي x264 اللذين سبق أن أشبعا موردي CPU.
|
|
|
|
|
|
|
|
|
|
|
|
|
| 140 |
|
| 141 |
+
## الاعتمادية
|
|
|
|
| 142 |
|
| 143 |
+
- تغيّر `AVCDecoderConfigurationRecord` أو `HEVCDecoderConfigurationRecord` لا يرمي `FormatChanged` ولا يقتل FFmpeg: يمر السجل الجديد قبل الإطار الذي يحتاجه عبر RTMPS المفتوح نفسه.
|
| 144 |
+
- `FLVBridge` يحافظ على بايتات الصورة وCTS، ويصل أزمنة DTS عند تجديد رابط HTTP-FLV من دون رأس FLV ثانٍ. سجل جديد كامل يحل محل السابق؛ لا تُخلط مجموعات قد تحمل IDs متعارضة.
|
| 145 |
+
- FFmpeg 7 ينقل تغيير extradata من demuxer إلى muxer ويعيد كتابة SequenceStart؛ يثبت الاختبار الحتمي ذلك لـH.264 وH.265.
|
| 146 |
+
- يسجل `stream_monitor.py` أحداث `CODEC_CHANGE` و`RESOLUTION_CHANGE` و`BITRATE_CHANGE` و`KEYFRAME_CHANGE` و`SOURCE_CHANGE` و`RECONNECT` و`CONNECTION_ERROR` و`YOUTUBE_HEALTH` في `logs/stream_events.json` داخل Storage Bucket، من دون وسائط أو روابط أو مفاتيح.
|
| 147 |
+
- إذا صمت رابط الجودة المثبت وبقي TikTok يعيد الرابط نفسه، يختار الجسر أقرب FLV أقل جودة من عائلة الترميز نفسها ويدخله في FFmpeg/RTMP المفتوح بدل ترك YouTube يتوقف. لا يقطع مصدرًا منخفضًا يعمل لمجرد تحسين الدقة؛ يعيد الجودة المفضلة فقط عند تجديد طبيعي لاحق بعد استقرار افتراضي قدره 300 ثانية (`YOUTUBE_SOURCE_UPGRADE_SECONDS`).
|
| 148 |
+
- يمكن قراءة آخر الأحداث من المسار المحمي `GET /api/stream-events?limit=200&broadcaster=user`، والملف محدود افتراضيً�� إلى 10,000 سجل وصلاحيته `0600`.
|
| 149 |
+
- إذا بقي خيط الإشراف حيًا ومات FFmpeg لسبب آخر، يعيد watchdog تدويره بدل بقاء YouTube في `noData`.
|
| 150 |
+
- روابط المصدر الموقعة تُرصد من جديد، مع حارس صمت افتراضي 12 ثانية. تُسحب صحة YouTube كل 20 ثانية أثناء الحدث وتدخل السجل. الوضع الافتراضي يمنع تحويل الفيديو؛ خيارات `matchgop` القديمة لا تعمل إلا إذا فعّلها المشغل ورفع `YOUTUBE_LIGHT_MAX` عمدًا.
|
| 151 |
+
- الحماية من تكرار مذيع واحد ومن خلط مذيعين على مفتاح RTMPS بيئي واحد مفعلة.
|
| 152 |
+
- الحالة والتوكنات تحفظ في Storage Bucket المركب على `/data`؛ كوكيز TikTok المخزنة تُكتب بصلاحية `0600`.
|
| 153 |
+
- كوكي TikTok لا يُرسل إلى روابط CDN الموقعة خارج `tiktok.com`؛ طلبات الوسائط العامة تستعمل `Referer` فقط.
|
| 154 |
+
- سجلات الأحداث المهمة تذهب إلى stdout، بينما access log الدوري معطل لتسهيل التشخيص.
|
| 155 |
|
| 156 |
+
> **حد معروف:** تبدل المقاس/الـprofile داخل **الترميز نفسه** مدعوم ومختبر. أما تبدل H.264↔H.265 على track واحد فيمثله الجسر بايتيًا من دون رمي استثناء، لكن FFmpeg 7 ينشئ له `AVStream` متأخرًا لا يدخل في خريطة الخرج المفتوحة. لذلك تُثبّت سياسة المصدر الترميز نفسه عند تجديد الرابط ولا تدّعي تبدلًا سلسًا بين codecين؛ دعمه الحقيقي يحتاج ناشر RTMP tag-level أو مسار Enhanced-RTMP متعدد المسارات واختبار قبول YouTube، لا دمج SPS/PPS ولا إعادة تشغيل مخفية.
|
| 157 |
|
| 158 |
+
## تنبيه التشغيل جنبًا إلى جنب
|
| 159 |
|
| 160 |
+
إذا فُعّلت أتمتة OAuth هنا **وعلى** `Reoo88/Tktktk` بالقناة نفسها، قد يفتح التطبيقان حدثين للمذيع نفسه. شغّل الأتمتة في Space واحد لكل قناة، أو استخدم قنوات/مفاتيح مختلفة.
|
|
|
|
|
|
|
| 161 |
|
| 162 |
+
## تحقق محلي
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 163 |
|
| 164 |
```bash
|
| 165 |
+
PASSWORD=test DATA_DIR="$(mktemp -d)" sh verify.sh
|
|
|
|
| 166 |
```
|
| 167 |
|
| 168 |
+
تفاصيل التشخيص، الأدلة، المخاطر، وخطة التشغيل: [`AUDIT_AR.md`](./AUDIT_AR.md).
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 169 |
|
| 170 |
+
## Privacy Policy & Terms
|
| 171 |
|
| 172 |
+
This application uses YouTube API Services to allow authenticated users to broadcast live content to their own YouTube channels.
|
| 173 |
+
- By using this app, users agree to be bound by the [YouTube Terms of Service](https://www.youtube.com/t/terms) and [Google Privacy Policy](https://www.google.com/policies/privacy).
|
| 174 |
+
- We do not store or share personal user data with third parties.
|
app.py
CHANGED
|
@@ -3,13 +3,11 @@ import os, re, json, time, threading, shutil, secrets, logging
|
|
| 3 |
from concurrent.futures import ThreadPoolExecutor, as_completed
|
| 4 |
from pathlib import Path
|
| 5 |
from urllib.parse import urlparse
|
| 6 |
-
from fastapi import FastAPI,
|
| 7 |
-
from fastapi.security import HTTPBasic, HTTPBasicCredentials
|
| 8 |
from fastapi.responses import HTMLResponse, JSONResponse
|
| 9 |
from pydantic import BaseModel
|
| 10 |
from curl_cffi import requests
|
| 11 |
import tiktok_auth
|
| 12 |
-
import kick_source
|
| 13 |
from ingest import hub, env_rtmp_destination, rtmp_configured, format_session_title, APP_VERSION, max_concurrent_relays
|
| 14 |
|
| 15 |
MSG=('تيك توك يحجب روابط البث لهذا الحساب (غرفة مقيدة بعمر 18+ أو جلسة تحتاج تحققًا)؛ '
|
|
@@ -49,6 +47,7 @@ try:
|
|
| 49 |
ROOT.mkdir(parents=True,exist_ok=True)
|
| 50 |
except OSError as e:
|
| 51 |
logging.error('cannot create %s (%s) — starting read-only', ROOT, type(e).__name__)
|
|
|
|
| 52 |
|
| 53 |
def _ensure_root():
|
| 54 |
try:
|
|
@@ -76,45 +75,64 @@ os.environ.setdefault('YOUTUBE_SCAN_SECONDS',os.getenv('CHECK_INTERVAL','20'))
|
|
| 76 |
print('[BOOT] TikTok Live Monitor → Direct Relay → YouTube version=%s CHECK_INTERVAL=%s SOURCE_STALL_TIMEOUT=%s rtmp=%s'%(APP_VERSION,INTERVAL,SOURCE_STALL_TIMEOUT,'yes' if rtmp_configured() else 'no'),flush=True)
|
| 77 |
|
| 78 |
lock=threading.RLock(); tasks={}; events=[]
|
| 79 |
-
security=HTTPBasic()
|
| 80 |
_monitor_alive=threading.Event()
|
| 81 |
_last_monitor_cycle=0.0
|
| 82 |
_monitor_stop=threading.Event()
|
| 83 |
_states=('OFFLINE','CHECKING','LIVE_DETECTED','STARTING','LIVE','STALLED','RECONNECTING','STOPPING','ERROR','BACKOFF')
|
| 84 |
|
| 85 |
-
def auth(c:HTTPBasicCredentials=Depends(security)):
|
| 86 |
-
if not (secrets.compare_digest(c.username.encode(),b'admin') and secrets.compare_digest(c.password.encode(),PASSWORD.encode())):
|
| 87 |
-
raise HTTPException(401,'Unauthorized',headers={'WWW-Authenticate':'Basic'})
|
| 88 |
-
|
| 89 |
app=FastAPI(docs_url=None,redoc_url=None,openapi_url=None)
|
| 90 |
|
| 91 |
@app.middleware('http')
|
| 92 |
async def _auth_mw(request:Request,call_next):
|
| 93 |
-
#
|
| 94 |
-
|
| 95 |
-
|
|
|
|
|
|
|
| 96 |
header=request.headers.get('authorization') or ''
|
| 97 |
-
if header.lower().startswith('basic '):
|
| 98 |
import base64
|
| 99 |
try:
|
| 100 |
-
raw=base64.b64decode(header.split(None,1)[1]).decode()
|
| 101 |
user,sep,pw=raw.partition(':')
|
| 102 |
-
|
| 103 |
-
|
| 104 |
except Exception:
|
| 105 |
-
|
| 106 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 107 |
|
| 108 |
def log(user,msg):
|
| 109 |
-
|
| 110 |
-
# ورثت كلمة «تيك توك» من زمن المنصة الواحدة، بلا لمس أي سلسلة حرفية في
|
| 111 |
-
# youtube_manager — وبعضها مُطابَق في is_fault_note وفي اختبارات دورة الحياة.
|
| 112 |
-
# آمن لأن events قائمة عرض محضة: تُقرأ في /api/state فقط ولا يُطابقها أي منطق.
|
| 113 |
-
if kick_source.is_kick(user):
|
| 114 |
-
msg=str(msg).replace('تيك توك','كيك').replace('TikTok','Kick')
|
| 115 |
with lock:
|
| 116 |
-
events.append({'time':time.strftime('%H:%M:%S'),'user':user,'message':
|
| 117 |
del events[:-100]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 118 |
|
| 119 |
def update(user,**kw):
|
| 120 |
with lock:
|
|
@@ -160,7 +178,15 @@ def load_tokens():
|
|
| 160 |
except (ValueError,OSError):pass
|
| 161 |
def save_tokens():
|
| 162 |
with lock:
|
| 163 |
-
tmp=ROOT/'tokens.tmp'
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 164 |
def set_token(user,token):
|
| 165 |
token=(token or '').strip()
|
| 166 |
with lock:
|
|
@@ -182,18 +208,10 @@ def _cookie_headers(tok):
|
|
| 182 |
if not sessionid:return {}
|
| 183 |
return {'Cookie':'; '.join('%s=%s'%(k,v) for k,v in pairs.items())}
|
| 184 |
def tiktok_headers(user):
|
| 185 |
-
# موجّه ترويسات حسب المنصة. الاسم لم يتغيّر لأنه ممرَّر كـheaders_for إلى
|
| 186 |
-
# Sender/ManagedYouTube؛ مسار تيك توك يسلك نفس السطرين السابقين حرفيًا.
|
| 187 |
-
if kick_source.is_kick(user):
|
| 188 |
-
return kick_source.media_headers(user)
|
| 189 |
h=tiktok_auth.headers(user)
|
| 190 |
return {'Cookie':h['Cookie']} if h.get('Cookie') else {}
|
| 191 |
-
|
| 192 |
def clean_user(raw):
|
| 193 |
raw=raw.strip()
|
| 194 |
-
# Kick: بادئة صريحة أو رابط kick.com. لا يلمس أي فرع من فروع تيك توك أدناه.
|
| 195 |
-
if kick_source.is_kick(raw) or re.match(r'https?://(www\.)?kick\.com/', raw, re.I):
|
| 196 |
-
return kick_source.clean(raw)
|
| 197 |
if raw.startswith('https://'):
|
| 198 |
p=urlparse(raw)
|
| 199 |
if p.hostname not in ('www.tiktok.com','tiktok.com','vm.tiktok.com','vt.tiktok.com'):raise ValueError('الرابط يجب أن يكون من TikTok')
|
|
@@ -281,18 +299,6 @@ def observe_session(user,force=False):
|
|
| 281 |
return result
|
| 282 |
|
| 283 |
def _observe_session(user):
|
| 284 |
-
# موجّه المنصة: Kick له وحدته المستقلة، وتيك توك يكمل في نفس الدالة الأصلية.
|
| 285 |
-
if kick_source.is_kick(user):
|
| 286 |
-
try:
|
| 287 |
-
return kick_source.observe(user)
|
| 288 |
-
except RuntimeError:
|
| 289 |
-
held=kick_source.last_good(user)
|
| 290 |
-
if held is not None:
|
| 291 |
-
return held
|
| 292 |
-
raise
|
| 293 |
-
return _observe_tiktok(user)
|
| 294 |
-
|
| 295 |
-
def _observe_tiktok(user):
|
| 296 |
"""TikTok room lookup. Null liveRoom/user/data must be Offline, not a crash.
|
| 297 |
|
| 298 |
Production 67c9415: several accounts returned liveRoom=null. `.get` on None
|
|
@@ -422,8 +428,12 @@ def rank_sources(source):
|
|
| 422 |
try:params=json.loads((source.get('flv_pull_url_params') or {}).get(quality) or '{}')
|
| 423 |
except (ValueError,TypeError):params={}
|
| 424 |
add(url,quality,'flv',params)
|
| 425 |
-
|
| 426 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 427 |
add(source.get('rtmp_pull_url'),'غير مصنفة','flv',assumed=True)
|
| 428 |
result=[];seen=set()
|
| 429 |
for item in sorted(candidates,key=lambda c:c['score'],reverse=True):
|
|
@@ -432,7 +442,8 @@ def rank_sources(source):
|
|
| 432 |
|
| 433 |
from youtube_manager import ManagedYouTube
|
| 434 |
from relay import Sender, SourceStalled, RelayStartError
|
| 435 |
-
from
|
|
|
|
| 436 |
def enabled_accounts():
|
| 437 |
with lock:return [u for u,t in tasks.items() if t.get('enabled')]
|
| 438 |
youtube=ManagedYouTube(FFMPEG,observe_session,log,enabled_accounts,ROOT/'youtube-api-state.json',headers_for=tiktok_headers)
|
|
@@ -516,6 +527,7 @@ def _direct_loop(user, dest, stop):
|
|
| 516 |
try:
|
| 517 |
log(user,'[RELAY] @%s starting'%user)
|
| 518 |
update(user, state='LIVE', source=brief, codec=cand.get('codec') or '', quality=cand.get('resolution') or '')
|
|
|
|
| 519 |
ok=sender.send(user, tagged, dest, stop)
|
| 520 |
sent=bool(ok)
|
| 521 |
if sent:break
|
|
@@ -530,10 +542,6 @@ def _direct_loop(user, dest, stop):
|
|
| 530 |
update(user, state='STALLED', last_error='source stalled')
|
| 531 |
log(user,'[SOURCE] @%s trying fallback'%user)
|
| 532 |
continue
|
| 533 |
-
except FormatChanged:
|
| 534 |
-
log(user,'[SOURCE] @%s format changed; reconnect'%user)
|
| 535 |
-
sent=True
|
| 536 |
-
break
|
| 537 |
except Exception as e:
|
| 538 |
log(user,'[RELAY] @%s error %s'%(user, type(e).__name__))
|
| 539 |
continue
|
|
@@ -873,69 +881,11 @@ def _pick_last_error(tasks_map):
|
|
| 873 |
@app.get('/health')
|
| 874 |
@app.get('/healthz')
|
| 875 |
def health_public():
|
| 876 |
-
|
| 877 |
-
|
| 878 |
-
|
| 879 |
-
|
| 880 |
-
|
| 881 |
-
yt_health={}
|
| 882 |
-
try:
|
| 883 |
-
for ev in (youtube.snapshot().get('events') or []):
|
| 884 |
-
if ev.get('username'):
|
| 885 |
-
yt_health[ev['username']]=ev
|
| 886 |
-
except Exception:
|
| 887 |
-
yt_health={}
|
| 888 |
-
per=[]
|
| 889 |
-
for u,tsk in users:
|
| 890 |
-
rs=_relay_snapshot(u)
|
| 891 |
-
ye=yt_health.get(u) or {}
|
| 892 |
-
per.append({'username':u,'status':tsk.get('state') or '',
|
| 893 |
-
'last_data_time':rs.get('last_data_time'),
|
| 894 |
-
'bytes_received':rs.get('bytes_received') or 0,
|
| 895 |
-
'relay_pid':rs.get('relay_pid'),'relay_alive':bool(rs.get('relay_alive')),
|
| 896 |
-
'room_id':tsk.get('room_id') or '','source':tsk.get('source') or '',
|
| 897 |
-
'restarts':rs.get('restarts') or 0,'dest':rs.get('relay_dest') or '',
|
| 898 |
-
'last_error':tsk.get('last_error') or '','source_age':rs.get('source_age'),
|
| 899 |
-
'output_seconds':rs.get('output_seconds') or 0,
|
| 900 |
-
'send_mode':rs.get('send_mode') or '',
|
| 901 |
-
'youtube_health':str(ye.get('youtube_health') or ''),
|
| 902 |
-
'youtube_issues':str(ye.get('youtube_issues') or '')[:120],
|
| 903 |
-
'youtube_status':str(ye.get('youtube_status') or '')})
|
| 904 |
-
res=resource_snapshot()
|
| 905 |
-
mgr=bool(youtube.manager_thread and youtube.manager_thread.is_alive())
|
| 906 |
-
y_events=0; y_hist=0; y_senders=0; y_status=''; y_skip=''
|
| 907 |
-
try:
|
| 908 |
-
jd=youtube.journal.read()
|
| 909 |
-
y_events=len(jd.get('events') or {})
|
| 910 |
-
y_hist=len(jd.get('history') or [])
|
| 911 |
-
y_status=str(getattr(youtube,'status_text','') or '')[:160]
|
| 912 |
-
y_senders=sum(1 for e in (youtube.senders or {}).values() if e.get('thread') and e['thread'].is_alive())
|
| 913 |
-
skip=getattr(youtube,'_skip_last',None) or {}
|
| 914 |
-
if skip:
|
| 915 |
-
y_skip='; '.join('%s: %s'%(u,str(t)[:80]) for u,t in list(skip.items())[-3:])[:200]
|
| 916 |
-
try:
|
| 917 |
-
acc=list(youtube.accounts() or [])
|
| 918 |
-
y_skip=(y_skip+(' | accounts='+','.join(acc)[:80])).strip(' |')
|
| 919 |
-
except Exception:
|
| 920 |
-
pass
|
| 921 |
-
except Exception:
|
| 922 |
-
pass
|
| 923 |
-
return {'application':'running','monitor':'running' if _monitor_alive.is_set() else 'stopped',
|
| 924 |
-
'accounts':n,'enabled':enabled,'active_relays':active,
|
| 925 |
-
'max_concurrent_relays':max_concurrent_relays(),
|
| 926 |
-
'source_stall_timeout':SOURCE_STALL_TIMEOUT,
|
| 927 |
-
'load1':res.get('load1'),'cpus':res.get('cpus'),
|
| 928 |
-
'mem_total_mb':res.get('mem_total_mb'),'mem_avail_mb':res.get('mem_avail_mb'),
|
| 929 |
-
'quota_cpus':res.get('quota_cpus'),'cpu_cores_used':res.get('cpu_cores_used'),
|
| 930 |
-
'cpu_pct_of_quota':res.get('cpu_pct_of_quota'),
|
| 931 |
-
'last_monitor_cycle':_last_monitor_cycle,'last_error':last_error,
|
| 932 |
-
'last_error_user':last_error_user,
|
| 933 |
-
'version':APP_VERSION,'rtmp_configured':rtmp_configured(),
|
| 934 |
-
'metadata_automation':_oauth_automation_on(),
|
| 935 |
-
'youtube_manager':'running' if mgr else 'stopped',
|
| 936 |
-
'youtube_status':y_status,'youtube_events':y_events,'youtube_history':y_hist,
|
| 937 |
-
'youtube_senders':y_senders,'youtube_skip':y_skip,
|
| 938 |
-
'broadcasters':per}
|
| 939 |
|
| 940 |
@app.get('/api/health')
|
| 941 |
def health_detail():
|
|
@@ -954,12 +904,21 @@ def health_detail():
|
|
| 954 |
return {'application':'running','monitor':'running' if _monitor_alive.is_set() else 'stopped',
|
| 955 |
'youtube_manager':'running' if mgr else 'stopped',
|
| 956 |
'accounts':n,'active_relays':hub.active_count(),'last_monitor_cycle':_last_monitor_cycle,
|
| 957 |
-
'last_error':last_error,'last_error_user':last_error_user,'version':APP_VERSION,'rtmp_configured':rtmp_configured(),
|
| 958 |
'oauth_configured':youtube.api.configured(),'metadata_automation':_oauth_automation_on(),
|
| 959 |
'broadcasters':per}
|
| 960 |
|
| 961 |
@app.get('/api/youtube')
|
| 962 |
def youtube_state():return youtube.snapshot()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 963 |
@app.post('/api/youtube/check')
|
| 964 |
def youtube_check():
|
| 965 |
try:return {'channel':youtube.check()}
|
|
@@ -967,6 +926,14 @@ def youtube_check():
|
|
| 967 |
from youtube_api import APIError
|
| 968 |
msg=str(e) if isinstance(e,(APIError,RuntimeError,ValueError)) else 'تعذر فحص تفويض يوتيوب'
|
| 969 |
raise HTTPException(400,msg)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 970 |
@app.post('/api/youtube/settings')
|
| 971 |
def youtube_settings(a:YouTubeSettings):
|
| 972 |
try:youtube.settings(a.model_dump())
|
|
@@ -1009,7 +976,7 @@ def state():
|
|
| 1009 |
'relay_pid':rs.get('relay_pid'),'bytes_received':rs.get('bytes_received') or 0,
|
| 1010 |
'last_data_time':rs.get('last_data_time'),'relay_alive':rs.get('relay_alive'),
|
| 1011 |
'session_title':rs.get('session_title') or '','restarts':rs.get('restarts') or 0,
|
| 1012 |
-
'source_age':rs.get('source_age'),
|
| 1013 |
'youtube_health':str(ye.get('youtube_health') or ''),
|
| 1014 |
'youtube_issues':str(ye.get('youtube_issues') or '')[:120],
|
| 1015 |
'youtube_status':str(ye.get('youtube_status') or ('relay' if rs.get('relay_alive') else (t.get('state') or '')))})
|
|
|
|
| 3 |
from concurrent.futures import ThreadPoolExecutor, as_completed
|
| 4 |
from pathlib import Path
|
| 5 |
from urllib.parse import urlparse
|
| 6 |
+
from fastapi import FastAPI, HTTPException, Request
|
|
|
|
| 7 |
from fastapi.responses import HTMLResponse, JSONResponse
|
| 8 |
from pydantic import BaseModel
|
| 9 |
from curl_cffi import requests
|
| 10 |
import tiktok_auth
|
|
|
|
| 11 |
from ingest import hub, env_rtmp_destination, rtmp_configured, format_session_title, APP_VERSION, max_concurrent_relays
|
| 12 |
|
| 13 |
MSG=('تيك توك يحجب روابط البث لهذا الحساب (غرفة مقيدة بعمر 18+ أو جلسة تحتاج تحققًا)؛ '
|
|
|
|
| 47 |
ROOT.mkdir(parents=True,exist_ok=True)
|
| 48 |
except OSError as e:
|
| 49 |
logging.error('cannot create %s (%s) — starting read-only', ROOT, type(e).__name__)
|
| 50 |
+
os.environ.setdefault('STREAM_EVENTS_PATH',str(ROOT/'logs'/'stream_events.json'))
|
| 51 |
|
| 52 |
def _ensure_root():
|
| 53 |
try:
|
|
|
|
| 75 |
print('[BOOT] TikTok Live Monitor → Direct Relay → YouTube version=%s CHECK_INTERVAL=%s SOURCE_STALL_TIMEOUT=%s rtmp=%s'%(APP_VERSION,INTERVAL,SOURCE_STALL_TIMEOUT,'yes' if rtmp_configured() else 'no'),flush=True)
|
| 76 |
|
| 77 |
lock=threading.RLock(); tasks={}; events=[]
|
|
|
|
| 78 |
_monitor_alive=threading.Event()
|
| 79 |
_last_monitor_cycle=0.0
|
| 80 |
_monitor_stop=threading.Event()
|
| 81 |
_states=('OFFLINE','CHECKING','LIVE_DETECTED','STARTING','LIVE','STALLED','RECONNECTING','STOPPING','ERROR','BACKOFF')
|
| 82 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 83 |
app=FastAPI(docs_url=None,redoc_url=None,openapi_url=None)
|
| 84 |
|
| 85 |
@app.middleware('http')
|
| 86 |
async def _auth_mw(request:Request,call_next):
|
| 87 |
+
# The HTML shell is public so an embedded Space can show its own login form. Browsers
|
| 88 |
+
# commonly suppress HTTP-Basic prompts in cross-origin iframes; every data/mutation API
|
| 89 |
+
# remains protected. /health stays minimal and public for the platform probe.
|
| 90 |
+
public=request.url.path in ('/','/health','/healthz')
|
| 91 |
+
allowed=public
|
| 92 |
header=request.headers.get('authorization') or ''
|
| 93 |
+
if not allowed and header.lower().startswith('basic '):
|
| 94 |
import base64
|
| 95 |
try:
|
| 96 |
+
raw=base64.b64decode(header.split(None,1)[1],validate=True).decode()
|
| 97 |
user,sep,pw=raw.partition(':')
|
| 98 |
+
allowed=bool(sep and secrets.compare_digest(user.encode(),b'admin') and
|
| 99 |
+
secrets.compare_digest(pw.encode(),PASSWORD.encode()))
|
| 100 |
except Exception:
|
| 101 |
+
allowed=False
|
| 102 |
+
if allowed:
|
| 103 |
+
response=await call_next(request)
|
| 104 |
+
else:
|
| 105 |
+
# No WWW-Authenticate challenge here: browsers may suppress or mishandle native Basic
|
| 106 |
+
# prompts inside the Hugging Face iframe. The in-page form sends the same Basic header.
|
| 107 |
+
response=JSONResponse({'detail':'Unauthorized'},status_code=401)
|
| 108 |
+
# The panel carries credentials and operational data: never cache it in an intermediary.
|
| 109 |
+
response.headers['Cache-Control']='no-store'
|
| 110 |
+
response.headers['X-Content-Type-Options']='nosniff'
|
| 111 |
+
response.headers['Referrer-Policy']='no-referrer'
|
| 112 |
+
response.headers['Permissions-Policy']='camera=(), microphone=(), geolocation=()'
|
| 113 |
+
response.headers['Content-Security-Policy']=(
|
| 114 |
+
"default-src 'self'; img-src 'self' data:; style-src 'self' 'unsafe-inline'; "
|
| 115 |
+
"script-src 'self' 'unsafe-inline'; connect-src 'self'; object-src 'none'; "
|
| 116 |
+
"base-uri 'none'; form-action 'self'; frame-ancestors 'self' https://huggingface.co https://*.huggingface.co")
|
| 117 |
+
return response
|
| 118 |
|
| 119 |
def log(user,msg):
|
| 120 |
+
text=str(msg or '').replace('\r',' ').replace('\n',' ')
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 121 |
with lock:
|
| 122 |
+
events.append({'time':time.strftime('%H:%M:%S'),'user':user,'message':text})
|
| 123 |
del events[:-100]
|
| 124 |
+
# Container logs used to contain only 5-second dashboard access lines, so a production
|
| 125 |
+
# noData incident had no diagnostic trace. Emit the already operator-facing event stream,
|
| 126 |
+
# with a final defensive redaction for URLs and credential-shaped query fields.
|
| 127 |
+
stdout_mode=str(os.getenv('LOG_EVENTS_STDOUT','important')).strip().lower()
|
| 128 |
+
important=any(tag in text for tag in ('[WATCHDOG]','[RESTART]','[CLEANUP]','[OFFLINE]','[WARN]')) or \
|
| 129 |
+
any(word in text.lower() for word in ('error','failed','stalled','dead','died','quota','traceback')) or \
|
| 130 |
+
any(word in text for word in ('فشل','تعذر','رفض','مات','انتهت مهلة')) or \
|
| 131 |
+
('[RELAY]' in text and any(word in text for word in (' starting','بدء FFmpeg',' stopping')))
|
| 132 |
+
if stdout_mode not in ('0','false','off','no') and (stdout_mode in ('1','all','true','on','yes') or important):
|
| 133 |
+
safe=re.sub(r'\b(?:rtmps?|rtsp|https?)://\S+','«رابط-مخفي»',text)
|
| 134 |
+
safe=re.sub(r'(?i)(sessionid|token|key|auth)\s*[=:]\s*[^\s;&]+',r'\1=«مخفي»',safe)
|
| 135 |
+
print('[EVENT] @%s %s'%(str(user or 'system')[:48],safe[:700]),flush=True)
|
| 136 |
|
| 137 |
def update(user,**kw):
|
| 138 |
with lock:
|
|
|
|
| 178 |
except (ValueError,OSError):pass
|
| 179 |
def save_tokens():
|
| 180 |
with lock:
|
| 181 |
+
tmp=ROOT/'tokens.tmp'
|
| 182 |
+
tmp.write_text(json.dumps(_tokens))
|
| 183 |
+
# This is a legacy compatibility store containing live TikTok cookies. Keep it
|
| 184 |
+
# owner-only just like tiktok_auth.py's primary store, including after replace().
|
| 185 |
+
try:tmp.chmod(0o600)
|
| 186 |
+
except OSError:pass
|
| 187 |
+
tmp.replace(TOKENS)
|
| 188 |
+
try:TOKENS.chmod(0o600)
|
| 189 |
+
except OSError:pass
|
| 190 |
def set_token(user,token):
|
| 191 |
token=(token or '').strip()
|
| 192 |
with lock:
|
|
|
|
| 208 |
if not sessionid:return {}
|
| 209 |
return {'Cookie':'; '.join('%s=%s'%(k,v) for k,v in pairs.items())}
|
| 210 |
def tiktok_headers(user):
|
|
|
|
|
|
|
|
|
|
|
|
|
| 211 |
h=tiktok_auth.headers(user)
|
| 212 |
return {'Cookie':h['Cookie']} if h.get('Cookie') else {}
|
|
|
|
| 213 |
def clean_user(raw):
|
| 214 |
raw=raw.strip()
|
|
|
|
|
|
|
|
|
|
| 215 |
if raw.startswith('https://'):
|
| 216 |
p=urlparse(raw)
|
| 217 |
if p.hostname not in ('www.tiktok.com','tiktok.com','vm.tiktok.com','vt.tiktok.com'):raise ValueError('الرابط يجب أن يكون من TikTok')
|
|
|
|
| 299 |
return result
|
| 300 |
|
| 301 |
def _observe_session(user):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 302 |
"""TikTok room lookup. Null liveRoom/user/data must be Offline, not a crash.
|
| 303 |
|
| 304 |
Production 67c9415: several accounts returned liveRoom=null. `.get` on None
|
|
|
|
| 428 |
try:params=json.loads((source.get('flv_pull_url_params') or {}).get(quality) or '{}')
|
| 429 |
except (ValueError,TypeError):params={}
|
| 430 |
add(url,quality,'flv',params)
|
| 431 |
+
hls=source.get('hls_pull_url') or source.get('hls_pull_url_map') or {}
|
| 432 |
+
if isinstance(hls,dict):
|
| 433 |
+
for quality,url in hls.items():add(url,quality,'hls')
|
| 434 |
+
elif isinstance(hls,str):
|
| 435 |
+
# webcast/room/info currently returns one signed HLS URL as a string, not a map.
|
| 436 |
+
add(hls,'origin','hls',assumed=True)
|
| 437 |
add(source.get('rtmp_pull_url'),'غير مصنفة','flv',assumed=True)
|
| 438 |
result=[];seen=set()
|
| 439 |
for item in sorted(candidates,key=lambda c:c['score'],reverse=True):
|
|
|
|
| 442 |
|
| 443 |
from youtube_manager import ManagedYouTube
|
| 444 |
from relay import Sender, SourceStalled, RelayStartError
|
| 445 |
+
from stream_monitor import read_events
|
| 446 |
+
from telemetry import read_records as telemetry_records, status as telemetry_status
|
| 447 |
def enabled_accounts():
|
| 448 |
with lock:return [u for u,t in tasks.items() if t.get('enabled')]
|
| 449 |
youtube=ManagedYouTube(FFMPEG,observe_session,log,enabled_accounts,ROOT/'youtube-api-state.json',headers_for=tiktok_headers)
|
|
|
|
| 527 |
try:
|
| 528 |
log(user,'[RELAY] @%s starting'%user)
|
| 529 |
update(user, state='LIVE', source=brief, codec=cand.get('codec') or '', quality=cand.get('resolution') or '')
|
| 530 |
+
sender.telemetry_context={'room_id':room,'path':'direct'}
|
| 531 |
ok=sender.send(user, tagged, dest, stop)
|
| 532 |
sent=bool(ok)
|
| 533 |
if sent:break
|
|
|
|
| 542 |
update(user, state='STALLED', last_error='source stalled')
|
| 543 |
log(user,'[SOURCE] @%s trying fallback'%user)
|
| 544 |
continue
|
|
|
|
|
|
|
|
|
|
|
|
|
| 545 |
except Exception as e:
|
| 546 |
log(user,'[RELAY] @%s error %s'%(user, type(e).__name__))
|
| 547 |
continue
|
|
|
|
| 881 |
@app.get('/health')
|
| 882 |
@app.get('/healthz')
|
| 883 |
def health_public():
|
| 884 |
+
# Liveness is intentionally non-secret. Detailed usernames, room IDs, errors and
|
| 885 |
+
# YouTube state belong to the authenticated /api/health and /api/state endpoints.
|
| 886 |
+
return {'status':'ok','application':'running',
|
| 887 |
+
'monitor':'running' if _monitor_alive.is_set() else 'starting',
|
| 888 |
+
'version':APP_VERSION}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 889 |
|
| 890 |
@app.get('/api/health')
|
| 891 |
def health_detail():
|
|
|
|
| 904 |
return {'application':'running','monitor':'running' if _monitor_alive.is_set() else 'stopped',
|
| 905 |
'youtube_manager':'running' if mgr else 'stopped',
|
| 906 |
'accounts':n,'active_relays':hub.active_count(),'last_monitor_cycle':_last_monitor_cycle,
|
| 907 |
+
'last_error':last_error,'last_error_user':last_error_user,'version':APP_VERSION,'telemetry':telemetry_status(),'rtmp_configured':rtmp_configured(),
|
| 908 |
'oauth_configured':youtube.api.configured(),'metadata_automation':_oauth_automation_on(),
|
| 909 |
'broadcasters':per}
|
| 910 |
|
| 911 |
@app.get('/api/youtube')
|
| 912 |
def youtube_state():return youtube.snapshot()
|
| 913 |
+
@app.get('/api/stream-events')
|
| 914 |
+
def stream_events(limit:int=200,broadcaster:str=''):
|
| 915 |
+
rows=read_events(limit,broadcaster.strip().lstrip('@') or None)
|
| 916 |
+
return {'count':len(rows),'events':rows,'file':'logs/stream_events.json'}
|
| 917 |
+
@app.get('/api/telemetry')
|
| 918 |
+
def telemetry_data(limit:int=200,broadcaster:str=''):
|
| 919 |
+
rows=telemetry_records(limit,broadcaster.strip().lstrip('@') or None)
|
| 920 |
+
return {'count':len(rows),'records':rows,'file':'telemetry/telemetry.jsonl',
|
| 921 |
+
'status':telemetry_status(),'retention':'manual_only_no_auto_delete'}
|
| 922 |
@app.post('/api/youtube/check')
|
| 923 |
def youtube_check():
|
| 924 |
try:return {'channel':youtube.check()}
|
|
|
|
| 926 |
from youtube_api import APIError
|
| 927 |
msg=str(e) if isinstance(e,(APIError,RuntimeError,ValueError)) else 'تعذر فحص تفويض يوتيوب'
|
| 928 |
raise HTTPException(400,msg)
|
| 929 |
+
@app.post('/api/youtube/channel')
|
| 930 |
+
def youtube_confirm_channel(a:YouTubeStart):
|
| 931 |
+
# Explicit channel adoption is separate from starting any public broadcast.
|
| 932 |
+
try:return {'ok':True,'channel':youtube.confirm_channel(a.channel_id)}
|
| 933 |
+
except Exception as e:
|
| 934 |
+
from youtube_api import APIError
|
| 935 |
+
msg=str(e) if isinstance(e,(APIError,RuntimeError,ValueError)) else 'تعذر اعتماد قناة يوتيوب'
|
| 936 |
+
raise HTTPException(400,msg)
|
| 937 |
@app.post('/api/youtube/settings')
|
| 938 |
def youtube_settings(a:YouTubeSettings):
|
| 939 |
try:youtube.settings(a.model_dump())
|
|
|
|
| 976 |
'relay_pid':rs.get('relay_pid'),'bytes_received':rs.get('bytes_received') or 0,
|
| 977 |
'last_data_time':rs.get('last_data_time'),'relay_alive':rs.get('relay_alive'),
|
| 978 |
'session_title':rs.get('session_title') or '','restarts':rs.get('restarts') or 0,
|
| 979 |
+
'source_age':rs.get('source_age'),'send_mode':rs.get('send_mode') or '',
|
| 980 |
'youtube_health':str(ye.get('youtube_health') or ''),
|
| 981 |
'youtube_issues':str(ye.get('youtube_issues') or '')[:120],
|
| 982 |
'youtube_status':str(ye.get('youtube_status') or ('relay' if rs.get('relay_alive') else (t.get('state') or '')))})
|
flv_bridge.py
CHANGED
|
@@ -1,42 +1,47 @@
|
|
| 1 |
-
"""
|
| 2 |
-
Only tag headers/container fields are changed. Encoded video payload, CTS and DTS
|
| 3 |
-
are preserved. H.264 and already-enhanced FLV tags pass through unchanged.
|
| 4 |
-
No whole-recording buffering, decoding, rescaling or frame-rate conversion.
|
| 5 |
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
what a phone does when the layout changes (solo <-> PK round) or when the
|
| 11 |
-
encoder restarts after the app was backgrounded and resumed.
|
| 12 |
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
|
|
|
|
|
|
| 20 |
|
| 21 |
-
|
| 22 |
-
|
|
|
|
|
|
|
| 23 |
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
and shifts tag timestamps so DTS stays strictly increasing.
|
| 29 |
"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 30 |
class FormatChanged(Exception):
|
| 31 |
-
"""
|
| 32 |
|
| 33 |
def _video_signature(body):
|
| 34 |
-
"""
|
| 35 |
if not body:return None
|
| 36 |
if body[0]&0x80: # Enhanced RTMP
|
| 37 |
-
if body[0]&0x0F:return None # PacketType 0 ==
|
| 38 |
-
|
|
|
|
| 39 |
if (body[0]&15)==7 and len(body)>1 and body[1]==0: # legacy AVC sequence header
|
|
|
|
| 40 |
return b'avc1'+body[5:]
|
| 41 |
return None
|
| 42 |
|
|
@@ -52,27 +57,59 @@ def _set_tag_ts(header, ts):
|
|
| 52 |
|
| 53 |
|
| 54 |
class FLVBridge:
|
| 55 |
-
def __init__(self,detect_format_change=
|
| 56 |
-
"""
|
| 57 |
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
"""
|
| 62 |
self.buffer=bytearray();self.header_done=False;self.converted_tags=0
|
| 63 |
-
self.detect_format_change=detect_format_change
|
| 64 |
self.allow_raise=allow_raise
|
| 65 |
-
self.
|
|
|
|
|
|
|
| 66 |
self.skip_file_header=False
|
| 67 |
self.skip_script=False
|
| 68 |
self.skip_same_cfg=False
|
| 69 |
self.last_out_ts=None
|
| 70 |
self.ts_bias=0
|
| 71 |
self.ts_bias_pending=False
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 72 |
def reconnect(self):
|
| 73 |
"""Prepare to splice a new TikTok FLV into the same FFmpeg stdin.
|
| 74 |
|
| 75 |
-
|
|
|
|
| 76 |
"""
|
| 77 |
self.buffer=bytearray()
|
| 78 |
self.header_done=False
|
|
@@ -80,6 +117,21 @@ class FLVBridge:
|
|
| 80 |
self.skip_script=True
|
| 81 |
self.skip_same_cfg=True
|
| 82 |
self.ts_bias_pending=self.last_out_ts is not None
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 83 |
def feed(self,chunk):
|
| 84 |
self.buffer.extend(chunk);output=bytearray()
|
| 85 |
if not self.header_done:
|
|
@@ -97,7 +149,7 @@ class FLVBridge:
|
|
| 97 |
if len(self.buffer)-offset<total:break
|
| 98 |
body=bytes(self.buffer[offset+11:offset+11+size]);tag_type=header[0]
|
| 99 |
if tag_type & 0x20:raise ValueError('Filtered/encrypted FLV tag is unsupported')
|
| 100 |
-
kind = tag_type & 31
|
| 101 |
if kind==18 and self.skip_script:
|
| 102 |
offset+=total
|
| 103 |
continue
|
|
@@ -115,28 +167,57 @@ class FLVBridge:
|
|
| 115 |
if kind==9:
|
| 116 |
signature=_video_signature(body)
|
| 117 |
if signature is not None:
|
| 118 |
-
|
| 119 |
-
|
|
|
|
|
|
|
|
|
|
| 120 |
self.format_changes+=1
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 130 |
if self.ts_bias_pending:
|
| 131 |
self.ts_bias=(self.last_out_ts or 0)+40-raw_ts
|
| 132 |
self.ts_bias_pending=False
|
| 133 |
out_ts=raw_ts+self.ts_bias
|
| 134 |
-
if self.last_out_ts is not None and out_ts<=self.last_out_ts:
|
| 135 |
-
out_ts=self.last_out_ts+1
|
| 136 |
_set_tag_ts(header, out_ts)
|
| 137 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 138 |
header[1:4]=len(body).to_bytes(3,'big')
|
| 139 |
-
|
|
|
|
|
|
|
| 140 |
offset+=total
|
| 141 |
if offset:del self.buffer[:offset]
|
| 142 |
if len(self.buffer)>17*1024*1024:raise ValueError('FLV packet buffer exceeds limit')
|
|
|
|
| 1 |
+
"""Byte-only FLV bridge for uninterrupted H.264/HEVC stream copy.
|
|
|
|
|
|
|
|
|
|
| 2 |
|
| 3 |
+
Legacy HEVC FLV codec-id 12 tags are rewritten to Enhanced RTMP ``hvc1``;
|
| 4 |
+
H.264 and already-enhanced tags otherwise pass through. Encoded access units,
|
| 5 |
+
keyframe flags and composition offsets are untouched. Continuous-source DTS is
|
| 6 |
+
preserved; reconnect applies only one constant offset to keep the timeline open.
|
|
|
|
|
|
|
| 7 |
|
| 8 |
+
A replacement AVCDecoderConfigurationRecord (SPS/PPS) or
|
| 9 |
+
HEVCDecoderConfigurationRecord (VPS/SPS/PPS) is deliberately emitted in the
|
| 10 |
+
same stream before the following coded frame. FFmpeg's FLV demuxer transports a
|
| 11 |
+
replacement as ``AV_PKT_DATA_NEW_EXTRADATA`` and its FLV muxer writes another
|
| 12 |
+
sequence header, so an isolated same-codec update stays in the current publisher.
|
| 13 |
+
The Sender separately counts real resolution changes; repeated changes can trigger
|
| 14 |
+
one per-broadcaster switch to a fixed canvas, reusing the same YouTube event. The
|
| 15 |
+
complete newest record is authoritative; combining old and new parameter sets can
|
| 16 |
+
leave conflicting parameter-set IDs and is not done.
|
| 17 |
|
| 18 |
+
``reconnect()`` splices a refreshed TikTok HTTP-FLV into the existing FFmpeg
|
| 19 |
+
stdin: it removes the second file header and startup metadata, suppresses only
|
| 20 |
+
the redundant startup decoder record, and shifts DTS monotonically. A genuinely
|
| 21 |
+
new decoder record is never suppressed.
|
| 22 |
|
| 23 |
+
References:
|
| 24 |
+
- Enhanced RTMP v2, ExVideoTagHeader/SequenceStart/CodedFrames (Veovera VSO)
|
| 25 |
+
- FFmpeg 7.1 ``flvdec.c``/``flvenc.c`` NEW_EXTRADATA handling
|
| 26 |
+
- GStreamer bugs 797255/797256 (stream headers/caps changes in streamable FLV)
|
|
|
|
| 27 |
"""
|
| 28 |
+
import os
|
| 29 |
+
from collections import deque
|
| 30 |
+
from stream_monitor import log_event, video_dimensions
|
| 31 |
+
|
| 32 |
+
|
| 33 |
class FormatChanged(Exception):
|
| 34 |
+
"""Compatibility name; decoder-configuration changes no longer raise it."""
|
| 35 |
|
| 36 |
def _video_signature(body):
|
| 37 |
+
"""Return ``FourCC + decoder config`` for a video SequenceStart, else None."""
|
| 38 |
if not body:return None
|
| 39 |
if body[0]&0x80: # Enhanced RTMP
|
| 40 |
+
if body[0]&0x0F:return None # PacketType 0 == SequenceStart
|
| 41 |
+
if len(body)<6:raise ValueError('Truncated Enhanced RTMP sequence header')
|
| 42 |
+
return bytes(body[1:5])+body[5:]
|
| 43 |
if (body[0]&15)==7 and len(body)>1 and body[1]==0: # legacy AVC sequence header
|
| 44 |
+
if len(body)<6:raise ValueError('Truncated AVC sequence header')
|
| 45 |
return b'avc1'+body[5:]
|
| 46 |
return None
|
| 47 |
|
|
|
|
| 57 |
|
| 58 |
|
| 59 |
class FLVBridge:
|
| 60 |
+
def __init__(self,detect_format_change=False,allow_raise=None,user='',event_logger=None):
|
| 61 |
+
"""Create a streaming bridge.
|
| 62 |
|
| 63 |
+
``detect_format_change`` and ``allow_raise`` remain accepted for callers from older
|
| 64 |
+
releases, but are intentionally non-operative: decoder-record replacement is a normal
|
| 65 |
+
streamable-FLV event and must not tear down the publisher.
|
| 66 |
"""
|
| 67 |
self.buffer=bytearray();self.header_done=False;self.converted_tags=0
|
| 68 |
+
self.detect_format_change=bool(detect_format_change) # compatibility/observability only
|
| 69 |
self.allow_raise=allow_raise
|
| 70 |
+
self.user=str(user or 'system');self.event_logger=event_logger or log_event
|
| 71 |
+
self.video_cfg=None;self.video_codec=None;self.video_size=None
|
| 72 |
+
self.format_changes=0;self.codec_changes=0
|
| 73 |
self.skip_file_header=False
|
| 74 |
self.skip_script=False
|
| 75 |
self.skip_same_cfg=False
|
| 76 |
self.last_out_ts=None
|
| 77 |
self.ts_bias=0
|
| 78 |
self.ts_bias_pending=False
|
| 79 |
+
self._video_samples=deque();self._bitrate_kbps=None;self._bitrate_check_ts=None
|
| 80 |
+
self._last_keyframe_ts=None;self._keyframe_interval=None;self._keyframe_event_ts=None
|
| 81 |
+
self._last_keyframe_tag=None # آخر وسم إطار مفتاحي مُرسل كاملًا: مادة حشو الفجوات
|
| 82 |
+
def _event(self,event,details):
|
| 83 |
+
try:self.event_logger(self.user,event,details)
|
| 84 |
+
except Exception:pass
|
| 85 |
+
def _observe_frame(self,ts,size,keyframe):
|
| 86 |
+
samples=self._video_samples;samples.append((ts,size))
|
| 87 |
+
while samples and ts-samples[0][0]>4000:samples.popleft()
|
| 88 |
+
if len(samples)>=2 and samples[-1][0]-samples[0][0]>=3000 and (
|
| 89 |
+
self._bitrate_check_ts is None or ts-self._bitrate_check_ts>=2000):
|
| 90 |
+
span=max(1,samples[-1][0]-samples[0][0]);kbps=round(sum(x[1] for x in samples)*8/span,1)
|
| 91 |
+
old=self._bitrate_kbps;self._bitrate_kbps=kbps;self._bitrate_check_ts=ts
|
| 92 |
+
ratio=abs(kbps-old)/max(old,1) if old is not None else 0
|
| 93 |
+
threshold=max(0.1,float(os.getenv('STREAM_BITRATE_CHANGE_RATIO','0.35')))
|
| 94 |
+
minimum=max(1.0,float(os.getenv('STREAM_BITRATE_CHANGE_KBPS','50')))
|
| 95 |
+
if old is not None and ratio>=threshold and abs(kbps-old)>=minimum:
|
| 96 |
+
self._event('BITRATE_CHANGE',{'old_kbps':old,'new_kbps':kbps,
|
| 97 |
+
'change_percent':round((kbps-old)*100/max(old,1),1),'source_dts_ms':ts})
|
| 98 |
+
if keyframe:
|
| 99 |
+
if self._last_keyframe_ts is not None and ts>self._last_keyframe_ts:
|
| 100 |
+
interval=ts-self._last_keyframe_ts;old=self._keyframe_interval
|
| 101 |
+
if old is not None and abs(interval-old)>=max(500,old*0.30) and (
|
| 102 |
+
self._keyframe_event_ts is None or ts-self._keyframe_event_ts>=5000):
|
| 103 |
+
self._event('KEYFRAME_CHANGE',{'old_interval_ms':round(old,1),
|
| 104 |
+
'new_interval_ms':interval,'source_dts_ms':ts})
|
| 105 |
+
self._keyframe_event_ts=ts
|
| 106 |
+
self._keyframe_interval=interval if old is None else old*0.7+interval*0.3
|
| 107 |
+
self._last_keyframe_ts=ts
|
| 108 |
def reconnect(self):
|
| 109 |
"""Prepare to splice a new TikTok FLV into the same FFmpeg stdin.
|
| 110 |
|
| 111 |
+
``video_cfg`` stays live so an identical startup record can be omitted while a changed
|
| 112 |
+
record is forwarded through the already-open publisher.
|
| 113 |
"""
|
| 114 |
self.buffer=bytearray()
|
| 115 |
self.header_done=False
|
|
|
|
| 117 |
self.skip_script=True
|
| 118 |
self.skip_same_cfg=True
|
| 119 |
self.ts_bias_pending=self.last_out_ts is not None
|
| 120 |
+
self._event('RECONNECT',{'scope':'tiktok_http','outbound_rtmp_reused':True,
|
| 121 |
+
'last_output_dts_ms':self.last_out_ts})
|
| 122 |
+
def freeze_bytes(self,step_ms=2000):
|
| 123 |
+
"""وسم الإطار المفتاحي الأخير مكرّرًا بطابع زمني متقدّم: صورة مجمّدة صحيحة
|
| 124 |
+
التشكيل تُبقي الخطّ الزمني (ووصلة يوتيوب) حيًّا أثناء صمت المصدر، بدل صمتٍ
|
| 125 |
+
تقفل بعده حافة يوتيوب النشر (~14-20 ث موثّق). أول وسم حقيقي بعد الحشو يأخذ
|
| 126 |
+
انحيازًا ثابتًا من آخر زمن مُرسل — نفس خياطة reconnect() تمامًا."""
|
| 127 |
+
if self._last_keyframe_tag is None or self.last_out_ts is None:return None
|
| 128 |
+
new_ts=int(self.last_out_ts)+max(40,int(step_ms))
|
| 129 |
+
header=bytearray(self._last_keyframe_tag[:11])
|
| 130 |
+
_set_tag_ts(header,new_ts)
|
| 131 |
+
self.last_out_ts=new_ts
|
| 132 |
+
self.ts_bias_pending=True
|
| 133 |
+
return bytes(header)+self._last_keyframe_tag[11:]
|
| 134 |
+
|
| 135 |
def feed(self,chunk):
|
| 136 |
self.buffer.extend(chunk);output=bytearray()
|
| 137 |
if not self.header_done:
|
|
|
|
| 149 |
if len(self.buffer)-offset<total:break
|
| 150 |
body=bytes(self.buffer[offset+11:offset+11+size]);tag_type=header[0]
|
| 151 |
if tag_type & 0x20:raise ValueError('Filtered/encrypted FLV tag is unsupported')
|
| 152 |
+
kind = tag_type & 31;raw_ts=_tag_ts(header)
|
| 153 |
if kind==18 and self.skip_script:
|
| 154 |
offset+=total
|
| 155 |
continue
|
|
|
|
| 167 |
if kind==9:
|
| 168 |
signature=_video_signature(body)
|
| 169 |
if signature is not None:
|
| 170 |
+
previous=self.video_cfg;old_size=self.video_size
|
| 171 |
+
changed=previous is not None and signature!=previous
|
| 172 |
+
codec=signature[:4].decode('ascii','replace')
|
| 173 |
+
new_size=video_dimensions(codec,signature[4:])
|
| 174 |
+
if changed:
|
| 175 |
self.format_changes+=1
|
| 176 |
+
old_codec=previous[:4].decode('ascii','replace')
|
| 177 |
+
codec_changed=codec!=old_codec
|
| 178 |
+
if codec_changed:
|
| 179 |
+
self.codec_changes+=1;self._video_samples.clear()
|
| 180 |
+
self._bitrate_kbps=None;self._last_keyframe_ts=None;self._keyframe_interval=None
|
| 181 |
+
details={'codec':codec,'previous_codec':old_codec,'source_dts_ms':raw_ts,
|
| 182 |
+
'old_config_bytes':len(previous)-4,'new_config_bytes':len(signature)-4,
|
| 183 |
+
'outbound_rtmp_reused':True}
|
| 184 |
+
self._event('DECODER_CONFIG_CHANGE',details)
|
| 185 |
+
if codec_changed:self._event('CODEC_CHANGE',details)
|
| 186 |
+
if old_size and new_size and old_size!=new_size:
|
| 187 |
+
self._event('RESOLUTION_CHANGE',{'codec':codec,
|
| 188 |
+
'old_width':old_size[0],'old_height':old_size[1],
|
| 189 |
+
'new_width':new_size[0],'new_height':new_size[1],
|
| 190 |
+
'source_dts_ms':raw_ts,'outbound_rtmp_reused':True})
|
| 191 |
+
elif previous is None:
|
| 192 |
+
self._event('STREAM_CONFIG',{'codec':codec,'width':new_size[0] if new_size else None,
|
| 193 |
+
'height':new_size[1] if new_size else None,'config_bytes':len(signature)-4})
|
| 194 |
+
self.video_cfg=signature;self.video_codec=codec;self.video_size=new_size
|
| 195 |
+
# Only the first identical record after reconnect is redundant. A changed
|
| 196 |
+
# record is emitted now, before any dependent coded frame in this input.
|
| 197 |
+
if self.skip_same_cfg:
|
| 198 |
+
self.skip_same_cfg=False
|
| 199 |
+
if previous is not None and not changed:
|
| 200 |
+
offset+=total
|
| 201 |
+
continue
|
| 202 |
if self.ts_bias_pending:
|
| 203 |
self.ts_bias=(self.last_out_ts or 0)+40-raw_ts
|
| 204 |
self.ts_bias_pending=False
|
| 205 |
out_ts=raw_ts+self.ts_bias
|
|
|
|
|
|
|
| 206 |
_set_tag_ts(header, out_ts)
|
| 207 |
+
# Equal DTS across audio/video (or config/frame) is valid and must not be rewritten.
|
| 208 |
+
# Only reconnect() adds one constant bias; last_out_ts tracks the emitted maximum.
|
| 209 |
+
self.last_out_ts=out_ts if self.last_out_ts is None else max(self.last_out_ts,out_ts)
|
| 210 |
+
is_keyframe=False
|
| 211 |
+
if kind==9 and body:
|
| 212 |
+
enhanced=bool(body[0]&0x80);packet=(body[0]&15) if enhanced else (body[1] if len(body)>1 else -1)
|
| 213 |
+
codec_id=body[0]&15
|
| 214 |
+
coded=(enhanced and packet in (1,3)) or (not enhanced and codec_id==7 and packet==1)
|
| 215 |
+
is_keyframe=coded and ((body[0]>>4)&7)==1
|
| 216 |
+
if coded:self._observe_frame(out_ts,len(body),is_keyframe)
|
| 217 |
header[1:4]=len(body).to_bytes(3,'big')
|
| 218 |
+
tag_bytes=bytes(header)+body+(11+len(body)).to_bytes(4,'big')
|
| 219 |
+
if is_keyframe:self._last_keyframe_tag=tag_bytes
|
| 220 |
+
output.extend(tag_bytes)
|
| 221 |
offset+=total
|
| 222 |
if offset:del self.buffer[:offset]
|
| 223 |
if len(self.buffer)>17*1024*1024:raise ValueError('FLV packet buffer exceeds limit')
|
index.html
CHANGED
|
@@ -1,5 +1,5 @@
|
|
| 1 |
<!doctype html><html lang="ar" dir="rtl"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
|
| 2 |
-
<title>TikTok
|
| 3 |
<style>
|
| 4 |
:root{color-scheme:dark;font-family:system-ui,sans-serif}
|
| 5 |
body{margin:0;background:#0b1220;color:#e6edf7}
|
|
@@ -30,20 +30,27 @@ footer{color:#8a9bb3;font-size:12px;margin:24px 0}
|
|
| 30 |
a{color:#79dcc5}
|
| 31 |
</style></head><body><main>
|
| 32 |
<header class="row" style="justify-content:space-between">
|
| 33 |
-
<div><small>TikTok
|
| 34 |
-
<span class="badge" id="sysbadge">System</span>
|
| 35 |
</header>
|
| 36 |
<p id="error" hidden></p>
|
| 37 |
|
| 38 |
-
<section class="panel" id="
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 39 |
<h2>Accounts</h2>
|
| 40 |
-
<form id="add" class="row"><input id="username" placeholder="
|
| 41 |
-
<input id="token" placeholder="توكن sessionid —
|
| 42 |
<button>إضافة ومراقبة</button></form>
|
| 43 |
<p class="row"><button class="secondary" id="reload" type="button">تحديث</button><small id="updated"></small></p>
|
| 44 |
<div id="tasks" class="cards"></div>
|
| 45 |
<details><summary>توكن تيك توك (للبثوث المقيدة عمريًا)</summary>
|
| 46 |
-
<label>الصق كامل سطر Cookie</label>
|
| 47 |
<textarea id="tokinput" rows="2" dir="ltr" placeholder="sessionid=...; sid_tt=..."></textarea>
|
| 48 |
<div class="row" style="margin-top:8px">
|
| 49 |
<button id="tokvalidate" class="secondary" type="button">فحص التوكن</button>
|
|
@@ -56,13 +63,15 @@ a{color:#79dcc5}
|
|
| 56 |
</details>
|
| 57 |
</section>
|
| 58 |
|
| 59 |
-
<section class="panel" id="youtube-panel">
|
| 60 |
<h2>YouTube</h2>
|
| 61 |
<div class="row">
|
| 62 |
-
<button id="ytcheck" class="secondary">فحص OAuth والقناة</button>
|
| 63 |
-
<button id="
|
| 64 |
-
<button id="
|
|
|
|
| 65 |
</div>
|
|
|
|
| 66 |
<div class="kv" style="margin:14px 0">
|
| 67 |
<b>الاتصال</b><span id="ytconn">—</span>
|
| 68 |
<b>حالة البث</b><span id="ytstate">—</span>
|
|
@@ -88,41 +97,81 @@ a{color:#79dcc5}
|
|
| 88 |
<input id="titletemplate">
|
| 89 |
<label>قالب الوصف</label>
|
| 90 |
<textarea id="desctemplate" rows="4"></textarea>
|
| 91 |
-
<p><small>المتغيرات: {broadcaster} {name} {title} {username} {
|
| 92 |
<button type="submit" id="savesettings">حفظ</button>
|
| 93 |
</form>
|
| 94 |
</details>
|
| 95 |
</section>
|
| 96 |
|
| 97 |
-
<section class="panel" id="system-panel">
|
| 98 |
<h2>System</h2>
|
| 99 |
<div class="kv">
|
| 100 |
<b>Monitoring</b><span id="mon">—</span>
|
| 101 |
<b>الحسابات</b><span id="nacc">—</span>
|
| 102 |
<b>Relay active</b><span id="nrel">—</span>
|
|
|
|
|
|
|
| 103 |
<b>آخر خطأ</b><span id="lasterr">لا يوجد</span>
|
| 104 |
</div>
|
| 105 |
<h2 style="margin-top:16px">السجل الحي</h2>
|
| 106 |
<div id="logs"></div>
|
| 107 |
</section>
|
| 108 |
-
<footer>لا تسجيل محلي ولا أرشيف فيديو. المسار: TikTok
|
| 109 |
</main>
|
| 110 |
<script>
|
| 111 |
const $=id=>document.getElementById(id),esc=s=>String(s).replace(/[&<>"']/g,c=>({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c]));
|
| 112 |
-
|
|
|
|
|
|
|
|
|
|
| 113 |
function error(text){$('error').textContent=text;$('error').hidden=!text}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 114 |
async function api(url,method='GET',body){
|
| 115 |
-
const
|
|
|
|
| 116 |
let j;try{j=await r.json()}catch{}
|
|
|
|
| 117 |
if(!r.ok)throw Error(typeof j?.detail==='string'?j.detail:'تعذر تنفيذ الطلب');return j;
|
| 118 |
}
|
| 119 |
function fillSettings(s){$('privacy').value=s.privacy||'public';$('titletemplate').value=s.title||'';$('desctemplate').value=s.description||'';settingsLoaded=true}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 120 |
function stateLabel(st){
|
| 121 |
const m={OFFLINE:'Offline',CHECKING:'فحص',LIVE_DETECTED:'اكتشاف LIVE',STARTING:'بدء',LIVE:'LIVE',STALLED:'توقّف المصدر',RECONNECTING:'إعادة اتصال',STOPPING:'إيقاف',ERROR:'خطأ',BACKOFF:'انتظار'};
|
| 122 |
return m[st]||st||'—';
|
| 123 |
}
|
| 124 |
function fmtDur(s){s=Math.max(0,s|0);const h=Math.floor(s/3600),m=Math.floor((s%3600)/60);return h?h+'س '+m+'د':m+'د '+ (s%60)+'ث'}
|
| 125 |
async function refresh(){
|
|
|
|
| 126 |
if(polling&&Date.now()-(pollingSince||0)<30000)return;
|
| 127 |
polling=true;pollingSince=Date.now();
|
| 128 |
try{
|
|
@@ -139,9 +188,7 @@ async function refresh(){
|
|
| 139 |
|
| 140 |
$('tasks').innerHTML=tasks.length?tasks.map(x=>{
|
| 141 |
const live=x.state==='LIVE';
|
| 142 |
-
|
| 143 |
-
const who=kick?("🟢 kick/"+esc(x.username.slice(5))):("🎵 @"+esc(x.username));
|
| 144 |
-
return `<article class="card"><h3>${who}</h3>
|
| 145 |
<p><span class="badge ${live?'live':(x.state==='OFFLINE'?'off':'')}">${esc(stateLabel(x.state))}</span>
|
| 146 |
${x.nickname?' · '+esc(x.nickname):''}</p>
|
| 147 |
<p>LIVE منذ: ${live?esc(fmtDur(x.live_for||0)):'—'}</p>
|
|
@@ -176,6 +223,8 @@ async function refresh(){
|
|
| 176 |
$('events').innerHTML=evs.length?evs.map(e=>`<article class="card"><h3>${esc(e.title||'بث')}</h3>
|
| 177 |
<p>@${esc(e.username)} · ${esc(e.phase||'')} · YT ${esc(e.youtube_status||'—')}</p>
|
| 178 |
<p>المصدر: ${esc(e.source||'—')}</p>
|
|
|
|
|
|
|
| 179 |
<small>${esc(e.status||e.note||'')} · ${Math.floor(e.output_seconds||0)} ث</small>
|
| 180 |
${e.broadcast_id?`<p><a target="_blank" rel="noopener" href="https://www.youtube.com/watch?v=${encodeURIComponent(e.broadcast_id)}">فتح على يوتيوب</a></p>`:''}
|
| 181 |
</article>`).join(''):'<p>عند LIVE يُفتح Relay عبر RTMPS (مفتاح البيئة أو OAuth). فشل تحديث العنوان لا يوقف الفيديو.</p>';
|
|
@@ -183,7 +232,7 @@ async function refresh(){
|
|
| 183 |
const lastErr=tasks.map(t=>t.last_error).filter(Boolean)[0] || (s0.logs||[]).filter(l=>/error|فشل|stall|خطأ/i.test(l.message||'')).slice(-1)[0]?.message || 'لا يوجد';
|
| 184 |
$('mon').textContent=s0.monitor_running?'يعمل':'متوقف';
|
| 185 |
$('nacc').textContent=String(tasks.length);
|
| 186 |
-
$('nrel').textContent=String(s0.active_relays||evs.length||0)+' / '+(s0.max_concurrent_relays||'?');
|
| 187 |
$('ncpu').textContent=(s0.cpu_pct_of_quota!=null
|
| 188 |
? (s0.cpu_pct_of_quota+'% من '+(s0.quota_cpus||'?')+' vCPU')
|
| 189 |
: (s0.load1!=null?('load '+s0.load1):'—'));
|
|
@@ -194,10 +243,9 @@ async function refresh(){
|
|
| 194 |
|
| 195 |
const cur=y.send_mode_setting||y.send_mode||'auto';
|
| 196 |
const sel=$('sendmode'); if(document.activeElement!==sel) sel.value=['auto','fixed720','fixed1080','copy'].includes(cur)?cur:'auto';
|
| 197 |
-
|
| 198 |
$('savesettings').disabled=!!y.automatic||!!evs.length;
|
| 199 |
if(!settingsLoaded&&y.settings)fillSettings(y.settings);
|
| 200 |
-
channelId=y.channel?.id||channelId;
|
| 201 |
|
| 202 |
$('logs').innerHTML=(s0.logs||[]).slice().reverse().map(l=>`<div>${esc(l.time||'')} · @${esc(l.user||'')} · ${esc(l.message||'')}</div>`).join('')||'<p>لا أحداث بعد.</p>';
|
| 203 |
renderTiktok(s0.tiktok);
|
|
@@ -209,6 +257,10 @@ function renderTiktok(t){if(!t){$('tokstate').innerHTML='';return}
|
|
| 209 |
rows+=accts.map(([u,v])=>`<div>@${esc(u)} — ${v.authenticated?esc(v.masked):'يعتمد على العام'}</div>`).join('');
|
| 210 |
$('tokstate').innerHTML=rows}
|
| 211 |
function tokShow(html){const e=$('tokresult');e.innerHTML=html;e.hidden=false}
|
|
|
|
|
|
|
|
|
|
|
|
|
| 212 |
$('tokvalidate').onclick=async()=>{const raw=$('tokinput').value.trim();if(!raw){tokShow('الصق التوكن أولًا');return}
|
| 213 |
try{$('tokvalidate').disabled=true;const r=await api('/api/tiktok/token/validate','POST',{token:raw});tokShow(esc(r.message||''));if(r.ok)await refresh()}catch(e){tokShow(esc(e.message))}finally{$('tokvalidate').disabled=false}};
|
| 214 |
$('toksave').onclick=async()=>{const raw=$('tokinput').value.trim();if(!raw){tokShow('الصق التوكن أولًا');return}
|
|
@@ -216,9 +268,36 @@ $('toksave').onclick=async()=>{const raw=$('tokinput').value.trim();if(!raw){tok
|
|
| 216 |
$('tokcheck').onclick=async()=>{const u=$('tokuser').value.trim();if(!u){tokShow('اكتب اسم الحساب');return}
|
| 217 |
try{$('tokcheck').disabled=true;const r=await api('/api/tiktok/token/check/'+encodeURIComponent(u),'POST');tokShow(esc(r.message||r.result||''))}catch(e){tokShow(esc(e.message))}finally{$('tokcheck').disabled=false}};
|
| 218 |
$('sendmodeset').onclick=async()=>{try{$('sendmodeset').disabled=true;await api('/api/youtube/settings','POST',{send_mode:$('sendmode').value});await refresh()}catch(e){error(e.message)}finally{$('sendmodeset').disabled=false}};
|
| 219 |
-
$('ytcheck').onclick=async()=>{
|
| 220 |
-
|
| 221 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 222 |
$('settingsform').onsubmit=async e=>{e.preventDefault();try{await api('/api/youtube/settings','POST',{name:'',privacy:$('privacy').value,title:$('titletemplate').value,description:$('desctemplate').value});settingsLoaded=false;await refresh()}catch(e){error(e.message)}};
|
| 223 |
$('add').onsubmit=async e=>{e.preventDefault();try{await api('/api/accounts','POST',{username:$('username').value,token:$('token').value});$('username').value='';$('token').value='';await refresh()}catch(e){error(e.message)}};
|
| 224 |
document.addEventListener('click',async e=>{const b=e.target.closest('button');if(!b)return;try{
|
|
@@ -227,5 +306,5 @@ document.addEventListener('click',async e=>{const b=e.target.closest('button');i
|
|
| 227 |
}catch(e){error(e.message)}});
|
| 228 |
$('reload').onclick=()=>refresh();
|
| 229 |
document.addEventListener('visibilitychange',()=>{if(!document.hidden)refresh()});
|
| 230 |
-
refresh();setInterval(refresh,
|
| 231 |
</script></body></html>
|
|
|
|
| 1 |
<!doctype html><html lang="ar" dir="rtl"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
|
| 2 |
+
<title>TikTok Live Monitor</title>
|
| 3 |
<style>
|
| 4 |
:root{color-scheme:dark;font-family:system-ui,sans-serif}
|
| 5 |
body{margin:0;background:#0b1220;color:#e6edf7}
|
|
|
|
| 30 |
a{color:#79dcc5}
|
| 31 |
</style></head><body><main>
|
| 32 |
<header class="row" style="justify-content:space-between">
|
| 33 |
+
<div><small>TikTok Live Monitor → Direct Relay → YouTube</small><h1>رصد البث المباشر</h1></div>
|
| 34 |
+
<div class="row"><span class="badge" id="sysbadge">System</span><button class="secondary" id="logout" type="button" hidden>خروج</button></div>
|
| 35 |
</header>
|
| 36 |
<p id="error" hidden></p>
|
| 37 |
|
| 38 |
+
<section class="panel" id="login-panel">
|
| 39 |
+
<h2>دخول الإدارة</h2>
|
| 40 |
+
<p>استخدم كلمة السر المحفوظة في Secret باسم <code>PASSWORD</code>. لا تستخدم توكن Hugging Face هنا.</p>
|
| 41 |
+
<form id="login" class="row"><input id="admin-password" type="password" autocomplete="current-password" placeholder="كلمة السر" required><button>دخول</button></form>
|
| 42 |
+
<p id="login-error" hidden></p>
|
| 43 |
+
</section>
|
| 44 |
+
|
| 45 |
+
<section class="panel" id="accounts-panel" hidden>
|
| 46 |
<h2>Accounts</h2>
|
| 47 |
+
<form id="add" class="row"><input id="username" placeholder="اسم المستخدم أو رابط الحساب" required>
|
| 48 |
+
<input id="token" placeholder="توكن sessionid — اختياري للغرف 18+">
|
| 49 |
<button>إضافة ومراقبة</button></form>
|
| 50 |
<p class="row"><button class="secondary" id="reload" type="button">تحديث</button><small id="updated"></small></p>
|
| 51 |
<div id="tasks" class="cards"></div>
|
| 52 |
<details><summary>توكن تيك توك (للبثوث المقيدة عمريًا)</summary>
|
| 53 |
+
<label>الصق كامل سطر Cookie أو JSON المُصدَّر من إضافة الكوكيز</label>
|
| 54 |
<textarea id="tokinput" rows="2" dir="ltr" placeholder="sessionid=...; sid_tt=..."></textarea>
|
| 55 |
<div class="row" style="margin-top:8px">
|
| 56 |
<button id="tokvalidate" class="secondary" type="button">فحص التوكن</button>
|
|
|
|
| 63 |
</details>
|
| 64 |
</section>
|
| 65 |
|
| 66 |
+
<section class="panel" id="youtube-panel" hidden>
|
| 67 |
<h2>YouTube</h2>
|
| 68 |
<div class="row">
|
| 69 |
+
<button id="ytcheck" class="secondary" type="button">فحص OAuth والقناة</button>
|
| 70 |
+
<button id="ytadopt" class="secondary" type="button" hidden>اعتماد القناة الجديدة فقط</button>
|
| 71 |
+
<button id="ytstart" type="button">تفعيل البث التلقائي</button>
|
| 72 |
+
<button id="ytstop" class="danger" type="button">إيقاف وإنهاء البث الجاري</button>
|
| 73 |
</div>
|
| 74 |
+
<p id="ytchannelnotice" role="status" aria-live="polite" hidden></p>
|
| 75 |
<div class="kv" style="margin:14px 0">
|
| 76 |
<b>الاتصال</b><span id="ytconn">—</span>
|
| 77 |
<b>حالة البث</b><span id="ytstate">—</span>
|
|
|
|
| 97 |
<input id="titletemplate">
|
| 98 |
<label>قالب الوصف</label>
|
| 99 |
<textarea id="desctemplate" rows="4"></textarea>
|
| 100 |
+
<p><small>المتغيرات: {broadcaster} {name} {title} {username} {date} {time} {hashtags} {room_id} — التاريخ والوقت بتوقيت بغداد لحظة بدء جلسة تيك توك.</small></p>
|
| 101 |
<button type="submit" id="savesettings">حفظ</button>
|
| 102 |
</form>
|
| 103 |
</details>
|
| 104 |
</section>
|
| 105 |
|
| 106 |
+
<section class="panel" id="system-panel" hidden>
|
| 107 |
<h2>System</h2>
|
| 108 |
<div class="kv">
|
| 109 |
<b>Monitoring</b><span id="mon">—</span>
|
| 110 |
<b>الحسابات</b><span id="nacc">—</span>
|
| 111 |
<b>Relay active</b><span id="nrel">—</span>
|
| 112 |
+
<b>CPU</b><span id="ncpu">—</span>
|
| 113 |
+
<b>RAM</b><span id="nram">—</span>
|
| 114 |
<b>آخر خطأ</b><span id="lasterr">لا يوجد</span>
|
| 115 |
</div>
|
| 116 |
<h2 style="margin-top:16px">السجل الحي</h2>
|
| 117 |
<div id="logs"></div>
|
| 118 |
</section>
|
| 119 |
+
<footer>لا تسجيل محلي ولا أرشيف فيديو. المسار: TikTok → الذاكرة/الأنبوب → FFmpeg → YouTube RTMPS. أسرار OAuth والتوكنات لا تظهر هنا.</footer>
|
| 120 |
</main>
|
| 121 |
<script>
|
| 122 |
const $=id=>document.getElementById(id),esc=s=>String(s).replace(/[&<>"']/g,c=>({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c]));
|
| 123 |
+
// An OAuth check is the operator's candidate, not the old journal's active channel.
|
| 124 |
+
// Periodic refresh must NEVER overwrite it with y.channel from the previous channel.
|
| 125 |
+
let settingsLoaded=false,checkedChannel=null,lastY=null,polling=false,pollingSince=0,youtubeBusy=false;
|
| 126 |
+
let authHeader='';try{authHeader=sessionStorage.getItem('on-basic-auth')||''}catch{}
|
| 127 |
function error(text){$('error').textContent=text;$('error').hidden=!text}
|
| 128 |
+
function showAuth(ok){
|
| 129 |
+
$('login-panel').hidden=ok;$('accounts-panel').hidden=!ok;$('youtube-panel').hidden=!ok;$('system-panel').hidden=!ok;$('logout').hidden=!ok;
|
| 130 |
+
if(!ok){authHeader='';checkedChannel=null;lastY=null;settingsLoaded=false;renderCheckedChannel();try{sessionStorage.removeItem('on-basic-auth')}catch{};$('admin-password').focus()}
|
| 131 |
+
}
|
| 132 |
+
function basicHeader(password){
|
| 133 |
+
const bytes=new TextEncoder().encode('admin:'+password);let raw='';for(const b of bytes)raw+=String.fromCharCode(b);return 'Basic '+btoa(raw)
|
| 134 |
+
}
|
| 135 |
async function api(url,method='GET',body){
|
| 136 |
+
const headers={};if(body)headers['Content-Type']='application/json';if(authHeader)headers.Authorization=authHeader;
|
| 137 |
+
const r=await fetch(url,{method,cache:'no-store',headers,body:body?JSON.stringify(body):undefined});
|
| 138 |
let j;try{j=await r.json()}catch{}
|
| 139 |
+
if(r.status===401){showAuth(false);throw Error('كلمة السر غير صحيحة أو انتهت جلسة الصفحة')}
|
| 140 |
if(!r.ok)throw Error(typeof j?.detail==='string'?j.detail:'تعذر تنفيذ الطلب');return j;
|
| 141 |
}
|
| 142 |
function fillSettings(s){$('privacy').value=s.privacy||'public';$('titletemplate').value=s.title||'';$('desctemplate').value=s.description||'';settingsLoaded=true}
|
| 143 |
+
function channelSwitchPending(){return !!(checkedChannel?.previous&&checkedChannel.previous.id!==checkedChannel.id)}
|
| 144 |
+
function renderCheckedChannel(){
|
| 145 |
+
const pending=channelSwitchPending(),notice=$('ytchannelnotice');
|
| 146 |
+
$('ytadopt').hidden=!pending;notice.hidden=!checkedChannel;
|
| 147 |
+
notice.textContent=!checkedChannel?'':pending
|
| 148 |
+
? 'القناة الجديدة بعد الفحص: «'+checkedChannel.title+'» ('+checkedChannel.id+') بدل «'+checkedChannel.previous.title+'». لم تُعتمد بعد؛ يمكنك اعتمادها فقط دون تشغيل بث. أحداث القناة السابقة تُؤرشف محليًا ولا تُعدَّل على يوتيوب.'
|
| 149 |
+
: 'القناة المؤكدة بالفحص: «'+checkedChannel.title+'» ('+checkedChannel.id+').';
|
| 150 |
+
}
|
| 151 |
+
function updateYouTubeControls(){
|
| 152 |
+
const y=lastY||{};
|
| 153 |
+
$('ytcheck').disabled=youtubeBusy;$('ytadopt').disabled=youtubeBusy;
|
| 154 |
+
$('ytstart').disabled=youtubeBusy||!!y.automatic;
|
| 155 |
+
$('ytstop').disabled=youtubeBusy||(!y.automatic&&!(y.events||[]).length);
|
| 156 |
+
}
|
| 157 |
+
async function checkYouTubeChannel(){
|
| 158 |
+
const j=await api('/api/youtube/check','POST');
|
| 159 |
+
if(!j.channel?.id)throw Error('لم يُرجع الفحص قناة مفوضة');
|
| 160 |
+
checkedChannel=j.channel;renderCheckedChannel();return checkedChannel;
|
| 161 |
+
}
|
| 162 |
+
function channelConfirmation(channel,start){
|
| 163 |
+
const previous=channel.previous&&channel.previous.id!==channel.id?channel.previous:null;
|
| 164 |
+
let text=previous?'تبديل القناة من «'+previous.title+'» إلى «'+channel.title+'» ('+channel.id+')؟\nستتوقف مرسلات القناة السابقة وتُؤرشف أحداثها محليًا فقط؛ لن تُحذف أو تُعدَّل على يوتيوب.\n'
|
| 165 |
+
:'القناة: «'+channel.title+'» ('+channel.id+').\n';
|
| 166 |
+
return text+(start?'تفعيل Relay التلقائي وإنشاء بث عند رصد LIVE على هذه القناة؟':'اعتماد القناة فقط، مع إبقاء الأتمتة معطلة عند التبديل؟');
|
| 167 |
+
}
|
| 168 |
function stateLabel(st){
|
| 169 |
const m={OFFLINE:'Offline',CHECKING:'فحص',LIVE_DETECTED:'اكتشاف LIVE',STARTING:'بدء',LIVE:'LIVE',STALLED:'توقّف المصدر',RECONNECTING:'إعادة اتصال',STOPPING:'إيقاف',ERROR:'خطأ',BACKOFF:'انتظار'};
|
| 170 |
return m[st]||st||'—';
|
| 171 |
}
|
| 172 |
function fmtDur(s){s=Math.max(0,s|0);const h=Math.floor(s/3600),m=Math.floor((s%3600)/60);return h?h+'س '+m+'د':m+'د '+ (s%60)+'ث'}
|
| 173 |
async function refresh(){
|
| 174 |
+
if(!authHeader||document.hidden)return;
|
| 175 |
if(polling&&Date.now()-(pollingSince||0)<30000)return;
|
| 176 |
polling=true;pollingSince=Date.now();
|
| 177 |
try{
|
|
|
|
| 188 |
|
| 189 |
$('tasks').innerHTML=tasks.length?tasks.map(x=>{
|
| 190 |
const live=x.state==='LIVE';
|
| 191 |
+
return `<article class="card"><h3>@${esc(x.username)}</h3>
|
|
|
|
|
|
|
| 192 |
<p><span class="badge ${live?'live':(x.state==='OFFLINE'?'off':'')}">${esc(stateLabel(x.state))}</span>
|
| 193 |
${x.nickname?' · '+esc(x.nickname):''}</p>
|
| 194 |
<p>LIVE منذ: ${live?esc(fmtDur(x.live_for||0)):'—'}</p>
|
|
|
|
| 223 |
$('events').innerHTML=evs.length?evs.map(e=>`<article class="card"><h3>${esc(e.title||'بث')}</h3>
|
| 224 |
<p>@${esc(e.username)} · ${esc(e.phase||'')} · YT ${esc(e.youtube_status||'—')}</p>
|
| 225 |
<p>المصدر: ${esc(e.source||'—')}</p>
|
| 226 |
+
<p>وضع الإرسال الفعلي: ${esc(e.send_mode||'قيد التحديد')}</p>
|
| 227 |
+
${e.pending_send_mode?`<p>الترميز الثابت ينتظر خانة: ${esc(e.pending_send_mode)}</p>`:''}
|
| 228 |
<small>${esc(e.status||e.note||'')} · ${Math.floor(e.output_seconds||0)} ث</small>
|
| 229 |
${e.broadcast_id?`<p><a target="_blank" rel="noopener" href="https://www.youtube.com/watch?v=${encodeURIComponent(e.broadcast_id)}">فتح على يوتيوب</a></p>`:''}
|
| 230 |
</article>`).join(''):'<p>عند LIVE يُفتح Relay عبر RTMPS (مفتاح البيئة أو OAuth). فشل تحديث العنوان لا يوقف الفيديو.</p>';
|
|
|
|
| 232 |
const lastErr=tasks.map(t=>t.last_error).filter(Boolean)[0] || (s0.logs||[]).filter(l=>/error|فشل|stall|خطأ/i.test(l.message||'')).slice(-1)[0]?.message || 'لا يوجد';
|
| 233 |
$('mon').textContent=s0.monitor_running?'يعمل':'متوقف';
|
| 234 |
$('nacc').textContent=String(tasks.length);
|
| 235 |
+
$('nrel').textContent=String(s0.active_relays||evs.length||0)+' / '+(Number(s0.max_concurrent_relays)===0?'∞':(s0.max_concurrent_relays||'?'));
|
| 236 |
$('ncpu').textContent=(s0.cpu_pct_of_quota!=null
|
| 237 |
? (s0.cpu_pct_of_quota+'% من '+(s0.quota_cpus||'?')+' vCPU')
|
| 238 |
: (s0.load1!=null?('load '+s0.load1):'—'));
|
|
|
|
| 243 |
|
| 244 |
const cur=y.send_mode_setting||y.send_mode||'auto';
|
| 245 |
const sel=$('sendmode'); if(document.activeElement!==sel) sel.value=['auto','fixed720','fixed1080','copy'].includes(cur)?cur:'auto';
|
| 246 |
+
updateYouTubeControls();renderCheckedChannel();
|
| 247 |
$('savesettings').disabled=!!y.automatic||!!evs.length;
|
| 248 |
if(!settingsLoaded&&y.settings)fillSettings(y.settings);
|
|
|
|
| 249 |
|
| 250 |
$('logs').innerHTML=(s0.logs||[]).slice().reverse().map(l=>`<div>${esc(l.time||'')} · @${esc(l.user||'')} · ${esc(l.message||'')}</div>`).join('')||'<p>لا أحداث بعد.</p>';
|
| 251 |
renderTiktok(s0.tiktok);
|
|
|
|
| 257 |
rows+=accts.map(([u,v])=>`<div>@${esc(u)} — ${v.authenticated?esc(v.masked):'يعتمد على العام'}</div>`).join('');
|
| 258 |
$('tokstate').innerHTML=rows}
|
| 259 |
function tokShow(html){const e=$('tokresult');e.innerHTML=html;e.hidden=false}
|
| 260 |
+
$('login').onsubmit=async e=>{e.preventDefault();const p=$('admin-password').value;const msg=$('login-error');msg.hidden=true;
|
| 261 |
+
authHeader=basicHeader(p);try{await api('/api/state');try{sessionStorage.setItem('on-basic-auth',authHeader)}catch{};$('admin-password').value='';showAuth(true);await refresh()}
|
| 262 |
+
catch(err){showAuth(false);msg.textContent='تعذر الدخول: '+String(err.message||err);msg.hidden=false}};
|
| 263 |
+
$('logout').onclick=()=>{showAuth(false);error('');$('login-error').hidden=true};
|
| 264 |
$('tokvalidate').onclick=async()=>{const raw=$('tokinput').value.trim();if(!raw){tokShow('الصق التوكن أولًا');return}
|
| 265 |
try{$('tokvalidate').disabled=true;const r=await api('/api/tiktok/token/validate','POST',{token:raw});tokShow(esc(r.message||''));if(r.ok)await refresh()}catch(e){tokShow(esc(e.message))}finally{$('tokvalidate').disabled=false}};
|
| 266 |
$('toksave').onclick=async()=>{const raw=$('tokinput').value.trim();if(!raw){tokShow('الصق التوكن أولًا');return}
|
|
|
|
| 268 |
$('tokcheck').onclick=async()=>{const u=$('tokuser').value.trim();if(!u){tokShow('اكتب اسم الحساب');return}
|
| 269 |
try{$('tokcheck').disabled=true;const r=await api('/api/tiktok/token/check/'+encodeURIComponent(u),'POST');tokShow(esc(r.message||r.result||''))}catch(e){tokShow(esc(e.message))}finally{$('tokcheck').disabled=false}};
|
| 270 |
$('sendmodeset').onclick=async()=>{try{$('sendmodeset').disabled=true;await api('/api/youtube/settings','POST',{send_mode:$('sendmode').value});await refresh()}catch(e){error(e.message)}finally{$('sendmodeset').disabled=false}};
|
| 271 |
+
$('ytcheck').onclick=async()=>{
|
| 272 |
+
if(youtubeBusy)return;youtubeBusy=true;updateYouTubeControls();
|
| 273 |
+
try{const channel=await checkYouTubeChannel();await refresh();alert('القناة المفوضة: '+channel.title+(channelSwitchPending()?' — بانتظار تأكيد اعتمادها':''))}
|
| 274 |
+
catch(e){error(e.message)}finally{youtubeBusy=false;updateYouTubeControls()}
|
| 275 |
+
};
|
| 276 |
+
$('ytadopt').onclick=async()=>{
|
| 277 |
+
if(youtubeBusy)return;youtubeBusy=true;updateYouTubeControls();
|
| 278 |
+
try{
|
| 279 |
+
const channel=await checkYouTubeChannel();
|
| 280 |
+
if(!confirm(channelConfirmation(channel,false)))return;
|
| 281 |
+
const j=await api('/api/youtube/channel','POST',{channel_id:channel.id});
|
| 282 |
+
checkedChannel=j.channel;renderCheckedChannel();await refresh();
|
| 283 |
+
alert('تم اعتماد القناة «'+j.channel.title+'». اعتماد القناة وحده لا يبدأ أي بث.');
|
| 284 |
+
}catch(e){error(e.message)}finally{youtubeBusy=false;updateYouTubeControls()}
|
| 285 |
+
};
|
| 286 |
+
$('ytstart').onclick=async()=>{
|
| 287 |
+
if(youtubeBusy)return;youtubeBusy=true;updateYouTubeControls();
|
| 288 |
+
try{
|
| 289 |
+
// Recheck even after a previous check: OAuth Secrets may have changed in another tab.
|
| 290 |
+
const channel=await checkYouTubeChannel();
|
| 291 |
+
if(!confirm(channelConfirmation(channel,true)))return;
|
| 292 |
+
await api('/api/youtube/start','POST',{channel_id:channel.id});
|
| 293 |
+
checkedChannel={id:channel.id,title:channel.title};renderCheckedChannel();await refresh();
|
| 294 |
+
}catch(e){error(e.message)}finally{youtubeBusy=false;updateYouTubeControls()}
|
| 295 |
+
};
|
| 296 |
+
$('ytstop').onclick=async()=>{
|
| 297 |
+
if(youtubeBusy||!confirm('إيقاف الأتمتة وإنهاء البث الجاري؟'))return;
|
| 298 |
+
youtubeBusy=true;updateYouTubeControls();
|
| 299 |
+
try{await api('/api/youtube/stop','POST');await refresh()}catch(e){error(e.message)}finally{youtubeBusy=false;updateYouTubeControls()}
|
| 300 |
+
};
|
| 301 |
$('settingsform').onsubmit=async e=>{e.preventDefault();try{await api('/api/youtube/settings','POST',{name:'',privacy:$('privacy').value,title:$('titletemplate').value,description:$('desctemplate').value});settingsLoaded=false;await refresh()}catch(e){error(e.message)}};
|
| 302 |
$('add').onsubmit=async e=>{e.preventDefault();try{await api('/api/accounts','POST',{username:$('username').value,token:$('token').value});$('username').value='';$('token').value='';await refresh()}catch(e){error(e.message)}};
|
| 303 |
document.addEventListener('click',async e=>{const b=e.target.closest('button');if(!b)return;try{
|
|
|
|
| 306 |
}catch(e){error(e.message)}});
|
| 307 |
$('reload').onclick=()=>refresh();
|
| 308 |
document.addEventListener('visibilitychange',()=>{if(!document.hidden)refresh()});
|
| 309 |
+
showAuth(!!authHeader);if(authHeader)refresh();setInterval(refresh,10000);
|
| 310 |
</script></body></html>
|
ingest.py
CHANGED
|
@@ -6,7 +6,7 @@ import os, threading, time
|
|
| 6 |
from datetime import datetime
|
| 7 |
from zoneinfo import ZoneInfo
|
| 8 |
|
| 9 |
-
APP_VERSION = 'relay-v2.
|
| 10 |
|
| 11 |
|
| 12 |
def env_rtmp_destination():
|
|
@@ -47,17 +47,16 @@ def max_concurrent_relays():
|
|
| 47 |
|
| 48 |
|
| 49 |
def light_max():
|
| 50 |
-
"""
|
| 51 |
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
HEVC/PK streams re-encode.
|
| 56 |
"""
|
| 57 |
try:
|
| 58 |
-
n = int(str(os.getenv('YOUTUBE_LIGHT_MAX', '
|
| 59 |
except (TypeError, ValueError):
|
| 60 |
-
n =
|
| 61 |
return max(0, min(n, 8))
|
| 62 |
|
| 63 |
|
|
@@ -91,6 +90,9 @@ class RelayHub:
|
|
| 91 |
self.lock = threading.RLock()
|
| 92 |
self.slots = {}
|
| 93 |
self.restarts = {}
|
|
|
|
|
|
|
|
|
|
| 94 |
|
| 95 |
@staticmethod
|
| 96 |
def _ffmpeg_alive(cur):
|
|
@@ -133,10 +135,12 @@ class RelayHub:
|
|
| 133 |
with self.lock:
|
| 134 |
cur = self.slots.get(user)
|
| 135 |
if not cur:
|
|
|
|
| 136 |
return
|
| 137 |
if owner and cur.get('owner') != owner:
|
| 138 |
return
|
| 139 |
self.slots.pop(user, None)
|
|
|
|
| 140 |
|
| 141 |
def busy(self, user):
|
| 142 |
with self.lock:
|
|
@@ -157,31 +161,47 @@ class RelayHub:
|
|
| 157 |
with self.lock:
|
| 158 |
return sum(1 for v in self.slots.values() if self._ffmpeg_alive(v))
|
| 159 |
|
| 160 |
-
def
|
| 161 |
-
"""
|
| 162 |
-
n
|
| 163 |
-
|
| 164 |
-
|
| 165 |
-
|
| 166 |
-
|
| 167 |
-
|
| 168 |
-
|
| 169 |
-
|
| 170 |
-
|
| 171 |
-
|
| 172 |
-
|
| 173 |
-
|
| 174 |
-
|
| 175 |
-
|
| 176 |
-
|
| 177 |
-
|
| 178 |
-
if mode in ('matchgop', 'fixed720', 'fixed1080'):
|
| 179 |
-
n += 1
|
| 180 |
return n
|
| 181 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 182 |
def light_available(self, except_user=None):
|
| 183 |
return self.light_count(except_user) < light_max()
|
| 184 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 185 |
def restart_count(self, user):
|
| 186 |
with self.lock:
|
| 187 |
return int(self.restarts.get(user) or 0)
|
|
|
|
| 6 |
from datetime import datetime
|
| 7 |
from zoneinfo import ZoneInfo
|
| 8 |
|
| 9 |
+
APP_VERSION = 'relay-v2.32-gap-filler'
|
| 10 |
|
| 11 |
|
| 12 |
def env_rtmp_destination():
|
|
|
|
| 47 |
|
| 48 |
|
| 49 |
def light_max():
|
| 50 |
+
"""Operator opt-in ceiling for legacy x264 fallback; zero disables video re-encoding.
|
| 51 |
|
| 52 |
+
The default is deliberately zero: AVC and Enhanced-RTMP HEVC are copied, including decoder
|
| 53 |
+
configuration replacement. Historical CBR/x264 modes remain available only by explicitly
|
| 54 |
+
raising this limit.
|
|
|
|
| 55 |
"""
|
| 56 |
try:
|
| 57 |
+
n = int(str(os.getenv('YOUTUBE_LIGHT_MAX', '0')).strip() or '0')
|
| 58 |
except (TypeError, ValueError):
|
| 59 |
+
n = 0
|
| 60 |
return max(0, min(n, 8))
|
| 61 |
|
| 62 |
|
|
|
|
| 90 |
self.lock = threading.RLock()
|
| 91 |
self.slots = {}
|
| 92 |
self.restarts = {}
|
| 93 |
+
# Atomic per-broadcaster reservations prevent simultaneous format fallbacks from
|
| 94 |
+
# exceeding YOUTUBE_LIGHT_MAX while their existing FFmpeg children are still exiting.
|
| 95 |
+
self.light_reservations = set()
|
| 96 |
|
| 97 |
@staticmethod
|
| 98 |
def _ffmpeg_alive(cur):
|
|
|
|
| 135 |
with self.lock:
|
| 136 |
cur = self.slots.get(user)
|
| 137 |
if not cur:
|
| 138 |
+
self.light_reservations.discard(user)
|
| 139 |
return
|
| 140 |
if owner and cur.get('owner') != owner:
|
| 141 |
return
|
| 142 |
self.slots.pop(user, None)
|
| 143 |
+
self.light_reservations.discard(user)
|
| 144 |
|
| 145 |
def busy(self, user):
|
| 146 |
with self.lock:
|
|
|
|
| 161 |
with self.lock:
|
| 162 |
return sum(1 for v in self.slots.values() if self._ffmpeg_alive(v))
|
| 163 |
|
| 164 |
+
def _light_count_locked(self, except_user=None):
|
| 165 |
+
"""Count active encoders plus reserved slots, without counting either twice."""
|
| 166 |
+
active=set();n=0
|
| 167 |
+
for u,v in self.slots.items():
|
| 168 |
+
if except_user and u==except_user:continue
|
| 169 |
+
if u in self.light_reservations:
|
| 170 |
+
active.add(u);n+=1
|
| 171 |
+
continue
|
| 172 |
+
if not self._ffmpeg_alive(v):continue
|
| 173 |
+
snd=v.get('sender');mode=''
|
| 174 |
+
try:
|
| 175 |
+
mode=str(getattr(snd,'sticky_mode',None) or '')
|
| 176 |
+
if not mode and snd:
|
| 177 |
+
snap=snd.snapshot() or {};mode=str(snap.get('send_mode') or '')
|
| 178 |
+
except Exception:pass
|
| 179 |
+
if mode in ('matchgop','fixed720','fixed1080'):
|
| 180 |
+
active.add(u);n+=1
|
| 181 |
+
n+=sum(1 for u in self.light_reservations if u!=except_user and u not in active)
|
|
|
|
|
|
|
| 182 |
return n
|
| 183 |
|
| 184 |
+
def light_count(self, except_user=None):
|
| 185 |
+
"""Publishers and atomic reservations using matchgop/fixed720/fixed1080."""
|
| 186 |
+
with self.lock:return self._light_count_locked(except_user)
|
| 187 |
+
|
| 188 |
def light_available(self, except_user=None):
|
| 189 |
return self.light_count(except_user) < light_max()
|
| 190 |
|
| 191 |
+
def reserve_light(self,user):
|
| 192 |
+
"""Atomically claim one per-user encoder slot before changing a live publisher."""
|
| 193 |
+
user=str(user or '')
|
| 194 |
+
if not user:return False
|
| 195 |
+
with self.lock:
|
| 196 |
+
if user in self.light_reservations:return True
|
| 197 |
+
limit=light_max()
|
| 198 |
+
if limit<=0 or self._light_count_locked(except_user=user)>=limit:return False
|
| 199 |
+
self.light_reservations.add(user)
|
| 200 |
+
return True
|
| 201 |
+
|
| 202 |
+
def release_light(self,user):
|
| 203 |
+
with self.lock:self.light_reservations.discard(str(user or ''))
|
| 204 |
+
|
| 205 |
def restart_count(self, user):
|
| 206 |
with self.lock:
|
| 207 |
return int(self.restarts.get(user) or 0)
|
kick_source.py
DELETED
|
@@ -1,371 +0,0 @@
|
|
| 1 |
-
"""مصدر Kick — رصد قناة Kick وإرجاع نفس عقد الرصد الذي يستعمله مسار تيك توك.
|
| 2 |
-
|
| 3 |
-
لماذا ملف مستقل
|
| 4 |
-
----------------
|
| 5 |
-
مسار تيك توك في app.py/relay.py/youtube_manager.py متكامل ومجرَّب، وأي تعديل داخله
|
| 6 |
-
مخاطرة. لذلك كل منطق Kick هنا، ونقطة التماس الوحيدة مع البقية هي دالة واحدة
|
| 7 |
-
`observe(user)` تُرجع القاموس نفسه الذي يُرجعه `_observe_session` لتيك توك:
|
| 8 |
-
|
| 9 |
-
{'status': 'live'|'offline', 'room_id': str, 'sources': [...],
|
| 10 |
-
'nickname': str, 'live_title': str}
|
| 11 |
-
|
| 12 |
-
وبهذا يمرّ بث Kick في نفس خط الأنابيب: _select_source → probe → Sender → RTMPS،
|
| 13 |
-
بلا أي تفرّع إضافي في منطق الحارس أو إدارة أحداث يوتيوب.
|
| 14 |
-
|
| 15 |
-
لماذا بلا إعادة ترميز فيديو
|
| 16 |
-
---------------------------
|
| 17 |
-
Kick يبثّ عبر Amazon IVS، وكل الجودات التي يعلنها الـmaster playlist هي
|
| 18 |
-
avc1 (H.264) + mp4a.40.2 (AAC) — مُقاس حيًّا على القناة absi:
|
| 19 |
-
|
| 20 |
-
1080p60 1920x1080 avc1.64002A / mp4a.40.2 ~9.0 Mbps
|
| 21 |
-
720p60 1280x720 avc1.4D401F / mp4a.40.2 ~3.4 Mbps
|
| 22 |
-
480p30 · 360p30 · 160p30
|
| 23 |
-
|
| 24 |
-
وهذا بالضبط ما تقبله حافة يوتيوب بالنسخ المباشر، فالمسار هو `-c:v copy`:
|
| 25 |
-
صفر إعادة ترميز للصورة، صفر خسارة جودة، وصفر حمل CPU على cpu-basic.
|
| 26 |
-
الصوت وحده يُعاد ترميزه إلى AAC 128k — وهذه سياسة المشروع القائمة أصلًا
|
| 27 |
-
(relay.command) وليست إضافة من Kick: كلفتها لا تُذكر وتُزيل صنفًا كاملًا من
|
| 28 |
-
التجمّد عند اختلاف إعدادات AAC بين المقاطع.
|
| 29 |
-
|
| 30 |
-
لأن المرشّح هنا يُعلن codec='h264' فإن `Sender.copy_is_safe` يسمح بالنسخ مباشرة،
|
| 31 |
-
و`Sender.input_args` يفتح الـm3u8 بنفسه (لا أنبوب stdin، ولا FLVBridge) — وهو
|
| 32 |
-
المسار الأهدأ: FFmpeg يجلب كل مقطع وحده فلا تقتل عثرةُ حافةٍ العمليةَ كلها.
|
| 33 |
-
|
| 34 |
-
ضمانات ضد التجميد عند المشاهد
|
| 35 |
-
------------------------------
|
| 36 |
-
1. نُرجع كل الجودات مرتَّبة، لا جودة واحدة: إن تعثّرت 1080p60 ينزل المشرف إلى
|
| 37 |
-
720p60 في نفس الدورة بدل أن يقف البث.
|
| 38 |
-
2. روابط IVS موقّعة ومنتهية الصلاحية؛ كل رصد يجلب playback_url طازجًا، فإعادة
|
| 39 |
-
الاتصال بعد أي صمت تبدأ برابط جديد لا برابط ميت.
|
| 40 |
-
3. نثبّت `-live_start_index` قرب حافة البث (عبر relay) فلا يتراكم تأخير.
|
| 41 |
-
4. لا نخلط الجودات داخل جلسة واحدة إلا عند الفشل: تغيّر الدقة وسط الجلسة هو
|
| 42 |
-
أكثر ما يُجمّد صورة يوتيوب.
|
| 43 |
-
"""
|
| 44 |
-
import json, os, re, threading, time
|
| 45 |
-
|
| 46 |
-
from curl_cffi import requests
|
| 47 |
-
|
| 48 |
-
PREFIX = 'kick:'
|
| 49 |
-
API_V2 = 'https://kick.com/api/v2/channels/%s'
|
| 50 |
-
API_V1 = 'https://kick.com/api/v1/channels/%s'
|
| 51 |
-
_HOSTS = ('kick.com', 'www.kick.com')
|
| 52 |
-
_SLUG_RE = re.compile(r'[A-Za-z0-9_][A-Za-z0-9_.-]{0,30}$')
|
| 53 |
-
|
| 54 |
-
_lock = threading.Lock()
|
| 55 |
-
_last_good = {} # slug -> (monotonic, observation) آخر رصد ناجح، لامتصاص عثرة API واحدة
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
# --------------------------------------------------------------------------- #
|
| 59 |
-
# هوية الحساب
|
| 60 |
-
# --------------------------------------------------------------------------- #
|
| 61 |
-
def is_kick(user):
|
| 62 |
-
return str(user or '').strip().lower().startswith(PREFIX)
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
def channel(user):
|
| 66 |
-
"""kick:absi -> absi"""
|
| 67 |
-
raw = str(user or '').strip()
|
| 68 |
-
if raw.lower().startswith(PREFIX):
|
| 69 |
-
raw = raw[len(PREFIX):]
|
| 70 |
-
return raw.strip().lstrip('@').lower()
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
def clean(raw):
|
| 74 |
-
"""يقبل: kick:absi · absi (مع تحديد المنصة) · https://kick.com/absi → 'kick:absi'."""
|
| 75 |
-
text = str(raw or '').strip()
|
| 76 |
-
if text.lower().startswith(PREFIX):
|
| 77 |
-
text = text[len(PREFIX):].strip()
|
| 78 |
-
if text.startswith(('http://', 'https://')):
|
| 79 |
-
from urllib.parse import urlparse
|
| 80 |
-
p = urlparse(text)
|
| 81 |
-
if (p.hostname or '').lower() not in _HOSTS:
|
| 82 |
-
raise ValueError('الرابط يجب أن يكون من Kick')
|
| 83 |
-
parts = [x for x in (p.path or '').split('/') if x]
|
| 84 |
-
if not parts:
|
| 85 |
-
raise ValueError('رابط Kick بلا اسم قناة')
|
| 86 |
-
text = parts[0]
|
| 87 |
-
text = text.lstrip('@')
|
| 88 |
-
if not _SLUG_RE.fullmatch(text):
|
| 89 |
-
raise ValueError('اسم قناة Kick غير صالح')
|
| 90 |
-
return PREFIX + text.lower()
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
def profile_url(user):
|
| 94 |
-
return 'https://kick.com/' + channel(user)
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
def headers(user=None):
|
| 98 |
-
"""ترويسات طلب Kick — لا تخصّ تيك توك ولا تحمل أي توكن ما لم يضعه المشغّل."""
|
| 99 |
-
out = {
|
| 100 |
-
'Referer': 'https://kick.com/',
|
| 101 |
-
'Origin': 'https://kick.com',
|
| 102 |
-
'Accept': 'application/json, text/plain, */*',
|
| 103 |
-
'Accept-Language': 'ar,en-US;q=0.9,en;q=0.8',
|
| 104 |
-
}
|
| 105 |
-
cookie = (os.getenv('KICK_COOKIE') or '').strip()
|
| 106 |
-
if cookie:
|
| 107 |
-
out['Cookie'] = cookie
|
| 108 |
-
return out
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
def media_headers(user=None):
|
| 112 |
-
"""ترويسات جلب الـm3u8/المقاطع من حافة IVS — بلا Cookie، فهي روابط موقّعة."""
|
| 113 |
-
return {'Referer': 'https://kick.com/', 'Origin': 'https://kick.com'}
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
# --------------------------------------------------------------------------- #
|
| 117 |
-
# شبكة
|
| 118 |
-
# --------------------------------------------------------------------------- #
|
| 119 |
-
def _timeout():
|
| 120 |
-
try:
|
| 121 |
-
return float(os.getenv('KICK_TIMEOUT', '20'))
|
| 122 |
-
except (TypeError, ValueError):
|
| 123 |
-
return 20.0
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
def _impersonate():
|
| 127 |
-
return (os.getenv('KICK_IMPERSONATE') or 'chrome').strip() or 'chrome'
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
def _get(url, hdrs=None, tries=2):
|
| 131 |
-
last = None
|
| 132 |
-
for attempt in range(max(1, tries)):
|
| 133 |
-
try:
|
| 134 |
-
r = requests.get(url, impersonate=_impersonate(),
|
| 135 |
-
headers=hdrs if hdrs is not None else headers(),
|
| 136 |
-
timeout=_timeout())
|
| 137 |
-
if r.status_code == 404:
|
| 138 |
-
raise RuntimeError('Kick لا يعرف هذه القناة (404) — تحقق من الاسم')
|
| 139 |
-
if r.status_code == 429:
|
| 140 |
-
raise RuntimeError('Kick حدّ الطلبات مؤقتًا (429)؛ سيُعاد في الدورة التالية')
|
| 141 |
-
if r.status_code in (401, 403):
|
| 142 |
-
raise RuntimeError('Kick رفض الطلب (%s) — حماية Cloudflare؛ جرّب ضبط KICK_COOKIE' % r.status_code)
|
| 143 |
-
if 500 <= r.status_code < 600:
|
| 144 |
-
raise RuntimeError('Kick أعاد %s؛ سيُعاد لاحقًا' % r.status_code)
|
| 145 |
-
r.raise_for_status()
|
| 146 |
-
return r
|
| 147 |
-
except RuntimeError:
|
| 148 |
-
raise
|
| 149 |
-
except Exception as e:
|
| 150 |
-
last = e
|
| 151 |
-
if attempt + 1 < max(1, tries):
|
| 152 |
-
time.sleep(1.0)
|
| 153 |
-
raise RuntimeError('تعذر الوصول إلى Kick (%s)' % type(last).__name__)
|
| 154 |
-
|
| 155 |
-
|
| 156 |
-
def _channel_payload(slug):
|
| 157 |
-
try:
|
| 158 |
-
return _get(API_V2 % slug).json()
|
| 159 |
-
except RuntimeError:
|
| 160 |
-
raise
|
| 161 |
-
except Exception:
|
| 162 |
-
pass
|
| 163 |
-
try:
|
| 164 |
-
return _get(API_V1 % slug).json()
|
| 165 |
-
except Exception as e:
|
| 166 |
-
raise RuntimeError('تعذر قراءة بيانات قناة Kick (%s)' % type(e).__name__)
|
| 167 |
-
|
| 168 |
-
|
| 169 |
-
# --------------------------------------------------------------------------- #
|
| 170 |
-
# تحليل master playlist
|
| 171 |
-
# --------------------------------------------------------------------------- #
|
| 172 |
-
def _attrs(line):
|
| 173 |
-
out = {}
|
| 174 |
-
for m in re.finditer(r'([A-Z0-9-]+)=("([^"]*)"|[^,]*)', line):
|
| 175 |
-
out[m.group(1)] = m.group(3) if m.group(3) is not None else m.group(2)
|
| 176 |
-
return out
|
| 177 |
-
|
| 178 |
-
|
| 179 |
-
def _codec_name(codecs):
|
| 180 |
-
c = str(codecs or '').lower()
|
| 181 |
-
if 'avc1' in c or 'h264' in c:
|
| 182 |
-
return 'h264'
|
| 183 |
-
if 'hvc1' in c or 'hev1' in c or 'h265' in c:
|
| 184 |
-
return 'h265'
|
| 185 |
-
return 'h264' if not c else c.split(',')[0]
|
| 186 |
-
|
| 187 |
-
|
| 188 |
-
def _max_height():
|
| 189 |
-
try:
|
| 190 |
-
return int(str(os.getenv('KICK_MAX_HEIGHT', '1080')).strip() or '1080')
|
| 191 |
-
except (TypeError, ValueError):
|
| 192 |
-
return 1080
|
| 193 |
-
|
| 194 |
-
|
| 195 |
-
def renditions(master_url):
|
| 196 |
-
"""كل جودات البث من الـmaster playlist، الأعلى أولًا، مع ترميزها الحقيقي.
|
| 197 |
-
|
| 198 |
-
نُعيد رابط الجودة نفسها (variant playlist) لا الـmaster: هكذا يثبت FFmpeg على
|
| 199 |
-
دقة واحدة طوال الجلسة بدل أن يقفز بين الجودات (ABR) — وقفزة الدقة وسط جلسة
|
| 200 |
-
RTMP هي أكثر أسباب التجمّد/الوميض عند مشاهد يوتيوب. الـmaster لا يُسلَّم لـFFmpeg
|
| 201 |
-
إطلاقًا: كل رصد يجلب روابط جودات طازجة، فلا حاجة إليه كاحتياطي.
|
| 202 |
-
"""
|
| 203 |
-
r = _get(master_url, hdrs=media_headers(), tries=2)
|
| 204 |
-
text = r.text or ''
|
| 205 |
-
if not text.lstrip().startswith('#EXTM3U'):
|
| 206 |
-
raise RuntimeError('Kick لم يُرجع قائمة تشغيل صالحة')
|
| 207 |
-
lines = [ln.strip() for ln in text.splitlines()]
|
| 208 |
-
names = {}
|
| 209 |
-
out = []
|
| 210 |
-
for i, ln in enumerate(lines):
|
| 211 |
-
if ln.startswith('#EXT-X-MEDIA:'):
|
| 212 |
-
a = _attrs(ln)
|
| 213 |
-
if a.get('GROUP-ID'):
|
| 214 |
-
names[a['GROUP-ID']] = a.get('NAME') or a['GROUP-ID']
|
| 215 |
-
continue
|
| 216 |
-
if not ln.startswith('#EXT-X-STREAM-INF:'):
|
| 217 |
-
continue
|
| 218 |
-
uri = next((lines[j] for j in range(i + 1, min(i + 4, len(lines)))
|
| 219 |
-
if lines[j] and not lines[j].startswith('#')), '')
|
| 220 |
-
if not uri.startswith('http'):
|
| 221 |
-
continue
|
| 222 |
-
a = _attrs(ln)
|
| 223 |
-
res = a.get('RESOLUTION') or ''
|
| 224 |
-
nums = re.findall(r'\d+', res)
|
| 225 |
-
width = int(nums[0]) if nums else 0
|
| 226 |
-
height = int(nums[1]) if len(nums) > 1 else 0
|
| 227 |
-
try:
|
| 228 |
-
bw = float(a.get('BANDWIDTH') or 0) / 1000.0
|
| 229 |
-
except (TypeError, ValueError):
|
| 230 |
-
bw = 0.0
|
| 231 |
-
try:
|
| 232 |
-
fps = float(a.get('FRAME-RATE') or 0)
|
| 233 |
-
except (TypeError, ValueError):
|
| 234 |
-
fps = 0.0
|
| 235 |
-
group = a.get('VIDEO') or ''
|
| 236 |
-
name = names.get(group) or group or (('%dp' % height) if height else 'auto')
|
| 237 |
-
codec = _codec_name(a.get('CODECS'))
|
| 238 |
-
out.append({
|
| 239 |
-
'url': uri,
|
| 240 |
-
'media': 'hls',
|
| 241 |
-
'platform': 'kick',
|
| 242 |
-
'codec': codec,
|
| 243 |
-
'quality_name': name,
|
| 244 |
-
'resolution': res,
|
| 245 |
-
'width': width,
|
| 246 |
-
'height': height,
|
| 247 |
-
'fps': fps,
|
| 248 |
-
'bitrate': round(bw, 1),
|
| 249 |
-
'source_ladder': group in ('chunked', 'source'),
|
| 250 |
-
})
|
| 251 |
-
cap = _max_height()
|
| 252 |
-
capped = [c for c in out if not c['height'] or c['height'] <= cap]
|
| 253 |
-
if capped:
|
| 254 |
-
out = capped
|
| 255 |
-
|
| 256 |
-
# بت لكل بكسل: مقياس الخبراء لجودة الترميز الفعلية. المرجع الشائع لـH.264
|
| 257 |
-
# هو 0.10 جيد جدًا و0.05 الحد الأدنى المقبول (Apple HLS / Jan Ozer).
|
| 258 |
-
for c in out:
|
| 259 |
-
px_rate = c['width'] * c['height'] * (c['fps'] or 30)
|
| 260 |
-
c['bpp'] = round(c['bitrate'] * 1000.0 / px_rate, 4) if px_rate and c['bitrate'] else 0.0
|
| 261 |
-
c['bpp_grade'] = (
|
| 262 |
-
'' if not c['bpp'] else
|
| 263 |
-
'excellent' if c['bpp'] >= 0.10 else
|
| 264 |
-
'good' if c['bpp'] >= 0.07 else
|
| 265 |
-
'fair' if c['bpp'] >= 0.05 else 'poor')
|
| 266 |
-
|
| 267 |
-
def _starved(c):
|
| 268 |
-
"""طبقة «مجوّعة»: دقتها أعلى لكن بتريتها أقل من طبقة أدنى منها.
|
| 269 |
-
|
| 270 |
-
بثّ 1080p بـ900 كيلوبت يبدو أسوأ من 720p بـ2400 لأن البتّات تتوزّع على
|
| 271 |
-
ضعف البكسلات. القاعدة نسبية داخل السلّم نفسه فلا تحتاج أي عتبة مُعايَرة،
|
| 272 |
-
ولا تتفعّل إطلاقًا على سلّم سليم (الذي يرتفع بتريته مع الدقة).
|
| 273 |
-
"""
|
| 274 |
-
px, br = c['width'] * c['height'], c['bitrate']
|
| 275 |
-
if not px or not br:
|
| 276 |
-
return False
|
| 277 |
-
return any(o['width'] * o['height'] and o['width'] * o['height'] < px
|
| 278 |
-
and o['bitrate'] >= br * 1.10 for o in out)
|
| 279 |
-
|
| 280 |
-
for c in out:
|
| 281 |
-
c['starved'] = _starved(c)
|
| 282 |
-
|
| 283 |
-
def rank(c):
|
| 284 |
-
# (1) ليست مجوّعة، (2) مسار المصدر chunked، (3) البكسلات، (4) الإطارات.
|
| 285 |
-
# المجوّعة تهبط لآخر السلّم ولا تُحذف؛ تبقى احتياطيًا إن فشل ما فوقها.
|
| 286 |
-
return (0 if c['starved'] else 1, 1 if c['source_ladder'] else 0,
|
| 287 |
-
c['width'] * c['height'], c['fps'])
|
| 288 |
-
|
| 289 |
-
out.sort(key=rank, reverse=True)
|
| 290 |
-
for c in out:
|
| 291 |
-
bits = [c['quality_name']]
|
| 292 |
-
if c['fps']:
|
| 293 |
-
bits.append('%gfps' % c['fps'])
|
| 294 |
-
bits.append('H264' if c['codec'] == 'h264' else c['codec'].upper())
|
| 295 |
-
c['brief'] = 'kick ' + ' '.join(bits)
|
| 296 |
-
c['label'] = '%s · %s · %s · HLS' % (c['quality_name'], c['resolution'] or 'auto',
|
| 297 |
-
c['codec'] or 'غير محدد')
|
| 298 |
-
return out
|
| 299 |
-
|
| 300 |
-
|
| 301 |
-
# --------------------------------------------------------------------------- #
|
| 302 |
-
# الرصد — نفس عقد تيك توك
|
| 303 |
-
# --------------------------------------------------------------------------- #
|
| 304 |
-
def _offline(room='', nickname='', live_title=''):
|
| 305 |
-
return {'status': 'offline', 'room_id': str(room or ''), 'sources': [],
|
| 306 |
-
'nickname': nickname or '', 'live_title': live_title or '', 'platform': 'kick'}
|
| 307 |
-
|
| 308 |
-
|
| 309 |
-
def _nickname(payload, slug):
|
| 310 |
-
user = payload.get('user') if isinstance(payload.get('user'), dict) else {}
|
| 311 |
-
for key in ('username', 'displayname', 'display_name'):
|
| 312 |
-
val = str(user.get(key) or '').strip()
|
| 313 |
-
if val:
|
| 314 |
-
return val
|
| 315 |
-
val = str(payload.get('slug') or '').strip()
|
| 316 |
-
return val or slug
|
| 317 |
-
|
| 318 |
-
|
| 319 |
-
def observe(user):
|
| 320 |
-
"""رصد قناة Kick. يرمي RuntimeError عند عطل مؤقت (كما يفعل مسار تيك توك)."""
|
| 321 |
-
slug = channel(user)
|
| 322 |
-
if not slug:
|
| 323 |
-
raise RuntimeError('اسم قناة Kick مفقود')
|
| 324 |
-
payload = _channel_payload(slug)
|
| 325 |
-
if not isinstance(payload, dict):
|
| 326 |
-
raise RuntimeError('رد Kick غير متوقع')
|
| 327 |
-
nickname = _nickname(payload, slug)
|
| 328 |
-
stream = payload.get('livestream')
|
| 329 |
-
stream = stream if isinstance(stream, dict) else {}
|
| 330 |
-
live_title = str(stream.get('session_title') or '').strip()
|
| 331 |
-
room = str(stream.get('id') or '')
|
| 332 |
-
is_live = bool(stream) and bool(stream.get('is_live', True))
|
| 333 |
-
if not is_live:
|
| 334 |
-
return _offline('', nickname, live_title)
|
| 335 |
-
playback = str(payload.get('playback_url') or '').strip()
|
| 336 |
-
if not playback.startswith('http'):
|
| 337 |
-
raise RuntimeError('Kick مباشر لكن رابط التشغيل غير متاح بعد')
|
| 338 |
-
sources = renditions(playback)
|
| 339 |
-
if not sources:
|
| 340 |
-
raise RuntimeError('Kick مباشر لكن لا جودات قابلة للنقل في قائمة التشغيل')
|
| 341 |
-
obs = {'status': 'live', 'room_id': room or str(abs(hash(playback)) % (10 ** 12)),
|
| 342 |
-
'sources': sources, 'nickname': nickname, 'live_title': live_title,
|
| 343 |
-
'platform': 'kick'}
|
| 344 |
-
with _lock:
|
| 345 |
-
_last_good[slug] = (time.monotonic(), obs)
|
| 346 |
-
return obs
|
| 347 |
-
|
| 348 |
-
|
| 349 |
-
def last_good(user, max_age=90):
|
| 350 |
-
"""آخر رصد ناجح، لامتصاص عثرة API واحدة دون قطع بث جارٍ."""
|
| 351 |
-
with _lock:
|
| 352 |
-
hit = _last_good.get(channel(user))
|
| 353 |
-
if not hit:
|
| 354 |
-
return None
|
| 355 |
-
when, obs = hit
|
| 356 |
-
return obs if (time.monotonic() - when) <= max_age else None
|
| 357 |
-
|
| 358 |
-
|
| 359 |
-
if __name__ == '__main__':
|
| 360 |
-
import sys
|
| 361 |
-
for target in (sys.argv[1:] or ['absi']):
|
| 362 |
-
try:
|
| 363 |
-
o = observe(target)
|
| 364 |
-
print('%s → %s | room=%s | %s | %s' % (target, o['status'], o['room_id'],
|
| 365 |
-
o['nickname'], o['live_title'][:40]))
|
| 366 |
-
for c in o['sources']:
|
| 367 |
-
print(' %-26s %-10s %-6s %s kbps %s' % (
|
| 368 |
-
c['brief'], c['resolution'] or '-', c['codec'], c['bitrate'],
|
| 369 |
-
'chunked' if c['source_ladder'] else ''))
|
| 370 |
-
except Exception as exc:
|
| 371 |
-
print('%s → %s: %s' % (target, type(exc).__name__, exc))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
relay.py
CHANGED
|
@@ -1,8 +1,36 @@
|
|
| 1 |
"""One FFmpeg push per live session. Multiple senders run concurrently, one per YouTube event."""
|
| 2 |
import fcntl, os, queue, re, select, threading, time, subprocess
|
| 3 |
from collections import deque
|
|
|
|
| 4 |
from curl_cffi import requests
|
| 5 |
-
from flv_bridge import FLVBridge
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 6 |
|
| 7 |
# أخطاء FFmpeg ← وصف عربي. قائمة واحدة على مستوى الوحدة حتى تُختبر على سطور FFmpeg حقيقية
|
| 8 |
# بدل أن تُدفن في إغلاق داخل send(): الإغلاق هو ما أخفى أن كلمة المفتاح كُتبت بالخطأ.
|
|
@@ -53,15 +81,37 @@ def _error_interesting(text):
|
|
| 53 |
def classify_ffmpeg_error(text):
|
| 54 |
"""أول وصف ينطبق على سطر من stderr، أو None. تصنيف نصي خالص بلا أي روابط."""
|
| 55 |
low = (text or '').lower()
|
|
|
|
|
|
|
| 56 |
for needle, label in FFMPEG_ERROR_LABELS:
|
| 57 |
if needle.lower() in low:
|
| 58 |
return label
|
| 59 |
return None
|
| 60 |
|
| 61 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 62 |
def redact_stderr(text):
|
| 63 |
"""يُبقي سبب الخطأ ويخفي كل ما لا يجوز قراءته في سجل عام: الروابط والمفاتيح والرموز."""
|
| 64 |
t = re.sub(r'\b(?:rtmps?|rtsp|srt|https?)://\S+', '«رابط-مخفي»', text or '')
|
|
|
|
|
|
|
|
|
|
| 65 |
t = re.sub(r'(?i)([?&=]|^|\s)((?:key|token|auth|sessionid|sign)\s*=\s*)[^\s&]+', r'\1\2«مخفي»', t)
|
| 66 |
return t.strip()[:240]
|
| 67 |
|
|
@@ -92,10 +142,22 @@ class Sender:
|
|
| 92 |
self.last_exit_code=None # آخر رمز خروج FFmpeg (من آخر جلسة)، يقرؤه المشرف
|
| 93 |
self.last_errors=[] # آخر سطور stderr مصنّفة ومُخفًى منها المفتاح: لماذا أقفلت الوجهة؟
|
| 94 |
self.on_stable=None # مستقبِل المدير: أول ≥25 ث مُسلَّمة = العقاب انتهى
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 95 |
self.last_diagnostics=[] # آخر الأوصاف العربية المصنَّفة، تُعرض في اللوحة كما في السجل
|
| 96 |
self.last_source_gap=0.0 # صمت المصدر لحظة التفكيك: يفصل جوع المصدر عن رفض الوجهة
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 97 |
# Timestamps of source resolution changes seen by this sender (anti-flap window).
|
| 98 |
self.flap=deque()
|
|
|
|
| 99 |
# Once the source proved to flap, stay on a constant canvas for the rest of the
|
| 100 |
# event. Without this the flap window expires after 10 quiet minutes and the
|
| 101 |
# sender silently drops back to copy mode, restarting the whole failure loop.
|
|
@@ -124,9 +186,13 @@ class Sender:
|
|
| 124 |
stamp=d.get('last_source_at')
|
| 125 |
if stamp:d['source_age']=round(max(0.0,time.monotonic()-stamp),1)
|
| 126 |
try:
|
| 127 |
-
|
|
|
|
|
|
|
|
|
|
| 128 |
except Exception:
|
| 129 |
d['send_mode']=''
|
|
|
|
| 130 |
return d
|
| 131 |
def wait_until(self,condition,stop,poll=1.0,timeout=None):
|
| 132 |
"""Block while `condition()` holds; returns as soon as it stops or a stop is requested."""
|
|
@@ -154,22 +220,17 @@ class Sender:
|
|
| 154 |
def send_mode(self):
|
| 155 |
"""Policy for what YouTube receives:
|
| 156 |
|
| 157 |
-
auto -> copy
|
| 158 |
-
|
| 159 |
-
|
| 160 |
-
and ffprobe cannot even decode the h265 payload). Forwarding h265 in
|
| 161 |
-
FLV is exactly the "picture froze, viewers must leave the app and come
|
| 162 |
-
back" symptom, because the player latches onto the first configuration.
|
| 163 |
-
copy -> forward the source untouched (needs a proven H.264 source)
|
| 164 |
fixed1080 -> constant 1080x1920 canvas, re-encodes
|
| 165 |
fixed720 -> constant 720x1280 canvas, re-encodes (lighter on CPU)
|
| 166 |
"""
|
| 167 |
mode=(self.mode_override or os.getenv('YOUTUBE_SEND_MODE','auto')).strip().lower()
|
| 168 |
if mode not in ('auto','copy','fixed1080','fixed720','matchgop'):
|
| 169 |
raise ValueError('وضع الإرسال يجب أن يكون auto أو copy أو fixed1080 أو fixed720 أو matchgop')
|
| 170 |
-
#
|
| 171 |
-
#
|
| 172 |
-
# health still good — no headroom for a third. If this candidate is H264, copy.
|
| 173 |
if self.sticky_mode:
|
| 174 |
# Do NOT drop LIGHT just because the next TikTok label says h264.
|
| 175 |
# That path produced COPY with output_seconds=0 on the same ingest
|
|
@@ -178,53 +239,62 @@ class Sender:
|
|
| 178 |
self._recovering_copy=True
|
| 179 |
return 'copy'
|
| 180 |
return self.sticky_mode
|
| 181 |
-
# Stream copy
|
| 182 |
-
# the caller may hand us the candidate it is about to send (
|
| 183 |
if mode in ('auto','copy') and self.current_candidate is not None:
|
| 184 |
-
# Copy needs
|
| 185 |
fb=self.allow_codec_fallback()
|
| 186 |
if fb:return fb
|
| 187 |
if mode=='auto':
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 188 |
# Proven H.264 and a stable source: forward it untouched.
|
| 189 |
return 'copy' if not self.sticky_mode else self.sticky_mode
|
| 190 |
-
# copy mode only: if the phone keeps flipping resolution, stop flapping the
|
| 191 |
-
# YouTube session and absorb the changes on a constant canvas instead.
|
| 192 |
-
if mode=='copy':
|
| 193 |
-
flap=self.flap
|
| 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','matchgop').strip().lower()
|
| 198 |
-
if mode not in ('fixed1080','fixed720','matchgop'):mode='matchgop'
|
| 199 |
-
self.sticky_mode=mode
|
| 200 |
-
self.sticky_since=time.monotonic()
|
| 201 |
-
self._recovering_copy=False
|
| 202 |
return mode
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 203 |
def _may_attempt_copy_recovery(self):
|
| 204 |
-
"""LIGHT→COPY
|
| 205 |
|
| 206 |
-
|
| 207 |
-
|
|
|
|
|
|
|
|
|
|
| 208 |
"""
|
| 209 |
-
|
| 210 |
-
# YouTube event. The mobile app then flashes/freezes until the viewer force-closes
|
| 211 |
-
# it — measured on Prayer-Time-Bot / On. Opt in with YOUTUBE_COPY_RECOVERY=1.
|
| 212 |
-
if str(os.getenv('YOUTUBE_COPY_RECOVERY','0')).strip().lower() in ('0','false','off','no',''):
|
| 213 |
return False
|
| 214 |
-
if
|
|
|
|
|
|
|
| 215 |
return False
|
| 216 |
-
|
| 217 |
-
if not self.sticky_since or (time.monotonic()-self.sticky_since)<need:
|
| 218 |
return False
|
| 219 |
-
|
|
|
|
|
|
|
| 220 |
return False
|
| 221 |
-
|
|
|
|
|
|
|
| 222 |
return False
|
| 223 |
-
|
| 224 |
-
blob=(str(cand.get('codec') or '')+' '+str(cand.get('label') or '')+' '+str(cand.get('brief') or '')).lower()
|
| 225 |
-
if any(k in blob for k in ('hevc','h265','hvc1')):
|
| 226 |
return False
|
| 227 |
-
return
|
| 228 |
def request_sticky(self, mode, user, reason):
|
| 229 |
"""Per-broadcaster: stick LIGHT/matchgop and end this FFmpeg only — not the Space."""
|
| 230 |
mode=(mode or 'matchgop').strip().lower()
|
|
@@ -232,17 +302,19 @@ class Sender:
|
|
| 232 |
if self.sticky_mode==mode and self.session:
|
| 233 |
return False
|
| 234 |
if not self.sticky_mode:
|
| 235 |
-
|
| 236 |
-
|
| 237 |
-
|
| 238 |
-
|
| 239 |
-
return False
|
| 240 |
-
except Exception:
|
| 241 |
-
pass
|
| 242 |
self.sticky_mode=mode
|
| 243 |
self.sticky_since=time.monotonic()
|
| 244 |
self._recovering_copy=False
|
| 245 |
self._no_copy_recovery=True
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 246 |
self.log(user, '[HEALTH] %s — sticky %s (this publisher only)'%(reason[:160], mode))
|
| 247 |
sess=self.session
|
| 248 |
if isinstance(sess, dict):
|
|
@@ -252,33 +324,102 @@ class Sender:
|
|
| 252 |
try: p.stdin.close()
|
| 253 |
except (OSError, ValueError): pass
|
| 254 |
return True
|
| 255 |
-
def
|
| 256 |
-
|
| 257 |
-
|
| 258 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 259 |
@staticmethod
|
| 260 |
def copy_is_safe(declared,probed):
|
| 261 |
-
"""
|
| 262 |
|
| 263 |
-
|
| 264 |
-
|
| 265 |
-
|
| 266 |
-
decoded — and an empty answer from an h265 FLV is normal, not a clean bill of health
|
| 267 |
-
(measured here: origin/hd5 → probe returns no video stream at all, hd → h264 720x1280).
|
| 268 |
-
A needless re-encode costs CPU; a wrong copy costs every viewer their picture until they
|
| 269 |
-
leave the YouTube app and come back.
|
| 270 |
"""
|
| 271 |
def norm(x):
|
| 272 |
x=str(x or '').strip().lower()
|
| 273 |
-
|
|
|
|
|
|
|
| 274 |
d,q=norm(declared),norm(probed)
|
| 275 |
-
if q
|
| 276 |
-
if q=='other':return False
|
| 277 |
-
|
| 278 |
-
return False # h265 / unknown / unreadable → re-encode
|
| 279 |
def allow_codec_fallback(self):
|
| 280 |
"""Decide from evidence once, then stick to it for the whole event."""
|
| 281 |
-
if str(os.getenv('YOUTUBE_AUTO_TRANSCODE','
|
| 282 |
cand=self.current_candidate
|
| 283 |
if cand is None:return None
|
| 284 |
found=self.live_probe(cand)
|
|
@@ -324,7 +465,7 @@ class Sender:
|
|
| 324 |
an already-open live event is exactly the flash that only a YouTube-app restart
|
| 325 |
clears for existing viewers.
|
| 326 |
"""
|
| 327 |
-
if int(getattr(self, '_gop_w', 0) or 0) >=
|
| 328 |
return (self._gop_w, self._gop_h)
|
| 329 |
if candidate and not (w and h):
|
| 330 |
try:
|
|
@@ -337,7 +478,7 @@ class Sender:
|
|
| 337 |
except (TypeError, ValueError):
|
| 338 |
w = h = 0
|
| 339 |
w, h = w - w % 2, h - h % 2
|
| 340 |
-
if w >=
|
| 341 |
w, h = self.youtube_safe_size(w, h)
|
| 342 |
self._gop_w, self._gop_h = w, h
|
| 343 |
return (int(getattr(self, '_gop_w', 0) or 0), int(getattr(self, '_gop_h', 0) or 0))
|
|
@@ -354,8 +495,8 @@ class Sender:
|
|
| 354 |
w, h = int(w or 0), int(h or 0)
|
| 355 |
except (TypeError, ValueError):
|
| 356 |
return 0, 0
|
| 357 |
-
if w <
|
| 358 |
-
return
|
| 359 |
short, long_ = min(w, h), max(w, h)
|
| 360 |
portrait = h >= w
|
| 361 |
if short <= 720 and long_ >= 1280:
|
|
@@ -390,37 +531,23 @@ class Sender:
|
|
| 390 |
# non-network input ("Option reconnect not found"), so it is applied only where it
|
| 391 |
# is both legal and wanted.
|
| 392 |
net=['-reconnect','1','-reconnect_streamed','1','-reconnect_delay_max','5'] if url.startswith(('http://','https://')) else []
|
| 393 |
-
# Kick (Amazon IVS) فقط — معلّق على platform=='kick' حصرًا فلا يمسّ تيك توك.
|
| 394 |
-
# خيار واحد فقط، وهو الوحيد الذي يغيّر سلوكًا فعليًا: seg_max_retry.
|
| 395 |
-
# افتراضي FFmpeg صفر، أي أن أول مقطع يفشل تنزيله (502/انقطاع CDN لحظي)
|
| 396 |
-
# يُنهي الإدخال فورًا ⇒ تموت الجلسة ويرى مشاهد يوتيوب تجمّدًا ثم انقطاعًا.
|
| 397 |
-
# بإعادتين تُبتلع العثرة اللحظية بصمت. ما عداه مُقاس على ffmpeg 7.1.5 وتبيّن
|
| 398 |
-
# أنه إمّا مطابق للافتراضي (http_persistent=true للمفكِّك) أو أسوأ منه
|
| 399 |
-
# (m3u8_hold_counters الافتراضي 1000 لا 10)، فحُذف بدل أن يُضعف الصلابة.
|
| 400 |
-
extra=[]
|
| 401 |
-
if (candidate or {}).get('platform')=='kick':
|
| 402 |
-
extra=['-seg_max_retry',os.getenv('KICK_SEG_RETRY','2')]
|
| 403 |
return {'stdin':None,'input':[
|
| 404 |
-
*net,*
|
| 405 |
*(('-headers',self.headers_blob(candidate)) if candidate.get('user') else ()),
|
| 406 |
'-i',url]}
|
| 407 |
return {'stdin':subprocess.PIPE,'input':['-rw_timeout','20000000',
|
| 408 |
'-fflags','+genpts','-i','pipe:0']}
|
| 409 |
def headers_blob(self,candidate):
|
| 410 |
-
"""FFmpeg
|
| 411 |
-
|
|
|
|
| 412 |
return ''.join('%s: %s\r\n'%(k,v) for k,v in items.items() if v)
|
| 413 |
@staticmethod
|
| 414 |
def codec_unusable(candidate):
|
| 415 |
-
"""True when the declared
|
| 416 |
-
|
| 417 |
-
The copy path never re-encodes video, so anything other than H.264 (HEVC-only
|
| 418 |
-
renditions, or a source whose codec we cannot read) is pushed to YouTube still
|
| 419 |
-
wrapped in FLV and rejected there. Better to transcode than to fail forever.
|
| 420 |
-
"""
|
| 421 |
codec=str((candidate or {}).get('codec') or '').strip().lower()
|
| 422 |
if not codec:return False
|
| 423 |
-
return not any(c in codec for c in ('h264','avc','264'))
|
| 424 |
@staticmethod
|
| 425 |
def hevc_payload(candidate):
|
| 426 |
"""هل ما سيدفعه FFmpeg فعلًا HEVC؟ الإعلان عن Enhanced-RTMP يُقاس على هذا لا على الوضع."""
|
|
@@ -431,10 +558,10 @@ class Sender:
|
|
| 431 |
def enhanced_advertisement(self, mode, candidate):
|
| 432 |
"""قائمة خيارات FFmpeg لإعلان fourCcLive (Enhanced RTMP) — فارغة على تدفق H.264.
|
| 433 |
|
| 434 |
-
|
| 435 |
-
|
| 436 |
-
|
| 437 |
-
|
| 438 |
"""
|
| 439 |
switch = os.getenv('YOUTUBE_ENHANCED_RTMP', 'auto').strip().lower()
|
| 440 |
if switch in ('0', 'off', 'no', 'legacy'):
|
|
@@ -448,21 +575,32 @@ class Sender:
|
|
| 448 |
def command(self,destination,candidate=None):
|
| 449 |
# إعلان Enhanced-RTMP يُقاس على الترميز المدفوع فعلًا؛ ملفات الاختبار المحلية لا بروتوكول لها.
|
| 450 |
mode=self.send_mode()
|
|
|
|
| 451 |
network=destination.startswith(('rtmp://','rtmps://'))
|
| 452 |
enhanced=self.enhanced_advertisement(mode,candidate) if network else []
|
| 453 |
if mode=='copy':
|
| 454 |
video=['-c:v','copy']
|
| 455 |
else:
|
| 456 |
if mode=='matchgop':
|
| 457 |
-
|
| 458 |
-
|
| 459 |
-
|
| 460 |
-
|
| 461 |
-
|
| 462 |
-
|
| 463 |
-
|
| 464 |
-
|
| 465 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 466 |
bitrate=os.getenv('VIDEO_BITRATE','').strip() or '4500k'
|
| 467 |
else:
|
| 468 |
width,height,bitrate=(1080,1920,'6000k') if mode=='fixed1080' else (720,1280,'4000k')
|
|
@@ -470,16 +608,20 @@ class Sender:
|
|
| 470 |
bitrate=os.getenv('VIDEO_BITRATE','').strip() or bitrate
|
| 471 |
bufsize=str(int(int(str(bitrate).rstrip('kK'))*1.5))+'k'
|
| 472 |
video=['-vf',vf,'-c:v','libx264','-preset',os.getenv('YOUTUBE_X264_PRESET','veryfast'),
|
| 473 |
-
'-tune','zerolatency','-profile:v','high',
|
| 474 |
-
#
|
| 475 |
-
#
|
| 476 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 477 |
# IDR at least every 2 s: a viewer who stalls (or joins) re-syncs on the next
|
| 478 |
# keyframe instead of waiting for the source's own GOP, which is what made
|
| 479 |
# people leave the YouTube app and come back to get a picture again.
|
| 480 |
'-force_key_frames','expr:gte(t,n_forced*2)',
|
| 481 |
'-g',os.getenv('YOUTUBE_GOP','60'),'-keyint_min','30','-sc_threshold','0','-bf','0',
|
| 482 |
-
'-x264-params','open-gop=0:scenecut=0:keyint=%s:min-keyint=30'%os.getenv('YOUTUBE_GOP','60'),
|
| 483 |
'-pix_fmt','yuv420p','-fps_mode','cfr',
|
| 484 |
'-colorspace','bt709','-color_primaries','bt709','-color_trc','bt709']
|
| 485 |
# Network output goes through the fifo pseudo-muxer instead of straight to flv.
|
|
@@ -528,7 +670,7 @@ class Sender:
|
|
| 528 |
else:
|
| 529 |
output=['-flvflags','no_duration_filesize','-f','flv']
|
| 530 |
ta=self.input_args(candidate)
|
| 531 |
-
return [self.ffmpeg,'-hide_banner','-loglevel',os.getenv('YOUTUBE_FFMPEG_LOGLEVEL','error'),
|
| 532 |
'-nostats','-progress','pipe:1',
|
| 533 |
*ta['input'],'-map','0:v:0','-map','0:a:0?',
|
| 534 |
# TikTok streams HE-AAC (SBR) at 64 kbit/s — measured on the live source. Copied
|
|
@@ -620,18 +762,21 @@ class Sender:
|
|
| 620 |
except BaseException as e: # تُعاد رفعها في خيط الضخّ لتُصنَّف هناك
|
| 621 |
out.put(e)
|
| 622 |
|
| 623 |
-
def _pump_source(self, response, p, bridge, stop, sess, read_timeout, retries):
|
| 624 |
"""نقل بايتات تيك توك إلى FFmpeg في خيط مستقل، مع تسجيل زمن آخر وصول فعلي.
|
| 625 |
|
| 626 |
القراءة هنا هي مصدر الحقيقة: `poll()` الخاص بـ FFmpeg يبقى ناجحًا وهو جالس ينتظر
|
| 627 |
stdin، ويوتيوب يبقى مستقبِلًا على آخر ما وصل — لذا يُقاس تدفق البيانات لا حالة العملية.
|
| 628 |
"""
|
|
|
|
|
|
|
| 629 |
it = response.iter_content(None).__iter__()
|
| 630 |
deadline = time.monotonic() + sess['max_seconds']
|
| 631 |
chunk_wait = min(read_timeout, max(1.0, self._stall_seconds() / 3.0)) if self._stall_seconds() else read_timeout
|
| 632 |
pending = None
|
| 633 |
reader = None
|
| 634 |
-
while not stop.is_set() and not sess['force_stop'] and not sess.get('swap_source')
|
|
|
|
| 635 |
if time.monotonic() > deadline:
|
| 636 |
sess['error'] = 'انتهت مهلة الجلسة القصوى (%ds)' % int(sess['max_seconds'])
|
| 637 |
return
|
|
@@ -647,12 +792,17 @@ class Sender:
|
|
| 647 |
try:
|
| 648 |
got = pending.get(timeout=chunk_wait)
|
| 649 |
except queue.Empty:
|
|
|
|
|
|
|
| 650 |
silent = time.monotonic() - sess['last']
|
| 651 |
if self._stall_seconds() and silent > self._stall_seconds():
|
| 652 |
sess['error'] = 'صمت من تيك توك (%.0f ث بلا بايت)' % silent
|
| 653 |
return
|
| 654 |
continue
|
| 655 |
pending = None
|
|
|
|
|
|
|
|
|
|
| 656 |
if isinstance(got, BaseException):
|
| 657 |
e = got
|
| 658 |
if self._is_timeout(e) and not sess['force_stop']:
|
|
@@ -681,24 +831,29 @@ class Sender:
|
|
| 681 |
buf = bridge.feed(chunk)
|
| 682 |
if not buf:
|
| 683 |
continue
|
| 684 |
-
|
| 685 |
-
|
| 686 |
-
|
| 687 |
-
|
| 688 |
-
|
| 689 |
-
|
| 690 |
-
|
| 691 |
-
|
| 692 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 693 |
except SourceStalled as e:
|
| 694 |
-
#
|
|
|
|
|
|
|
|
|
|
| 695 |
sess['error'] = str(e)
|
| 696 |
return
|
| 697 |
except (BrokenPipeError, OSError, ValueError):
|
| 698 |
return # FFmpeg هو من مات؛ الحلقة الرئيسية تتصرف
|
| 699 |
-
except FormatChanged:
|
| 700 |
-
sess['format_changed'] = True
|
| 701 |
-
return
|
| 702 |
|
| 703 |
def _try_reattach(self, user, p, bridge, sess, stop, refresh, read_timeout, retries, response, pump):
|
| 704 |
"""Close only the TikTok HTTP; keep FFmpeg stdin so YouTube does not see a new ingest.
|
|
@@ -706,13 +861,17 @@ class Sender:
|
|
| 706 |
Returns (new_response, new_pump) or None. Viewer cuts come from killing FFmpeg, not from
|
| 707 |
a 1–2 s TikTok URL refresh into the same process.
|
| 708 |
"""
|
| 709 |
-
if not refresh or p is None or p.stdin is None or p.poll() is not None
|
|
|
|
| 710 |
return None
|
| 711 |
if int(sess.get('reattaches') or 0) >= 24:
|
| 712 |
return None
|
| 713 |
sess['swapping'] = True
|
| 714 |
sess['swap_source'] = True
|
| 715 |
sess['swap_started'] = time.monotonic()
|
|
|
|
|
|
|
|
|
|
| 716 |
try:
|
| 717 |
if response:
|
| 718 |
try:
|
|
@@ -721,35 +880,59 @@ class Sender:
|
|
| 721 |
pass
|
| 722 |
if pump is not None:
|
| 723 |
pump.join(timeout=float(os.getenv('YOUTUBE_PUMP_JOIN_SECONDS', '2')))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 724 |
try:
|
| 725 |
cand = refresh()
|
| 726 |
except Exception as e:
|
| 727 |
self.log(user, '[RELAY] تعذر رصد مصدر بديل دون قطع يوتيوب (%s)' % type(e).__name__)
|
| 728 |
return None
|
| 729 |
-
if not cand or cand.get('media') == 'hls' or not cand.get('url')
|
|
|
|
| 730 |
return None
|
| 731 |
try:
|
| 732 |
new_resp = requests.get(cand['url'],
|
| 733 |
-
headers=
|
| 734 |
impersonate='chrome', stream=True,
|
| 735 |
timeout=(5, min(8, read_timeout or 8)))
|
| 736 |
new_resp.raise_for_status()
|
| 737 |
except Exception as e:
|
|
|
|
|
|
|
|
|
|
| 738 |
self.log(user, '[RELAY] فشل فتح مصدر تيك توك البديل (%s)' % type(e).__name__)
|
| 739 |
return None
|
|
|
|
|
|
|
|
|
|
| 740 |
bridge.reconnect()
|
| 741 |
sess['ended'] = False
|
| 742 |
sess['error'] = ''
|
| 743 |
sess['stall_reason'] = ''
|
| 744 |
-
sess['force_stop'] = False
|
| 745 |
sess['timeouts'] = 0
|
| 746 |
# Do not bump sess['last'] here: that hid 40–57s of silence from the
|
| 747 |
# 12s stall watchdog (measured @vimtoo.2: out frozen, age 42–57, yh still good).
|
| 748 |
sess['reattaches'] = int(sess.get('reattaches') or 0) + 1
|
| 749 |
self.current_candidate = cand
|
| 750 |
self.set(source=cand.get('label') or cand.get('brief') or '', stalled=False)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 751 |
new_pump = threading.Thread(target=self._pump_source,
|
| 752 |
-
args=(new_resp, p, bridge, stop, sess, read_timeout, retries),
|
| 753 |
daemon=True)
|
| 754 |
new_pump.start()
|
| 755 |
self.log(user, '[RELAY] أُعيد توصيل تيك توك على نفس جلسة يوتيوب — بلا قتل FFmpeg')
|
|
@@ -758,6 +941,19 @@ class Sender:
|
|
| 758 |
sess['swap_source'] = False
|
| 759 |
sess['swapping'] = False
|
| 760 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 761 |
def _teardown(self, user, p, response, sess, stop, reason):
|
| 762 |
"""إنهاء مرتب — FFmpeg أولًا ثم الأنبوب ثم المصدر، مع wait محدود ثم kill.
|
| 763 |
|
|
@@ -824,7 +1020,7 @@ class Sender:
|
|
| 824 |
self.last_source_gap = round(max(0.0, time.monotonic() - sess['last']), 1) \
|
| 825 |
if (sess.get('src_metered') and sess.get('last')) else 0.0
|
| 826 |
self.set(status='', stalled=bool(sess.get('stall_reason') or sess.get('error')), note=reason,
|
| 827 |
-
source_gap=self.last_source_gap,
|
| 828 |
ffmpeg_errors=list(self.last_errors),
|
| 829 |
ffmpeg_diagnostics=list(self.last_diagnostics)[-3:])
|
| 830 |
codes = [c for c in codes if c]
|
|
@@ -839,62 +1035,94 @@ class Sender:
|
|
| 839 |
الإشراف في `sender_loop` التي تُعيد رصد LIVE وتبني جلسة جديدة من الصفر.
|
| 840 |
"""
|
| 841 |
self.current_candidate = candidate
|
|
|
|
|
|
|
|
|
|
| 842 |
self.lock_gold(candidate)
|
| 843 |
-
if self.hevc_payload(candidate) and self.sticky_mode not in ('matchgop','fixed720','fixed1080'):
|
| 844 |
-
ok=True
|
| 845 |
-
try:
|
| 846 |
-
from ingest import hub
|
| 847 |
-
ok=hub.light_available()
|
| 848 |
-
except Exception:
|
| 849 |
-
ok=True
|
| 850 |
-
if not ok:
|
| 851 |
-
raise RelayStartError('HEVC يحتاج ترميز وخيارات CPU ممتلئة')
|
| 852 |
-
self.sticky_mode='matchgop'
|
| 853 |
-
self.sticky_since=time.monotonic()
|
| 854 |
-
self._recovering_copy=False
|
| 855 |
-
guard = os.getenv('YOUTUBE_FORMAT_GUARD', 'on').lower() in ('1', 'on', 'true', 'yes')
|
| 856 |
hls = (candidate or {}).get('media') == 'hls'
|
| 857 |
-
|
|
|
|
|
|
|
| 858 |
response = None
|
| 859 |
p = None
|
| 860 |
error_reader = None
|
| 861 |
done = threading.Event()
|
| 862 |
-
progress = {'last': time.monotonic(), 'seconds': -1}
|
| 863 |
pump = None
|
| 864 |
diagnostics = []
|
| 865 |
raw_tail = [] # آخر سطور stderr بعد الإخفاء: تُطبع عند الخروج، لا تُخزَّن خامًا
|
| 866 |
read_timeout, retries, max_seconds = self._stream_tuning()
|
| 867 |
-
sess = {'last': time.monotonic(), 'ended': False, 'error': '',
|
| 868 |
'src_metered': False,
|
| 869 |
'force_stop': False, 'timeouts': 0, 'orphan': False, 'stable_notified': False, 'max_seconds': max_seconds,
|
| 870 |
'stall_reason': '', 'spawned': False, 'spawn_error': '',
|
| 871 |
-
'
|
|
|
|
|
|
|
| 872 |
self.set(status='الاتصال بيوتيوب', source=candidate['label'], output_seconds=0,
|
| 873 |
-
last_output_at=None, stalled=False, last_source_at=sess['last'], source_bytes=0
|
|
|
|
| 874 |
with self.lock:
|
| 875 |
self.session = sess
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 876 |
try:
|
| 877 |
sess['src_metered'] = not hls # HLS: FFmpeg يقرأ القائمة، فلا عدّاد مصدر لنا
|
| 878 |
args = self.command(destination, candidate)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 879 |
if hls: # noqa: E999 — HLS: بلا أنبوب stdin
|
| 880 |
# FFmpeg يفتح القائمة بنفسه: لا HTTP عندنا ولا ضخّ على stdin ⇒ الحارس هنا
|
| 881 |
# هو تقدّم FFmpeg نفسه (out_time)، لأن لا مصدر بايتات ثانٍ نقيسه.
|
| 882 |
p = subprocess.Popen(args, stdin=None, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
|
| 883 |
else:
|
| 884 |
-
|
| 885 |
-
|
| 886 |
-
|
| 887 |
-
|
| 888 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 889 |
p = subprocess.Popen(args, stdin=subprocess.PIPE, stdout=subprocess.PIPE,
|
| 890 |
stderr=subprocess.PIPE, bufsize=0)
|
| 891 |
sess['spawned'] = True
|
| 892 |
sess['spawned_at'] = time.monotonic()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 893 |
with self.lock:
|
| 894 |
self.process = p
|
| 895 |
-
self.log(user, '[RELAY] بدء FFmpeg ← %s (%s)' % (candidate['label'],
|
| 896 |
'إعلان Enhanced-RTMP: hvc1' if '-rtmp_enhanced_codecs' in ' '.join(args)
|
| 897 |
-
else 'FLV تقليدي: لا إعلان hvc1')) # لا إعادة ترميز في هذا الوضع: انقطاع copy لا يترك عملية ورائها
|
| 898 |
|
| 899 |
def read_errors():
|
| 900 |
# يصنّف أخطاء FFmpeg المختارة؛ لا يُسرّب stderr خامًا ولا روابط البث — الذيل
|
|
@@ -902,6 +1130,16 @@ class Sender:
|
|
| 902 |
try:
|
| 903 |
for line in iter(p.stderr.readline, b''):
|
| 904 |
text = line.decode('utf-8', 'replace')
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 905 |
label = classify_ffmpeg_error(text)
|
| 906 |
if label and label not in diagnostics:
|
| 907 |
diagnostics.append(label)
|
|
@@ -923,6 +1161,34 @@ class Sender:
|
|
| 923 |
def read_progress():
|
| 924 |
try:
|
| 925 |
for line in iter(p.stdout.readline, b''):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 926 |
if line.startswith(b'out_time_us='):
|
| 927 |
try:
|
| 928 |
seconds = int(line.split(b'=', 1)[1]) / 1000000
|
|
@@ -951,15 +1217,76 @@ class Sender:
|
|
| 951 |
threading.Thread(target=read_progress, daemon=True).start()
|
| 952 |
pump = None
|
| 953 |
if response is not None:
|
|
|
|
| 954 |
pump = threading.Thread(target=self._pump_source,
|
| 955 |
-
args=(response, p, bridge, stop, sess, read_timeout, retries),
|
| 956 |
daemon=True)
|
| 957 |
pump.start()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 958 |
# ---- الحارس: لا تعتمد على poll() ولا على رمز الخروج ----
|
| 959 |
stall_limit = self._stall_seconds()
|
| 960 |
progress_limit = max(30.0, float(os.getenv('YOUTUBE_PROGRESS_STALL_SECONDS', '60')))
|
| 961 |
next_report = 0.0
|
| 962 |
while not stop.is_set():
|
|
|
|
|
|
|
| 963 |
now = time.monotonic()
|
| 964 |
# الدليل على أن المصدر لم يصمت هو بايتات تيك توك نفسها. تقدّم FFmpeg وحده لا
|
| 965 |
# يكفي: في وضع النسخ يفرّغ المخزن الداخلي لدقائق بعد صمت المصدر، فيبدو البث
|
|
@@ -967,6 +1294,20 @@ class Sender:
|
|
| 967 |
# في HLS يستحيل القياس إلا على FFmpeg (هو من يفتح القائمة)، فنقبل تقدّمه.
|
| 968 |
_fresh = (sess['ff_last'] if response is None else sess['last'])
|
| 969 |
swap_for = (now - float(sess.get('swap_started') or 0)) if sess.get('swapping') else 0.0
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 970 |
# swapping must not disable the stall watchdog for longer than the stall
|
| 971 |
# limit: refresh()+HTTP open was measured at 40–57s of frozen viewers.
|
| 972 |
if self._recovering_copy:
|
|
@@ -977,23 +1318,76 @@ class Sender:
|
|
| 977 |
self.log(user,'[RECOVERY] COPY produced no output in %.0fs; staying on %s (fail %d)'%(
|
| 978 |
ran, self.sticky_mode or 'light', self.copy_recovery_fails))
|
| 979 |
raise SourceStalled('COPY recovery produced no output; reverting to light')
|
| 980 |
-
|
|
|
|
|
|
|
| 981 |
self.log(user,'[RECOVERY] COPY output verified (%.1fs); leaving light sticky'%progress['seconds'])
|
| 982 |
self.sticky_mode=None
|
| 983 |
self.sticky_since=0.0
|
| 984 |
self._recovering_copy=False
|
| 985 |
-
|
| 986 |
-
|
| 987 |
-
|
| 988 |
-
|
| 989 |
-
|
| 990 |
-
|
| 991 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 992 |
attached = self._try_reattach(user, p, bridge, sess, stop, refresh,
|
| 993 |
read_timeout, retries, response, pump)
|
| 994 |
if attached:
|
| 995 |
response, pump = attached
|
| 996 |
continue
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 997 |
# نُفيق الخيط أولًا (قد يكون محبوسًا في write على أنبوب ممتلئ)، ثم نرفع:
|
| 998 |
# إغلاق stdin يجعل FFmpeg يرى EOF ويتوقف بلطف بدل SIGKILL.
|
| 999 |
sess['force_stop'] = True
|
|
@@ -1002,12 +1396,14 @@ class Sender:
|
|
| 1002 |
p.stdin.close()
|
| 1003 |
except (OSError, ValueError):
|
| 1004 |
pass
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1005 |
raise SourceStalled('انقطع تدفق المصدر منذ %.0f ث (FFmpeg ما زال حيًا، '
|
| 1006 |
'ويوتيوب يبقى على آخر ثانية وصلته)' % (now - _fresh))
|
| 1007 |
rc = p.poll()
|
| 1008 |
if rc is not None:
|
| 1009 |
-
if sess['format_changed']:
|
| 1010 |
-
raise FormatChanged()
|
| 1011 |
if not sess['ended'] and not stop.is_set() and rc:
|
| 1012 |
gap = max(0.0, time.monotonic() - sess['last']) if sess.get('src_metered') else 0.0
|
| 1013 |
suspect = float(os.getenv('YOUTUBE_SOURCE_GAP_SUSPECT_SECONDS', '8'))
|
|
@@ -1022,10 +1418,10 @@ class Sender:
|
|
| 1022 |
break
|
| 1023 |
if now - progress['last'] > progress_limit:
|
| 1024 |
raise SourceStalled('لم يتقدّم FFmpeg منذ %.0f ث' % (now - progress['last']))
|
| 1025 |
-
if sess['ended'] and not sess['error']:
|
| 1026 |
self.log(user, '[MONITOR] أغلق تيك توك الاستجابة؛ الجلسة تُعاد من جديد')
|
| 1027 |
break
|
| 1028 |
-
if sess['error']:
|
| 1029 |
raise SourceStalled(sess['error'])
|
| 1030 |
if response is not None and now >= next_report:
|
| 1031 |
# بمعدل مضبوط: لا logging لكل بايت (كان سيملأ السجل في دقائق).
|
|
@@ -1033,20 +1429,49 @@ class Sender:
|
|
| 1033 |
self.log(user, '[WATCHDOG] المصدر يعمل؛ آخر بايت قبل %.0f ث، خرج %.1f ث'
|
| 1034 |
% (now - sess['last'], max(0, progress['seconds'])))
|
| 1035 |
if pump is not None and not pump.is_alive() and response is not None and not stop.is_set():
|
| 1036 |
-
if sess['force_stop'] or sess['error'] or sess['ended']:
|
| 1037 |
break
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1038 |
time.sleep(1)
|
| 1039 |
except (OSError, ValueError) as e:
|
| 1040 |
if p is None:
|
| 1041 |
sess['spawn_error'] = 'تعذر بدء FFmpeg/المصدر (%s)' % type(e).__name__
|
| 1042 |
self.log(user, '[RELAY] فشل بدء الإرسال: %s' % sess['spawn_error'])
|
| 1043 |
-
|
| 1044 |
-
|
| 1045 |
-
|
|
|
|
|
|
|
| 1046 |
raise
|
| 1047 |
except SourceStalled as e:
|
| 1048 |
sess['stall_reason'] = str(e)
|
| 1049 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1050 |
raise
|
| 1051 |
finally:
|
| 1052 |
done.set()
|
|
@@ -1060,8 +1485,19 @@ class Sender:
|
|
| 1060 |
with self.lock:
|
| 1061 |
self.session = None
|
| 1062 |
self.set(status='', stalled=False, note='لم يبدأ FFmpeg أصلًا')
|
|
|
|
|
|
|
|
|
|
| 1063 |
raise RelayStartError(sess.get('spawn_error') or 'تعذر بدء جلسة الإرسال')
|
| 1064 |
-
_why =
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1065 |
self._teardown(user, p, response, sess, stop, _why)
|
| 1066 |
if error_reader:
|
| 1067 |
error_reader.join(timeout=1)
|
|
@@ -1069,11 +1505,18 @@ class Sender:
|
|
| 1069 |
# مهلة قصيرة عمدًا: الخيط قد يكون محبوسًا في next() على مقبس مُغلق؛ لا معنى
|
| 1070 |
# لتعليق الإشراف كله لأجله — FFmpeg أُقرِت والطرف القارئ أُغلق.
|
| 1071 |
pump.join(timeout=float(os.getenv('YOUTUBE_PUMP_JOIN_SECONDS', '2')))
|
|
|
|
|
|
|
| 1072 |
if pump.is_alive():
|
| 1073 |
sess['orphan'] = True
|
| 1074 |
self.log(user, '[CLEANUP] ⚠ خيط القراءة ما زال يعمل؛ سيُترك كـ daemon ويُعاد الرصد')
|
| 1075 |
with self.lock:
|
| 1076 |
self.session = None
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1077 |
if sess['orphan']:
|
| 1078 |
raise RuntimeError('بقيت عملية/خيط من جلسة سابقة؛ تُراجع قبل جلسة جديدة')
|
| 1079 |
return progress['seconds'] > 0
|
|
|
|
| 1 |
"""One FFmpeg push per live session. Multiple senders run concurrently, one per YouTube event."""
|
| 2 |
import fcntl, os, queue, re, select, threading, time, subprocess
|
| 3 |
from collections import deque
|
| 4 |
+
from urllib.parse import urlparse
|
| 5 |
from curl_cffi import requests
|
| 6 |
+
from flv_bridge import FLVBridge
|
| 7 |
+
from stream_monitor import log_event, note_rtmp_open
|
| 8 |
+
from telemetry import (
|
| 9 |
+
checkpoint as telemetry_checkpoint,
|
| 10 |
+
finish as telemetry_finish,
|
| 11 |
+
http_status_from_exception,
|
| 12 |
+
observe as telemetry_observe,
|
| 13 |
+
record_event as telemetry_event,
|
| 14 |
+
start_session as telemetry_start,
|
| 15 |
+
)
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def source_http_headers(url, user=None, headers_for=None):
|
| 19 |
+
"""Headers for a signed media URL without leaking TikTok login cookies to a CDN.
|
| 20 |
+
|
| 21 |
+
Browsers do not send a tiktok.com session cookie to tiktokcdn-us.com/byteoversea
|
| 22 |
+
hosts. The relay used to do so manually, which exposed the cookie cross-domain and
|
| 23 |
+
could also change how a CDN edge handles an otherwise-public signed media URL.
|
| 24 |
+
Only a real tiktok.com host may receive the account headers; signed CDN URLs get the
|
| 25 |
+
Referer alone.
|
| 26 |
+
"""
|
| 27 |
+
out={'Referer':'https://www.tiktok.com/'}
|
| 28 |
+
try:host=(urlparse(str(url or '')).hostname or '').lower().rstrip('.')
|
| 29 |
+
except Exception:host=''
|
| 30 |
+
if host=='tiktok.com' or host.endswith('.tiktok.com'):
|
| 31 |
+
extra=(headers_for or (lambda _u:{}))(user) or {}
|
| 32 |
+
out.update({str(k):str(v) for k,v in extra.items() if v and str(k).lower()!='host'})
|
| 33 |
+
return out
|
| 34 |
|
| 35 |
# أخطاء FFmpeg ← وصف عربي. قائمة واحدة على مستوى الوحدة حتى تُختبر على سطور FFmpeg حقيقية
|
| 36 |
# بدل أن تُدفن في إغلاق داخل send(): الإغلاق هو ما أخفى أن كلمة المفتاح كُتبت بالخطأ.
|
|
|
|
| 81 |
def classify_ffmpeg_error(text):
|
| 82 |
"""أول وصف ينطبق على سطر من stderr، أو None. تصنيف نصي خالص بلا أي روابط."""
|
| 83 |
low = (text or '').lower()
|
| 84 |
+
if 'netstream.publish.start' in low or 'fcpublish stream...' in low:
|
| 85 |
+
return None # Successful/debug publish status is not a rejection.
|
| 86 |
for needle, label in FFMPEG_ERROR_LABELS:
|
| 87 |
if needle.lower() in low:
|
| 88 |
return label
|
| 89 |
return None
|
| 90 |
|
| 91 |
|
| 92 |
+
def ffmpeg_output_failure(text):
|
| 93 |
+
"""True only for stderr evidence that FFmpeg's publishing side failed.
|
| 94 |
+
|
| 95 |
+
This distinction matters: once RTMPS stops consuming, FFmpeg stops reading stdin and
|
| 96 |
+
the source meter ages too. Calling that a TikTok stall creates a reconnect storm and
|
| 97 |
+
never refreshes the YouTube destination or normalizes the feed.
|
| 98 |
+
"""
|
| 99 |
+
low=(text or '').lower()
|
| 100 |
+
if 'netstream.publish.start' in low or 'fcpublish stream...' in low:
|
| 101 |
+
return False
|
| 102 |
+
return (any(x in low for x in (
|
| 103 |
+
'error opening output', 'error writing', 'broken pipe', 'netstream.publish',
|
| 104 |
+
'server error, publish')) or
|
| 105 |
+
(('[out#' in low or 'publish stream' in low) and
|
| 106 |
+
any(x in low for x in ('error', 'failed', 'rejected', 'denied', 'unable', 'broken pipe'))))
|
| 107 |
+
|
| 108 |
+
|
| 109 |
def redact_stderr(text):
|
| 110 |
"""يُبقي سبب الخطأ ويخفي كل ما لا يجوز قراءته في سجل عام: الروابط والمفاتيح والرموز."""
|
| 111 |
t = re.sub(r'\b(?:rtmps?|rtsp|srt|https?)://\S+', '«رابط-مخفي»', text or '')
|
| 112 |
+
# FFmpeg debug prints the RTMP playpath WITHOUT its URL scheme.
|
| 113 |
+
t = re.sub(r"(?i)((?:publish|play) command for\s+)'[^']*'", r"\1'«مفتاح-مخفي»'", t)
|
| 114 |
+
t = re.sub(r'(?i)(\b(?:fname|playpath)\s*=\s*)[^,\s]+', r'\1«مفتاح-مخفي»', t)
|
| 115 |
t = re.sub(r'(?i)([?&=]|^|\s)((?:key|token|auth|sessionid|sign)\s*=\s*)[^\s&]+', r'\1\2«مخفي»', t)
|
| 116 |
return t.strip()[:240]
|
| 117 |
|
|
|
|
| 142 |
self.last_exit_code=None # آخر رمز خروج FFmpeg (من آخر جلسة)، يقرؤه المشرف
|
| 143 |
self.last_errors=[] # آخر سطور stderr مصنّفة ومُخفًى منها المفتاح: لماذا أقفلت الوجهة؟
|
| 144 |
self.on_stable=None # مستقبِل المدير: أول ≥25 ث مُسلَّمة = العقاب انتهى
|
| 145 |
+
self.on_sticky=None # Persist a per-event format fallback before this FFmpeg is restarted.
|
| 146 |
+
self.on_sticky_clear=None # Persist the verified return to copy (journal must not re-apply transcode).
|
| 147 |
+
self.sticky_operator_locked=False # An operator-forced transcode is never auto-probed back to copy.
|
| 148 |
+
self.on_sticky_pending=None
|
| 149 |
+
self.pending_sticky=None # (mode, reason) while the bounded encoder slots are occupied.
|
| 150 |
self.last_diagnostics=[] # آخر الأوصاف العربية المصنَّفة، تُعرض في اللوحة كما في السجل
|
| 151 |
self.last_source_gap=0.0 # صمت المصدر لحظة التفكيك: يفصل جوع المصدر عن رفض الوجهة
|
| 152 |
+
self.last_failure_side='' # 'source' or 'output'; stderr/backpressure outranks an aged meter
|
| 153 |
+
self.format_unstable=False # رأى الجسر فاصل إطارات مفتاحية مضطربًا: لا COPY على هذا المصدر حتى يبرد الترميز
|
| 154 |
+
self.trace_rtmp=False # One failed startup enables redacted handshake diagnostics.
|
| 155 |
+
self.active_mode='' # exact FFmpeg mode, safe to expose in operational logs/state
|
| 156 |
+
self.telemetry_key=None # Append-only diagnostics only; never used for control decisions.
|
| 157 |
+
self.telemetry_context={} # Safe manager context (event/room labels), set before send().
|
| 158 |
# Timestamps of source resolution changes seen by this sender (anti-flap window).
|
| 159 |
self.flap=deque()
|
| 160 |
+
self._format_fallback_last_attempt=0.0
|
| 161 |
# Once the source proved to flap, stay on a constant canvas for the rest of the
|
| 162 |
# event. Without this the flap window expires after 10 quiet minutes and the
|
| 163 |
# sender silently drops back to copy mode, restarting the whole failure loop.
|
|
|
|
| 186 |
stamp=d.get('last_source_at')
|
| 187 |
if stamp:d['source_age']=round(max(0.0,time.monotonic()-stamp),1)
|
| 188 |
try:
|
| 189 |
+
# active_mode is the exact mode used by this sender's current/last FFmpeg,
|
| 190 |
+
# unlike the UI preference ("auto") or a global default (which can differ per account).
|
| 191 |
+
d['send_mode']=self.active_mode or self.sticky_mode or self.mode_override or ''
|
| 192 |
+
d['pending_send_mode']=self.pending_sticky[0] if self.pending_sticky else ''
|
| 193 |
except Exception:
|
| 194 |
d['send_mode']=''
|
| 195 |
+
d['pending_send_mode']=''
|
| 196 |
return d
|
| 197 |
def wait_until(self,condition,stop,poll=1.0,timeout=None):
|
| 198 |
"""Block while `condition()` holds; returns as soon as it stops or a stop is requested."""
|
|
|
|
| 220 |
def send_mode(self):
|
| 221 |
"""Policy for what YouTube receives:
|
| 222 |
|
| 223 |
+
auto -> copy a positively identified H.264 or HEVC source. HEVC is carried as
|
| 224 |
+
Enhanced RTMP hvc1; no video decoder/encoder is inserted.
|
| 225 |
+
copy -> forward supported encoded video access units untouched
|
|
|
|
|
|
|
|
|
|
|
|
|
| 226 |
fixed1080 -> constant 1080x1920 canvas, re-encodes
|
| 227 |
fixed720 -> constant 720x1280 canvas, re-encodes (lighter on CPU)
|
| 228 |
"""
|
| 229 |
mode=(self.mode_override or os.getenv('YOUTUBE_SEND_MODE','auto')).strip().lower()
|
| 230 |
if mode not in ('auto','copy','fixed1080','fixed720','matchgop'):
|
| 231 |
raise ValueError('وضع الإرسال يجب أن يكون auto أو copy أو fixed1080 أو fixed720 أو matchgop')
|
| 232 |
+
# Optional legacy transcode fallback remains operator-selectable, but ordinary AVC/HEVC
|
| 233 |
+
# decoder-record replacement never selects it; the image defaults to byte-only copy.
|
|
|
|
| 234 |
if self.sticky_mode:
|
| 235 |
# Do NOT drop LIGHT just because the next TikTok label says h264.
|
| 236 |
# That path produced COPY with output_seconds=0 on the same ingest
|
|
|
|
| 239 |
self._recovering_copy=True
|
| 240 |
return 'copy'
|
| 241 |
return self.sticky_mode
|
| 242 |
+
# Stream copy supports legacy AVC and Enhanced-RTMP HEVC. Before trusting TikTok's
|
| 243 |
+
# label, the caller may hand us the candidate it is about to send (current_candidate).
|
| 244 |
if mode in ('auto','copy') and self.current_candidate is not None:
|
| 245 |
+
# Copy still needs positive codec evidence — see copy_is_safe().
|
| 246 |
fb=self.allow_codec_fallback()
|
| 247 |
if fb:return fb
|
| 248 |
if mode=='auto':
|
| 249 |
+
# مصدر رأينا فاصل إطاراته يتأرجح (0.4-4 ث) أو خطه الزمني يقفز: النسخ يمرّر
|
| 250 |
+
# هذا الاضطراب إلى ��وتيوب كما هو (شرطه الرسمي GOP ~2 ث)، والتطبيع يزيل
|
| 251 |
+
# المتغيّر كله. القفل لجلسة هذا الناشر؛ لا يمس اختيارًا صريحًا من المشغّل.
|
| 252 |
+
if self.format_unstable:
|
| 253 |
+
return 'matchgop'
|
| 254 |
# Proven H.264 and a stable source: forward it untouched.
|
| 255 |
return 'copy' if not self.sticky_mode else self.sticky_mode
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 256 |
return mode
|
| 257 |
+
@staticmethod
|
| 258 |
+
def _copy_supported(candidate):
|
| 259 |
+
"""Cheap, local evidence that byte copy is even possible for this source.
|
| 260 |
+
|
| 261 |
+
Supported means positively AVC or HEVC (Enhanced RTMP carries hvc1);
|
| 262 |
+
an unknown/other codec is never probed blind. This reads only the
|
| 263 |
+
candidate's own labels — no network probe is spent on a mode decision.
|
| 264 |
+
"""
|
| 265 |
+
cand=candidate or {}
|
| 266 |
+
text=(str(cand.get('codec') or '')+' '+str(cand.get('label') or '')+' '+
|
| 267 |
+
str(cand.get('brief') or ''))
|
| 268 |
+
return Sender.copy_is_safe(text,'')
|
| 269 |
+
|
| 270 |
def _may_attempt_copy_recovery(self):
|
| 271 |
+
"""LIGHT→COPY probe after a stable light run, for AVC *and* HEVC sources.
|
| 272 |
|
| 273 |
+
The probe is verified in send(): output that survives the threshold
|
| 274 |
+
clears the sticky mode everywhere (including the manager journal);
|
| 275 |
+
a probe that produces nothing re-enters the transcode and counts a
|
| 276 |
+
failure, so a bad source cannot flap the publisher forever.
|
| 277 |
+
Disable only explicitly with YOUTUBE_COPY_RECOVERY=0.
|
| 278 |
"""
|
| 279 |
+
if getattr(self,'sticky_operator_locked',False):
|
|
|
|
|
|
|
|
|
|
| 280 |
return False
|
| 281 |
+
if getattr(self,'format_unstable',False):
|
| 282 |
+
# GOP/DTS مضطرب موثّق بالجسر: فحص COPY هنا يعيد فتح جرح أغلقه التطبيع.
|
| 283 |
+
# الاستثناء الوحيد: حاكم البطء يمسح القفل بنفسه قبل طلب الفحص (انظر send).
|
| 284 |
return False
|
| 285 |
+
if str(os.getenv('YOUTUBE_COPY_RECOVERY','1')).strip().lower() in ('0','false','off','no'):
|
|
|
|
| 286 |
return False
|
| 287 |
+
try:max_fails=max(0,int(os.getenv('YOUTUBE_COPY_RECOVERY_MAX_FAILS','2')))
|
| 288 |
+
except (TypeError,ValueError):max_fails=2
|
| 289 |
+
if self.copy_recovery_fails>=max_fails:
|
| 290 |
return False
|
| 291 |
+
try:need=max(30.0, float(os.getenv('YOUTUBE_COPY_RECOVERY_SECONDS','60')))
|
| 292 |
+
except (TypeError,ValueError):need=60.0
|
| 293 |
+
if not self.sticky_since or (time.monotonic()-self.sticky_since)<need:
|
| 294 |
return False
|
| 295 |
+
if float(self._last_light_output or 0)<20:
|
|
|
|
|
|
|
| 296 |
return False
|
| 297 |
+
return self._copy_supported(self.current_candidate)
|
| 298 |
def request_sticky(self, mode, user, reason):
|
| 299 |
"""Per-broadcaster: stick LIGHT/matchgop and end this FFmpeg only — not the Space."""
|
| 300 |
mode=(mode or 'matchgop').strip().lower()
|
|
|
|
| 302 |
if self.sticky_mode==mode and self.session:
|
| 303 |
return False
|
| 304 |
if not self.sticky_mode:
|
| 305 |
+
from ingest import hub
|
| 306 |
+
if not hub.reserve_light(user):
|
| 307 |
+
self.log(user, '[HEALTH] skip sticky %s — transcode slots full (%s)'%(mode, reason[:120]))
|
| 308 |
+
return False
|
|
|
|
|
|
|
|
|
|
| 309 |
self.sticky_mode=mode
|
| 310 |
self.sticky_since=time.monotonic()
|
| 311 |
self._recovering_copy=False
|
| 312 |
self._no_copy_recovery=True
|
| 313 |
+
self.pending_sticky=None
|
| 314 |
+
cb=getattr(self,'on_sticky',None)
|
| 315 |
+
if cb:
|
| 316 |
+
try:cb(user,mode,int(self._gop_w or 0),int(self._gop_h or 0))
|
| 317 |
+
except Exception as e:self.log(user,'[HEALTH] could not persist sticky mode: '+str(e)[:80])
|
| 318 |
self.log(user, '[HEALTH] %s — sticky %s (this publisher only)'%(reason[:160], mode))
|
| 319 |
sess=self.session
|
| 320 |
if isinstance(sess, dict):
|
|
|
|
| 324 |
try: p.stdin.close()
|
| 325 |
except (OSError, ValueError): pass
|
| 326 |
return True
|
| 327 |
+
def _bridge_event(self,user,event,details):
|
| 328 |
+
"""Persist a redacted source event, then let the sender policy react to dimensions."""
|
| 329 |
+
try:log_event(user,event,details)
|
| 330 |
+
except Exception:pass
|
| 331 |
+
# Telemetry mirrors the already-redacted operational event only. Its
|
| 332 |
+
# public functions are fail-open and non-blocking; no result is read
|
| 333 |
+
# back into any streaming decision.
|
| 334 |
+
telemetry_event(self.telemetry_key,user,event,details)
|
| 335 |
+
if event=='BITRATE_CHANGE' and isinstance(details,dict):
|
| 336 |
+
telemetry_observe(self.telemetry_key,{'source_bitrate_kbps':details.get('new_kbps')})
|
| 337 |
+
elif event=='STREAM_CONFIG' and isinstance(details,dict):
|
| 338 |
+
telemetry_observe(self.telemetry_key,{
|
| 339 |
+
'source_width':details.get('width'),'source_height':details.get('height')})
|
| 340 |
+
if event=='RESOLUTION_CHANGE':
|
| 341 |
+
self.note_format_change(user,details)
|
| 342 |
+
elif event=='KEYFRAME_CHANGE':
|
| 343 |
+
# الجسر قاس فاصل الإطارات المفتاحية يتغيّر جوهريًا: مصدر غير مستقر الصيغة.
|
| 344 |
+
# تُقفل عودة COPY لهذا الناشر ويُطبَّع الخرج — يوتيوب يريد GOP ثابتًا ~2 ث.
|
| 345 |
+
self.format_unstable=True
|
| 346 |
+
def note_format_change(self,user='system',details=None):
|
| 347 |
+
"""A bounded anti-flap policy: copy remains default until real resolution changes recur.
|
| 348 |
+
|
| 349 |
+
The old counter was dead code: FLVBridge emitted RESOLUTION_CHANGE but no sender ever
|
| 350 |
+
called this method. Once the configured threshold is reached, only that broadcaster's
|
| 351 |
+
copy publisher is restarted into a constant-canvas encoder; the YouTube event is reused.
|
| 352 |
+
"""
|
| 353 |
+
now=time.monotonic()
|
| 354 |
+
try:window=max(30.0,float(os.getenv('YOUTUBE_FLAP_WINDOW_SECONDS','600')))
|
| 355 |
+
except (TypeError,ValueError):window=600.0
|
| 356 |
+
while self.flap and now-self.flap[0]>window:self.flap.popleft()
|
| 357 |
+
self.flap.append(now)
|
| 358 |
+
try:limit=max(1,int(os.getenv('YOUTUBE_FLAP_LIMIT','4')))
|
| 359 |
+
except (TypeError,ValueError):limit=4
|
| 360 |
+
if len(self.flap)<limit or self.sticky_mode:
|
| 361 |
+
return False
|
| 362 |
+
active=(self.active_mode or self.sticky_mode or self.mode_override or
|
| 363 |
+
os.getenv('YOUTUBE_SEND_MODE','auto')).strip().lower()
|
| 364 |
+
if active not in ('auto','copy'):
|
| 365 |
+
return False
|
| 366 |
+
# If transcode slots are full, preserve the current live copy stream and retry on a later
|
| 367 |
+
# genuine resolution transition; do not evict another broadcaster or stop this event.
|
| 368 |
+
if now-self._format_fallback_last_attempt<5.0:
|
| 369 |
+
return False
|
| 370 |
+
self._format_fallback_last_attempt=now
|
| 371 |
+
mode=os.getenv('YOUTUBE_FLAP_FALLBACK_MODE','matchgop').strip().lower()
|
| 372 |
+
if mode not in ('fixed1080','fixed720','matchgop'):mode='matchgop'
|
| 373 |
+
d=details or {}
|
| 374 |
+
reason=('source resolution changed %d times within %.0fs (last %sx%s→%sx%s)'%(
|
| 375 |
+
len(self.flap),window,d.get('old_width','?'),d.get('old_height','?'),
|
| 376 |
+
d.get('new_width','?'),d.get('new_height','?')))
|
| 377 |
+
if not self.request_sticky(mode,user,reason):
|
| 378 |
+
if not self.sticky_mode and self.pending_sticky is None:
|
| 379 |
+
self.pending_sticky=(mode,reason)
|
| 380 |
+
cb=getattr(self,'on_sticky_pending',None)
|
| 381 |
+
if cb:
|
| 382 |
+
try:cb(user,mode,reason)
|
| 383 |
+
except Exception as e:self.log(user,'[HEALTH] could not persist pending format fallback: '+str(e)[:80])
|
| 384 |
+
return False
|
| 385 |
+
log_event(user,'FORMAT_FALLBACK',{'mode':mode,'changes_in_window':len(self.flap),
|
| 386 |
+
'window_seconds':int(window),'reason':'repeated_resolution_change'})
|
| 387 |
+
return True
|
| 388 |
+
def apply_pending_sticky(self,user):
|
| 389 |
+
"""Take a free encoder slot later without stopping/evicting another broadcaster."""
|
| 390 |
+
pending=self.pending_sticky
|
| 391 |
+
if not pending:return False
|
| 392 |
+
mode,reason=pending
|
| 393 |
+
from ingest import hub
|
| 394 |
+
if not hub.reserve_light(user):return False
|
| 395 |
+
if self.request_sticky(mode,user,reason):
|
| 396 |
+
log_event(user,'FORMAT_FALLBACK',{'mode':mode,'reason':'resolution_change_pending_slot'})
|
| 397 |
+
return True
|
| 398 |
+
if not self.sticky_mode:
|
| 399 |
+
hub.release_light(user)
|
| 400 |
+
else:
|
| 401 |
+
self.pending_sticky=None
|
| 402 |
+
return False
|
| 403 |
@staticmethod
|
| 404 |
def copy_is_safe(declared,probed):
|
| 405 |
+
"""Allow byte copy only with positive, non-conflicting AVC/HEVC evidence.
|
| 406 |
|
| 407 |
+
FFmpeg 7's FLV path preserves replacement decoder records for both codecs. HEVC output
|
| 408 |
+
additionally uses the Enhanced-RTMP ``hvc1`` advertisement; unknown codecs and a label /
|
| 409 |
+
probe disagreement remain unsafe rather than being guessed.
|
|
|
|
|
|
|
|
|
|
|
|
|
| 410 |
"""
|
| 411 |
def norm(x):
|
| 412 |
x=str(x or '').strip().lower()
|
| 413 |
+
if any(c in x for c in ('h264','avc')):return 'h264'
|
| 414 |
+
if any(c in x for c in ('h265','hevc','hvc1')):return 'h265'
|
| 415 |
+
return 'other' if x else ''
|
| 416 |
d,q=norm(declared),norm(probed)
|
| 417 |
+
if q in ('h264','h265'):return d in ('',q)
|
| 418 |
+
if q=='other':return False
|
| 419 |
+
return d in ('h264','h265')
|
|
|
|
| 420 |
def allow_codec_fallback(self):
|
| 421 |
"""Decide from evidence once, then stick to it for the whole event."""
|
| 422 |
+
if str(os.getenv('YOUTUBE_AUTO_TRANSCODE','0')).strip().lower() in ('0','false','off','no'):return None
|
| 423 |
cand=self.current_candidate
|
| 424 |
if cand is None:return None
|
| 425 |
found=self.live_probe(cand)
|
|
|
|
| 465 |
an already-open live event is exactly the flash that only a YouTube-app restart
|
| 466 |
clears for existing viewers.
|
| 467 |
"""
|
| 468 |
+
if int(getattr(self, '_gop_w', 0) or 0) >= 32:
|
| 469 |
return (self._gop_w, self._gop_h)
|
| 470 |
if candidate and not (w and h):
|
| 471 |
try:
|
|
|
|
| 478 |
except (TypeError, ValueError):
|
| 479 |
w = h = 0
|
| 480 |
w, h = w - w % 2, h - h % 2
|
| 481 |
+
if w >= 32 and h >= 32:
|
| 482 |
w, h = self.youtube_safe_size(w, h)
|
| 483 |
self._gop_w, self._gop_h = w, h
|
| 484 |
return (int(getattr(self, '_gop_w', 0) or 0), int(getattr(self, '_gop_h', 0) or 0))
|
|
|
|
| 495 |
w, h = int(w or 0), int(h or 0)
|
| 496 |
except (TypeError, ValueError):
|
| 497 |
return 0, 0
|
| 498 |
+
if w < 32 or h < 32:
|
| 499 |
+
return 0, 0 # TikTok may begin with a 16x16 placeholder configuration.
|
| 500 |
short, long_ = min(w, h), max(w, h)
|
| 501 |
portrait = h >= w
|
| 502 |
if short <= 720 and long_ >= 1280:
|
|
|
|
| 531 |
# non-network input ("Option reconnect not found"), so it is applied only where it
|
| 532 |
# is both legal and wanted.
|
| 533 |
net=['-reconnect','1','-reconnect_streamed','1','-reconnect_delay_max','5'] if url.startswith(('http://','https://')) else []
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 534 |
return {'stdin':None,'input':[
|
| 535 |
+
*net,*resync,'-live_start_index',os.getenv('HLS_START_INDEX','-3'),
|
| 536 |
*(('-headers',self.headers_blob(candidate)) if candidate.get('user') else ()),
|
| 537 |
'-i',url]}
|
| 538 |
return {'stdin':subprocess.PIPE,'input':['-rw_timeout','20000000',
|
| 539 |
'-fflags','+genpts','-i','pipe:0']}
|
| 540 |
def headers_blob(self,candidate):
|
| 541 |
+
"""FFmpeg HTTP headers, applying the same cross-domain cookie boundary as FLV."""
|
| 542 |
+
c=candidate or {}
|
| 543 |
+
items=source_http_headers(c.get('url'),c.get('user'),self.headers_for)
|
| 544 |
return ''.join('%s: %s\r\n'%(k,v) for k,v in items.items() if v)
|
| 545 |
@staticmethod
|
| 546 |
def codec_unusable(candidate):
|
| 547 |
+
"""True when the declared codec is neither AVC nor Enhanced-RTMP HEVC."""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 548 |
codec=str((candidate or {}).get('codec') or '').strip().lower()
|
| 549 |
if not codec:return False
|
| 550 |
+
return not any(c in codec for c in ('h264','avc','264','h265','hevc','hvc1','265'))
|
| 551 |
@staticmethod
|
| 552 |
def hevc_payload(candidate):
|
| 553 |
"""هل ما سيدفعه FFmpeg فعلًا HEVC؟ الإعلان عن Enhanced-RTMP يُقاس على هذا لا على الوضع."""
|
|
|
|
| 558 |
def enhanced_advertisement(self, mode, candidate):
|
| 559 |
"""قائمة خيارات FFmpeg لإعلان fourCcLive (Enhanced RTMP) — فارغة على تدفق H.264.
|
| 560 |
|
| 561 |
+
`rtmp_enhanced_codecs` advertises fourCcLive in the RTMP connect command. It is emitted
|
| 562 |
+
only when the bytes actually carried are HEVC; advertising hvc1 on an AVC-only source
|
| 563 |
+
previously caused receiver-side rejection. ``YOUTUBE_ENHANCED_RTMP=off`` remains an
|
| 564 |
+
emergency compatibility override.
|
| 565 |
"""
|
| 566 |
switch = os.getenv('YOUTUBE_ENHANCED_RTMP', 'auto').strip().lower()
|
| 567 |
if switch in ('0', 'off', 'no', 'legacy'):
|
|
|
|
| 575 |
def command(self,destination,candidate=None):
|
| 576 |
# إعلان Enhanced-RTMP يُقاس على الترميز المدفوع فعلًا؛ ملفات الاختبار المحلية لا بروتوكول لها.
|
| 577 |
mode=self.send_mode()
|
| 578 |
+
self.active_mode=mode
|
| 579 |
network=destination.startswith(('rtmp://','rtmps://'))
|
| 580 |
enhanced=self.enhanced_advertisement(mode,candidate) if network else []
|
| 581 |
if mode=='copy':
|
| 582 |
video=['-c:v','copy']
|
| 583 |
else:
|
| 584 |
if mode=='matchgop':
|
| 585 |
+
self.lock_gold(candidate)
|
| 586 |
+
if not self._gop_w or not self._gop_h:
|
| 587 |
+
# A 16x16 startup header is not the player's real canvas. Unknown
|
| 588 |
+
# dimensions still need a constant output, not a reinitializing scale.
|
| 589 |
+
self._gop_w,self._gop_h=720,1280
|
| 590 |
+
# CPU guard: re-encoding a 960x1920 (or larger) picture at full
|
| 591 |
+
# size is what saturates a cpu-basic Space while the source is
|
| 592 |
+
# only 720-class in bitrate. The fallback canvas is capped at
|
| 593 |
+
# 720p-class; an explicit fixed1080 operator mode is not capped.
|
| 594 |
+
if str(os.getenv('YOUTUBE_TRANSCODE_CAP','1')).strip().lower() not in ('0','off','false','no'):
|
| 595 |
+
try:cap_short=max(144,int(os.getenv('YOUTUBE_TRANSCODE_MAX_SHORT','720')))
|
| 596 |
+
except (TypeError,ValueError):cap_short=720
|
| 597 |
+
try:cap_long=max(256,int(os.getenv('YOUTUBE_TRANSCODE_MAX_LONG','1280')))
|
| 598 |
+
except (TypeError,ValueError):cap_long=1280
|
| 599 |
+
w,h=int(self._gop_w),int(self._gop_h)
|
| 600 |
+
if min(w,h)>cap_short or max(w,h)>cap_long:
|
| 601 |
+
scale=min(cap_short/min(w,h),cap_long/max(w,h))
|
| 602 |
+
self._gop_w=max(2,int(w*scale)//2*2);self._gop_h=max(2,int(h*scale)//2*2)
|
| 603 |
+
vf=self.canvas(self._gop_w,self._gop_h)
|
| 604 |
bitrate=os.getenv('VIDEO_BITRATE','').strip() or '4500k'
|
| 605 |
else:
|
| 606 |
width,height,bitrate=(1080,1920,'6000k') if mode=='fixed1080' else (720,1280,'4000k')
|
|
|
|
| 608 |
bitrate=os.getenv('VIDEO_BITRATE','').strip() or bitrate
|
| 609 |
bufsize=str(int(int(str(bitrate).rstrip('kK'))*1.5))+'k'
|
| 610 |
video=['-vf',vf,'-c:v','libx264','-preset',os.getenv('YOUTUBE_X264_PRESET','veryfast'),
|
| 611 |
+
'-tune','zerolatency','-profile:v','high',
|
| 612 |
+
# Live Control Room requires CBR. `-crf 22 -b:v/-maxrate` was only capped
|
| 613 |
+
# CRF: a measured static 720x1280 input produced 14 kbit/s although FFmpeg's
|
| 614 |
+
# stream header claimed 4500 kbit/s, and YouTube reported
|
| 615 |
+
# videoIngestionStarved for both live relays. minrate + nal-hrd=cbr makes
|
| 616 |
+
# x264 emit filler when a simple frame needs few bits (measured 4444 kbit/s),
|
| 617 |
+
# keeping the ingest clock fed rather than merely raising a nominal field.
|
| 618 |
+
'-b:v',bitrate,'-minrate',bitrate,'-maxrate',bitrate,'-bufsize',bufsize,
|
| 619 |
# IDR at least every 2 s: a viewer who stalls (or joins) re-syncs on the next
|
| 620 |
# keyframe instead of waiting for the source's own GOP, which is what made
|
| 621 |
# people leave the YouTube app and come back to get a picture again.
|
| 622 |
'-force_key_frames','expr:gte(t,n_forced*2)',
|
| 623 |
'-g',os.getenv('YOUTUBE_GOP','60'),'-keyint_min','30','-sc_threshold','0','-bf','0',
|
| 624 |
+
'-x264-params','nal-hrd=cbr:force-cfr=1:open-gop=0:scenecut=0:keyint=%s:min-keyint=30'%os.getenv('YOUTUBE_GOP','60'),
|
| 625 |
'-pix_fmt','yuv420p','-fps_mode','cfr',
|
| 626 |
'-colorspace','bt709','-color_primaries','bt709','-color_trc','bt709']
|
| 627 |
# Network output goes through the fifo pseudo-muxer instead of straight to flv.
|
|
|
|
| 670 |
else:
|
| 671 |
output=['-flvflags','no_duration_filesize','-f','flv']
|
| 672 |
ta=self.input_args(candidate)
|
| 673 |
+
return [self.ffmpeg,'-hide_banner','-loglevel',('debug' if network and self.trace_rtmp else os.getenv('YOUTUBE_FFMPEG_LOGLEVEL','error')),
|
| 674 |
'-nostats','-progress','pipe:1',
|
| 675 |
*ta['input'],'-map','0:v:0','-map','0:a:0?',
|
| 676 |
# TikTok streams HE-AAC (SBR) at 64 kbit/s — measured on the live source. Copied
|
|
|
|
| 762 |
except BaseException as e: # تُعاد رفعها في خيط الضخّ لتُصنَّف هناك
|
| 763 |
out.put(e)
|
| 764 |
|
| 765 |
+
def _pump_source(self, response, p, bridge, stop, sess, read_timeout, retries, cancel=None):
|
| 766 |
"""نقل بايتات تيك توك إلى FFmpeg في خيط مستقل، مع تسجيل زمن آخر وصول فعلي.
|
| 767 |
|
| 768 |
القراءة هنا هي مصدر الحقيقة: `poll()` الخاص بـ FFmpeg يبقى ناجحًا وهو جالس ينتظر
|
| 769 |
stdin، ويوتيوب يبقى مستقبِلًا على آخر ما وصل — لذا يُقاس تدفق البيانات لا حالة العملية.
|
| 770 |
"""
|
| 771 |
+
sess.setdefault('stdin_lock', threading.Lock())
|
| 772 |
+
sess.setdefault('filling', False); sess.setdefault('filling_at', 0.0)
|
| 773 |
it = response.iter_content(None).__iter__()
|
| 774 |
deadline = time.monotonic() + sess['max_seconds']
|
| 775 |
chunk_wait = min(read_timeout, max(1.0, self._stall_seconds() / 3.0)) if self._stall_seconds() else read_timeout
|
| 776 |
pending = None
|
| 777 |
reader = None
|
| 778 |
+
while (not stop.is_set() and not sess['force_stop'] and not sess.get('swap_source')
|
| 779 |
+
and not (cancel and cancel.is_set())):
|
| 780 |
if time.monotonic() > deadline:
|
| 781 |
sess['error'] = 'انتهت مهلة الجلسة القصوى (%ds)' % int(sess['max_seconds'])
|
| 782 |
return
|
|
|
|
| 792 |
try:
|
| 793 |
got = pending.get(timeout=chunk_wait)
|
| 794 |
except queue.Empty:
|
| 795 |
+
if stop.is_set() or sess['force_stop'] or sess.get('swap_source') or (cancel and cancel.is_set()):
|
| 796 |
+
return
|
| 797 |
silent = time.monotonic() - sess['last']
|
| 798 |
if self._stall_seconds() and silent > self._stall_seconds():
|
| 799 |
sess['error'] = 'صمت من تيك توك (%.0f ث بلا بايت)' % silent
|
| 800 |
return
|
| 801 |
continue
|
| 802 |
pending = None
|
| 803 |
+
# A late result from the old HTTP reader cannot mutate the replacement pump.
|
| 804 |
+
if stop.is_set() or sess['force_stop'] or sess.get('swap_source') or (cancel and cancel.is_set()):
|
| 805 |
+
return
|
| 806 |
if isinstance(got, BaseException):
|
| 807 |
e = got
|
| 808 |
if self._is_timeout(e) and not sess['force_stop']:
|
|
|
|
| 831 |
buf = bridge.feed(chunk)
|
| 832 |
if not buf:
|
| 833 |
continue
|
| 834 |
+
sess['writing'] = True
|
| 835 |
+
try:
|
| 836 |
+
with sess['stdin_lock']:
|
| 837 |
+
if stall_limit:
|
| 838 |
+
self._write_deadline(p.stdin, buf, sess['last'] + stall_limit)
|
| 839 |
+
else:
|
| 840 |
+
view = memoryview(buf)
|
| 841 |
+
while view and not stop.is_set() and not sess['force_stop']:
|
| 842 |
+
n = p.stdin.write(view)
|
| 843 |
+
if not n:
|
| 844 |
+
raise BrokenPipeError()
|
| 845 |
+
view = view[n:]
|
| 846 |
+
finally:
|
| 847 |
+
sess['writing'] = False
|
| 848 |
except SourceStalled as e:
|
| 849 |
+
# A full stdin pipe means FFmpeg stopped consuming because its demux/output side
|
| 850 |
+
# is stuck. It is not evidence that TikTok stopped sending this chunk.
|
| 851 |
+
self.last_failure_side = 'output'
|
| 852 |
+
sess['output_failure'] = True
|
| 853 |
sess['error'] = str(e)
|
| 854 |
return
|
| 855 |
except (BrokenPipeError, OSError, ValueError):
|
| 856 |
return # FFmpeg هو من مات؛ الحلقة الرئيسية تتصرف
|
|
|
|
|
|
|
|
|
|
| 857 |
|
| 858 |
def _try_reattach(self, user, p, bridge, sess, stop, refresh, read_timeout, retries, response, pump):
|
| 859 |
"""Close only the TikTok HTTP; keep FFmpeg stdin so YouTube does not see a new ingest.
|
|
|
|
| 861 |
Returns (new_response, new_pump) or None. Viewer cuts come from killing FFmpeg, not from
|
| 862 |
a 1–2 s TikTok URL refresh into the same process.
|
| 863 |
"""
|
| 864 |
+
if (not refresh or p is None or p.stdin is None or p.poll() is not None
|
| 865 |
+
or stop.is_set() or sess.get('force_stop')):
|
| 866 |
return None
|
| 867 |
if int(sess.get('reattaches') or 0) >= 24:
|
| 868 |
return None
|
| 869 |
sess['swapping'] = True
|
| 870 |
sess['swap_source'] = True
|
| 871 |
sess['swap_started'] = time.monotonic()
|
| 872 |
+
old_cancel = sess.get('pump_cancel')
|
| 873 |
+
if old_cancel is not None:
|
| 874 |
+
old_cancel.set()
|
| 875 |
try:
|
| 876 |
if response:
|
| 877 |
try:
|
|
|
|
| 880 |
pass
|
| 881 |
if pump is not None:
|
| 882 |
pump.join(timeout=float(os.getenv('YOUTUBE_PUMP_JOIN_SECONDS', '2')))
|
| 883 |
+
if pump.is_alive():
|
| 884 |
+
self.log(user, '[RELAY] قارئ المصدر السابق لم يتوقف؛ لا نشارك معه الجسر أو أنبوب FFmpeg')
|
| 885 |
+
return None
|
| 886 |
+
if stop.is_set() or sess.get('force_stop'):
|
| 887 |
+
return None
|
| 888 |
try:
|
| 889 |
cand = refresh()
|
| 890 |
except Exception as e:
|
| 891 |
self.log(user, '[RELAY] تعذر رصد مصدر بديل دون قطع يوتيوب (%s)' % type(e).__name__)
|
| 892 |
return None
|
| 893 |
+
if (not cand or cand.get('media') == 'hls' or not cand.get('url')
|
| 894 |
+
or stop.is_set() or sess.get('force_stop') or p.poll() is not None):
|
| 895 |
return None
|
| 896 |
try:
|
| 897 |
new_resp = requests.get(cand['url'],
|
| 898 |
+
headers=source_http_headers(cand.get('url'),user,self.headers_for),
|
| 899 |
impersonate='chrome', stream=True,
|
| 900 |
timeout=(5, min(8, read_timeout or 8)))
|
| 901 |
new_resp.raise_for_status()
|
| 902 |
except Exception as e:
|
| 903 |
+
telemetry_event(self.telemetry_key,user,'SOURCE_OPEN_ERROR',{
|
| 904 |
+
'stage':'reattach','error_type':type(e).__name__,
|
| 905 |
+
'http_status':http_status_from_exception(e)})
|
| 906 |
self.log(user, '[RELAY] فشل فتح مصدر تيك توك البديل (%s)' % type(e).__name__)
|
| 907 |
return None
|
| 908 |
+
if stop.is_set() or sess.get('force_stop') or p.poll() is not None:
|
| 909 |
+
new_resp.close()
|
| 910 |
+
return None
|
| 911 |
bridge.reconnect()
|
| 912 |
sess['ended'] = False
|
| 913 |
sess['error'] = ''
|
| 914 |
sess['stall_reason'] = ''
|
|
|
|
| 915 |
sess['timeouts'] = 0
|
| 916 |
# Do not bump sess['last'] here: that hid 40–57s of silence from the
|
| 917 |
# 12s stall watchdog (measured @vimtoo.2: out frozen, age 42–57, yh still good).
|
| 918 |
sess['reattaches'] = int(sess.get('reattaches') or 0) + 1
|
| 919 |
self.current_candidate = cand
|
| 920 |
self.set(source=cand.get('label') or cand.get('brief') or '', stalled=False)
|
| 921 |
+
try:
|
| 922 |
+
grace = max(0.5, min(5.0, float(os.getenv('YOUTUBE_REATTACH_GRACE_SECONDS', '2'))))
|
| 923 |
+
except (TypeError, ValueError):
|
| 924 |
+
grace = 2.0
|
| 925 |
+
limit = self._stall_seconds()
|
| 926 |
+
if limit:
|
| 927 |
+
grace = min(grace, max(0.5, limit / 2.0))
|
| 928 |
+
sess['reattach_not_before'] = time.monotonic() + grace
|
| 929 |
+
new_cancel = threading.Event()
|
| 930 |
+
sess['pump_cancel'] = new_cancel
|
| 931 |
+
# Clear the OLD reader's handover flag BEFORE starting its replacement. If
|
| 932 |
+
# start() schedules the new target immediately, a true flag kills it unread.
|
| 933 |
+
sess['swap_source'] = False
|
| 934 |
new_pump = threading.Thread(target=self._pump_source,
|
| 935 |
+
args=(new_resp, p, bridge, stop, sess, read_timeout, retries, new_cancel),
|
| 936 |
daemon=True)
|
| 937 |
new_pump.start()
|
| 938 |
self.log(user, '[RELAY] أُعيد توصيل تيك توك على نفس جلسة يوتيوب — بلا قتل FFmpeg')
|
|
|
|
| 941 |
sess['swap_source'] = False
|
| 942 |
sess['swapping'] = False
|
| 943 |
|
| 944 |
+
def _close_reason(self,sess,p):
|
| 945 |
+
"""Describe intentional stops and output failures truthfully in the persisted audit."""
|
| 946 |
+
reason=sess.get('stall_reason') or sess.get('error')
|
| 947 |
+
if reason:return str(reason)[:300]
|
| 948 |
+
if self.last_failure_side=='output':
|
| 949 |
+
try:code=p.poll() if p is not None else self.last_exit_code
|
| 950 |
+
except Exception:code=self.last_exit_code
|
| 951 |
+
reason='فشل خرج RTMPS (FFmpeg exit code %s)'%(code if code is not None else 'unknown')
|
| 952 |
+
if self.last_diagnostics:
|
| 953 |
+
reason+=' — '+str(self.last_diagnostics[-1])[:120]
|
| 954 |
+
return reason
|
| 955 |
+
return 'إيقاف عادي'
|
| 956 |
+
|
| 957 |
def _teardown(self, user, p, response, sess, stop, reason):
|
| 958 |
"""إنهاء مرتب — FFmpeg أولًا ثم الأنبوب ثم المصدر، مع wait محدود ثم kill.
|
| 959 |
|
|
|
|
| 1020 |
self.last_source_gap = round(max(0.0, time.monotonic() - sess['last']), 1) \
|
| 1021 |
if (sess.get('src_metered') and sess.get('last')) else 0.0
|
| 1022 |
self.set(status='', stalled=bool(sess.get('stall_reason') or sess.get('error')), note=reason,
|
| 1023 |
+
source_gap=self.last_source_gap, failure_side=self.last_failure_side,
|
| 1024 |
ffmpeg_errors=list(self.last_errors),
|
| 1025 |
ffmpeg_diagnostics=list(self.last_diagnostics)[-3:])
|
| 1026 |
codes = [c for c in codes if c]
|
|
|
|
| 1035 |
الإشراف في `sender_loop` التي تُعيد رصد LIVE وتبني جلسة جديدة من الصفر.
|
| 1036 |
"""
|
| 1037 |
self.current_candidate = candidate
|
| 1038 |
+
self.last_failure_side = ''
|
| 1039 |
+
self.last_errors=[]
|
| 1040 |
+
self.last_diagnostics=[]
|
| 1041 |
self.lock_gold(candidate)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1042 |
hls = (candidate or {}).get('media') == 'hls'
|
| 1043 |
+
# Replacement SPS/PPS or VPS/SPS/PPS records are forwarded through this bridge and the
|
| 1044 |
+
# same FFmpeg/RTMPS publisher. They are not a reason to select x264 or restart output.
|
| 1045 |
+
bridge = FLVBridge(user=user,event_logger=self._bridge_event)
|
| 1046 |
response = None
|
| 1047 |
p = None
|
| 1048 |
error_reader = None
|
| 1049 |
done = threading.Event()
|
| 1050 |
+
progress = {'last': time.monotonic(), 'seconds': -1, 'slow_since': None}
|
| 1051 |
pump = None
|
| 1052 |
diagnostics = []
|
| 1053 |
raw_tail = [] # آخر سطور stderr بعد الإخفاء: تُطبع عند الخروج، لا تُخزَّن خامًا
|
| 1054 |
read_timeout, retries, max_seconds = self._stream_tuning()
|
| 1055 |
+
sess = {'last': time.monotonic(), 'ended': False, 'error': '',
|
| 1056 |
'src_metered': False,
|
| 1057 |
'force_stop': False, 'timeouts': 0, 'orphan': False, 'stable_notified': False, 'max_seconds': max_seconds,
|
| 1058 |
'stall_reason': '', 'spawned': False, 'spawn_error': '',
|
| 1059 |
+
'writing': False, 'output_failure': False, 'connection_event': False,
|
| 1060 |
+
'ff_last': time.monotonic(),
|
| 1061 |
+
'stdin_lock': threading.Lock(), 'filling': False, 'filling_at': 0.0}
|
| 1062 |
self.set(status='الاتصال بيوتيوب', source=candidate['label'], output_seconds=0,
|
| 1063 |
+
last_output_at=None, stalled=False, last_source_at=sess['last'], source_bytes=0,
|
| 1064 |
+
rtmp_phase='')
|
| 1065 |
with self.lock:
|
| 1066 |
self.session = sess
|
| 1067 |
+
# Telemetry session boundaries are observational only. The key is
|
| 1068 |
+
# never consulted by mode, watchdog, reconnect, or quality decisions.
|
| 1069 |
+
tele_meta={'candidate_label':candidate.get('label'),'candidate_brief':candidate.get('brief'),
|
| 1070 |
+
'media':candidate.get('media'),'codec':candidate.get('codec'),
|
| 1071 |
+
'quality_name':candidate.get('quality_name'),'width':candidate.get('width'),
|
| 1072 |
+
'height':candidate.get('height'),'declared_bitrate_kbps':candidate.get('bitrate')}
|
| 1073 |
+
if isinstance(self.telemetry_context,dict):
|
| 1074 |
+
tele_meta.update(self.telemetry_context)
|
| 1075 |
+
self.telemetry_key=telemetry_start(user,tele_meta)
|
| 1076 |
+
tele_key=self.telemetry_key
|
| 1077 |
+
tele_fields={}
|
| 1078 |
+
tele_last_observe=time.monotonic()
|
| 1079 |
+
tele_last_checkpoint=time.monotonic()
|
| 1080 |
+
tele_last_source_bytes=0
|
| 1081 |
+
tele_finished=False
|
| 1082 |
+
def tele_finish(reason,extra=None):
|
| 1083 |
+
nonlocal tele_finished
|
| 1084 |
+
if tele_finished:return
|
| 1085 |
+
tele_finished=True
|
| 1086 |
+
telemetry_finish(tele_key,reason,extra)
|
| 1087 |
+
if self.telemetry_key==tele_key:self.telemetry_key=None
|
| 1088 |
try:
|
| 1089 |
sess['src_metered'] = not hls # HLS: FFmpeg يقرأ القائمة، فلا عدّاد مصدر لنا
|
| 1090 |
args = self.command(destination, candidate)
|
| 1091 |
+
telemetry_observe(tele_key,{'mode':self.active_mode or self.send_mode(),
|
| 1092 |
+
'source_width':candidate.get('width'),
|
| 1093 |
+
'source_height':candidate.get('height'),
|
| 1094 |
+
'declared_bitrate_kbps':candidate.get('bitrate')})
|
| 1095 |
if hls: # noqa: E999 — HLS: بلا أنبوب stdin
|
| 1096 |
# FFmpeg يفتح القائمة بنفسه: لا HTTP عندنا ولا ضخّ على stdin ⇒ الحارس هنا
|
| 1097 |
# هو تقدّم FFmpeg نفسه (out_time)، لأن لا مصدر بايتات ثانٍ نقيسه.
|
| 1098 |
p = subprocess.Popen(args, stdin=None, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
|
| 1099 |
else:
|
| 1100 |
+
try:
|
| 1101 |
+
response = requests.get(candidate['url'],
|
| 1102 |
+
headers=source_http_headers(candidate.get('url'),user,self.headers_for),
|
| 1103 |
+
impersonate='chrome', stream=True,
|
| 1104 |
+
timeout=(10, read_timeout))
|
| 1105 |
+
response.raise_for_status()
|
| 1106 |
+
except Exception as e:
|
| 1107 |
+
telemetry_event(tele_key,user,'SOURCE_OPEN_ERROR',{
|
| 1108 |
+
'stage':'initial_open','error_type':type(e).__name__,
|
| 1109 |
+
'http_status':http_status_from_exception(e)})
|
| 1110 |
+
raise
|
| 1111 |
p = subprocess.Popen(args, stdin=subprocess.PIPE, stdout=subprocess.PIPE,
|
| 1112 |
stderr=subprocess.PIPE, bufsize=0)
|
| 1113 |
sess['spawned'] = True
|
| 1114 |
sess['spawned_at'] = time.monotonic()
|
| 1115 |
+
if destination.startswith(('rtmp://','rtmps://')):
|
| 1116 |
+
note_rtmp_open(user,{'mode':self.active_mode or self.send_mode(),
|
| 1117 |
+
'codec':'h265' if self.hevc_payload(candidate) else 'h264'})
|
| 1118 |
+
telemetry_event(tele_key,user,'RTMP_OPEN',{
|
| 1119 |
+
'mode':self.active_mode or self.send_mode(),
|
| 1120 |
+
'codec':'h265' if self.hevc_payload(candidate) else 'h264'})
|
| 1121 |
with self.lock:
|
| 1122 |
self.process = p
|
| 1123 |
+
self.log(user, '[RELAY] بدء FFmpeg ← %s (%s؛ mode=%s)' % (candidate['label'],
|
| 1124 |
'إعلان Enhanced-RTMP: hvc1' if '-rtmp_enhanced_codecs' in ' '.join(args)
|
| 1125 |
+
else 'FLV تقليدي: لا إعلان hvc1', self.active_mode or 'unknown')) # لا إعادة ترميز في هذا الوضع: انقطاع copy لا يترك عملية ورائها
|
| 1126 |
|
| 1127 |
def read_errors():
|
| 1128 |
# يصنّف أخطاء FFmpeg المختارة؛ لا يُسرّب stderr خامًا ولا روابط البث — الذيل
|
|
|
|
| 1130 |
try:
|
| 1131 |
for line in iter(p.stderr.readline, b''):
|
| 1132 |
text = line.decode('utf-8', 'replace')
|
| 1133 |
+
low = text.lower()
|
| 1134 |
+
if 'handshak' in low:
|
| 1135 |
+
self.set(rtmp_phase='handshake')
|
| 1136 |
+
elif 'fcpublish stream' in low or 'sending publish command' in low:
|
| 1137 |
+
self.set(rtmp_phase='publish')
|
| 1138 |
+
elif 'netstream.publish.start' in low or 'publishing stream at bitrates' in low:
|
| 1139 |
+
self.set(rtmp_phase='accepted')
|
| 1140 |
+
if ffmpeg_output_failure(text):
|
| 1141 |
+
sess['output_failure'] = True
|
| 1142 |
+
self.last_failure_side = 'output'
|
| 1143 |
label = classify_ffmpeg_error(text)
|
| 1144 |
if label and label not in diagnostics:
|
| 1145 |
diagnostics.append(label)
|
|
|
|
| 1161 |
def read_progress():
|
| 1162 |
try:
|
| 1163 |
for line in iter(p.stdout.readline, b''):
|
| 1164 |
+
if b'=' in line:
|
| 1165 |
+
raw_name, raw_value = line.split(b'=', 1)
|
| 1166 |
+
name = raw_name.decode('ascii', 'ignore').strip()
|
| 1167 |
+
value = raw_value.decode('ascii', 'ignore').strip()
|
| 1168 |
+
# The same progress stream FFmpeg already emits is
|
| 1169 |
+
# parsed for diagnostics; no extra probe/process is
|
| 1170 |
+
# introduced and telemetry only updates memory here.
|
| 1171 |
+
try:
|
| 1172 |
+
if name == 'frame': tele_fields['ffmpeg_frame'] = int(value)
|
| 1173 |
+
elif name == 'fps': tele_fields['ffmpeg_fps'] = float(value)
|
| 1174 |
+
elif name == 'bitrate' and value not in ('', 'N/A'):
|
| 1175 |
+
tele_fields['ffmpeg_bitrate_kbps'] = float(value.split('kbits/s', 1)[0])
|
| 1176 |
+
elif name == 'total_size': tele_fields['ffmpeg_total_size'] = int(value)
|
| 1177 |
+
elif name == 'dup_frames': tele_fields['ffmpeg_dup_frames'] = int(value)
|
| 1178 |
+
elif name == 'drop_frames': tele_fields['ffmpeg_drop_frames'] = int(value)
|
| 1179 |
+
elif name == 'speed' and value not in ('', 'N/A'):
|
| 1180 |
+
tele_fields['ffmpeg_speed'] = float(value.rstrip('x'))
|
| 1181 |
+
if tele_fields['ffmpeg_speed'] < 0.90:
|
| 1182 |
+
if not progress.get('slow_since'):
|
| 1183 |
+
progress['slow_since'] = time.monotonic()
|
| 1184 |
+
elif tele_fields['ffmpeg_speed'] >= 0.95:
|
| 1185 |
+
progress['slow_since'] = None
|
| 1186 |
+
elif name == 'progress':
|
| 1187 |
+
snapshot = dict(tele_fields)
|
| 1188 |
+
snapshot['output_seconds'] = max(0.0, progress['seconds'])
|
| 1189 |
+
telemetry_observe(tele_key, snapshot)
|
| 1190 |
+
except (TypeError, ValueError):
|
| 1191 |
+
pass
|
| 1192 |
if line.startswith(b'out_time_us='):
|
| 1193 |
try:
|
| 1194 |
seconds = int(line.split(b'=', 1)[1]) / 1000000
|
|
|
|
| 1217 |
threading.Thread(target=read_progress, daemon=True).start()
|
| 1218 |
pump = None
|
| 1219 |
if response is not None:
|
| 1220 |
+
sess['pump_cancel'] = threading.Event()
|
| 1221 |
pump = threading.Thread(target=self._pump_source,
|
| 1222 |
+
args=(response, p, bridge, stop, sess, read_timeout, retries, sess['pump_cancel']),
|
| 1223 |
daemon=True)
|
| 1224 |
pump.start()
|
| 1225 |
+
# ---- حشو الفجوات: صورة مجمّدة بدل صمتٍ تقفل بعده حافة يوتيوب النشر ----
|
| 1226 |
+
# صمت المصدر 13-30 ث كان يقتل جلسة سليمة ثم نصطدم بإعادة نشر مرفوضة.
|
| 1227 |
+
# الحشو يُبقي الخطّ الزمني والوصلة حيّين حتى يعود المصدر فيُخاط في نفس
|
| 1228 |
+
# الاتصال (انحياز الجسر)، بسقف زمني بعده يتصرّف الحارس كصمت مصدر عادي.
|
| 1229 |
+
fill_state={'started':None,'emitted':0,'last_emit':0.0}
|
| 1230 |
+
try:fill_after=max(0.5,float(os.getenv('YOUTUBE_FILL_AFTER_SECONDS','2')))
|
| 1231 |
+
except (TypeError,ValueError):fill_after=2.0
|
| 1232 |
+
try:fill_max=max(0.0,float(os.getenv('YOUTUBE_FILL_MAX_SECONDS','90')))
|
| 1233 |
+
except (TypeError,ValueError):fill_max=90.0
|
| 1234 |
+
try:fill_step=max(250,int(os.getenv('YOUTUBE_FILL_STEP_MS','2000')))
|
| 1235 |
+
except (TypeError,ValueError):fill_step=2000
|
| 1236 |
+
def fill_loop():
|
| 1237 |
+
try:
|
| 1238 |
+
while not stop.is_set():
|
| 1239 |
+
time.sleep(0.5)
|
| 1240 |
+
if p is None or p.poll() is not None or p.stdin is None or sess.get('force_stop'):
|
| 1241 |
+
return
|
| 1242 |
+
now_f=time.monotonic()
|
| 1243 |
+
silent_for=now_f-float(sess.get('last') or now_f)
|
| 1244 |
+
if silent_for<fill_after:
|
| 1245 |
+
if fill_state['started'] is not None:
|
| 1246 |
+
filled_for=now_f-fill_state['started']
|
| 1247 |
+
self.log(user,'[FILL] عاد المصدر بعد %.0f ث حشو (%d إطارًا مجمّدًا)؛ الاستئناف في نفس اتصال يوتيوب بلا إعادة نشر'%(filled_for,fill_state['emitted']))
|
| 1248 |
+
log_event(user,'GAP_FILL_END',{'filled_seconds':round(filled_for,1),'frames':fill_state['emitted']})
|
| 1249 |
+
telemetry_event(tele_key,user,'GAP_FILL_END',{'filled_seconds':round(filled_for,1),'frames':fill_state['emitted']})
|
| 1250 |
+
fill_state['started']=None;fill_state['emitted']=0
|
| 1251 |
+
sess['filling']=False
|
| 1252 |
+
continue
|
| 1253 |
+
if not fill_max or bridge._last_keyframe_tag is None:
|
| 1254 |
+
sess['filling']=False;continue
|
| 1255 |
+
if fill_state['started'] is None:
|
| 1256 |
+
fill_state['started']=now_f;fill_state['last_emit']=0.0
|
| 1257 |
+
self.log(user,'[FILL] صمت المصدر %.0f ث؛ حشو بإطار مجمّد حتى لا يرى يوتيوب فجوة (سقف %.0f ث)'%(silent_for,fill_max))
|
| 1258 |
+
log_event(user,'GAP_FILL_START',{'silent_seconds':round(silent_for,1),'cap_seconds':fill_max})
|
| 1259 |
+
telemetry_event(tele_key,user,'GAP_FILL_START',{'silent_seconds':round(silent_for,1),'cap_seconds':fill_max})
|
| 1260 |
+
if now_f-fill_state['started']>fill_max:
|
| 1261 |
+
sess['filling']=False;continue
|
| 1262 |
+
sess['filling']=True;sess['filling_at']=now_f
|
| 1263 |
+
if now_f-fill_state['last_emit']<fill_step/1000.0*0.95:continue
|
| 1264 |
+
data=bridge.freeze_bytes(fill_step)
|
| 1265 |
+
if not data:continue
|
| 1266 |
+
try:
|
| 1267 |
+
with sess['stdin_lock']:
|
| 1268 |
+
if time.monotonic()-float(sess.get('last') or 0)<fill_after:continue
|
| 1269 |
+
view=memoryview(data)
|
| 1270 |
+
while view:
|
| 1271 |
+
n=p.stdin.write(view)
|
| 1272 |
+
if not n:raise BrokenPipeError()
|
| 1273 |
+
view=view[n:]
|
| 1274 |
+
except (BrokenPipeError,OSError,ValueError):
|
| 1275 |
+
return
|
| 1276 |
+
fill_state['emitted']+=1;fill_state['last_emit']=time.monotonic()
|
| 1277 |
+
except Exception:
|
| 1278 |
+
sess['filling']=False
|
| 1279 |
+
return
|
| 1280 |
+
filler=None
|
| 1281 |
+
if response is not None:
|
| 1282 |
+
filler=threading.Thread(target=fill_loop,daemon=True);filler.start()
|
| 1283 |
# ---- الحارس: لا تعتمد على poll() ولا على رمز الخروج ----
|
| 1284 |
stall_limit = self._stall_seconds()
|
| 1285 |
progress_limit = max(30.0, float(os.getenv('YOUTUBE_PROGRESS_STALL_SECONDS', '60')))
|
| 1286 |
next_report = 0.0
|
| 1287 |
while not stop.is_set():
|
| 1288 |
+
if self.pending_sticky and self.apply_pending_sticky(user):
|
| 1289 |
+
break
|
| 1290 |
now = time.monotonic()
|
| 1291 |
# الدليل على أن المصدر لم يصمت هو بايتات تيك توك نفسها. تقدّم FFmpeg وحده لا
|
| 1292 |
# يكفي: في وضع النسخ يفرّغ المخزن الداخلي لدقائق بعد صمت المصدر، فيبدو البث
|
|
|
|
| 1294 |
# في HLS يستحيل القياس إلا على FFmpeg (هو من يفتح القائمة)، فنقبل تقدّمه.
|
| 1295 |
_fresh = (sess['ff_last'] if response is None else sess['last'])
|
| 1296 |
swap_for = (now - float(sess.get('swap_started') or 0)) if sess.get('swapping') else 0.0
|
| 1297 |
+
# Give a newly opened HTTP source time to deliver its first actual bytes.
|
| 1298 |
+
# Do not alter sess['last']: source age remains honest while we wait.
|
| 1299 |
+
recent_attach = now < float(sess.get('reattach_not_before') or 0)
|
| 1300 |
+
tried_reattach = False
|
| 1301 |
+
source_done = response is not None and (sess.get('ended') or sess.get('error') or
|
| 1302 |
+
(pump is not None and not pump.is_alive()))
|
| 1303 |
+
if (source_done and not recent_attach and not sess.get('force_stop')
|
| 1304 |
+
and not sess.get('writing') and not sess.get('output_failure')):
|
| 1305 |
+
tried_reattach = True
|
| 1306 |
+
attached = self._try_reattach(user, p, bridge, sess, stop, refresh,
|
| 1307 |
+
read_timeout, retries, response, pump)
|
| 1308 |
+
if attached:
|
| 1309 |
+
response, pump = attached
|
| 1310 |
+
continue
|
| 1311 |
# swapping must not disable the stall watchdog for longer than the stall
|
| 1312 |
# limit: refresh()+HTTP open was measured at 40–57s of frozen viewers.
|
| 1313 |
if self._recovering_copy:
|
|
|
|
| 1318 |
self.log(user,'[RECOVERY] COPY produced no output in %.0fs; staying on %s (fail %d)'%(
|
| 1319 |
ran, self.sticky_mode or 'light', self.copy_recovery_fails))
|
| 1320 |
raise SourceStalled('COPY recovery produced no output; reverting to light')
|
| 1321 |
+
try:verify_seconds=max(5.0,float(os.getenv('YOUTUBE_COPY_RECOVERY_VERIFY_SECONDS','15')))
|
| 1322 |
+
except (TypeError,ValueError):verify_seconds=15.0
|
| 1323 |
+
if progress['seconds']>=verify_seconds:
|
| 1324 |
self.log(user,'[RECOVERY] COPY output verified (%.1fs); leaving light sticky'%progress['seconds'])
|
| 1325 |
self.sticky_mode=None
|
| 1326 |
self.sticky_since=0.0
|
| 1327 |
self._recovering_copy=False
|
| 1328 |
+
self.copy_recovery_fails=0
|
| 1329 |
+
try:
|
| 1330 |
+
from ingest import hub
|
| 1331 |
+
hub.release_light(user)
|
| 1332 |
+
except Exception:
|
| 1333 |
+
pass
|
| 1334 |
+
# The journal copy of the mode is the one that used to
|
| 1335 |
+
# resurrect the transcode on every later FFmpeg. A
|
| 1336 |
+
# verified probe must clear it there too.
|
| 1337 |
+
cb=getattr(self,'on_sticky_clear',None)
|
| 1338 |
+
if cb:
|
| 1339 |
+
try:cb(user)
|
| 1340 |
+
except Exception as e:self.log(user,'[RECOVERY] could not clear persisted mode: '+str(e)[:80])
|
| 1341 |
+
log_event(user,'COPY_RECOVERY',{'mode':'copy','verified_seconds':round(progress['seconds'],1)})
|
| 1342 |
+
telemetry_event(tele_key,user,'COPY_RECOVERY',{'verified_seconds':round(progress['seconds'],1)})
|
| 1343 |
+
# Governor: a transcode that cannot keep real time is the
|
| 1344 |
+
# bottleneck itself (measured: HEVC 960x1920 in matchgop on
|
| 1345 |
+
# cpu-basic -> CPU saturation -> YouTube starved). End this
|
| 1346 |
+
# publisher and let the next one probe byte copy instead of
|
| 1347 |
+
# burning the whole event behind a falling-behind encoder.
|
| 1348 |
+
if (self.active_mode not in ('','copy') and progress.get('slow_since')
|
| 1349 |
+
and progress['seconds'] >= 20 and not sess.get('governor_switch')
|
| 1350 |
+
and not getattr(self,'sticky_operator_locked',False)
|
| 1351 |
+
and self._copy_supported(self.current_candidate)):
|
| 1352 |
+
try:slow_for=max(10.0,float(os.getenv('YOUTUBE_TRANSCODE_SLOW_SECONDS','30')))
|
| 1353 |
+
except (TypeError,ValueError):slow_for=30.0
|
| 1354 |
+
if now-float(progress['slow_since'])>=slow_for:
|
| 1355 |
+
sess['governor_switch']='copy_probe'
|
| 1356 |
+
# ترميز يخنق البث أخطر من GOP مضطرب: الحاكم يملك وحده مسح قفل الصيغة
|
| 1357 |
+
self.format_unstable=False
|
| 1358 |
+
self.sticky_since=min(float(self.sticky_since or now),now-3600.0)
|
| 1359 |
+
self.log(user,'[GOVERNOR] الترميز أبطأ من الزمن الحقيقي %.0f ث — إنهاء هذا الناشر وفحص COPY بدل استمرار ترميز خاسر'%slow_for)
|
| 1360 |
+
log_event(user,'TRANSCODE_TOO_SLOW',{'mode':self.active_mode,'slow_seconds':round(slow_for,1),
|
| 1361 |
+
'output_seconds':round(progress['seconds'],1)})
|
| 1362 |
+
telemetry_event(tele_key,user,'TRANSCODE_TOO_SLOW',{'mode':self.active_mode,
|
| 1363 |
+
'slow_seconds':round(slow_for,1),'output_seconds':round(progress['seconds'],1)})
|
| 1364 |
+
break
|
| 1365 |
+
if (stall_limit and now - _fresh > 3 and not recent_attach and not tried_reattach
|
| 1366 |
+
and not sess.get('force_stop')
|
| 1367 |
+
and not sess.get('swapping')
|
| 1368 |
+
and not sess.get('swap_source') and not sess.get('writing')
|
| 1369 |
+
and not sess.get('output_failure')):
|
| 1370 |
+
tried_reattach = True
|
| 1371 |
attached = self._try_reattach(user, p, bridge, sess, stop, refresh,
|
| 1372 |
read_timeout, retries, response, pump)
|
| 1373 |
if attached:
|
| 1374 |
response, pump = attached
|
| 1375 |
continue
|
| 1376 |
+
if (stall_limit and now - _fresh > stall_limit and
|
| 1377 |
+
(not recent_attach or sess.get('output_failure') or sess.get('writing')) and
|
| 1378 |
+
not (sess.get('filling') and now-float(sess.get('filling_at') or 0)<10) and
|
| 1379 |
+
(not sess.get('swapping') or swap_for > stall_limit)):
|
| 1380 |
+
# A full stdin pipe proves the source delivered a chunk but FFmpeg stopped
|
| 1381 |
+
# consuming it. Reopening TikTok cannot repair a blocked RTMPS output.
|
| 1382 |
+
if sess.get('writing') or sess.get('output_failure'):
|
| 1383 |
+
self.last_failure_side = 'output'
|
| 1384 |
+
sess['output_failure'] = True
|
| 1385 |
+
elif not tried_reattach:
|
| 1386 |
+
attached = self._try_reattach(user, p, bridge, sess, stop, refresh,
|
| 1387 |
+
read_timeout, retries, response, pump)
|
| 1388 |
+
if attached:
|
| 1389 |
+
response, pump = attached
|
| 1390 |
+
continue
|
| 1391 |
# نُفيق الخيط أولًا (قد يكون محبوسًا في write على أنبوب ممتلئ)، ثم نرفع:
|
| 1392 |
# إغلاق stdin يجعل FFmpeg يرى EOF ويتوقف بلطف بدل SIGKILL.
|
| 1393 |
sess['force_stop'] = True
|
|
|
|
| 1396 |
p.stdin.close()
|
| 1397 |
except (OSError, ValueError):
|
| 1398 |
pass
|
| 1399 |
+
if sess.get('output_failure'):
|
| 1400 |
+
raise SourceStalled('توقف FFmpeg عن استهلاك المصدر لأن خرج RTMPS عالق منذ %.0f ث'
|
| 1401 |
+
% (now - _fresh))
|
| 1402 |
+
self.last_failure_side = 'source'
|
| 1403 |
raise SourceStalled('انقطع تدفق المصدر منذ %.0f ث (FFmpeg ما زال حيًا، '
|
| 1404 |
'ويوتيوب يبقى على آخر ثانية وصلته)' % (now - _fresh))
|
| 1405 |
rc = p.poll()
|
| 1406 |
if rc is not None:
|
|
|
|
|
|
|
| 1407 |
if not sess['ended'] and not stop.is_set() and rc:
|
| 1408 |
gap = max(0.0, time.monotonic() - sess['last']) if sess.get('src_metered') else 0.0
|
| 1409 |
suspect = float(os.getenv('YOUTUBE_SOURCE_GAP_SUSPECT_SECONDS', '8'))
|
|
|
|
| 1418 |
break
|
| 1419 |
if now - progress['last'] > progress_limit:
|
| 1420 |
raise SourceStalled('لم يتقدّم FFmpeg منذ %.0f ث' % (now - progress['last']))
|
| 1421 |
+
if sess['ended'] and not sess['error'] and not recent_attach:
|
| 1422 |
self.log(user, '[MONITOR] أغلق تيك توك الاستجابة؛ الجلسة تُعاد من جديد')
|
| 1423 |
break
|
| 1424 |
+
if sess['error'] and not recent_attach:
|
| 1425 |
raise SourceStalled(sess['error'])
|
| 1426 |
if response is not None and now >= next_report:
|
| 1427 |
# بمعدل مضبوط: لا logging لكل بايت (كان سيملأ السجل في دقائق).
|
|
|
|
| 1429 |
self.log(user, '[WATCHDOG] المصدر يعمل؛ آخر بايت قبل %.0f ث، خرج %.1f ث'
|
| 1430 |
% (now - sess['last'], max(0, progress['seconds'])))
|
| 1431 |
if pump is not None and not pump.is_alive() and response is not None and not stop.is_set():
|
| 1432 |
+
if sess['force_stop'] or ((sess['error'] or sess['ended']) and not recent_attach):
|
| 1433 |
break
|
| 1434 |
+
if now - tele_last_observe >= 15.0:
|
| 1435 |
+
elapsed_tele = max(0.001, now - tele_last_observe)
|
| 1436 |
+
snap_tele = self.snapshot()
|
| 1437 |
+
current_bytes = float(snap_tele.get('source_bytes') or 0)
|
| 1438 |
+
tele_sample = {
|
| 1439 |
+
'output_seconds': max(0.0, progress['seconds']),
|
| 1440 |
+
'source_age_seconds': max(0.0, now - sess['last']),
|
| 1441 |
+
'source_bytes_total': current_bytes,
|
| 1442 |
+
'mode': self.active_mode or self.send_mode(),
|
| 1443 |
+
}
|
| 1444 |
+
if sess.get('src_metered'):
|
| 1445 |
+
tele_sample['source_bps'] = max(
|
| 1446 |
+
0.0, (current_bytes - tele_last_source_bytes) * 8.0 / elapsed_tele)
|
| 1447 |
+
telemetry_observe(tele_key, tele_sample)
|
| 1448 |
+
tele_last_source_bytes = current_bytes
|
| 1449 |
+
tele_last_observe = now
|
| 1450 |
+
if now - tele_last_checkpoint >= 60.0:
|
| 1451 |
+
telemetry_checkpoint(tele_key, 'periodic')
|
| 1452 |
+
tele_last_checkpoint = now
|
| 1453 |
time.sleep(1)
|
| 1454 |
except (OSError, ValueError) as e:
|
| 1455 |
if p is None:
|
| 1456 |
sess['spawn_error'] = 'تعذر بدء FFmpeg/المصدر (%s)' % type(e).__name__
|
| 1457 |
self.log(user, '[RELAY] فشل بدء الإرسال: %s' % sess['spawn_error'])
|
| 1458 |
+
log_event(user,'CONNECTION_ERROR',{'scope':self.last_failure_side or 'startup',
|
| 1459 |
+
'error_type':type(e).__name__,'stage':'open'});sess['connection_event']=True
|
| 1460 |
+
telemetry_event(tele_key,user,'SESSION_FAILURE',{
|
| 1461 |
+
'scope':self.last_failure_side or 'startup','stage':'open',
|
| 1462 |
+
'error_type':type(e).__name__})
|
| 1463 |
raise
|
| 1464 |
except SourceStalled as e:
|
| 1465 |
sess['stall_reason'] = str(e)
|
| 1466 |
+
if not self.last_failure_side:
|
| 1467 |
+
self.last_failure_side = 'source'
|
| 1468 |
+
log_event(user,'CONNECTION_ERROR',{'scope':self.last_failure_side,
|
| 1469 |
+
'error_type':type(e).__name__,'reason':str(e)[:300]});sess['connection_event']=True
|
| 1470 |
+
telemetry_event(tele_key,user,'SESSION_FAILURE',{
|
| 1471 |
+
'scope':self.last_failure_side,'stage':'watchdog',
|
| 1472 |
+
'error_type':type(e).__name__,'reason':str(e)[:300]})
|
| 1473 |
+
tag = 'خرج الإرسال' if self.last_failure_side == 'output' else 'المصدر'
|
| 1474 |
+
self.log(user, '[WATCHDOG] توقف %s: %s' % (tag, e))
|
| 1475 |
raise
|
| 1476 |
finally:
|
| 1477 |
done.set()
|
|
|
|
| 1485 |
with self.lock:
|
| 1486 |
self.session = None
|
| 1487 |
self.set(status='', stalled=False, note='لم يبدأ FFmpeg أصلًا')
|
| 1488 |
+
tele_finish('start_failed',{'spawn_error':sess.get('spawn_error') or '',
|
| 1489 |
+
'source_bytes':self.data.get('source_bytes',0),
|
| 1490 |
+
'mode':self.active_mode or ''})
|
| 1491 |
raise RelayStartError(sess.get('spawn_error') or 'تعذر بدء جلسة الإرسال')
|
| 1492 |
+
_why = self._close_reason(sess,p)
|
| 1493 |
+
if self.last_failure_side=='output' and not sess.get('connection_event'):
|
| 1494 |
+
log_event(user,'CONNECTION_ERROR',{'scope':'youtube_rtmp','reason':_why[:300],
|
| 1495 |
+
'ffmpeg_exit_code':p.poll()});sess['connection_event']=True
|
| 1496 |
+
if destination.startswith(('rtmp://','rtmps://')) and progress['seconds'] <= 0:
|
| 1497 |
+
self.log(user, '[RTMP] لم يصل أول إطار؛ مرحلة=%s؛ دخل=%d بايت؛ pipe_busy=%s' %
|
| 1498 |
+
(self.data.get('rtmp_phase') or 'opening', self.data.get('source_bytes',0), bool(sess.get('writing'))))
|
| 1499 |
+
for line in self.last_errors[-8:]:
|
| 1500 |
+
self.log(user, '[RTMP] ' + redact_stderr(line))
|
| 1501 |
self._teardown(user, p, response, sess, stop, _why)
|
| 1502 |
if error_reader:
|
| 1503 |
error_reader.join(timeout=1)
|
|
|
|
| 1505 |
# مهلة قصيرة عمدًا: الخيط قد يكون محبوسًا في next() على مقبس مُغلق؛ لا معنى
|
| 1506 |
# لتعليق الإشراف كله لأجله — FFmpeg أُقرِت والطرف القارئ أُغلق.
|
| 1507 |
pump.join(timeout=float(os.getenv('YOUTUBE_PUMP_JOIN_SECONDS', '2')))
|
| 1508 |
+
if filler:
|
| 1509 |
+
filler.join(timeout=1)
|
| 1510 |
if pump.is_alive():
|
| 1511 |
sess['orphan'] = True
|
| 1512 |
self.log(user, '[CLEANUP] ⚠ خيط القراءة ما زال يعمل؛ سيُترك كـ daemon ويُعاد الرصد')
|
| 1513 |
with self.lock:
|
| 1514 |
self.session = None
|
| 1515 |
+
tele_finish(_why or sess.get('error') or 'session_ended',{
|
| 1516 |
+
'ffmpeg_exit_code':p.poll(),'output_seconds':round(max(0.0,progress['seconds']),3),
|
| 1517 |
+
'source_bytes':self.data.get('source_bytes',0),
|
| 1518 |
+
'last_failure_side':self.last_failure_side or '',
|
| 1519 |
+
'mode':self.active_mode or '','orphan':bool(sess.get('orphan'))})
|
| 1520 |
if sess['orphan']:
|
| 1521 |
raise RuntimeError('بقيت عملية/خيط من جلسة سابقة؛ تُراجع قبل جلسة جديدة')
|
| 1522 |
return progress['seconds'] > 0
|
requirements.txt
CHANGED
|
@@ -1,3 +1,5 @@
|
|
| 1 |
-
|
| 2 |
-
|
| 3 |
-
|
|
|
|
|
|
|
|
|
| 1 |
+
# Direct runtime dependencies are pinned so a rebuild does not silently change the relay.
|
| 2 |
+
fastapi==0.142.2
|
| 3 |
+
uvicorn==0.54.0
|
| 4 |
+
curl_cffi==0.16.3
|
| 5 |
+
pydantic==2.13.5
|
stream_monitor.py
ADDED
|
@@ -0,0 +1,220 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Persistent, bounded diagnostics for byte-copy live streams.
|
| 2 |
+
|
| 3 |
+
Events are operational metadata only: no media, URLs, stream keys, cookies, or
|
| 4 |
+
encoded payloads are written. The JSON array lives under DATA_DIR/logs, appends
|
| 5 |
+
one compact object per event, and is periodically compacted with atomic replace.
|
| 6 |
+
"""
|
| 7 |
+
import json
|
| 8 |
+
import os
|
| 9 |
+
import re
|
| 10 |
+
import threading
|
| 11 |
+
from datetime import datetime, timezone
|
| 12 |
+
from pathlib import Path
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
class _Bits:
|
| 16 |
+
def __init__(self,data):
|
| 17 |
+
self.data=data;self.bit=0
|
| 18 |
+
def read(self,n):
|
| 19 |
+
if n<0 or self.bit+n>len(self.data)*8:raise ValueError('truncated bitstream')
|
| 20 |
+
value=0
|
| 21 |
+
for _ in range(n):
|
| 22 |
+
value=(value<<1)|((self.data[self.bit>>3]>>(7-(self.bit&7)))&1);self.bit+=1
|
| 23 |
+
return value
|
| 24 |
+
def ue(self):
|
| 25 |
+
zeros=0
|
| 26 |
+
while self.read(1)==0:
|
| 27 |
+
zeros+=1
|
| 28 |
+
if zeros>31:raise ValueError('invalid Exp-Golomb value')
|
| 29 |
+
return (1<<zeros)-1+(self.read(zeros) if zeros else 0)
|
| 30 |
+
def se(self):
|
| 31 |
+
value=self.ue()
|
| 32 |
+
return (value+1)//2 if value&1 else -(value//2)
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def _rbsp(nal):
|
| 36 |
+
out=bytearray();zeros=0
|
| 37 |
+
for byte in nal:
|
| 38 |
+
if zeros>=2 and byte==3:
|
| 39 |
+
zeros=0;continue
|
| 40 |
+
out.append(byte)
|
| 41 |
+
zeros=zeros+1 if byte==0 else 0
|
| 42 |
+
return bytes(out)
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def _skip_h264_scaling(bits,size):
|
| 46 |
+
last=next_scale=8
|
| 47 |
+
for j in range(size):
|
| 48 |
+
if next_scale:
|
| 49 |
+
next_scale=(last+bits.se()+256)%256
|
| 50 |
+
last=next_scale or last
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def _h264_sps_size(nal):
|
| 54 |
+
data=_rbsp(nal[1:]);b=_Bits(data)
|
| 55 |
+
profile=b.read(8);b.read(8);b.read(8);b.ue()
|
| 56 |
+
chroma=1;separate=0
|
| 57 |
+
if profile in (44,83,86,100,110,118,122,128,138,139,134,135,144,244):
|
| 58 |
+
chroma=b.ue()
|
| 59 |
+
if chroma==3:separate=b.read(1)
|
| 60 |
+
b.ue();b.ue();b.read(1)
|
| 61 |
+
if b.read(1):
|
| 62 |
+
for i in range(8 if chroma!=3 else 12):
|
| 63 |
+
if b.read(1):_skip_h264_scaling(b,16 if i<6 else 64)
|
| 64 |
+
b.ue();poc=b.ue()
|
| 65 |
+
if poc==0:b.ue()
|
| 66 |
+
elif poc==1:
|
| 67 |
+
b.read(1);b.se();b.se()
|
| 68 |
+
for _ in range(b.ue()):b.se()
|
| 69 |
+
b.ue();b.read(1)
|
| 70 |
+
width_mbs=b.ue()+1;height_maps=b.ue()+1
|
| 71 |
+
frame_only=b.read(1)
|
| 72 |
+
if not frame_only:b.read(1)
|
| 73 |
+
b.read(1)
|
| 74 |
+
crop=(0,0,0,0)
|
| 75 |
+
if b.read(1):crop=tuple(b.ue() for _ in range(4))
|
| 76 |
+
chroma_array=0 if separate else chroma
|
| 77 |
+
sub_w=(1,2,2,1)[chroma_array];sub_h=(1,2,1,1)[chroma_array]
|
| 78 |
+
unit_x=1 if chroma_array==0 else sub_w
|
| 79 |
+
unit_y=(2-frame_only)*(1 if chroma_array==0 else sub_h)
|
| 80 |
+
width=width_mbs*16-(crop[0]+crop[1])*unit_x
|
| 81 |
+
height=(2-frame_only)*height_maps*16-(crop[2]+crop[3])*unit_y
|
| 82 |
+
return (width,height) if width>0 and height>0 else None
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
def _hevc_profile_tier_level(bits,max_sub_layers):
|
| 86 |
+
bits.read(96)
|
| 87 |
+
profiles=[];levels=[]
|
| 88 |
+
for _ in range(max_sub_layers):profiles.append(bits.read(1));levels.append(bits.read(1))
|
| 89 |
+
if max_sub_layers:
|
| 90 |
+
for _ in range(max_sub_layers,8):bits.read(2)
|
| 91 |
+
for profile,level in zip(profiles,levels):
|
| 92 |
+
if profile:bits.read(88)
|
| 93 |
+
if level:bits.read(8)
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
def _hevc_sps_size(nal):
|
| 97 |
+
data=_rbsp(nal[2:]);b=_Bits(data)
|
| 98 |
+
b.read(4);max_sub=b.read(3);b.read(1)
|
| 99 |
+
_hevc_profile_tier_level(b,max_sub)
|
| 100 |
+
b.ue();chroma=b.ue()
|
| 101 |
+
separate=b.read(1) if chroma==3 else 0
|
| 102 |
+
width=b.ue();height=b.ue();crop=(0,0,0,0)
|
| 103 |
+
if b.read(1):crop=tuple(b.ue() for _ in range(4))
|
| 104 |
+
chroma_array=0 if separate else chroma
|
| 105 |
+
sub_w=(1,2,2,1)[chroma_array];sub_h=(1,2,1,1)[chroma_array]
|
| 106 |
+
width-=(crop[0]+crop[1])*sub_w;height-=(crop[2]+crop[3])*sub_h
|
| 107 |
+
return (width,height) if width>0 and height>0 else None
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
def video_dimensions(codec,config):
|
| 111 |
+
"""Read coded width/height from avcC or hvcC; malformed records return None."""
|
| 112 |
+
try:
|
| 113 |
+
if codec=='avc1':
|
| 114 |
+
if len(config)<7:return None
|
| 115 |
+
count=config[5]&31;offset=6
|
| 116 |
+
for _ in range(count):
|
| 117 |
+
size=int.from_bytes(config[offset:offset+2],'big');offset+=2
|
| 118 |
+
nal=config[offset:offset+size];offset+=size
|
| 119 |
+
if nal and nal[0]&31==7:return _h264_sps_size(nal)
|
| 120 |
+
return None
|
| 121 |
+
if codec=='hvc1':
|
| 122 |
+
if len(config)<23:return None
|
| 123 |
+
offset=23
|
| 124 |
+
for _ in range(config[22]):
|
| 125 |
+
nal_type=config[offset]&63;count=int.from_bytes(config[offset+1:offset+3],'big');offset+=3
|
| 126 |
+
for _ in range(count):
|
| 127 |
+
size=int.from_bytes(config[offset:offset+2],'big');offset+=2
|
| 128 |
+
nal=config[offset:offset+size];offset+=size
|
| 129 |
+
if nal_type==33:return _hevc_sps_size(nal)
|
| 130 |
+
except (IndexError,ValueError):
|
| 131 |
+
return None
|
| 132 |
+
return None
|
| 133 |
+
|
| 134 |
+
|
| 135 |
+
class StreamMonitor:
|
| 136 |
+
def __init__(self,path=None):
|
| 137 |
+
root=os.getenv('DATA_DIR') or ('/data/tiktok-relay' if Path('/data').is_dir() else './storage')
|
| 138 |
+
base=Path(root)
|
| 139 |
+
self.path=Path(path or os.getenv('STREAM_EVENTS_PATH') or base/'logs/stream_events.json')
|
| 140 |
+
try:self.maximum=max(100,min(int(os.getenv('STREAM_EVENT_MAX','10000')),100000))
|
| 141 |
+
except (TypeError,ValueError):self.maximum=10000
|
| 142 |
+
self.lock=threading.RLock();self.events=[];self.sequence=0;self.rtmp_opens={}
|
| 143 |
+
self._load()
|
| 144 |
+
def _load(self):
|
| 145 |
+
try:
|
| 146 |
+
data=json.loads(self.path.read_text())
|
| 147 |
+
if isinstance(data,list):
|
| 148 |
+
self.events=[x for x in data[-self.maximum:] if isinstance(x,dict)]
|
| 149 |
+
self.sequence=max((int(x.get('sequence') or 0) for x in self.events),default=0)
|
| 150 |
+
except (OSError,ValueError,TypeError):
|
| 151 |
+
pass
|
| 152 |
+
@staticmethod
|
| 153 |
+
def _safe(value,depth=0):
|
| 154 |
+
if depth>4:return '…'
|
| 155 |
+
if isinstance(value,dict):
|
| 156 |
+
return {str(k)[:80]:StreamMonitor._safe(v,depth+1) for k,v in value.items()
|
| 157 |
+
if not any(x in str(k).lower() for x in ('url','token','cookie','key','auth'))}
|
| 158 |
+
if isinstance(value,(list,tuple)):return [StreamMonitor._safe(x,depth+1) for x in value[:50]]
|
| 159 |
+
if isinstance(value,str):
|
| 160 |
+
value=re.sub(r'(?i)\b(?:rtmps?|https?)://\S+','«رابط-مخفي»',value)
|
| 161 |
+
value=re.sub(r'(?i)(sessionid|token|stream[_ -]?key|authorization)\s*[=:]\s*[^\s;&]+',
|
| 162 |
+
r'\1=«مخفي»',value)
|
| 163 |
+
return value[:500]
|
| 164 |
+
if isinstance(value,(int,float,bool)) or value is None:return value
|
| 165 |
+
return StreamMonitor._safe(str(value),depth+1)
|
| 166 |
+
def _rewrite(self):
|
| 167 |
+
self.path.parent.mkdir(parents=True,exist_ok=True)
|
| 168 |
+
tmp=self.path.with_name(self.path.name+'.tmp')
|
| 169 |
+
tmp.write_text(json.dumps(self.events,ensure_ascii=False,separators=(',',':')))
|
| 170 |
+
try:os.chmod(tmp,0o600)
|
| 171 |
+
except OSError:pass
|
| 172 |
+
os.replace(tmp,self.path)
|
| 173 |
+
def _append(self,item):
|
| 174 |
+
encoded=json.dumps(item,ensure_ascii=False,separators=(',',':')).encode()
|
| 175 |
+
try:
|
| 176 |
+
with self.path.open('r+b') as fh:
|
| 177 |
+
fh.seek(-1,os.SEEK_END)
|
| 178 |
+
if fh.read(1)!=b']':raise ValueError('invalid JSON tail')
|
| 179 |
+
fh.seek(-1,os.SEEK_END)
|
| 180 |
+
fh.write((b',' if len(self.events)>1 else b'')+encoded+b']');fh.truncate()
|
| 181 |
+
try:os.chmod(self.path,0o600)
|
| 182 |
+
except OSError:pass
|
| 183 |
+
except (OSError,ValueError):
|
| 184 |
+
self._rewrite()
|
| 185 |
+
def log(self,broadcaster,event,details=None):
|
| 186 |
+
try:
|
| 187 |
+
with self.lock:
|
| 188 |
+
self.sequence+=1
|
| 189 |
+
item={'timestamp':datetime.now(timezone.utc).isoformat(timespec='milliseconds').replace('+00:00','Z'),
|
| 190 |
+
'sequence':self.sequence,'broadcaster':str(broadcaster or 'system')[:100],
|
| 191 |
+
'event':str(event or 'UNKNOWN')[:80],'details':self._safe(details or {})}
|
| 192 |
+
self.events.append(item)
|
| 193 |
+
if len(self.events)>self.maximum:
|
| 194 |
+
self.events=self.events[-max(100,int(self.maximum*0.9)):];self._rewrite()
|
| 195 |
+
elif not self.path.exists():self._rewrite()
|
| 196 |
+
else:self._append(item)
|
| 197 |
+
return item
|
| 198 |
+
except (OSError,TypeError,ValueError):
|
| 199 |
+
return None
|
| 200 |
+
def read(self,limit=200,broadcaster=None):
|
| 201 |
+
try:limit=max(1,min(int(limit),2000))
|
| 202 |
+
except (TypeError,ValueError):limit=200
|
| 203 |
+
with self.lock:
|
| 204 |
+
rows=self.events
|
| 205 |
+
if broadcaster:rows=[x for x in rows if x.get('broadcaster')==broadcaster]
|
| 206 |
+
return [dict(x) for x in rows[-limit:]]
|
| 207 |
+
def note_rtmp_open(self,broadcaster,details=None):
|
| 208 |
+
user=str(broadcaster or 'system')
|
| 209 |
+
with self.lock:
|
| 210 |
+
count=self.rtmp_opens.get(user,0)+1;self.rtmp_opens[user]=count
|
| 211 |
+
if count>1:
|
| 212 |
+
merged={'scope':'youtube_rtmp','session_number':count};merged.update(details or {})
|
| 213 |
+
return self.log(user,'RECONNECT',merged)
|
| 214 |
+
return None
|
| 215 |
+
|
| 216 |
+
|
| 217 |
+
monitor=StreamMonitor()
|
| 218 |
+
def log_event(broadcaster,event,details=None):return monitor.log(broadcaster,event,details)
|
| 219 |
+
def read_events(limit=200,broadcaster=None):return monitor.read(limit,broadcaster)
|
| 220 |
+
def note_rtmp_open(broadcaster,details=None):return monitor.note_rtmp_open(broadcaster,details)
|
telemetry.py
ADDED
|
@@ -0,0 +1,589 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Append-only, fail-open production telemetry.
|
| 2 |
+
|
| 3 |
+
This module is deliberately *not* part of the media/control path:
|
| 4 |
+
|
| 5 |
+
* Public calls only update in-memory counters or put a small record on a
|
| 6 |
+
bounded queue. They never write to disk, never wait for I/O, and never raise
|
| 7 |
+
into a relay/manager thread.
|
| 8 |
+
* A single daemon writer appends compact JSON lines. If storage is slow or
|
| 9 |
+
unavailable, telemetry records are dropped and counted; the stream is not.
|
| 10 |
+
* There is intentionally no rotate/truncate/delete API. Records live under the
|
| 11 |
+
persistent data root (``<DATA_ROOT>/telemetry/telemetry.jsonl``) and are
|
| 12 |
+
removed only by an explicit, manual operator action outside this code.
|
| 13 |
+
* No media, signed URLs, stream keys, cookies, tokens, or credentials are
|
| 14 |
+
recorded. Potentially sensitive keys/values are stripped defensively.
|
| 15 |
+
|
| 16 |
+
Set ``TELEMETRY_ENABLED=0`` to disable collection without touching streaming.
|
| 17 |
+
"""
|
| 18 |
+
|
| 19 |
+
import json
|
| 20 |
+
import math
|
| 21 |
+
import os
|
| 22 |
+
import queue
|
| 23 |
+
import re
|
| 24 |
+
import threading
|
| 25 |
+
import time
|
| 26 |
+
from datetime import datetime, timezone
|
| 27 |
+
from pathlib import Path
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
_QUEUE_MAX = 4096
|
| 31 |
+
_SENSITIVE_PARTS = (
|
| 32 |
+
"url", "token", "cookie", "authorization", "sessionid", "password",
|
| 33 |
+
"secret", "stream_key", "rtmp_key", "access_key", "refresh_token",
|
| 34 |
+
)
|
| 35 |
+
_URL_RE = re.compile(r"(?i)\b(?:rtmps?|https?)://\S+")
|
| 36 |
+
_SECRET_ASSIGNMENT_RE = re.compile(
|
| 37 |
+
r"(?i)\b(sessionid|token|stream[_ -]?key|authorization|sign|signature)\s*[=:]\s*[^\s;&]+"
|
| 38 |
+
)
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def _iso_now():
|
| 42 |
+
return datetime.now(timezone.utc).isoformat(timespec="milliseconds").replace("+00:00", "Z")
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def _enabled():
|
| 46 |
+
return str(os.getenv("TELEMETRY_ENABLED", "1")).strip().lower() not in (
|
| 47 |
+
"0", "false", "off", "no", ""
|
| 48 |
+
)
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def _default_path():
|
| 52 |
+
explicit = str(os.getenv("TELEMETRY_PATH", "") or "").strip()
|
| 53 |
+
if explicit:
|
| 54 |
+
return Path(explicit).expanduser()
|
| 55 |
+
|
| 56 |
+
events_path = str(os.getenv("STREAM_EVENTS_PATH", "") or "").strip()
|
| 57 |
+
if events_path:
|
| 58 |
+
events = Path(events_path).expanduser()
|
| 59 |
+
root = events.parent.parent if events.parent.name == "logs" else events.parent
|
| 60 |
+
return root / "telemetry" / "telemetry.jsonl"
|
| 61 |
+
|
| 62 |
+
data_dir = str(os.getenv("DATA_DIR", "") or "").strip()
|
| 63 |
+
if data_dir:
|
| 64 |
+
return Path(data_dir).expanduser() / "telemetry" / "telemetry.jsonl"
|
| 65 |
+
if Path("/data").is_dir():
|
| 66 |
+
return Path("/data/tiktok-relay/telemetry/telemetry.jsonl")
|
| 67 |
+
return Path("./storage/telemetry/telemetry.jsonl")
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
def _safe(value, depth=0):
|
| 71 |
+
if depth > 5:
|
| 72 |
+
return "…"
|
| 73 |
+
if isinstance(value, dict):
|
| 74 |
+
out = {}
|
| 75 |
+
for key, item in list(value.items())[:80]:
|
| 76 |
+
name = str(key)[:80]
|
| 77 |
+
lowered = name.lower()
|
| 78 |
+
if any(part in lowered for part in _SENSITIVE_PARTS):
|
| 79 |
+
continue
|
| 80 |
+
out[name] = _safe(item, depth + 1)
|
| 81 |
+
return out
|
| 82 |
+
if isinstance(value, (list, tuple)):
|
| 83 |
+
return [_safe(item, depth + 1) for item in value[:30]]
|
| 84 |
+
if isinstance(value, str):
|
| 85 |
+
value = _URL_RE.sub("«hidden-url»", value)
|
| 86 |
+
value = _SECRET_ASSIGNMENT_RE.sub(r"\1=«hidden»", value)
|
| 87 |
+
return value[:300]
|
| 88 |
+
if isinstance(value, bool) or value is None:
|
| 89 |
+
return value
|
| 90 |
+
if isinstance(value, (int, float)):
|
| 91 |
+
return value if math.isfinite(float(value)) else None
|
| 92 |
+
return _safe(str(value), depth + 1)
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
def http_status_from_exception(error):
|
| 96 |
+
"""Best-effort HTTP status from curl/httpx/requests-style exceptions."""
|
| 97 |
+
response = getattr(error, "response", None)
|
| 98 |
+
for candidate in (
|
| 99 |
+
getattr(response, "status_code", None),
|
| 100 |
+
getattr(error, "status_code", None),
|
| 101 |
+
getattr(error, "status", None),
|
| 102 |
+
):
|
| 103 |
+
try:
|
| 104 |
+
status = int(candidate)
|
| 105 |
+
except (TypeError, ValueError):
|
| 106 |
+
continue
|
| 107 |
+
if 100 <= status < 600:
|
| 108 |
+
return status
|
| 109 |
+
# curl_cffi sometimes exposes only a rendered message. Accept an explicit
|
| 110 |
+
# HTTP-looking code rather than persisting the exception text or any URL.
|
| 111 |
+
match = re.search(r"\bHTTP(?:/[\d.]+)?\s+([1-5]\d\d)\b", str(error or ""), re.I)
|
| 112 |
+
if match:
|
| 113 |
+
try:
|
| 114 |
+
return int(match.group(1))
|
| 115 |
+
except ValueError:
|
| 116 |
+
return 0
|
| 117 |
+
return 0
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
class _CpuSampler:
|
| 121 |
+
"""Cached cgroup CPU sampler; reads tiny proc files at most every 10s."""
|
| 122 |
+
|
| 123 |
+
def __init__(self):
|
| 124 |
+
self._lock = threading.Lock()
|
| 125 |
+
self._last_at = 0.0
|
| 126 |
+
self._last_usage_seconds = None
|
| 127 |
+
self._cached = {}
|
| 128 |
+
|
| 129 |
+
@staticmethod
|
| 130 |
+
def _read_text(path):
|
| 131 |
+
try:
|
| 132 |
+
return Path(path).read_text(encoding="utf-8", errors="ignore")
|
| 133 |
+
except OSError:
|
| 134 |
+
return ""
|
| 135 |
+
|
| 136 |
+
def _usage_seconds(self):
|
| 137 |
+
text = self._read_text("/sys/fs/cgroup/cpu.stat")
|
| 138 |
+
for line in text.splitlines():
|
| 139 |
+
if line.startswith("usage_usec"):
|
| 140 |
+
try:
|
| 141 |
+
return int(line.split()[1]) / 1_000_000.0
|
| 142 |
+
except (IndexError, ValueError):
|
| 143 |
+
pass
|
| 144 |
+
for path in (
|
| 145 |
+
"/sys/fs/cgroup/cpuacct/cpuacct.usage",
|
| 146 |
+
"/sys/fs/cgroup/cpu,cpuacct/cpuacct.usage",
|
| 147 |
+
):
|
| 148 |
+
text = self._read_text(path).strip()
|
| 149 |
+
if text:
|
| 150 |
+
try:
|
| 151 |
+
return int(text) / 1_000_000_000.0
|
| 152 |
+
except ValueError:
|
| 153 |
+
pass
|
| 154 |
+
return None
|
| 155 |
+
|
| 156 |
+
def _quota_cpus(self):
|
| 157 |
+
text = self._read_text("/sys/fs/cgroup/cpu.max").split()
|
| 158 |
+
if len(text) >= 2 and text[0] != "max":
|
| 159 |
+
try:
|
| 160 |
+
return max(0.01, int(text[0]) / int(text[1]))
|
| 161 |
+
except (ValueError, ZeroDivisionError):
|
| 162 |
+
pass
|
| 163 |
+
try:
|
| 164 |
+
quota = int(self._read_text("/sys/fs/cgroup/cpu/cpu.cfs_quota_us").strip())
|
| 165 |
+
period = int(self._read_text("/sys/fs/cgroup/cpu/cpu.cfs_period_us").strip())
|
| 166 |
+
if quota > 0 and period > 0:
|
| 167 |
+
return quota / period
|
| 168 |
+
except ValueError:
|
| 169 |
+
pass
|
| 170 |
+
return float(os.cpu_count() or 1)
|
| 171 |
+
|
| 172 |
+
def fields(self):
|
| 173 |
+
now = time.monotonic()
|
| 174 |
+
with self._lock:
|
| 175 |
+
if self._cached and now - self._last_at < 10.0:
|
| 176 |
+
return dict(self._cached)
|
| 177 |
+
out = {}
|
| 178 |
+
try:
|
| 179 |
+
out["load1"] = round(float(os.getloadavg()[0]), 3)
|
| 180 |
+
except (AttributeError, OSError, ValueError):
|
| 181 |
+
pass
|
| 182 |
+
usage = self._usage_seconds()
|
| 183 |
+
if usage is not None and self._last_usage_seconds is not None:
|
| 184 |
+
elapsed = now - self._last_at
|
| 185 |
+
if elapsed > 0:
|
| 186 |
+
cores = max(0.0, (usage - self._last_usage_seconds) / elapsed)
|
| 187 |
+
quota = self._quota_cpus()
|
| 188 |
+
out["cpu_cores_used"] = round(cores, 4)
|
| 189 |
+
out["cpu_pct_of_quota"] = round(min(999.0, 100.0 * cores / quota), 2) if quota else None
|
| 190 |
+
if usage is not None:
|
| 191 |
+
self._last_usage_seconds = usage
|
| 192 |
+
# Only advance the timestamp when we actually sampled usage; this
|
| 193 |
+
# also makes the first real interval available about 10s later.
|
| 194 |
+
self._last_at = now
|
| 195 |
+
self._cached = dict(out)
|
| 196 |
+
return out
|
| 197 |
+
|
| 198 |
+
|
| 199 |
+
class Telemetry:
|
| 200 |
+
"""In-memory session aggregation plus a non-blocking append-only writer."""
|
| 201 |
+
|
| 202 |
+
def __init__(self, path=None):
|
| 203 |
+
self.path = Path(path).expanduser() if path else _default_path()
|
| 204 |
+
self.enabled = _enabled()
|
| 205 |
+
self._queue = queue.Queue(maxsize=_QUEUE_MAX) if self.enabled else None
|
| 206 |
+
self._lock = threading.RLock()
|
| 207 |
+
self._writer_lock = threading.Lock()
|
| 208 |
+
self._writer = None
|
| 209 |
+
self._sessions = {}
|
| 210 |
+
self._sequence = 0
|
| 211 |
+
self.dropped_records = 0
|
| 212 |
+
self.write_errors = 0
|
| 213 |
+
self._cpu = _CpuSampler()
|
| 214 |
+
|
| 215 |
+
# ---------- writer ----------
|
| 216 |
+
def _ensure_writer(self):
|
| 217 |
+
if not self.enabled:
|
| 218 |
+
return False
|
| 219 |
+
writer = self._writer
|
| 220 |
+
if writer is not None and writer.is_alive():
|
| 221 |
+
return True
|
| 222 |
+
with self._writer_lock:
|
| 223 |
+
writer = self._writer
|
| 224 |
+
if writer is not None and writer.is_alive():
|
| 225 |
+
return True
|
| 226 |
+
self._writer = threading.Thread(
|
| 227 |
+
target=self._writer_loop, name="telemetry-writer", daemon=True
|
| 228 |
+
)
|
| 229 |
+
self._writer.start()
|
| 230 |
+
return True
|
| 231 |
+
|
| 232 |
+
def _writer_loop(self):
|
| 233 |
+
while True:
|
| 234 |
+
record = self._queue.get()
|
| 235 |
+
try:
|
| 236 |
+
line = json.dumps(record, ensure_ascii=False, separators=(",", ":")) + "\n"
|
| 237 |
+
self.path.parent.mkdir(parents=True, exist_ok=True)
|
| 238 |
+
with self.path.open("a", encoding="utf-8") as handle:
|
| 239 |
+
handle.write(line)
|
| 240 |
+
handle.flush()
|
| 241 |
+
if record.get("type") in ("session_finish", "session_start"):
|
| 242 |
+
try:
|
| 243 |
+
os.fsync(handle.fileno())
|
| 244 |
+
except OSError:
|
| 245 |
+
pass
|
| 246 |
+
try:
|
| 247 |
+
os.chmod(self.path, 0o600)
|
| 248 |
+
except OSError:
|
| 249 |
+
pass
|
| 250 |
+
except Exception:
|
| 251 |
+
with self._lock:
|
| 252 |
+
self.write_errors += 1
|
| 253 |
+
finally:
|
| 254 |
+
self._queue.task_done()
|
| 255 |
+
|
| 256 |
+
def _enqueue(self, record):
|
| 257 |
+
if not self.enabled:
|
| 258 |
+
return False
|
| 259 |
+
try:
|
| 260 |
+
if not self._ensure_writer():
|
| 261 |
+
return False
|
| 262 |
+
self._queue.put_nowait(_safe(record))
|
| 263 |
+
return True
|
| 264 |
+
except queue.Full:
|
| 265 |
+
with self._lock:
|
| 266 |
+
self.dropped_records += 1
|
| 267 |
+
return False
|
| 268 |
+
except Exception:
|
| 269 |
+
return False
|
| 270 |
+
|
| 271 |
+
# ---------- aggregation ----------
|
| 272 |
+
@staticmethod
|
| 273 |
+
def _new_stat(value):
|
| 274 |
+
return {"count": 1, "sum": float(value), "min": float(value), "max": float(value), "last": float(value)}
|
| 275 |
+
|
| 276 |
+
def _update_session_locked(self, session, fields):
|
| 277 |
+
now = time.monotonic()
|
| 278 |
+
stats = session["stats"]
|
| 279 |
+
last = session["last"]
|
| 280 |
+
for name, value in (fields or {}).items():
|
| 281 |
+
name = str(name)[:80]
|
| 282 |
+
if isinstance(value, bool) or value is None:
|
| 283 |
+
if value is not None:
|
| 284 |
+
last[name] = value
|
| 285 |
+
continue
|
| 286 |
+
if isinstance(value, (int, float)) and math.isfinite(float(value)):
|
| 287 |
+
number = float(value)
|
| 288 |
+
stat = stats.get(name)
|
| 289 |
+
if stat is None:
|
| 290 |
+
stats[name] = self._new_stat(number)
|
| 291 |
+
else:
|
| 292 |
+
stat["count"] += 1
|
| 293 |
+
stat["sum"] += number
|
| 294 |
+
stat["min"] = min(stat["min"], number)
|
| 295 |
+
stat["max"] = max(stat["max"], number)
|
| 296 |
+
stat["last"] = number
|
| 297 |
+
last[name] = number
|
| 298 |
+
if name == "ffmpeg_speed":
|
| 299 |
+
if number < 0.95:
|
| 300 |
+
session["counters"]["ffmpeg_speed_below_0_95_samples"] = (
|
| 301 |
+
session["counters"].get("ffmpeg_speed_below_0_95_samples", 0) + 1
|
| 302 |
+
)
|
| 303 |
+
if number < 1.0:
|
| 304 |
+
session["counters"]["ffmpeg_speed_below_1_samples"] = (
|
| 305 |
+
session["counters"].get("ffmpeg_speed_below_1_samples", 0) + 1
|
| 306 |
+
)
|
| 307 |
+
elif isinstance(value, (str, int, float)):
|
| 308 |
+
last[name] = _safe(value)
|
| 309 |
+
|
| 310 |
+
minute = int(max(0.0, now - session["started_monotonic"]) // 60)
|
| 311 |
+
bucket = session["minutes"].setdefault(
|
| 312 |
+
str(minute),
|
| 313 |
+
{"samples": 0, "ffmpeg_speed_sum": 0.0, "ffmpeg_speed_samples": 0,
|
| 314 |
+
"ffmpeg_speed_below_0_95": 0, "source_bps_sum": 0.0, "source_bps_samples": 0},
|
| 315 |
+
)
|
| 316 |
+
bucket["samples"] += 1
|
| 317 |
+
if isinstance((fields or {}).get("ffmpeg_speed"), (int, float)):
|
| 318 |
+
speed = float(fields["ffmpeg_speed"])
|
| 319 |
+
bucket["ffmpeg_speed_sum"] += speed
|
| 320 |
+
bucket["ffmpeg_speed_samples"] += 1
|
| 321 |
+
if speed < 0.95:
|
| 322 |
+
bucket["ffmpeg_speed_below_0_95"] += 1
|
| 323 |
+
if isinstance((fields or {}).get("source_bps"), (int, float)):
|
| 324 |
+
bucket["source_bps_sum"] += float(fields["source_bps"])
|
| 325 |
+
bucket["source_bps_samples"] += 1
|
| 326 |
+
session["last_observed_at"] = _iso_now()
|
| 327 |
+
session["last_observed_monotonic"] = now
|
| 328 |
+
|
| 329 |
+
def _summary_locked(self, session, *, finished=False, reason="", extra=None, include_minutes=True):
|
| 330 |
+
now = time.monotonic()
|
| 331 |
+
stats = {}
|
| 332 |
+
for name, stat in session["stats"].items():
|
| 333 |
+
count = int(stat["count"])
|
| 334 |
+
stats[name] = {
|
| 335 |
+
"count": count,
|
| 336 |
+
"avg": round(stat["sum"] / count, 4) if count else None,
|
| 337 |
+
"min": round(stat["min"], 4),
|
| 338 |
+
"max": round(stat["max"], 4),
|
| 339 |
+
"last": round(stat["last"], 4),
|
| 340 |
+
}
|
| 341 |
+
minutes = []
|
| 342 |
+
if include_minutes:
|
| 343 |
+
for minute, bucket in sorted(session["minutes"].items(), key=lambda item: int(item[0])):
|
| 344 |
+
speed_samples = int(bucket["ffmpeg_speed_samples"])
|
| 345 |
+
source_samples = int(bucket["source_bps_samples"])
|
| 346 |
+
minutes.append({
|
| 347 |
+
"minute": int(minute),
|
| 348 |
+
"samples": int(bucket["samples"]),
|
| 349 |
+
"ffmpeg_speed_avg": round(bucket["ffmpeg_speed_sum"] / speed_samples, 4) if speed_samples else None,
|
| 350 |
+
"ffmpeg_speed_below_0_95": int(bucket["ffmpeg_speed_below_0_95"]),
|
| 351 |
+
"source_bps_avg": round(bucket["source_bps_sum"] / source_samples, 1) if source_samples else None,
|
| 352 |
+
})
|
| 353 |
+
return _safe({
|
| 354 |
+
"session_key": session["key"],
|
| 355 |
+
"broadcaster": session["broadcaster"],
|
| 356 |
+
"started_at": session["started_at"],
|
| 357 |
+
"ended_at": _iso_now() if finished else None,
|
| 358 |
+
"duration_seconds": round(max(0.0, now - session["started_monotonic"]), 3),
|
| 359 |
+
"meta": session["meta"],
|
| 360 |
+
"counters": dict(session["counters"]),
|
| 361 |
+
"stats": stats,
|
| 362 |
+
"last": dict(session["last"]),
|
| 363 |
+
"minutes": minutes,
|
| 364 |
+
"minutes_omitted": not include_minutes,
|
| 365 |
+
"reason": str(reason or "")[:200],
|
| 366 |
+
"extra": extra or {},
|
| 367 |
+
"host": self._cpu.fields(),
|
| 368 |
+
"telemetry_dropped_records": self.dropped_records,
|
| 369 |
+
"telemetry_write_errors": self.write_errors,
|
| 370 |
+
})
|
| 371 |
+
|
| 372 |
+
# ---------- public fail-open API ----------
|
| 373 |
+
def start_session(self, broadcaster, meta=None):
|
| 374 |
+
if not self.enabled:
|
| 375 |
+
return None
|
| 376 |
+
try:
|
| 377 |
+
user = str(broadcaster or "system")[:100]
|
| 378 |
+
with self._lock:
|
| 379 |
+
self._sequence += 1
|
| 380 |
+
key = "%s:%d:%d" % (user, int(time.time() * 1000), self._sequence)
|
| 381 |
+
session = {
|
| 382 |
+
"key": key,
|
| 383 |
+
"broadcaster": user,
|
| 384 |
+
"started_at": _iso_now(),
|
| 385 |
+
"started_monotonic": time.monotonic(),
|
| 386 |
+
"meta": _safe(meta or {}),
|
| 387 |
+
"counters": {},
|
| 388 |
+
"stats": {},
|
| 389 |
+
"last": {},
|
| 390 |
+
"minutes": {},
|
| 391 |
+
"dedupe": {},
|
| 392 |
+
"last_observed_at": None,
|
| 393 |
+
"last_observed_monotonic": time.monotonic(),
|
| 394 |
+
}
|
| 395 |
+
self._sessions[key] = session
|
| 396 |
+
summary = self._summary_locked(session)
|
| 397 |
+
self._enqueue({
|
| 398 |
+
"type": "session_start", "recorded_at": _iso_now(),
|
| 399 |
+
"session_key": key, "broadcaster": user, "summary": summary,
|
| 400 |
+
})
|
| 401 |
+
return key
|
| 402 |
+
except Exception:
|
| 403 |
+
return None
|
| 404 |
+
|
| 405 |
+
def observe(self, session_key, fields=None):
|
| 406 |
+
if not self.enabled or not session_key:
|
| 407 |
+
return False
|
| 408 |
+
try:
|
| 409 |
+
with self._lock:
|
| 410 |
+
session = self._sessions.get(session_key)
|
| 411 |
+
if session is None:
|
| 412 |
+
return False
|
| 413 |
+
self._update_session_locked(session, fields or {})
|
| 414 |
+
return True
|
| 415 |
+
except Exception:
|
| 416 |
+
return False
|
| 417 |
+
|
| 418 |
+
def event(self, session_key, broadcaster, event, details=None, dedupe_key=None):
|
| 419 |
+
if not self.enabled:
|
| 420 |
+
return False
|
| 421 |
+
try:
|
| 422 |
+
name = str(event or "UNKNOWN")[:80]
|
| 423 |
+
safe_details = _safe(details or {})
|
| 424 |
+
elapsed = None
|
| 425 |
+
with self._lock:
|
| 426 |
+
session = self._sessions.get(session_key) if session_key else None
|
| 427 |
+
if session is not None:
|
| 428 |
+
counters = session["counters"]
|
| 429 |
+
counters[name] = counters.get(name, 0) + 1
|
| 430 |
+
if name == "SOURCE_OPEN_ERROR":
|
| 431 |
+
status = (safe_details or {}).get("http_status")
|
| 432 |
+
if status:
|
| 433 |
+
label = "source_open_http_%s" % status
|
| 434 |
+
counters[label] = counters.get(label, 0) + 1
|
| 435 |
+
elapsed = round(max(0.0, time.monotonic() - session["started_monotonic"]), 3)
|
| 436 |
+
if dedupe_key:
|
| 437 |
+
previous = session["dedupe"].get(str(dedupe_key))
|
| 438 |
+
if previous == safe_details:
|
| 439 |
+
label = name + "_suppressed"
|
| 440 |
+
counters[label] = counters.get(label, 0) + 1
|
| 441 |
+
return True
|
| 442 |
+
session["dedupe"][str(dedupe_key)] = safe_details
|
| 443 |
+
return self._enqueue({
|
| 444 |
+
"type": "event", "recorded_at": _iso_now(), "session_key": session_key,
|
| 445 |
+
"broadcaster": str(broadcaster or "system")[:100], "event": name,
|
| 446 |
+
"elapsed_seconds": elapsed, "details": safe_details,
|
| 447 |
+
})
|
| 448 |
+
except Exception:
|
| 449 |
+
return False
|
| 450 |
+
|
| 451 |
+
def checkpoint(self, session_key, reason="periodic"):
|
| 452 |
+
if not self.enabled or not session_key:
|
| 453 |
+
return False
|
| 454 |
+
try:
|
| 455 |
+
with self._lock:
|
| 456 |
+
session = self._sessions.get(session_key)
|
| 457 |
+
if session is None:
|
| 458 |
+
return False
|
| 459 |
+
summary = self._summary_locked(session, reason=reason, include_minutes=False)
|
| 460 |
+
user = session["broadcaster"]
|
| 461 |
+
return self._enqueue({
|
| 462 |
+
"type": "checkpoint", "recorded_at": _iso_now(), "session_key": session_key,
|
| 463 |
+
"broadcaster": user, "summary": summary,
|
| 464 |
+
})
|
| 465 |
+
except Exception:
|
| 466 |
+
return False
|
| 467 |
+
|
| 468 |
+
def finish(self, session_key, reason="", extra=None):
|
| 469 |
+
if not self.enabled or not session_key:
|
| 470 |
+
return False
|
| 471 |
+
try:
|
| 472 |
+
with self._lock:
|
| 473 |
+
session = self._sessions.pop(session_key, None)
|
| 474 |
+
if session is None:
|
| 475 |
+
return False
|
| 476 |
+
summary = self._summary_locked(
|
| 477 |
+
session, finished=True, reason=reason, extra=_safe(extra or {})
|
| 478 |
+
)
|
| 479 |
+
user = session["broadcaster"]
|
| 480 |
+
return self._enqueue({
|
| 481 |
+
"type": "session_finish", "recorded_at": _iso_now(), "session_key": session_key,
|
| 482 |
+
"broadcaster": user, "summary": summary,
|
| 483 |
+
})
|
| 484 |
+
except Exception:
|
| 485 |
+
return False
|
| 486 |
+
|
| 487 |
+
def read_records(self, limit=200, broadcaster=None):
|
| 488 |
+
"""Read recent records for the authenticated diagnostics API.
|
| 489 |
+
|
| 490 |
+
This is an operator/read path only; it is never called by media code.
|
| 491 |
+
It reads a bounded tail so a long-lived append-only file cannot make
|
| 492 |
+
the request consume unbounded memory.
|
| 493 |
+
"""
|
| 494 |
+
try:
|
| 495 |
+
limit = max(1, min(int(limit), 5000))
|
| 496 |
+
except (TypeError, ValueError):
|
| 497 |
+
limit = 200
|
| 498 |
+
try:
|
| 499 |
+
if not self.path.exists():
|
| 500 |
+
return []
|
| 501 |
+
size = self.path.stat().st_size
|
| 502 |
+
max_bytes = 16 * 1024 * 1024
|
| 503 |
+
offset = max(0, size - max_bytes)
|
| 504 |
+
with self.path.open("rb") as handle:
|
| 505 |
+
handle.seek(offset)
|
| 506 |
+
raw = handle.read()
|
| 507 |
+
if offset:
|
| 508 |
+
newline = raw.find(b"\n")
|
| 509 |
+
raw = raw[newline + 1:] if newline >= 0 else b""
|
| 510 |
+
records = []
|
| 511 |
+
wanted = str(broadcaster or "").strip().lstrip("@")
|
| 512 |
+
for line in raw.decode("utf-8", "ignore").splitlines():
|
| 513 |
+
try:
|
| 514 |
+
item = json.loads(line)
|
| 515 |
+
except ValueError:
|
| 516 |
+
continue
|
| 517 |
+
if not isinstance(item, dict):
|
| 518 |
+
continue
|
| 519 |
+
if wanted:
|
| 520 |
+
summary = item.get("summary") or {}
|
| 521 |
+
if item.get("broadcaster") != wanted and summary.get("broadcaster") != wanted:
|
| 522 |
+
continue
|
| 523 |
+
records.append(item)
|
| 524 |
+
return records[-limit:]
|
| 525 |
+
except OSError:
|
| 526 |
+
return []
|
| 527 |
+
|
| 528 |
+
def status(self):
|
| 529 |
+
with self._lock:
|
| 530 |
+
return {
|
| 531 |
+
"enabled": bool(self.enabled),
|
| 532 |
+
"file": "telemetry/telemetry.jsonl",
|
| 533 |
+
"active_sessions": len(self._sessions),
|
| 534 |
+
"dropped_records": self.dropped_records,
|
| 535 |
+
"write_errors": self.write_errors,
|
| 536 |
+
"queued_records": self._queue.qsize() if self._queue is not None else 0,
|
| 537 |
+
}
|
| 538 |
+
|
| 539 |
+
|
| 540 |
+
telemetry = Telemetry()
|
| 541 |
+
|
| 542 |
+
|
| 543 |
+
def start_session(broadcaster, meta=None):
|
| 544 |
+
try:
|
| 545 |
+
return telemetry.start_session(broadcaster, meta)
|
| 546 |
+
except Exception:
|
| 547 |
+
return None
|
| 548 |
+
|
| 549 |
+
|
| 550 |
+
def observe(session_key, fields=None):
|
| 551 |
+
try:
|
| 552 |
+
return telemetry.observe(session_key, fields)
|
| 553 |
+
except Exception:
|
| 554 |
+
return False
|
| 555 |
+
|
| 556 |
+
|
| 557 |
+
def record_event(session_key, broadcaster, event, details=None, dedupe_key=None):
|
| 558 |
+
try:
|
| 559 |
+
return telemetry.event(session_key, broadcaster, event, details, dedupe_key=dedupe_key)
|
| 560 |
+
except Exception:
|
| 561 |
+
return False
|
| 562 |
+
|
| 563 |
+
|
| 564 |
+
def checkpoint(session_key, reason="periodic"):
|
| 565 |
+
try:
|
| 566 |
+
return telemetry.checkpoint(session_key, reason)
|
| 567 |
+
except Exception:
|
| 568 |
+
return False
|
| 569 |
+
|
| 570 |
+
|
| 571 |
+
def finish(session_key, reason="", extra=None):
|
| 572 |
+
try:
|
| 573 |
+
return telemetry.finish(session_key, reason, extra)
|
| 574 |
+
except Exception:
|
| 575 |
+
return False
|
| 576 |
+
|
| 577 |
+
|
| 578 |
+
def read_records(limit=200, broadcaster=None):
|
| 579 |
+
try:
|
| 580 |
+
return telemetry.read_records(limit, broadcaster)
|
| 581 |
+
except Exception:
|
| 582 |
+
return []
|
| 583 |
+
|
| 584 |
+
|
| 585 |
+
def status():
|
| 586 |
+
try:
|
| 587 |
+
return telemetry.status()
|
| 588 |
+
except Exception:
|
| 589 |
+
return {"enabled": False, "file": "telemetry/telemetry.jsonl", "active_sessions": 0}
|
test_adaptive_format.py
ADDED
|
@@ -0,0 +1,335 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Regression and local-media experiment for adaptive handling of TikTok format changes."""
|
| 3 |
+
import collections
|
| 4 |
+
import json
|
| 5 |
+
import os
|
| 6 |
+
import pathlib
|
| 7 |
+
import shutil
|
| 8 |
+
import subprocess
|
| 9 |
+
import sys
|
| 10 |
+
import tempfile
|
| 11 |
+
import threading
|
| 12 |
+
import time
|
| 13 |
+
import unittest
|
| 14 |
+
from unittest.mock import patch
|
| 15 |
+
|
| 16 |
+
ROOT=pathlib.Path(sys.argv[1]).resolve() if len(sys.argv)>1 else pathlib.Path(__file__).parent
|
| 17 |
+
sys.path.insert(0,str(ROOT))
|
| 18 |
+
from flv_bridge import FLVBridge
|
| 19 |
+
from ingest import RelayHub
|
| 20 |
+
from relay import Sender
|
| 21 |
+
from youtube_manager import ManagedYouTube
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def tag(kind,ts,body):
|
| 25 |
+
size=len(body)
|
| 26 |
+
header=bytes([kind])+size.to_bytes(3,'big')+bytes([
|
| 27 |
+
(ts>>16)&255,(ts>>8)&255,ts&255,(ts>>24)&255,0,0,0])
|
| 28 |
+
return header+body+(11+size).to_bytes(4,'big')
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def flv(*records):
|
| 32 |
+
return b'FLV\x01\x05\x00\x00\x00\x09\x00\x00\x00\x00'+b''.join(records)
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def seq(cfg):return b'\x17\x00\x00\x00\x00'+cfg
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def coded(payload=b'\x00\x00\x00\x02\x65\x88'):
|
| 39 |
+
return b'\x27\x01\x00\x00\x00'+payload
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
AVC_A=bytes.fromhex('0142c00dffe100166742c00dda0507ec0440000003004000000ca3c50aa801000468ce0fc8')
|
| 43 |
+
AVC_B=bytes.fromhex('0142c01effe100196742c01eda0280bfe5c044000003000400000300ca3c58ba8001000468ce0fc8')
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
class FakePipe:
|
| 47 |
+
def __init__(self):self.close_count=0
|
| 48 |
+
def close(self):self.close_count+=1
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
class FakeProcess:
|
| 52 |
+
def __init__(self,exit_code=None):self.stdin=FakePipe();self.exit_code=exit_code
|
| 53 |
+
def poll(self):return self.exit_code
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
class AdaptivePolicyTests(unittest.TestCase):
|
| 57 |
+
def setUp(self):
|
| 58 |
+
self.env=patch.dict(os.environ,{
|
| 59 |
+
'YOUTUBE_LIGHT_MAX':'2','YOUTUBE_FLAP_LIMIT':'3',
|
| 60 |
+
'YOUTUBE_FLAP_WINDOW_SECONDS':'600','YOUTUBE_FLAP_FALLBACK_MODE':'matchgop',
|
| 61 |
+
'YOUTUBE_SEND_MODE':'auto','YOUTUBE_AUTO_TRANSCODE':'0'})
|
| 62 |
+
self.env.start();self.addCleanup(self.env.stop)
|
| 63 |
+
self.light_hub=RelayHub()
|
| 64 |
+
self.hub_patch=patch('ingest.hub',self.light_hub)
|
| 65 |
+
self.hub_patch.start();self.addCleanup(self.hub_patch.stop)
|
| 66 |
+
|
| 67 |
+
def make_sender(self):
|
| 68 |
+
messages=[];sender=Sender('/bin/true',lambda user,text:messages.append((user,text)))
|
| 69 |
+
sender.current_candidate={'codec':'h264','label':'h264','width':320,'height':240}
|
| 70 |
+
sender.lock_gold(sender.current_candidate)
|
| 71 |
+
sender.active_mode='copy'
|
| 72 |
+
sender.session={'force_stop':False}
|
| 73 |
+
sender.process=FakeProcess()
|
| 74 |
+
persisted=[];sender.on_sticky=lambda *args:persisted.append(args)
|
| 75 |
+
return sender,messages,persisted
|
| 76 |
+
|
| 77 |
+
def test_real_flv_resolution_events_trigger_one_per_sender_fallback_at_threshold(self):
|
| 78 |
+
sender,messages,persisted=self.make_sender()
|
| 79 |
+
with patch('relay.log_event') as saved:
|
| 80 |
+
bridge=FLVBridge(user='alice',event_logger=sender._bridge_event)
|
| 81 |
+
bridge.feed(flv(tag(9,0,seq(AVC_A)),tag(9,1,coded())))
|
| 82 |
+
self.assertIsNone(sender.sticky_mode)
|
| 83 |
+
self.assertEqual(sender.process.stdin.close_count,0)
|
| 84 |
+
for ts,config in ((40,AVC_B),(80,AVC_A)):
|
| 85 |
+
bridge.feed(tag(9,ts,seq(config)))
|
| 86 |
+
bridge.feed(tag(9,ts+1,coded()))
|
| 87 |
+
self.assertIsNone(sender.sticky_mode)
|
| 88 |
+
self.assertEqual(sender.process.stdin.close_count,0)
|
| 89 |
+
bridge.feed(tag(9,120,seq(AVC_B)))
|
| 90 |
+
self.assertEqual(bridge.format_changes,3)
|
| 91 |
+
self.assertEqual(sender.sticky_mode,'matchgop')
|
| 92 |
+
self.assertTrue(sender.session['force_stop'])
|
| 93 |
+
self.assertEqual(sender.process.stdin.close_count,1)
|
| 94 |
+
self.assertEqual(persisted,[('alice','matchgop',320,240)])
|
| 95 |
+
self.assertEqual(sum(c.args[1]=='RESOLUTION_CHANGE' for c in saved.call_args_list),3)
|
| 96 |
+
self.assertTrue(any(c.args[1]=='FORMAT_FALLBACK' for c in saved.call_args_list))
|
| 97 |
+
bridge.feed(tag(9,160,seq(AVC_A)))
|
| 98 |
+
self.assertEqual(sender.process.stdin.close_count,1,'one format flap must not restart the RTMP publisher repeatedly')
|
| 99 |
+
self.assertTrue(any('sticky matchgop' in text for _,text in messages))
|
| 100 |
+
|
| 101 |
+
def test_full_light_cap_keeps_copy_alive_then_retries_without_overbooking(self):
|
| 102 |
+
self.assertTrue(self.light_hub.reserve_light('peer-a'))
|
| 103 |
+
self.assertTrue(self.light_hub.reserve_light('peer-b'))
|
| 104 |
+
sender,_,_=self.make_sender()
|
| 105 |
+
bridge=FLVBridge(user='alice',event_logger=sender._bridge_event)
|
| 106 |
+
with patch('relay.log_event') as saved:
|
| 107 |
+
bridge.feed(flv(tag(9,0,seq(AVC_A)),tag(9,1,coded())))
|
| 108 |
+
for ts,config in ((40,AVC_B),(80,AVC_A),(120,AVC_B)):
|
| 109 |
+
bridge.feed(tag(9,ts,seq(config)))
|
| 110 |
+
bridge.feed(tag(9,ts+1,coded()))
|
| 111 |
+
self.assertIsNone(sender.sticky_mode)
|
| 112 |
+
self.assertEqual(sender.pending_sticky[0],'matchgop')
|
| 113 |
+
self.assertFalse(sender.session['force_stop'])
|
| 114 |
+
self.assertEqual(sender.process.stdin.close_count,0)
|
| 115 |
+
self.assertEqual(self.light_hub.light_count(),2)
|
| 116 |
+
self.light_hub.release_light('peer-a')
|
| 117 |
+
self.assertTrue(sender.apply_pending_sticky('alice'))
|
| 118 |
+
self.assertEqual(sender.sticky_mode,'matchgop')
|
| 119 |
+
self.assertIsNone(sender.pending_sticky)
|
| 120 |
+
self.assertEqual(sender.process.stdin.close_count,1)
|
| 121 |
+
self.assertEqual(self.light_hub.light_count(),2)
|
| 122 |
+
self.assertTrue(any(call.args[1]=='FORMAT_FALLBACK' for call in saved.call_args_list))
|
| 123 |
+
|
| 124 |
+
def test_format_changes_outside_window_do_not_force_transcoding(self):
|
| 125 |
+
sender,_,_=self.make_sender()
|
| 126 |
+
sender.flap.append(time.monotonic()-601)
|
| 127 |
+
self.assertFalse(sender.note_format_change('alice',{'old_width':320,'old_height':240,
|
| 128 |
+
'new_width':640,'new_height':360}))
|
| 129 |
+
self.assertEqual(len(sender.flap),1)
|
| 130 |
+
self.assertIsNone(sender.sticky_mode)
|
| 131 |
+
self.assertEqual(sender.process.stdin.close_count,0)
|
| 132 |
+
|
| 133 |
+
def test_reservation_is_released_with_relay_owner(self):
|
| 134 |
+
self.assertTrue(self.light_hub.reserve_light('alice'))
|
| 135 |
+
self.assertEqual(self.light_hub.light_count(),1)
|
| 136 |
+
self.light_hub.release('alice','oauth')
|
| 137 |
+
self.assertEqual(self.light_hub.light_count(),0)
|
| 138 |
+
|
| 139 |
+
def test_light_reservation_is_atomic_under_simultaneous_fallbacks(self):
|
| 140 |
+
with patch.dict(os.environ,{'YOUTUBE_LIGHT_MAX':'1'}):
|
| 141 |
+
gate=threading.Barrier(3);results=[]
|
| 142 |
+
def reserve(user):
|
| 143 |
+
gate.wait();results.append(self.light_hub.reserve_light(user))
|
| 144 |
+
threads=[threading.Thread(target=reserve,args=(u,)) for u in ('alice','bob')]
|
| 145 |
+
for thread in threads:thread.start()
|
| 146 |
+
gate.wait()
|
| 147 |
+
for thread in threads:thread.join(timeout=2)
|
| 148 |
+
self.assertEqual(sum(bool(x) for x in results),1)
|
| 149 |
+
self.assertEqual(self.light_hub.light_count(),1)
|
| 150 |
+
|
| 151 |
+
def test_sender_snapshot_reports_effective_mode_not_ui_preference(self):
|
| 152 |
+
sender=Sender('/bin/true',lambda *a:None)
|
| 153 |
+
sender.mode_override='auto'
|
| 154 |
+
sender.active_mode='matchgop'
|
| 155 |
+
self.assertEqual(sender.snapshot()['send_mode'],'matchgop')
|
| 156 |
+
|
| 157 |
+
def test_output_failure_reason_is_not_mislabeled_as_normal_stop(self):
|
| 158 |
+
sender=Sender('/bin/true',lambda *a:None)
|
| 159 |
+
sender.last_failure_side='output'
|
| 160 |
+
reason=sender._close_reason({},FakeProcess(exit_code=187))
|
| 161 |
+
self.assertIn('RTMPS',reason)
|
| 162 |
+
self.assertIn('187',reason)
|
| 163 |
+
self.assertNotEqual(reason,'إيقاف عادي')
|
| 164 |
+
|
| 165 |
+
def test_explicit_stop_keeps_normal_stop_diagnostic(self):
|
| 166 |
+
sender=Sender('/bin/true',lambda *a:None)
|
| 167 |
+
self.assertEqual(sender._close_reason({},FakeProcess(exit_code=0)),'إيقاف عادي')
|
| 168 |
+
|
| 169 |
+
|
| 170 |
+
class EventModePersistenceTests(unittest.TestCase):
|
| 171 |
+
def setUp(self):
|
| 172 |
+
self.tmp=tempfile.TemporaryDirectory(prefix='sender-mode-journal-')
|
| 173 |
+
self.addCleanup(self.tmp.cleanup)
|
| 174 |
+
self.path=pathlib.Path(self.tmp.name)/'journal.json'
|
| 175 |
+
self.manager=ManagedYouTube('/bin/true',lambda u:None,lambda *a:None,lambda:['alice'],self.path)
|
| 176 |
+
self.key='alice:room'
|
| 177 |
+
event={'username':'alice','session_key':self.key,'room_id':'room','broadcast_id':'VIDEO',
|
| 178 |
+
'title':'test','nickname':'Alice','phase':'live','youtube_status':'live','closing':False}
|
| 179 |
+
self.manager.journal.change(lambda d:d['events'].update({self.key:event}))
|
| 180 |
+
|
| 181 |
+
def test_adaptive_mode_canvas_and_pending_request_survive_manager_recreation(self):
|
| 182 |
+
self.manager._remember_pending_sender_mode('alice','matchgop','four source resolution changes')
|
| 183 |
+
original=self.manager.journal.read()['events'][self.key]
|
| 184 |
+
self.assertEqual(original['sender_pending_mode'],'matchgop')
|
| 185 |
+
restored=ManagedYouTube('/bin/true',lambda u:None,lambda *a:None,lambda:['alice'],self.path)
|
| 186 |
+
restored._remember_sender_mode('alice','matchgop',720,1280)
|
| 187 |
+
ev=restored.journal.read()['events'][self.key]
|
| 188 |
+
self.assertEqual((ev['sender_mode'],ev['sender_canvas_width'],ev['sender_canvas_height']),
|
| 189 |
+
('matchgop',720,1280))
|
| 190 |
+
self.assertEqual(ev['sender_pending_mode'],'')
|
| 191 |
+
|
| 192 |
+
def test_journaled_mode_is_visible_before_sender_thread_restarts(self):
|
| 193 |
+
self.manager._remember_sender_mode('alice','matchgop',720,1280)
|
| 194 |
+
self.manager._remember_pending_sender_mode('alice','matchgop','format flapping')
|
| 195 |
+
row=self.manager.snapshot()['events'][0]
|
| 196 |
+
self.assertEqual(row['send_mode'],'matchgop')
|
| 197 |
+
self.assertEqual(row['pending_send_mode'],'matchgop')
|
| 198 |
+
|
| 199 |
+
def test_archiving_event_clears_per_event_mode_and_pending_reservation(self):
|
| 200 |
+
self.manager._remember_sender_mode('alice','matchgop',720,1280)
|
| 201 |
+
self.manager._remember_pending_sender_mode('alice','matchgop','format flapping')
|
| 202 |
+
self.manager._sender_sticky['alice']='matchgop'
|
| 203 |
+
self.manager._sender_gop['alice']=(720,1280)
|
| 204 |
+
self.manager._sender_pending['alice']=('matchgop','format flapping')
|
| 205 |
+
self.manager.archive_event(self.key,'done')
|
| 206 |
+
self.assertNotIn(self.key,self.manager.journal.read()['events'])
|
| 207 |
+
self.assertNotIn('alice',self.manager._sender_sticky)
|
| 208 |
+
self.assertNotIn('alice',self.manager._sender_gop)
|
| 209 |
+
self.assertNotIn('alice',self.manager._sender_pending)
|
| 210 |
+
|
| 211 |
+
|
| 212 |
+
class IdleHousekeepingTests(unittest.TestCase):
|
| 213 |
+
def setUp(self):
|
| 214 |
+
self.tmp=tempfile.TemporaryDirectory(prefix='idle-clean-')
|
| 215 |
+
self.addCleanup(self.tmp.cleanup)
|
| 216 |
+
self.path=pathlib.Path(self.tmp.name)/'journal.json'
|
| 217 |
+
self.manager=ManagedYouTube('/bin/true',lambda u:None,lambda *a:None,lambda:['alice'],self.path)
|
| 218 |
+
self.manager.idle_reset_seconds=600.0
|
| 219 |
+
self.manager.journal.change(lambda d:(d['streams'].update({'alice':{'id':'STREAM1'}}),
|
| 220 |
+
d.update(channel={'id':'CHAN','title':'قناتي'})))
|
| 221 |
+
self.manager._sender_sticky['alice']='matchgop'
|
| 222 |
+
self.manager._sender_gop['alice']=(720,1280)
|
| 223 |
+
self.manager.hammer['alice']=3
|
| 224 |
+
self.manager.destinations['alice']='rtmps://cached.example.invalid/live/KEY'
|
| 225 |
+
|
| 226 |
+
def test_no_clean_before_full_idle_threshold_then_clean_once(self):
|
| 227 |
+
m=self.manager
|
| 228 |
+
self.assertFalse(m.idle_housekeeping(now=1000.0)) # يبدأ المؤقّت فقط
|
| 229 |
+
self.assertFalse(m.idle_housekeeping(now=1599.0))
|
| 230 |
+
self.assertEqual(m._sender_sticky.get('alice'),'matchgop')
|
| 231 |
+
self.assertTrue(m.idle_housekeeping(now=1600.0))
|
| 232 |
+
self.assertEqual(m._sender_sticky,{})
|
| 233 |
+
self.assertEqual(m._sender_gop,{})
|
| 234 |
+
self.assertEqual(m.hammer,{})
|
| 235 |
+
self.assertEqual(m.destinations,{})
|
| 236 |
+
self.assertFalse(m.idle_housekeeping(now=9999.0)) # مرة واحدة في كل خمول
|
| 237 |
+
|
| 238 |
+
def test_clean_preserves_channel_binding_streams_and_settings(self):
|
| 239 |
+
m=self.manager
|
| 240 |
+
m.idle_housekeeping(now=0.0);m.idle_housekeeping(now=600.0)
|
| 241 |
+
d=m.journal.read()
|
| 242 |
+
self.assertEqual(d['channel'],{'id':'CHAN','title':'قناتي'})
|
| 243 |
+
self.assertEqual(d['streams']['alice']['id'],'STREAM1')
|
| 244 |
+
self.assertIn('title',d['settings'])
|
| 245 |
+
self.assertGreater(d.get('last_idle_clean') or 0,0)
|
| 246 |
+
|
| 247 |
+
def test_any_event_counts_as_activity_and_restarts_the_timer(self):
|
| 248 |
+
m=self.manager
|
| 249 |
+
key='alice:room'
|
| 250 |
+
event={'username':'alice','session_key':key,'room_id':'room','broadcast_id':'VIDEO',
|
| 251 |
+
'title':'test','nickname':'Alice','phase':'live','youtube_status':'live','closing':False}
|
| 252 |
+
m.journal.change(lambda d:d['events'].update({key:event}))
|
| 253 |
+
self.assertFalse(m.idle_housekeeping(now=1000.0))
|
| 254 |
+
self.assertFalse(m.idle_housekeeping(now=99999.0)) # حدث موجود = نشاط
|
| 255 |
+
self.assertEqual(m._sender_sticky.get('alice'),'matchgop')
|
| 256 |
+
m.journal.change(lambda d:d['events'].pop(key,None))
|
| 257 |
+
self.assertFalse(m.idle_housekeeping(now=100000.0)) # المؤقّت من الصفر
|
| 258 |
+
self.assertFalse(m.idle_housekeeping(now=100599.0))
|
| 259 |
+
self.assertTrue(m.idle_housekeeping(now=100600.0)) # خمول جديد = تنظيف جديد
|
| 260 |
+
|
| 261 |
+
def test_zero_disables_housekeeping(self):
|
| 262 |
+
self.manager.idle_reset_seconds=0.0
|
| 263 |
+
self.assertFalse(self.manager.idle_housekeeping(now=10**9))
|
| 264 |
+
self.assertEqual(self.manager._sender_sticky.get('alice'),'matchgop')
|
| 265 |
+
|
| 266 |
+
|
| 267 |
+
@unittest.skipUnless(shutil.which('ffmpeg') and shutil.which('ffprobe'),'FFmpeg and ffprobe required')
|
| 268 |
+
class RealResolutionTransitionTests(unittest.TestCase):
|
| 269 |
+
def setUp(self):
|
| 270 |
+
self.tmp=tempfile.TemporaryDirectory(prefix='adaptive-format-')
|
| 271 |
+
self.addCleanup(self.tmp.cleanup)
|
| 272 |
+
self.root=pathlib.Path(self.tmp.name)
|
| 273 |
+
self.ff=shutil.which('ffmpeg');self.fp=shutil.which('ffprobe')
|
| 274 |
+
|
| 275 |
+
def run_checked(self,args,**kw):
|
| 276 |
+
return subprocess.run(args,check=True,capture_output=True,timeout=60,**kw)
|
| 277 |
+
|
| 278 |
+
def probe(self,path,*extra):
|
| 279 |
+
return json.loads(self.run_checked([self.fp,'-v','error',*extra,'-of','json',str(path)],text=True).stdout)
|
| 280 |
+
|
| 281 |
+
def test_copy_preserves_dynamic_dimensions_and_matchgop_normalizes_them(self):
|
| 282 |
+
sources=[]
|
| 283 |
+
for n,(width,height) in enumerate(((320,640),(480,960))):
|
| 284 |
+
path=self.root/('source-%d.flv'%n)
|
| 285 |
+
self.run_checked([self.ff,'-hide_banner','-v','error','-y','-f','lavfi','-i',
|
| 286 |
+
'testsrc2=size=%dx%d:rate=20'%(width,height),'-f','lavfi','-i','sine=sample_rate=48000',
|
| 287 |
+
'-t','2.5','-c:v','libx264','-preset','ultrafast','-pix_fmt','yuv420p',
|
| 288 |
+
'-g','40','-keyint_min','40','-sc_threshold','0','-c:a','aac','-b:a','96k',
|
| 289 |
+
'-ar','48000','-f','flv',str(path)])
|
| 290 |
+
sources.append(path.read_bytes())
|
| 291 |
+
observed=[]
|
| 292 |
+
bridge=FLVBridge(user='fixture',event_logger=lambda user,event,details:observed.append((event,details)))
|
| 293 |
+
joined=bridge.feed(sources[0]);bridge.reconnect();joined+=bridge.feed(sources[1])
|
| 294 |
+
source=self.root/'transition.flv';source.write_bytes(joined)
|
| 295 |
+
self.assertEqual(bridge.format_changes,1)
|
| 296 |
+
self.assertTrue(any(event=='RESOLUTION_CHANGE' for event,_ in observed))
|
| 297 |
+
|
| 298 |
+
copied=self.root/'copy.flv'
|
| 299 |
+
self.run_checked([self.ff,'-hide_banner','-v','error','-y','-i',str(source),
|
| 300 |
+
'-map','0:v:0','-map','0:a:0?','-c:v','copy','-c:a','aac','-ar','48000','-f','flv',str(copied)])
|
| 301 |
+
normalized=self.root/'matchgop.flv'
|
| 302 |
+
vf=('scale=w=320:h=640:force_original_aspect_ratio=decrease:flags=lanczos:eval=frame,'
|
| 303 |
+
'pad=320:640:(ow-iw)/2:(oh-ih)/2:color=black:eval=frame,setsar=1,format=yuv420p')
|
| 304 |
+
self.run_checked([self.ff,'-hide_banner','-v','error','-y','-i',str(source),
|
| 305 |
+
'-map','0:v:0','-map','0:a:0?','-vf',vf,'-c:v','libx264','-preset','ultrafast',
|
| 306 |
+
'-tune','zerolatency','-b:v','900k','-minrate','900k','-maxrate','900k','-bufsize','1350k',
|
| 307 |
+
'-force_key_frames','expr:gte(t,n_forced*2)','-g','40','-keyint_min','30','-sc_threshold','0',
|
| 308 |
+
'-bf','0','-x264-params','nal-hrd=cbr:force-cfr=1:open-gop=0:scenecut=0:keyint=40:min-keyint=30',
|
| 309 |
+
'-pix_fmt','yuv420p','-fps_mode','cfr','-c:a','aac','-ar','48000','-f','flv',str(normalized)])
|
| 310 |
+
|
| 311 |
+
copied_frames=self.probe(copied,'-select_streams','v:0','-show_frames','-show_entries','frame=width,height')['frames']
|
| 312 |
+
copied_sizes=collections.Counter((int(f['width']),int(f['height'])) for f in copied_frames if 'width' in f)
|
| 313 |
+
self.assertGreater(copied_sizes[(320,640)],30)
|
| 314 |
+
self.assertGreater(copied_sizes[(480,960)],30)
|
| 315 |
+
normalized_frames=self.probe(normalized,'-select_streams','v:0','-show_frames','-show_entries','frame=width,height')['frames']
|
| 316 |
+
normalized_sizes=collections.Counter((int(f['width']),int(f['height'])) for f in normalized_frames if 'width' in f)
|
| 317 |
+
self.assertGreater(len(normalized_frames),90)
|
| 318 |
+
self.assertEqual(set(normalized_sizes),{(320,640)})
|
| 319 |
+
|
| 320 |
+
for output in (copied,normalized):
|
| 321 |
+
packets=self.probe(output,'-show_packets','-show_entries','packet=stream_index,dts_time')['packets']
|
| 322 |
+
per_stream={}
|
| 323 |
+
for packet in packets:
|
| 324 |
+
if packet.get('dts_time') is not None:
|
| 325 |
+
per_stream.setdefault(packet['stream_index'],[]).append(float(packet['dts_time']))
|
| 326 |
+
self.assertGreaterEqual(len(per_stream),2)
|
| 327 |
+
for times in per_stream.values():
|
| 328 |
+
self.assertTrue(all(b>=a for a,b in zip(times,times[1:])),
|
| 329 |
+
'DTS must not regress at a same-event source handover')
|
| 330 |
+
self.run_checked([self.ff,'-hide_banner','-v','error','-i',str(output),'-map','0:v:0','-f','null','-'])
|
| 331 |
+
fmt=self.probe(output,'-show_format')['format']
|
| 332 |
+
self.assertGreater(float(fmt['duration']),4.5)
|
| 333 |
+
|
| 334 |
+
|
| 335 |
+
if __name__=='__main__':unittest.main(argv=[sys.argv[0]],verbosity=2)
|
test_channel_switch.py
ADDED
|
@@ -0,0 +1,236 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Channel confirmation / cookie-export regressions. No live services or real credentials."""
|
| 3 |
+
import json
|
| 4 |
+
import os
|
| 5 |
+
import pathlib
|
| 6 |
+
import sys
|
| 7 |
+
import tempfile
|
| 8 |
+
import time
|
| 9 |
+
import unittest
|
| 10 |
+
from unittest.mock import patch
|
| 11 |
+
|
| 12 |
+
ROOT = pathlib.Path(sys.argv[1]).resolve() if len(sys.argv) > 1 else pathlib.Path(__file__).parent
|
| 13 |
+
sys.path.insert(0, str(ROOT))
|
| 14 |
+
os.environ.setdefault('PASSWORD', 'channel-test-password')
|
| 15 |
+
os.environ.setdefault('DATA_DIR', tempfile.mkdtemp(prefix='channel-app-test-'))
|
| 16 |
+
os.environ.setdefault('FFMPEG_PATH', '/bin/true')
|
| 17 |
+
|
| 18 |
+
from youtube_manager import ManagedYouTube
|
| 19 |
+
import tiktok_auth
|
| 20 |
+
|
| 21 |
+
OLD = {'id': 'OLD_CHANNEL', 'title': 'Old channel'}
|
| 22 |
+
NEW = {'id': 'NEW_CHANNEL', 'title': 'New channel'}
|
| 23 |
+
KEY = 'alice:room1'
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
class ChannelAPI:
|
| 27 |
+
def __init__(self, channel=NEW):
|
| 28 |
+
self.channel = dict(channel)
|
| 29 |
+
self.calls = []
|
| 30 |
+
|
| 31 |
+
def configured(self):
|
| 32 |
+
return True
|
| 33 |
+
|
| 34 |
+
def call(self, resource, method='GET', params=None, body=None):
|
| 35 |
+
self.calls.append((resource, method))
|
| 36 |
+
if resource != 'channels' or method != 'GET':
|
| 37 |
+
raise AssertionError('Channel switching must not touch remote events or streams')
|
| 38 |
+
return {'items': [{'id': self.channel['id'], 'snippet': {'title': self.channel['title']}}]}
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
class ChannelTests(unittest.TestCase):
|
| 42 |
+
def setUp(self):
|
| 43 |
+
self.tmp = tempfile.TemporaryDirectory()
|
| 44 |
+
self.addCleanup(self.tmp.cleanup)
|
| 45 |
+
self.logs = []
|
| 46 |
+
self.mgr = ManagedYouTube('/bin/true', lambda u: {'status': 'offline', 'sources': []},
|
| 47 |
+
lambda u, m: self.logs.append((u, m)), lambda: ['alice'],
|
| 48 |
+
pathlib.Path(self.tmp.name) / 'journal.json')
|
| 49 |
+
self.mgr.api = ChannelAPI()
|
| 50 |
+
self.mgr.journal.change(lambda d: d.update(channel=dict(OLD), enabled=True,
|
| 51 |
+
streams={'alice': {'id': 'old-stream'}},
|
| 52 |
+
events={KEY: {'session_key': KEY, 'username': 'alice', 'room_id': 'room1',
|
| 53 |
+
'broadcast_id': 'old-broadcast', 'title': 'Old event'}},
|
| 54 |
+
history=[{'session_key': 'bob:oldroom', 'broadcast_id': 'older-broadcast'}]))
|
| 55 |
+
self.mgr.destinations['alice'] = 'rtmps://example.invalid/old-test-destination'
|
| 56 |
+
self.launches = []
|
| 57 |
+
self.mgr.launch = lambda: self.launches.append(True)
|
| 58 |
+
|
| 59 |
+
def test_check_reports_new_without_adopting(self):
|
| 60 |
+
before = self.mgr.journal.read()
|
| 61 |
+
reported = self.mgr.check()
|
| 62 |
+
self.assertEqual(reported, dict(NEW, previous=OLD))
|
| 63 |
+
self.assertEqual(self.mgr.journal.read(), before)
|
| 64 |
+
self.assertEqual(self.mgr.api.calls, [('channels', 'GET')])
|
| 65 |
+
|
| 66 |
+
def test_unconfirmed_switch_is_still_fail_closed(self):
|
| 67 |
+
before = self.mgr.journal.read()
|
| 68 |
+
with self.assertRaisesRegex(RuntimeError, 'القناة المفوضة تغيرت'):
|
| 69 |
+
self.mgr.check_channel()
|
| 70 |
+
self.assertEqual(self.mgr.journal.read(), before)
|
| 71 |
+
|
| 72 |
+
def test_wrong_confirmation_does_not_modify_journal(self):
|
| 73 |
+
before = self.mgr.journal.read()
|
| 74 |
+
with self.assertRaisesRegex(ValueError, 'لا تطابق آخر فحص'):
|
| 75 |
+
self.mgr.confirm_channel(OLD['id'])
|
| 76 |
+
self.assertEqual(self.mgr.journal.read(), before)
|
| 77 |
+
self.assertTrue(self.mgr.destinations)
|
| 78 |
+
with self.assertRaises(ValueError):
|
| 79 |
+
self.mgr.confirm_channel('')
|
| 80 |
+
|
| 81 |
+
def test_confirm_stops_before_archiving_and_does_not_start(self):
|
| 82 |
+
self.mgr.senders[KEY] = {'fake': True}
|
| 83 |
+
stopped = []
|
| 84 |
+
def stop(key):
|
| 85 |
+
stopped.append(self.mgr.journal.read()['events'][key]['username'])
|
| 86 |
+
self.mgr.senders.pop(key)
|
| 87 |
+
return True
|
| 88 |
+
self.mgr.stop_sender = stop
|
| 89 |
+
result = self.mgr.confirm_channel(NEW['id'])
|
| 90 |
+
d = self.mgr.journal.read()
|
| 91 |
+
self.assertEqual(result, NEW)
|
| 92 |
+
self.assertEqual(d['channel'], NEW)
|
| 93 |
+
self.assertFalse(d['enabled'])
|
| 94 |
+
self.assertFalse(d['events'])
|
| 95 |
+
self.assertFalse(d['streams'])
|
| 96 |
+
self.assertFalse(self.mgr.destinations)
|
| 97 |
+
self.assertEqual(stopped, ['alice'])
|
| 98 |
+
self.assertFalse(self.launches)
|
| 99 |
+
self.assertEqual(len(d['history']), 2)
|
| 100 |
+
self.assertTrue(all(h['channel_id'] == OLD['id'] for h in d['history']))
|
| 101 |
+
archived = next(h for h in d['history'] if h['session_key'] == KEY)
|
| 102 |
+
self.assertEqual(archived['broadcast_id'], 'old-broadcast')
|
| 103 |
+
self.assertEqual(archived['outcome'], 'local_cancelled_channel_switch')
|
| 104 |
+
self.assertEqual(self.mgr.api.calls, [('channels', 'GET')])
|
| 105 |
+
|
| 106 |
+
def test_failed_stop_keeps_old_channel_and_events(self):
|
| 107 |
+
before = self.mgr.journal.read()
|
| 108 |
+
self.mgr.senders[KEY] = {'fake': True}
|
| 109 |
+
self.mgr.stop_sender = lambda key: False
|
| 110 |
+
with self.assertRaisesRegex(RuntimeError, 'لم تُعتمد القناة الجديدة'):
|
| 111 |
+
self.mgr.confirm_channel(NEW['id'])
|
| 112 |
+
self.assertEqual(self.mgr.journal.read(), before)
|
| 113 |
+
self.assertTrue(self.mgr.destinations)
|
| 114 |
+
|
| 115 |
+
def test_wrong_first_confirmation_is_read_only(self):
|
| 116 |
+
self.mgr.journal.change(lambda d: d.update(channel=None, enabled=False, events={}, streams={}))
|
| 117 |
+
before = self.mgr.journal.read()
|
| 118 |
+
with self.assertRaises(ValueError):
|
| 119 |
+
self.mgr.confirm_channel(OLD['id'])
|
| 120 |
+
self.assertEqual(self.mgr.journal.read(), before)
|
| 121 |
+
|
| 122 |
+
def test_same_channel_confirmation_preserves_running_state(self):
|
| 123 |
+
self.mgr.api.channel = dict(OLD)
|
| 124 |
+
before = self.mgr.journal.read()
|
| 125 |
+
self.assertEqual(self.mgr.confirm_channel(OLD['id']), OLD)
|
| 126 |
+
self.assertEqual(self.mgr.journal.read(), before)
|
| 127 |
+
self.assertTrue(self.mgr.destinations)
|
| 128 |
+
self.assertFalse(self.launches)
|
| 129 |
+
|
| 130 |
+
def test_explicit_enable_switches_then_starts_new_channel(self):
|
| 131 |
+
self.mgr.enable(NEW['id'])
|
| 132 |
+
d = self.mgr.journal.read()
|
| 133 |
+
self.assertEqual(d['channel'], NEW)
|
| 134 |
+
self.assertTrue(d['enabled'])
|
| 135 |
+
self.assertFalse(d['events'])
|
| 136 |
+
self.assertFalse(self.mgr.destinations)
|
| 137 |
+
self.assertEqual(self.launches, [True])
|
| 138 |
+
|
| 139 |
+
def test_previous_channel_history_does_not_block_or_resume_room(self):
|
| 140 |
+
self.mgr.confirm_channel(NEW['id'])
|
| 141 |
+
old_entry = next(h for h in self.mgr.journal.read()['history'] if h['session_key'] == KEY)
|
| 142 |
+
before_calls = list(self.mgr.api.calls)
|
| 143 |
+
self.assertIsNone(self.mgr._history_entry(KEY))
|
| 144 |
+
self.assertTrue(self.mgr._republish_allowed(KEY, old_entry))
|
| 145 |
+
self.assertFalse(self.mgr._resume_archived_event('alice', {'room_id': 'room1'}, old_entry))
|
| 146 |
+
self.assertEqual(self.mgr.api.calls, before_calls)
|
| 147 |
+
self.assertTrue(self.mgr.open_event('alice', {'room_id': 'room1', 'nickname': 'Alice'}))
|
| 148 |
+
self.assertTrue(any(h['broadcast_id'] == 'old-broadcast' for h in self.mgr.journal.read()['history']))
|
| 149 |
+
|
| 150 |
+
def test_forget_history_only_for_current_channel(self):
|
| 151 |
+
self.mgr.confirm_channel(NEW['id'])
|
| 152 |
+
self.mgr.journal.change(lambda d: d['history'].append(
|
| 153 |
+
{'session_key': KEY, 'channel_id': NEW['id'], 'broadcast_id': 'new-broadcast'}))
|
| 154 |
+
self.assertEqual(self.mgr._history_entry(KEY)['broadcast_id'], 'new-broadcast')
|
| 155 |
+
self.mgr._forget_history(KEY)
|
| 156 |
+
self.assertIsNone(self.mgr._history_entry(KEY))
|
| 157 |
+
self.assertTrue(any(h['broadcast_id'] == 'old-broadcast' for h in self.mgr.journal.read()['history']))
|
| 158 |
+
|
| 159 |
+
def test_confirmation_http_endpoint_is_protected_and_separate_from_start(self):
|
| 160 |
+
import importlib.util
|
| 161 |
+
if importlib.util.find_spec('httpx') is None:
|
| 162 |
+
self.skipTest('HTTP endpoint test needs the optional httpx test dependency')
|
| 163 |
+
from fastapi.testclient import TestClient
|
| 164 |
+
import app
|
| 165 |
+
client = TestClient(app.app)
|
| 166 |
+
self.addCleanup(client.close)
|
| 167 |
+
before = self.mgr.journal.read()
|
| 168 |
+
with patch.object(app, 'youtube', self.mgr):
|
| 169 |
+
denied = client.post('/api/youtube/channel', json={'channel_id': NEW['id']})
|
| 170 |
+
self.assertEqual(denied.status_code, 401)
|
| 171 |
+
self.assertEqual(self.mgr.journal.read(), before)
|
| 172 |
+
auth = ('admin', os.environ['PASSWORD'])
|
| 173 |
+
wrong = client.post('/api/youtube/channel', json={'channel_id': OLD['id']}, auth=auth)
|
| 174 |
+
self.assertEqual(wrong.status_code, 400)
|
| 175 |
+
self.assertEqual(self.mgr.journal.read(), before)
|
| 176 |
+
accepted = client.post('/api/youtube/channel', json={'channel_id': NEW['id']}, auth=auth)
|
| 177 |
+
self.assertEqual(accepted.status_code, 200)
|
| 178 |
+
self.assertEqual(accepted.json()['channel'], NEW)
|
| 179 |
+
self.assertFalse(self.mgr.journal.read()['enabled'])
|
| 180 |
+
self.assertFalse(self.launches)
|
| 181 |
+
|
| 182 |
+
|
| 183 |
+
class CookieExportTests(unittest.TestCase):
|
| 184 |
+
SID = 'a' * 32
|
| 185 |
+
|
| 186 |
+
def test_json_export_filters_expired_foreign_and_unsafe_cookies(self):
|
| 187 |
+
future = time.time() + 3600
|
| 188 |
+
items = [
|
| 189 |
+
{'name': 'sessionid', 'value': self.SID, 'domain': '.tiktok.com', 'expirationDate': future},
|
| 190 |
+
{'name': 'sid_guard', 'value': self.SID + '%7C1700000000%7C15552000', 'domain': '.tiktok.com'},
|
| 191 |
+
{'name': 'tt-target-idc', 'value': 'alisg', 'domain': '.tiktok.com'},
|
| 192 |
+
{'name': 'expired', 'value': 'old', 'domain': '.tiktok.com', 'expirationDate': time.time() - 1},
|
| 193 |
+
{'name': 'foreign', 'value': 'no', 'domain': 'tiktok.com.attacker.invalid'},
|
| 194 |
+
{'name': 'header_injection', 'value': 'no\r\nX-Header: x', 'domain': '.tiktok.com'},
|
| 195 |
+
{'name': 'wrong_path', 'value': 'no', 'domain': '.tiktok.com', 'path': '/other'},
|
| 196 |
+
]
|
| 197 |
+
sid, pairs = tiktok_auth.parse_token(json.dumps(items))
|
| 198 |
+
self.assertEqual(sid, self.SID)
|
| 199 |
+
self.assertEqual(pairs['sessionid_ss'], self.SID)
|
| 200 |
+
self.assertEqual(pairs['tt-target-idc'], 'alisg')
|
| 201 |
+
for rejected in ('expired', 'foreign', 'header_injection', 'wrong_path'):
|
| 202 |
+
self.assertNotIn(rejected, pairs)
|
| 203 |
+
|
| 204 |
+
def test_www_cookie_wins_in_either_export_order(self):
|
| 205 |
+
cookies = [{'name': 'sessionid', 'value': self.SID, 'domain': '.tiktok.com'},
|
| 206 |
+
{'name': 'msToken', 'value': 'specific==', 'domain': 'www.tiktok.com', 'hostOnly': True},
|
| 207 |
+
{'name': 'msToken', 'value': 'broad==', 'domain': '.tiktok.com'}]
|
| 208 |
+
for values in (cookies, cookies[::-1]):
|
| 209 |
+
sid, pairs = tiktok_auth.parse_token(json.dumps(values))
|
| 210 |
+
self.assertEqual(sid, self.SID)
|
| 211 |
+
self.assertEqual(pairs['msToken'], 'specific==')
|
| 212 |
+
|
| 213 |
+
def test_wrapped_json_and_malformed_export(self):
|
| 214 |
+
sid, pairs = tiktok_auth.parse_token(json.dumps({'cookies': [
|
| 215 |
+
{'name': 'sessionid', 'value': self.SID, 'domain': '.tiktok.com'}]}))
|
| 216 |
+
self.assertEqual(sid, self.SID)
|
| 217 |
+
for text in ('[{broken]', '{}', '[1, null, "bad"]'):
|
| 218 |
+
self.assertEqual(tiktok_auth.parse_token(text), ('', {}))
|
| 219 |
+
|
| 220 |
+
def test_expired_session_cannot_synthesize_login(self):
|
| 221 |
+
text = json.dumps([{'name': 'sessionid', 'value': self.SID,
|
| 222 |
+
'domain': '.tiktok.com', 'expirationDate': time.time() - 1}])
|
| 223 |
+
self.assertEqual(tiktok_auth.parse_token(text), ('', {}))
|
| 224 |
+
|
| 225 |
+
def test_old_formats_still_supported(self):
|
| 226 |
+
for token in (self.SID, 'sessionid=' + self.SID,
|
| 227 |
+
'.tiktok.com\tTRUE\t/\tTRUE\t0\tsessionid\t' + self.SID):
|
| 228 |
+
self.assertEqual(tiktok_auth.parse_token(token)[0], self.SID)
|
| 229 |
+
sid, pairs = tiktok_auth.parse_token('sessionid=' + self.SID + '; msToken=extra==; tt-target-idc=alisg')
|
| 230 |
+
self.assertEqual(sid, self.SID)
|
| 231 |
+
self.assertEqual(pairs['msToken'], 'extra==')
|
| 232 |
+
self.assertEqual(pairs['tt-target-idc'], 'alisg')
|
| 233 |
+
|
| 234 |
+
|
| 235 |
+
if __name__ == '__main__':
|
| 236 |
+
unittest.main(argv=[sys.argv[0]], verbosity=2)
|
test_completion.py
CHANGED
|
@@ -35,13 +35,13 @@ os.environ.pop('YOUTUBE_MAX_EVENTS', None)
|
|
| 35 |
import importlib
|
| 36 |
import ingest
|
| 37 |
importlib.reload(ingest)
|
| 38 |
-
check('
|
| 39 |
os.environ['MAX_CONCURRENT_RELAYS'] = '7'
|
| 40 |
importlib.reload(ingest)
|
| 41 |
check('env 7 is accepted as a cap (not a promise of 7 healthy streams)', ingest.max_concurrent_relays() == 7)
|
| 42 |
os.environ['MAX_CONCURRENT_RELAYS'] = '99'
|
| 43 |
importlib.reload(ingest)
|
| 44 |
-
check('
|
| 45 |
os.environ['MAX_CONCURRENT_RELAYS'] = '2'
|
| 46 |
importlib.reload(ingest)
|
| 47 |
check('env 2 in force', ingest.max_concurrent_relays() == 2)
|
|
|
|
| 35 |
import importlib
|
| 36 |
import ingest
|
| 37 |
importlib.reload(ingest)
|
| 38 |
+
check('without an env cap MAX_CONCURRENT_RELAYS is open (0)', ingest.max_concurrent_relays() == 0, str(ingest.max_concurrent_relays()))
|
| 39 |
os.environ['MAX_CONCURRENT_RELAYS'] = '7'
|
| 40 |
importlib.reload(ingest)
|
| 41 |
check('env 7 is accepted as a cap (not a promise of 7 healthy streams)', ingest.max_concurrent_relays() == 7)
|
| 42 |
os.environ['MAX_CONCURRENT_RELAYS'] = '99'
|
| 43 |
importlib.reload(ingest)
|
| 44 |
+
check('an explicit operator cap is reported exactly', ingest.max_concurrent_relays() == 99)
|
| 45 |
os.environ['MAX_CONCURRENT_RELAYS'] = '2'
|
| 46 |
importlib.reload(ingest)
|
| 47 |
check('env 2 in force', ingest.max_concurrent_relays() == 2)
|
test_dashboard.js
ADDED
|
@@ -0,0 +1,138 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env node
|
| 2 |
+
'use strict';
|
| 3 |
+
// Execute the real inline dashboard script with a small DOM/fetch harness. No live API.
|
| 4 |
+
const assert = require('node:assert/strict');
|
| 5 |
+
const fs = require('node:fs');
|
| 6 |
+
const path = require('node:path');
|
| 7 |
+
const vm = require('node:vm');
|
| 8 |
+
const root = process.argv[2] || __dirname;
|
| 9 |
+
const html = fs.readFileSync(path.join(root, 'index.html'), 'utf8');
|
| 10 |
+
const script = html.match(/<script>([\s\S]*?)<\/script>/)[1];
|
| 11 |
+
const ids = [...html.matchAll(/id="([^"]+)"/g)].map(m => m[1]);
|
| 12 |
+
const OLD = {id: 'OLD_CHANNEL', title: 'Old channel'};
|
| 13 |
+
const NEW = {id: 'NEW_CHANNEL', title: 'New channel'};
|
| 14 |
+
const clone = o => JSON.parse(JSON.stringify(o));
|
| 15 |
+
let passed = 0;
|
| 16 |
+
|
| 17 |
+
function harness() {
|
| 18 |
+
const elements = new Map(ids.map(id => [id, {
|
| 19 |
+
hidden: false, disabled: false, value: '', textContent: '', innerHTML: '', focus() {}
|
| 20 |
+
}]));
|
| 21 |
+
const state = {active: clone(OLD), authorized: clone(NEW), automatic: false, events: [],
|
| 22 |
+
requests: [], prompts: [], alerts: [], accept: true, blockCheck: null, failCheck: false};
|
| 23 |
+
const storage = new Map();
|
| 24 |
+
const sandbox = {
|
| 25 |
+
console, TextEncoder, Date, JSON, String, Number, Math, Promise,
|
| 26 |
+
btoa: s => Buffer.from(s, 'binary').toString('base64'),
|
| 27 |
+
sessionStorage: {getItem: k => storage.get(k) || null, setItem: (k,v) => storage.set(k,v), removeItem: k => storage.delete(k)},
|
| 28 |
+
document: {hidden: false, activeElement: null,
|
| 29 |
+
getElementById(id) {assert(elements.has(id), 'missing DOM element: ' + id);return elements.get(id)},
|
| 30 |
+
addEventListener() {}},
|
| 31 |
+
setInterval(fn) {state.timer = fn;return 1},
|
| 32 |
+
alert(text) {state.alerts.push(text)},
|
| 33 |
+
confirm(text) {state.prompts.push(text);return state.accept},
|
| 34 |
+
async fetch(url, opts) {
|
| 35 |
+
const body = opts.body ? JSON.parse(opts.body) : null;
|
| 36 |
+
state.requests.push({url, method: opts.method, body, headers: opts.headers});
|
| 37 |
+
let data, status = 200;
|
| 38 |
+
if (url === '/api/youtube') data = {channel: clone(state.active), automatic: state.automatic,
|
| 39 |
+
configured: true, events: clone(state.events), settings: {privacy:'public', title:'title', description:'description'}};
|
| 40 |
+
else if (url === '/api/state') data = {tasks:[], logs:[], monitor_running:true, check_interval:20};
|
| 41 |
+
else if (url === '/api/youtube/check') {
|
| 42 |
+
if (state.blockCheck) await state.blockCheck;
|
| 43 |
+
if (state.failCheck) {status=400;data={detail:'OAuth check failed'}}
|
| 44 |
+
else data={channel:Object.assign(clone(state.authorized),
|
| 45 |
+
state.active.id!==state.authorized.id ? {previous:clone(state.active)} : {})};
|
| 46 |
+
} else if (url === '/api/youtube/start' || url === '/api/youtube/channel') {
|
| 47 |
+
assert.equal(body.channel_id, state.authorized.id, 'must send the freshly checked channel id');
|
| 48 |
+
state.active=clone(state.authorized);state.automatic=url.endsWith('/start');
|
| 49 |
+
data={ok:true, channel:clone(state.active)};
|
| 50 |
+
} else if (url === '/api/youtube/stop') {state.automatic=false;data={ok:true}}
|
| 51 |
+
else throw Error('Unexpected route: '+url);
|
| 52 |
+
return {ok:status<400,status,async json(){return clone(data)}};
|
| 53 |
+
}
|
| 54 |
+
};
|
| 55 |
+
const context=vm.createContext(sandbox);
|
| 56 |
+
vm.runInContext(script, context);
|
| 57 |
+
vm.runInContext("authHeader='Basic dGVzdDp0ZXN0'", context);
|
| 58 |
+
return {state, elements, context,
|
| 59 |
+
async click(id){await vm.runInContext("$('"+id+"').onclick()",context)},
|
| 60 |
+
async refresh(){await vm.runInContext('refresh()',context)},
|
| 61 |
+
read(expr){return vm.runInContext(expr,context)}};
|
| 62 |
+
}
|
| 63 |
+
function pass(name){passed++;console.log('PASS '+name)}
|
| 64 |
+
|
| 65 |
+
(async()=>{
|
| 66 |
+
let h=harness();
|
| 67 |
+
h.state.events=[{username:'muhajer_iraqi',title:'Live event',phase:'live',youtube_status:'live',
|
| 68 |
+
source:'hd 720p',send_mode:'copy',pending_send_mode:'matchgop',output_seconds:60}];
|
| 69 |
+
await h.refresh();
|
| 70 |
+
assert.match(h.elements.get('events').innerHTML,/وضع الإرسال الفعلي: copy/);
|
| 71 |
+
assert.match(h.elements.get('events').innerHTML,/الترميز الثابت ينتظر خانة: matchgop/);
|
| 72 |
+
pass('Per-event sender mode is shown instead of hiding an account-specific fallback behind the global preference');
|
| 73 |
+
await h.click('ytcheck');
|
| 74 |
+
assert.equal(h.read('checkedChannel.id'),NEW.id);
|
| 75 |
+
assert.equal(h.state.active.id,OLD.id);
|
| 76 |
+
await h.refresh();await h.state.timer();
|
| 77 |
+
assert.equal(h.read('checkedChannel.id'),NEW.id);
|
| 78 |
+
assert.equal(h.read('lastY.channel.id'),OLD.id);
|
| 79 |
+
assert.equal(h.elements.get('ytadopt').hidden,false);
|
| 80 |
+
assert.match(h.elements.get('ytchannelnotice').textContent,/New channel/);
|
| 81 |
+
pass('OAuth check → refresh → timer retains NEW, not the journal OLD (production regression)');
|
| 82 |
+
|
| 83 |
+
await h.click('ytstart');
|
| 84 |
+
const posts=h.state.requests.filter(r=>r.method==='POST');
|
| 85 |
+
assert.equal(posts.at(-2).url,'/api/youtube/check');
|
| 86 |
+
assert.equal(posts.at(-1).url,'/api/youtube/start');
|
| 87 |
+
assert.equal(posts.at(-1).body.channel_id,NEW.id);
|
| 88 |
+
assert.match(h.state.prompts.at(-1),/Old channel/);
|
| 89 |
+
assert.match(h.state.prompts.at(-1),/New channel/);
|
| 90 |
+
assert.equal(h.state.automatic,true);
|
| 91 |
+
assert.equal(h.elements.get('ytadopt').hidden,true);
|
| 92 |
+
pass('Start rechecks OAuth and explicitly confirms both channel names before NEW is enabled');
|
| 93 |
+
|
| 94 |
+
h=harness();await h.click('ytcheck');await h.click('ytadopt');
|
| 95 |
+
assert.equal(h.state.active.id,NEW.id);
|
| 96 |
+
assert.equal(h.state.automatic,false);
|
| 97 |
+
assert(!h.state.requests.some(r=>r.url==='/api/youtube/start'));
|
| 98 |
+
assert.equal(h.elements.get('ytadopt').hidden,true);
|
| 99 |
+
pass('Adopt-only confirms the new channel without starting a broadcast');
|
| 100 |
+
|
| 101 |
+
h=harness();await h.click('ytcheck');h.state.accept=false;await h.click('ytstart');
|
| 102 |
+
assert.equal(h.state.active.id,OLD.id);
|
| 103 |
+
assert(!h.state.requests.some(r=>r.url==='/api/youtube/start'));
|
| 104 |
+
pass('Cancelled start never sends a start request or adopts the channel');
|
| 105 |
+
|
| 106 |
+
h=harness();await h.click('ytcheck');h.state.accept=false;await h.click('ytadopt');
|
| 107 |
+
assert(!h.state.requests.some(r=>r.url==='/api/youtube/channel'));
|
| 108 |
+
assert.equal(h.state.active.id,OLD.id);
|
| 109 |
+
pass('Cancelled adoption leaves the previous channel unchanged');
|
| 110 |
+
|
| 111 |
+
h=harness();await h.click('ytcheck');
|
| 112 |
+
h.state.authorized={id:'THIRD_CHANNEL',title:'Rotated channel'};
|
| 113 |
+
await h.click('ytstart');
|
| 114 |
+
assert.equal(h.state.active.id,'THIRD_CHANNEL');
|
| 115 |
+
assert.match(h.state.prompts.at(-1),/Rotated channel/);
|
| 116 |
+
pass('Secrets rotated after check are freshly discovered, not silently confirmed with a stale id');
|
| 117 |
+
|
| 118 |
+
h=harness();h.state.failCheck=true;await h.click('ytstart');
|
| 119 |
+
assert(!h.state.requests.some(r=>r.url==='/api/youtube/start'));
|
| 120 |
+
assert.match(h.elements.get('error').textContent,/OAuth check failed/);
|
| 121 |
+
assert.equal(h.elements.get('ytcheck').disabled,false);
|
| 122 |
+
pass('Failed OAuth check cannot start and restores the controls');
|
| 123 |
+
|
| 124 |
+
h=harness();let release;
|
| 125 |
+
h.state.blockCheck=new Promise(resolve=>{release=resolve});
|
| 126 |
+
const first=h.click('ytstart');await Promise.resolve();await h.click('ytstart');release();await first;
|
| 127 |
+
assert.equal(h.state.requests.filter(r=>r.url==='/api/youtube/start').length,1);
|
| 128 |
+
assert.equal(h.state.requests.filter(r=>r.url==='/api/youtube/check').length,1);
|
| 129 |
+
pass('Double-click while OAuth is pending sends only one check and one start');
|
| 130 |
+
|
| 131 |
+
h=harness();await h.click('ytcheck');await h.click('logout');
|
| 132 |
+
assert.equal(h.read('checkedChannel'),null);
|
| 133 |
+
assert.equal(h.read('authHeader'),'');
|
| 134 |
+
assert.equal(h.elements.get('ytadopt').hidden,true);
|
| 135 |
+
pass('Logout clears the checked channel and credentials');
|
| 136 |
+
|
| 137 |
+
console.log('\n'+passed+' dashboard regressions passed');
|
| 138 |
+
})().catch(err=>{console.error(err);process.exitCode=1});
|
test_flv_bridge.py
ADDED
|
@@ -0,0 +1,244 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Deterministic decoder-record/reconnect tests; no network or transcoding."""
|
| 3 |
+
import json
|
| 4 |
+
import os
|
| 5 |
+
import pathlib
|
| 6 |
+
import shutil
|
| 7 |
+
import subprocess
|
| 8 |
+
import sys
|
| 9 |
+
import tempfile
|
| 10 |
+
|
| 11 |
+
ROOT=pathlib.Path(sys.argv[1] if len(sys.argv)>1 else pathlib.Path(__file__).parent).resolve()
|
| 12 |
+
sys.path.insert(0,str(ROOT))
|
| 13 |
+
from flv_bridge import FLVBridge # noqa: E402
|
| 14 |
+
from stream_monitor import StreamMonitor, video_dimensions # noqa: E402
|
| 15 |
+
|
| 16 |
+
passed=failed=0
|
| 17 |
+
def check(name,ok,detail=''):
|
| 18 |
+
global passed,failed
|
| 19 |
+
if ok:
|
| 20 |
+
passed+=1;print('PASS ',name)
|
| 21 |
+
else:
|
| 22 |
+
failed+=1;print('FAIL ',name,detail)
|
| 23 |
+
|
| 24 |
+
def tag(kind,ts,body):
|
| 25 |
+
size=len(body)
|
| 26 |
+
header=bytes([kind])+size.to_bytes(3,'big')+bytes([
|
| 27 |
+
(ts>>16)&255,(ts>>8)&255,ts&255,(ts>>24)&255,0,0,0])
|
| 28 |
+
return header+body+(11+size).to_bytes(4,'big')
|
| 29 |
+
|
| 30 |
+
def flv(*records):
|
| 31 |
+
return b'FLV\x01\x05\x00\x00\x00\x09\x00\x00\x00\x00'+b''.join(records)
|
| 32 |
+
|
| 33 |
+
def parse(blob):
|
| 34 |
+
assert blob[:3]==b'FLV'
|
| 35 |
+
offset=int.from_bytes(blob[5:9],'big')+4;out=[]
|
| 36 |
+
while offset+15<=len(blob):
|
| 37 |
+
header=blob[offset:offset+11];size=int.from_bytes(header[1:4],'big')
|
| 38 |
+
total=11+size+4
|
| 39 |
+
assert offset+total<=len(blob)
|
| 40 |
+
body=blob[offset+11:offset+11+size]
|
| 41 |
+
assert int.from_bytes(blob[offset+11+size:offset+total],'big')==11+size
|
| 42 |
+
ts=(header[7]<<24)|(header[4]<<16)|(header[5]<<8)|header[6]
|
| 43 |
+
out.append((header[0]&31,ts,body));offset+=total
|
| 44 |
+
assert offset==len(blob)
|
| 45 |
+
return out
|
| 46 |
+
|
| 47 |
+
def chunked(bridge,data):
|
| 48 |
+
cuts=(1,2,7,3,19,5,31,11);out=[];pos=0;i=0
|
| 49 |
+
while pos<len(data):
|
| 50 |
+
n=cuts[i%len(cuts)];out.append(bridge.feed(data[pos:pos+n]));pos+=n;i+=1
|
| 51 |
+
return b''.join(out)
|
| 52 |
+
|
| 53 |
+
def seq(codec,cfg,legacy=True,frame=1):
|
| 54 |
+
if legacy:
|
| 55 |
+
codec_id=7 if codec=='avc1' else 12
|
| 56 |
+
return bytes([(frame<<4)|codec_id,0,0,0,0])+cfg
|
| 57 |
+
return bytes([0x80|(frame<<4)])+codec.encode()+cfg
|
| 58 |
+
|
| 59 |
+
def coded(codec,payload,cts=b'\x00\x00\x00',legacy=True,frame=2):
|
| 60 |
+
if legacy:
|
| 61 |
+
codec_id=7 if codec=='avc1' else 12
|
| 62 |
+
return bytes([(frame<<4)|codec_id,1])+cts+payload
|
| 63 |
+
return bytes([0x80|(frame<<4)|1])+codec.encode()+cts+payload
|
| 64 |
+
|
| 65 |
+
AVC_A=bytes.fromhex('0142c00dffe100166742c00dda0507ec0440000003004000000ca3c50aa801000468ce0fc8')
|
| 66 |
+
AVC_B=bytes.fromhex('0142c01effe100196742c01eda0280bfe5c044000003000400000300ca3c58ba8001000468ce0fc8')
|
| 67 |
+
HEVC_A=bytes.fromhex('0101600000009000000000003cf000fcfdf8f800000f03200001001840010c01ffff01600000030090000003000003003c959409210001002a42010101600000030090000003000003003ca00a080f16595952930bc05a02000003000200000300321022000100064401c073c189')
|
| 68 |
+
HEVC_B=bytes.fromhex('0101600000009000000000003ff000fcfdf8f800000f03200001001840010c01ffff01600000030090000003000003003f959409210001002b42010101600000030090000003000003003fa005020171f2e595952930bc05a0200000030020000003032122000100064401c073c189')
|
| 69 |
+
VIDEO_A=b'\x00\x00\x00\x03\x65\x88\x84'
|
| 70 |
+
VIDEO_H=b'\x00\x00\x00\x04\x26\x01\xaf\x09'
|
| 71 |
+
|
| 72 |
+
# A changed AVCDecoderConfigurationRecord must precede its dependent frame and must not raise,
|
| 73 |
+
# even when an old caller still enables detect_format_change.
|
| 74 |
+
events=[]
|
| 75 |
+
b=FLVBridge(detect_format_change=True,allow_raise=lambda:True,user='alice',
|
| 76 |
+
event_logger=lambda user,event,details:events.append((user,event,details)))
|
| 77 |
+
avc_input=flv(tag(9,0,seq('avc1',AVC_A)),tag(9,0,coded('avc1',VIDEO_A,b'\xff\xff\xfe')),
|
| 78 |
+
tag(9,40,seq('avc1',AVC_B)),tag(9,40,coded('avc1',VIDEO_A)))
|
| 79 |
+
avc_out=chunked(b,avc_input);avc_tags=parse(avc_out)
|
| 80 |
+
check('AVC configuration replacement stays in one bridge session',b.format_changes==1)
|
| 81 |
+
check('AVC replacement is not classified as a codec switch',b.codec_changes==0 and b.video_codec=='avc1')
|
| 82 |
+
check('both AVC configuration records are emitted in order',
|
| 83 |
+
[x[2][5:] for x in avc_tags if x[0]==9 and x[2][1:2]==b'\x00']==[AVC_A,AVC_B])
|
| 84 |
+
check('AVC coded bytes and signed CTS pass unchanged',
|
| 85 |
+
[x[2] for x in avc_tags if x[0]==9 and x[2][1:2]==b'\x01']==
|
| 86 |
+
[coded('avc1',VIDEO_A,b'\xff\xff\xfe'),coded('avc1',VIDEO_A)])
|
| 87 |
+
check('continuous-source DTS is preserved exactly',[x[1] for x in avc_tags]==[0,0,40,40])
|
| 88 |
+
check('AVC config and resolution changes are recorded with broadcaster identity',
|
| 89 |
+
[x[1] for x in events]==['STREAM_CONFIG','DECODER_CONFIG_CHANGE','RESOLUTION_CHANGE'] and
|
| 90 |
+
events[-1][0]=='alice' and events[-1][2]['new_width']==640)
|
| 91 |
+
|
| 92 |
+
# A complete avcC may itself contain accumulated arrays. Preserve the record as a unit rather
|
| 93 |
+
# than trying to append old records with potentially conflicting parameter-set IDs.
|
| 94 |
+
sps=(b'\x67\x64\x00\x1f\xac',b'\x67\x64\x00\x1f\xad')
|
| 95 |
+
pps=(b'\x68\xee\x3c\x80',b'\x68\xee\x3c\x81')
|
| 96 |
+
MULTI_AVC=b'\x01\x64\x00\x1f\xff\xe2'+b''.join(len(x).to_bytes(2,'big')+x for x in sps)+b'\x02'+b''.join(len(x).to_bytes(2,'big')+x for x in pps)
|
| 97 |
+
multi=parse(FLVBridge().feed(flv(tag(9,0,seq('avc1',MULTI_AVC)))))
|
| 98 |
+
check('multi-SPS/PPS AVC record is preserved whole',multi[0][2][5:]==MULTI_AVC)
|
| 99 |
+
|
| 100 |
+
# TikTok's legacy HEVC convention is translated tag-for-tag to Enhanced RTMP hvc1.
|
| 101 |
+
bh=FLVBridge(detect_format_change=True)
|
| 102 |
+
h_in=flv(tag(9,0,seq('hvc1',HEVC_A)),
|
| 103 |
+
tag(9,1,coded('hvc1',VIDEO_H,b'\xff\xff\xfd',frame=2)),
|
| 104 |
+
tag(9,40,seq('hvc1',HEVC_B)),tag(9,41,coded('hvc1',VIDEO_H,frame=1)))
|
| 105 |
+
h_out=chunked(bh,h_in);h_tags=parse(h_out)
|
| 106 |
+
check('legacy HEVC records are monitored without interruption',bh.format_changes==1 and bh.codec_changes==0)
|
| 107 |
+
check('legacy HEVC SequenceStart becomes Enhanced RTMP hvc1',
|
| 108 |
+
[x[2] for x in h_tags if x[0]==9 and (x[2][0]&15)==0]==[b'\x90hvc1'+HEVC_A,b'\x90hvc1'+HEVC_B])
|
| 109 |
+
check('legacy HEVC coded payload and CTS are byte-identical after envelope rewrite',
|
| 110 |
+
[x[2] for x in h_tags if x[0]==9 and (x[2][0]&15)==1]==
|
| 111 |
+
[b'\xa1hvc1\xff\xff\xfd'+VIDEO_H,b'\x91hvc1\x00\x00\x00'+VIDEO_H])
|
| 112 |
+
check('all legacy HEVC video tags were converted',bh.converted_tags==4)
|
| 113 |
+
|
| 114 |
+
# Already-enhanced hvc1 must not be rewritten at all.
|
| 115 |
+
eh_seq=seq('hvc1',HEVC_A,legacy=False);eh_frame=coded('hvc1',VIDEO_H,b'\x00\x00\x07',legacy=False)
|
| 116 |
+
eh=parse(FLVBridge().feed(flv(tag(9,0,eh_seq),tag(9,1,eh_frame))))
|
| 117 |
+
check('already-enhanced hvc1 bodies pass unchanged',[x[2] for x in eh]==[eh_seq,eh_frame])
|
| 118 |
+
|
| 119 |
+
# Reattach suppresses only an identical startup record and preserves timestamp continuity.
|
| 120 |
+
reconnect_events=[]
|
| 121 |
+
br=FLVBridge(user='alice',event_logger=lambda user,event,details:reconnect_events.append((event,details)))
|
| 122 |
+
first=br.feed(flv(tag(9,100,seq('avc1',AVC_A)),tag(9,140,coded('avc1',VIDEO_A))))
|
| 123 |
+
last=br.last_out_ts;br.reconnect()
|
| 124 |
+
second=br.feed(flv(tag(18,0,b'metadata'),tag(9,0,seq('avc1',AVC_A)),tag(9,40,coded('avc1',VIDEO_A))))
|
| 125 |
+
joined=parse(first+second)
|
| 126 |
+
check('reattach drops second FLV header and startup metadata',len(second)>0 and not second.startswith(b'FLV') and all(x[0]!=18 for x in joined))
|
| 127 |
+
check('source reattach is recorded without claiming RTMP closure',
|
| 128 |
+
reconnect_events[-1][0]=='RECONNECT' and reconnect_events[-1][1]['outbound_rtmp_reused'] is True)
|
| 129 |
+
check('reattach drops only identical startup decoder record',sum(1 for x in joined if x[0]==9 and x[2][1:2]==b'\x00')==1)
|
| 130 |
+
check('reattach shifts DTS once while preserving valid equal timestamps',
|
| 131 |
+
br.last_out_ts>last and all(a[1]<=z[1] for a,z in zip(joined,joined[1:])))
|
| 132 |
+
|
| 133 |
+
bc=FLVBridge();part1=bc.feed(flv(tag(9,0,seq('avc1',AVC_A)),tag(9,20,coded('avc1',VIDEO_A))))
|
| 134 |
+
bc.reconnect();part2=bc.feed(flv(tag(9,0,seq('avc1',AVC_B)),tag(9,20,coded('avc1',VIDEO_A))))
|
| 135 |
+
changed=parse(part1+part2)
|
| 136 |
+
check('reattach never suppresses a changed decoder record',
|
| 137 |
+
[x[2][5:] for x in changed if x[0]==9 and x[2][1:2]==b'\x00']==[AVC_A,AVC_B])
|
| 138 |
+
check('changed reattach remains on one FLV byte stream',not part2.startswith(b'FLV') and bc.format_changes==1)
|
| 139 |
+
|
| 140 |
+
# The byte bridge can represent a FourCC transition without raising or closing. FFmpeg 7 creates
|
| 141 |
+
# a new late AVStream for such a transition, so production source selection still pins one codec;
|
| 142 |
+
# same-codec decoder-record replacement above is the fully verified path.
|
| 143 |
+
switch_events=[]
|
| 144 |
+
bs=FLVBridge(detect_format_change=True,user='alice',
|
| 145 |
+
event_logger=lambda user,event,details:switch_events.append(event))
|
| 146 |
+
switch=bs.feed(flv(tag(9,0,seq('avc1',AVC_A)),tag(9,1,coded('avc1',VIDEO_A)),
|
| 147 |
+
tag(9,40,seq('hvc1',HEVC_A,legacy=False)),tag(9,41,coded('hvc1',VIDEO_H,legacy=False))))
|
| 148 |
+
switch_tags=parse(switch)
|
| 149 |
+
check('AVC to HEVC transition does not raise or truncate bridge output',len(switch_tags)==4)
|
| 150 |
+
check('codec transition is separately observable',bs.format_changes==1 and bs.codec_changes==1 and bs.video_codec=='hvc1')
|
| 151 |
+
check('codec transition writes CODEC_CHANGE without stopping the bridge','CODEC_CHANGE' in switch_events)
|
| 152 |
+
|
| 153 |
+
try:
|
| 154 |
+
FLVBridge().feed(flv(tag(9,0,b'\x90hvc1')))
|
| 155 |
+
truncated=False
|
| 156 |
+
except ValueError:
|
| 157 |
+
truncated=True
|
| 158 |
+
check('truncated Enhanced SequenceStart fails in a controlled way',truncated)
|
| 159 |
+
|
| 160 |
+
# Metric transitions are inferred from tag bytes/timestamps, never by decoding the picture.
|
| 161 |
+
metric_events=[];records=[tag(9,0,seq('avc1',AVC_A))]
|
| 162 |
+
for ts in range(0,10000,40):
|
| 163 |
+
frame=1 if ts in (0,2000,4000,5000,6000,7000,8000,9000) else 2
|
| 164 |
+
payload=(b'x'*100) if ts<5000 else (b'y'*1000)
|
| 165 |
+
records.append(tag(9,ts,coded('avc1',payload,frame=frame)))
|
| 166 |
+
FLVBridge(user='alice',event_logger=lambda user,event,details:metric_events.append(event)).feed(flv(*records))
|
| 167 |
+
check('byte-level monitor detects a sudden bitrate change','BITRATE_CHANGE' in metric_events)
|
| 168 |
+
check('byte-level monitor detects a keyframe-interval change','KEYFRAME_CHANGE' in metric_events)
|
| 169 |
+
check('AVC and HEVC SPS dimensions are parsed without decoding',
|
| 170 |
+
video_dimensions('avc1',AVC_A)==(320,240) and video_dimensions('avc1',AVC_B)==(640,360) and
|
| 171 |
+
video_dimensions('hvc1',HEVC_A)==(320,240) and video_dimensions('hvc1',HEVC_B)==(640,360))
|
| 172 |
+
|
| 173 |
+
with tempfile.TemporaryDirectory() as mon_dir:
|
| 174 |
+
mon_path=pathlib.Path(mon_dir)/'logs'/'stream_events.json';mon=StreamMonitor(mon_path)
|
| 175 |
+
mon.log('alice','CONNECTION_ERROR',{'scope':'youtube_rtmp','url':'secret-url',
|
| 176 |
+
'stream_key':'secret-key','reason':'failed https://secret-host/live/SECRET'})
|
| 177 |
+
mon.note_rtmp_open('alice');mon.note_rtmp_open('alice',{'mode':'copy'})
|
| 178 |
+
saved=json.loads(mon_path.read_text())
|
| 179 |
+
check('stream event file is valid JSON with the required schema',
|
| 180 |
+
len(saved)==2 and all(set(('timestamp','broadcaster','event','details'))<=set(x) for x in saved))
|
| 181 |
+
check('stream monitor never persists URLs, keys or tokens',
|
| 182 |
+
all(x not in mon_path.read_text() for x in ('secret-url','secret-key','secret-host','SECRET')))
|
| 183 |
+
check('stream event file is owner-only',mon_path.stat().st_mode&0o777==0o600)
|
| 184 |
+
check('second outbound publisher open is recorded as RECONNECT',saved[-1]['event']=='RECONNECT')
|
| 185 |
+
|
| 186 |
+
# FFmpeg 7 is the real outbound middle layer. If available, prove its FLV demux/mux pair writes
|
| 187 |
+
# replacement AVC and HEVC configuration records instead of fixing extradata at startup.
|
| 188 |
+
ff=os.environ.get('FFMPEG_PATH') or shutil.which('ffmpeg')
|
| 189 |
+
if ff and pathlib.Path(ff).is_file():
|
| 190 |
+
with tempfile.TemporaryDirectory() as td:
|
| 191 |
+
td=pathlib.Path(td)
|
| 192 |
+
fixtures=(
|
| 193 |
+
('avc',flv(tag(9,0,seq('avc1',AVC_A)),tag(9,1,coded('avc1',VIDEO_A,frame=1)),
|
| 194 |
+
tag(9,40,seq('avc1',AVC_B)),tag(9,41,coded('avc1',VIDEO_A,frame=1))),[AVC_A,AVC_B]),
|
| 195 |
+
('hevc',flv(tag(9,0,seq('hvc1',HEVC_A,legacy=False)),tag(9,1,coded('hvc1',VIDEO_H,legacy=False,frame=1)),
|
| 196 |
+
tag(9,40,seq('hvc1',HEVC_B,legacy=False)),tag(9,41,coded('hvc1',VIDEO_H,legacy=False,frame=1))),[HEVC_A,HEVC_B]),
|
| 197 |
+
)
|
| 198 |
+
for name,data,expected in fixtures:
|
| 199 |
+
src=td/(name+'.flv');dst=td/(name+'-out.flv');src.write_bytes(data)
|
| 200 |
+
run=subprocess.run([ff,'-y','-hide_banner','-loglevel','error','-i',str(src),
|
| 201 |
+
'-map','0:v:0','-c:v','copy','-flvflags','no_duration_filesize','-f','flv',str(dst)],
|
| 202 |
+
stdout=subprocess.PIPE,stderr=subprocess.PIPE,timeout=20)
|
| 203 |
+
bodies=[x[2] for x in parse(dst.read_bytes()) if x[0]==9] if run.returncode==0 and dst.exists() else []
|
| 204 |
+
configs=[]
|
| 205 |
+
for body in bodies:
|
| 206 |
+
if body[0]&0x80 and (body[0]&15)==0:configs.append(body[5:])
|
| 207 |
+
elif len(body)>5 and (body[0]&15)==7 and body[1]==0:configs.append(body[5:])
|
| 208 |
+
check('FFmpeg copy re-emits both %s decoder records'%name,run.returncode==0 and configs==expected,
|
| 209 |
+
run.stderr.decode(errors='replace')[-300:])
|
| 210 |
+
units=[]
|
| 211 |
+
for body in bodies:
|
| 212 |
+
if name=='avc' and len(body)>5 and not(body[0]&0x80) and body[1]==1:
|
| 213 |
+
units.append(body[5:])
|
| 214 |
+
elif name=='hevc' and len(body)>5 and body[0]&0x80:
|
| 215 |
+
if (body[0]&15)==1 and len(body)>=8:units.append(body[8:])
|
| 216 |
+
elif (body[0]&15)==3:units.append(body[5:])
|
| 217 |
+
payload=VIDEO_A if name=='avc' else VIDEO_H
|
| 218 |
+
check('FFmpeg copy preserves %s encoded access units byte-for-byte'%name,units==[payload,payload])
|
| 219 |
+
else:
|
| 220 |
+
print('SKIP FFmpeg decoder-record remux checks (ffmpeg unavailable)')
|
| 221 |
+
|
| 222 |
+
# --- Gap filler: frozen keyframes keep the timeline (and YouTube leg) alive ---
|
| 223 |
+
b2=FLVBridge(user='alice',event_logger=lambda *a:None)
|
| 224 |
+
check('no filler before any keyframe was emitted',b2.freeze_bytes() is None)
|
| 225 |
+
src=flv(tag(9,1000,seq('avc1',AVC_A)),tag(9,1000,coded('avc1',VIDEO_A,frame=1)),
|
| 226 |
+
tag(9,1040,coded('avc1',VIDEO_H,frame=2)),tag(8,1040,b'\xaf\x01\x11\x22'))
|
| 227 |
+
out2=b2.feed(src)
|
| 228 |
+
f1=b2.freeze_bytes();f2=b2.freeze_bytes()
|
| 229 |
+
ftags=parse(b'FLV\x01\x05\x00\x00\x00\x09\x00\x00\x00\x00'+f1+f2)
|
| 230 |
+
check('filler repeats the last keyframe body untouched',
|
| 231 |
+
[t[2] for t in ftags]==[coded('avc1',VIDEO_A,frame=1)]*2, str(ftags))
|
| 232 |
+
check('filler timestamps advance monotonically by the step',
|
| 233 |
+
[t[1] for t in ftags]==[3040,5040], str([t[1] for t in ftags]))
|
| 234 |
+
# Real source resumes after filling on the same connection: output must continue
|
| 235 |
+
# from the filler-advanced clock, never backwards into a corrupted timeline.
|
| 236 |
+
resumed=b2.feed(tag(9,1080,coded('avc1',VIDEO_H,frame=2)))
|
| 237 |
+
rtags=parse(b'FLV\x01\x05\x00\x00\x00\x09\x00\x00\x00\x00'+resumed)
|
| 238 |
+
check('resumed source is spliced after the filler clock',
|
| 239 |
+
rtags and rtags[0][1]>=5040, str(rtags))
|
| 240 |
+
check('filler does not rewrite the resumed frame body',
|
| 241 |
+
rtags and rtags[0][2]==coded('avc1',VIDEO_H,frame=2))
|
| 242 |
+
|
| 243 |
+
print('\n%d passed, %d failed'%(passed,failed))
|
| 244 |
+
sys.exit(1 if failed else 0)
|
test_ingest_routes.py
ADDED
|
@@ -0,0 +1,190 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Secure primary/backup ingest and diagnostic redaction; no real keys or cloud calls."""
|
| 3 |
+
import os
|
| 4 |
+
import pathlib
|
| 5 |
+
import sys
|
| 6 |
+
import tempfile
|
| 7 |
+
import unittest
|
| 8 |
+
from urllib.parse import urlparse
|
| 9 |
+
from unittest.mock import patch
|
| 10 |
+
ROOT=pathlib.Path(sys.argv[1]).resolve() if len(sys.argv)>1 else pathlib.Path(__file__).parent
|
| 11 |
+
sys.path.insert(0,str(ROOT))
|
| 12 |
+
from youtube_manager import ManagedYouTube
|
| 13 |
+
from relay import Sender,redact_stderr,ffmpeg_output_failure,classify_ffmpeg_error
|
| 14 |
+
|
| 15 |
+
class IngestRouteTests(unittest.TestCase):
|
| 16 |
+
def setUp(self):
|
| 17 |
+
self.tmp=tempfile.TemporaryDirectory();self.addCleanup(self.tmp.cleanup)
|
| 18 |
+
self.mgr=ManagedYouTube('/bin/true',lambda u:None,lambda *a:None,lambda:['alice'],
|
| 19 |
+
pathlib.Path(self.tmp.name)/'journal.json')
|
| 20 |
+
self.mgr.journal.change(lambda d:d.update(channel={'id':'CHANNEL'},streams={'alice':{'id':'STREAM'}}))
|
| 21 |
+
self.primary='rtmps://a.rtmps.youtube.com/live2/test-ingest-only'
|
| 22 |
+
self.backup='rtmps://b.rtmps.youtube.com:443/live2/test-ingest-only?backup=1'
|
| 23 |
+
self.mgr._ingest_routes['alice']={'urls':[self.primary,self.backup], 'channel_id':'CHANNEL','stream_id':'STREAM'}
|
| 24 |
+
self.mgr.destinations['alice']=self.primary
|
| 25 |
+
|
| 26 |
+
def test_backup_query_follows_key_not_the_other_way_around(self):
|
| 27 |
+
url=self.mgr.secure_ingest_url('rtmps://b.rtmps.youtube.com:443/live2?backup=1','test-key')
|
| 28 |
+
p=urlparse(url);self.assertEqual(p.path,'/live2/test-key');self.assertEqual(p.query,'backup=1')
|
| 29 |
+
|
| 30 |
+
def test_plaintext_foreign_and_userinfo_addresses_are_rejected(self):
|
| 31 |
+
for address in ('rtmp://a.rtmp.youtube.com/live2','rtmps://attacker.invalid/live2',
|
| 32 |
+
'rtmps://youtube.com.attacker.invalid/live2','rtmps://user:password@a.rtmps.youtube.com/live2'):
|
| 33 |
+
with self.assertRaises(RuntimeError):self.mgr.secure_ingest_url(address,'test-key')
|
| 34 |
+
|
| 35 |
+
def test_route_switch_preserves_key_event_and_quota_state(self):
|
| 36 |
+
before=self.mgr.journal.read()
|
| 37 |
+
self.assertTrue(self.mgr.switch_ingest_route('alice'))
|
| 38 |
+
self.assertEqual(self.mgr.destinations['alice'],self.backup)
|
| 39 |
+
self.assertEqual(self.mgr.journal.read(),before)
|
| 40 |
+
|
| 41 |
+
def test_route_is_not_reused_after_channel_or_stream_change(self):
|
| 42 |
+
self.mgr.journal.change(lambda d:d.update(channel={'id':'DIFFERENT_CHANNEL'}))
|
| 43 |
+
self.assertFalse(self.mgr.switch_ingest_route('alice'))
|
| 44 |
+
self.mgr.journal.change(lambda d:d.update(channel={'id':'CHANNEL'},streams={'alice':{'id':'DIFFERENT_STREAM'}}))
|
| 45 |
+
self.assertFalse(self.mgr.switch_ingest_route('alice'))
|
| 46 |
+
|
| 47 |
+
def test_no_second_route_means_no_change(self):
|
| 48 |
+
self.mgr._ingest_routes['alice']['urls']=[self.primary]
|
| 49 |
+
self.assertFalse(self.mgr.switch_ingest_route('alice'))
|
| 50 |
+
self.assertEqual(self.mgr.destinations['alice'],self.primary)
|
| 51 |
+
|
| 52 |
+
class DiagnosticTests(unittest.TestCase):
|
| 53 |
+
def test_publish_command_hides_playpath_even_without_url(self):
|
| 54 |
+
for text in ("Sending publish command for 'SECRET-STREAM-NAME'", "Sending play command for 'SECRET-STREAM-NAME'",
|
| 55 |
+
'Proto=rtmps, fname=SECRET-STREAM-NAME, app=live2'):
|
| 56 |
+
self.assertNotIn('SECRET-STREAM-NAME',redact_stderr(text))
|
| 57 |
+
|
| 58 |
+
def test_debug_success_messages_are_not_output_failures(self):
|
| 59 |
+
for line in ('NetStream.Publish.Start','FCPublish stream...', '[out#0/flv] Output stream created'):
|
| 60 |
+
self.assertFalse(ffmpeg_output_failure(line))
|
| 61 |
+
self.assertIsNone(classify_ffmpeg_error('NetStream.Publish.Start'))
|
| 62 |
+
|
| 63 |
+
def test_real_output_failures_still_classify(self):
|
| 64 |
+
for line in ('NetStream.Publish.BadName','[out#0/flv] Error opening output: End of file',
|
| 65 |
+
'Broken pipe','Failed to publish stream'):
|
| 66 |
+
self.assertTrue(ffmpeg_output_failure(line))
|
| 67 |
+
|
| 68 |
+
def test_handshake_trace_is_opt_in_and_local_file_stays_normal(self):
|
| 69 |
+
s=Sender('/bin/true',lambda *a:None);s.mode_override='copy';s.trace_rtmp=True
|
| 70 |
+
with patch.dict(os.environ,{'YOUTUBE_FFMPEG_LOGLEVEL':'info'}):
|
| 71 |
+
args=s.command('rtmps://a.rtmps.youtube.com/live2/test-key',{'codec':'h264'})
|
| 72 |
+
self.assertEqual(args[args.index('-loglevel')+1],'debug')
|
| 73 |
+
local=s.command('out.flv',{'codec':'h264'})
|
| 74 |
+
self.assertEqual(local[local.index('-loglevel')+1],'info')
|
| 75 |
+
|
| 76 |
+
class _FakeSender:
|
| 77 |
+
"""أصغر مرسل يراه _note_early_exit: فشل خرج لم يفتح الاتصال أصلًا."""
|
| 78 |
+
def __init__(self,phase='opening',output=0.0):
|
| 79 |
+
self.last_exit_code=187;self.last_failure_side='output';self.last_source_gap=0.0
|
| 80 |
+
self._snap={'output_seconds':output,'rtmp_phase':phase,'source_bytes':309046,'send_mode':'copy'}
|
| 81 |
+
def snapshot(self):return dict(self._snap)
|
| 82 |
+
def send_mode(self):return 'copy'
|
| 83 |
+
def request_sticky(self,*a,**k):return False
|
| 84 |
+
|
| 85 |
+
class IngestFallbackTests(unittest.TestCase):
|
| 86 |
+
"""حادثة 2026-10-14: البديل b.rtmps لا يفتح TLS من المساحة، والتفضي�� المحفوظ
|
| 87 |
+
كان يُعيد تثبيته في كل تجديد فلا يبدأ الحدث أبدًا. الرجوع للأساسي بعد فتحين فاشلين."""
|
| 88 |
+
def setUp(self):
|
| 89 |
+
self.tmp=tempfile.TemporaryDirectory();self.addCleanup(self.tmp.cleanup)
|
| 90 |
+
self.mgr=ManagedYouTube('/bin/true',lambda u:None,lambda *a:None,lambda:['alice'],
|
| 91 |
+
pathlib.Path(self.tmp.name)/'journal.json')
|
| 92 |
+
self.mgr.journal.change(lambda d:d.update(channel={'id':'CHANNEL'},streams={'alice':{'id':'STREAM'}}))
|
| 93 |
+
self.primary='rtmps://a.rtmps.youtube.com/live2/test-ingest-only'
|
| 94 |
+
self.backup='rtmps://b.rtmps.youtube.com:443/live2/test-ingest-only?backup=1'
|
| 95 |
+
self.mgr._ingest_routes['alice']={'urls':[self.primary,self.backup], 'channel_id':'CHANNEL','stream_id':'STREAM'}
|
| 96 |
+
self.mgr.destinations['alice']=self.backup
|
| 97 |
+
self.mgr._ingest_preferred['alice']=1
|
| 98 |
+
|
| 99 |
+
def test_never_opened_classification(self):
|
| 100 |
+
self.assertTrue(ManagedYouTube._never_opened(_FakeSender('opening')))
|
| 101 |
+
self.assertTrue(ManagedYouTube._never_opened(_FakeSender('handshake')))
|
| 102 |
+
self.assertTrue(ManagedYouTube._never_opened(_FakeSender('')))
|
| 103 |
+
self.assertFalse(ManagedYouTube._never_opened(_FakeSender('publish'))) # رفض نشر لا فشل فتح
|
| 104 |
+
self.assertFalse(ManagedYouTube._never_opened(_FakeSender('accepted')))
|
| 105 |
+
self.assertFalse(ManagedYouTube._never_opened(_FakeSender('opening',output=3.0))) # وصل خرج فعلًا
|
| 106 |
+
|
| 107 |
+
def test_second_open_failure_falls_back_to_primary_and_blocks_backup(self):
|
| 108 |
+
s=_FakeSender()
|
| 109 |
+
self.mgr._note_early_exit('alice',s,11.0)
|
| 110 |
+
self.assertEqual(self.mgr.destinations['alice'],self.backup) # فرصة فتح ثانية أولًا
|
| 111 |
+
self.assertEqual(self.mgr._ingest_open_failures.get('alice'),1)
|
| 112 |
+
self.mgr.hammer['alice']=3 # عقوبة متراكمة على البديل الميت يجب أن تذهب معه
|
| 113 |
+
self.mgr._note_early_exit('alice',s,11.0)
|
| 114 |
+
self.assertEqual(self.mgr.destinations['alice'],self.primary)
|
| 115 |
+
self.assertEqual(self.mgr._ingest_preferred['alice'],0)
|
| 116 |
+
self.assertIn(1,self.mgr._ingest_route_blocked.get('alice') or set())
|
| 117 |
+
self.assertNotIn('alice',self.mgr.hammer)
|
| 118 |
+
self.assertNotIn('alice',self.mgr._ingest_open_failures)
|
| 119 |
+
|
| 120 |
+
def test_blocked_backup_is_not_switched_back_to(self):
|
| 121 |
+
s=_FakeSender()
|
| 122 |
+
self.mgr._note_early_exit('alice',s,11.0)
|
| 123 |
+
self.mgr._note_early_exit('alice',s,11.0)
|
| 124 |
+
self.assertFalse(self.mgr.switch_ingest_route('alice'))
|
| 125 |
+
self.assertEqual(self.mgr.destinations['alice'],self.primary)
|
| 126 |
+
|
| 127 |
+
def test_stable_stream_forgives_blocked_route(self):
|
| 128 |
+
s=_FakeSender()
|
| 129 |
+
self.mgr._note_early_exit('alice',s,11.0)
|
| 130 |
+
self.mgr._note_early_exit('alice',s,11.0)
|
| 131 |
+
self.assertIn(1,self.mgr._ingest_route_blocked.get('alice') or set())
|
| 132 |
+
self.mgr.mark_stream_stable('alice')
|
| 133 |
+
self.assertFalse(self.mgr._ingest_route_blocked.get('alice'))
|
| 134 |
+
self.assertTrue(self.mgr.switch_ingest_route('alice')) # يُجرَّب من جديد في حادثة قادمة
|
| 135 |
+
|
| 136 |
+
def test_publish_rejection_on_backup_is_not_counted_as_open_failure(self):
|
| 137 |
+
self.mgr._note_early_exit('alice',_FakeSender('publish'),11.0)
|
| 138 |
+
self.assertFalse(self.mgr._ingest_open_failures.get('alice'))
|
| 139 |
+
self.assertEqual(self.mgr._ingest_preferred['alice'],1) # مسار الرفض الطبيعي لا الرجوع الفوري
|
| 140 |
+
|
| 141 |
+
def test_open_failure_on_primary_counts_then_rotates_to_backup(self):
|
| 142 |
+
# التماثل (v2.31): فشل الفتح على الأساسي يُدوَّر إلى الاحتياطي بعد مرتين أيضًا
|
| 143 |
+
self.mgr.destinations['alice']=self.primary
|
| 144 |
+
self.mgr._ingest_preferred['alice']=0
|
| 145 |
+
s=_FakeSender('opening')
|
| 146 |
+
self.mgr._note_early_exit('alice',s,11.0)
|
| 147 |
+
self.assertEqual(self.mgr.destinations['alice'],self.primary)
|
| 148 |
+
self.assertEqual(self.mgr._ingest_open_failures.get('alice'),1)
|
| 149 |
+
self.mgr._note_early_exit('alice',s,11.0)
|
| 150 |
+
self.assertEqual(self.mgr.destinations['alice'],self.backup)
|
| 151 |
+
self.assertEqual(self.mgr._ingest_preferred['alice'],1)
|
| 152 |
+
self.assertIn(0,self.mgr._ingest_route_blocked.get('alice') or set())
|
| 153 |
+
|
| 154 |
+
class PublishDisciplineTests(unittest.TestCase):
|
| 155 |
+
"""انضباط النشر: اتصال أسرع من تحرير مقعد يوتيوب يُرفض فيولّد عاصفة 187.
|
| 156 |
+
تهدئة 10/15/20 بسقف — عودة سريعة بلا نقر على حافة ترفض."""
|
| 157 |
+
def setUp(self):
|
| 158 |
+
self.tmp=tempfile.TemporaryDirectory();self.addCleanup(self.tmp.cleanup)
|
| 159 |
+
self.mgr=ManagedYouTube('/bin/true',lambda u:None,lambda *a:None,lambda:['alice'],
|
| 160 |
+
pathlib.Path(self.tmp.name)/'journal.json')
|
| 161 |
+
self.mgr.journal.change(lambda d:d.update(channel={'id':'CHANNEL'},streams={'alice':{'id':'STREAM'}}))
|
| 162 |
+
self.primary='rtmps://a.rtmps.youtube.com/live2/test-ingest-only'
|
| 163 |
+
self.backup='rtmps://b.rtmps.youtube.com:443/live2/test-ingest-only?backup=1'
|
| 164 |
+
self.mgr._ingest_routes['alice']={'urls':[self.primary,self.backup], 'channel_id':'CHANNEL','stream_id':'STREAM'}
|
| 165 |
+
self.mgr.destinations['alice']=self.primary
|
| 166 |
+
self.mgr._ingest_preferred['alice']=0
|
| 167 |
+
|
| 168 |
+
def test_pacing_grows_then_caps_at_twenty(self):
|
| 169 |
+
s=_FakeSender('accepted',output=5.0)
|
| 170 |
+
self.mgr._note_early_exit('alice',s,11.0)
|
| 171 |
+
self.assertEqual(self.mgr.retry['alice'],10.0)
|
| 172 |
+
self.mgr._note_early_exit('alice',s,11.0)
|
| 173 |
+
self.assertEqual(self.mgr.retry['alice'],15.0)
|
| 174 |
+
self.mgr._note_early_exit('alice',s,11.0)
|
| 175 |
+
self.assertEqual(self.mgr.retry['alice'],20.0)
|
| 176 |
+
self.mgr._note_early_exit('alice',s,11.0)
|
| 177 |
+
self.assertEqual(self.mgr.retry['alice'],20.0) # لا تصاعد 40/80/120 بعد اليوم
|
| 178 |
+
|
| 179 |
+
def test_stable_stream_clears_pacing(self):
|
| 180 |
+
self.mgr._publish_wait['alice']=20.0
|
| 181 |
+
self.mgr.mark_stream_stable('alice')
|
| 182 |
+
self.assertNotIn('alice',self.mgr._publish_wait)
|
| 183 |
+
|
| 184 |
+
def test_source_side_death_is_not_paced(self):
|
| 185 |
+
s=_FakeSender('accepted',output=5.0);s.last_failure_side='source'
|
| 186 |
+
self.mgr._publish_wait['alice']=20.0
|
| 187 |
+
self.mgr._note_early_exit('alice',s,11.0)
|
| 188 |
+
self.assertNotIn('alice',self.mgr._publish_wait) # رجوع المصدر سريع دائمًا
|
| 189 |
+
|
| 190 |
+
if __name__=='__main__':unittest.main(argv=[sys.argv[0]],verbosity=2)
|
test_kick.py
DELETED
|
@@ -1,346 +0,0 @@
|
|
| 1 |
-
"""اختبارات مسار Kick — عزل تيك توك، صحة الرصد، واختيار النسخ المباشر.
|
| 2 |
-
|
| 3 |
-
تشغيل:
|
| 4 |
-
python3 test_kick.py # اختبارات غير شبكية فقط
|
| 5 |
-
KICK_LIVE=1 python3 test_kick.py [channel] # يضيف اختبارًا حيًّا على قناة مباشرة
|
| 6 |
-
|
| 7 |
-
الاختبارات غير الشبكية هي ما يجب أن يبقى أخضر في كل بناء؛ الاختبار الحيّ يعتمد على
|
| 8 |
-
وجود مذيع مباشر فعلًا، فلا يُفشل البناء عند غيابه.
|
| 9 |
-
"""
|
| 10 |
-
import os, sys
|
| 11 |
-
|
| 12 |
-
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)) or '.')
|
| 13 |
-
os.environ.setdefault('FFMPEG', '/usr/bin/ffmpeg')
|
| 14 |
-
|
| 15 |
-
passed = []
|
| 16 |
-
failed = []
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
def check(name, cond, detail=''):
|
| 20 |
-
(passed if cond else failed).append(name)
|
| 21 |
-
print('%-5s %s%s' % ('PASS' if cond else 'FAIL', name, (' — ' + str(detail)) if detail else ''))
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
import kick_source
|
| 25 |
-
from relay import Sender
|
| 26 |
-
|
| 27 |
-
MASTER = '''#EXTM3U
|
| 28 |
-
#EXT-X-MEDIA:TYPE=VIDEO,GROUP-ID="chunked",NAME="1080p60",AUTOSELECT=YES,DEFAULT=YES
|
| 29 |
-
#EXT-X-STREAM-INF:BANDWIDTH=9011593,RESOLUTION=1920x1080,CODECS="avc1.64002A,mp4a.40.2",VIDEO="chunked",FRAME-RATE=60.000
|
| 30 |
-
https://edge.example/v1/playlist/AAA
|
| 31 |
-
#EXT-X-MEDIA:TYPE=VIDEO,GROUP-ID="720p60",NAME="720p60",AUTOSELECT=YES,DEFAULT=YES
|
| 32 |
-
#EXT-X-STREAM-INF:BANDWIDTH=3422999,RESOLUTION=1280x720,CODECS="avc1.4D401F,mp4a.40.2",VIDEO="720p60",FRAME-RATE=60.000
|
| 33 |
-
https://edge.example/v1/playlist/BBB
|
| 34 |
-
#EXT-X-MEDIA:TYPE=VIDEO,GROUP-ID="360p30",NAME="360p",AUTOSELECT=YES,DEFAULT=YES
|
| 35 |
-
#EXT-X-STREAM-INF:BANDWIDTH=630000,RESOLUTION=640x360,CODECS="avc1.4D401F,mp4a.40.2",VIDEO="360p30",FRAME-RATE=30.000
|
| 36 |
-
https://edge.example/v1/playlist/CCC
|
| 37 |
-
'''
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
class _Resp:
|
| 41 |
-
status_code = 200
|
| 42 |
-
text = MASTER
|
| 43 |
-
|
| 44 |
-
def raise_for_status(self):
|
| 45 |
-
pass
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
# --------------------------------------------------------------------------- #
|
| 49 |
-
# 1. هوية الحساب وعزل تيك توك
|
| 50 |
-
# --------------------------------------------------------------------------- #
|
| 51 |
-
check('kick: يُتعرّف عليه', kick_source.is_kick('kick:absi') and kick_source.is_kick('KICK:Absi'))
|
| 52 |
-
check('حساب تيك توك لا يُعتبر كيك', not kick_source.is_kick('emadpes') and not kick_source.is_kick('viggoo313'))
|
| 53 |
-
check('clean يقبل البادئة', kick_source.clean('kick:ABSI') == 'kick:absi')
|
| 54 |
-
check('clean يقبل الرابط', kick_source.clean('https://kick.com/absi/') == 'kick:absi')
|
| 55 |
-
try:
|
| 56 |
-
kick_source.clean('https://twitch.tv/absi')
|
| 57 |
-
check('clean يرفض رابطًا أجنبيًا', False, 'قُبل رابط غير Kick')
|
| 58 |
-
except ValueError:
|
| 59 |
-
check('clean يرفض رابطًا أجنبيًا', True)
|
| 60 |
-
|
| 61 |
-
check('channel يجرّد البادئة', kick_source.channel('kick:emadpes') == 'emadpes')
|
| 62 |
-
check('profile_url صحيح', kick_source.profile_url('kick:emadpes') == 'https://kick.com/emadpes')
|
| 63 |
-
|
| 64 |
-
# clean_user في app.py يوجّه المنصتين دون خلط
|
| 65 |
-
import re as _re
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
def _clean_user_router(raw):
|
| 69 |
-
"""نسخة مطابقة لمنطق التوجيه في app.clean_user (بلا استيراد FastAPI)."""
|
| 70 |
-
raw = raw.strip()
|
| 71 |
-
if kick_source.is_kick(raw) or _re.match(r'https?://(www\.)?kick\.com/', raw, _re.I):
|
| 72 |
-
return kick_source.clean(raw)
|
| 73 |
-
return 'tiktok:' + raw.lstrip('@').lower()
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
check('التوجيه: كيك → kick:', _clean_user_router('https://kick.com/absi') == 'kick:absi')
|
| 77 |
-
check('التوجيه: تيك توك لم يتغيّر مساره', _clean_user_router('@Emadpes') == 'tiktok:emadpes')
|
| 78 |
-
|
| 79 |
-
# --------------------------------------------------------------------------- #
|
| 80 |
-
# 2. تحليل master playlist
|
| 81 |
-
# --------------------------------------------------------------------------- #
|
| 82 |
-
_orig_get = kick_source._get
|
| 83 |
-
kick_source._get = lambda url, hdrs=None, tries=2: _Resp()
|
| 84 |
-
try:
|
| 85 |
-
rend = kick_source.renditions('https://edge.example/master.m3u8')
|
| 86 |
-
finally:
|
| 87 |
-
kick_source._get = _orig_get
|
| 88 |
-
|
| 89 |
-
check('كل الجودات مُستخرجة', len(rend) == 3, [r['quality_name'] for r in rend])
|
| 90 |
-
check('الأعلى أولًا 1080p60', rend[0]['quality_name'] == '1080p60' and rend[0]['height'] == 1080)
|
| 91 |
-
check('الترتيب تنازلي', [r['height'] for r in rend[:3]] == [1080, 720, 360])
|
| 92 |
-
check('كل الجودات H264', all(r['codec'] == 'h264' for r in rend))
|
| 93 |
-
check('كلها HLS', all(r['media'] == 'hls' for r in rend))
|
| 94 |
-
check('كلها موسومة platform=kick', all(r['platform'] == 'kick' for r in rend))
|
| 95 |
-
check('مسار المصدر chunked مُعلَّم', rend[0]['source_ladder'] is True)
|
| 96 |
-
check('الـmaster لا يُسلَّم لـFFmpeg أبدًا',
|
| 97 |
-
all('master' not in r['url'] for r in rend))
|
| 98 |
-
check('الروابط هي روابط الجودة لا الـmaster',
|
| 99 |
-
rend[0]['url'] == 'https://edge.example/v1/playlist/AAA')
|
| 100 |
-
check('brief بلا روابط ولا توكنات', all('http' not in r['brief'] for r in rend))
|
| 101 |
-
|
| 102 |
-
# سقف الارتفاع يحترم المشغّل
|
| 103 |
-
os.environ['KICK_MAX_HEIGHT'] = '720'
|
| 104 |
-
kick_source._get = lambda url, hdrs=None, tries=2: _Resp()
|
| 105 |
-
try:
|
| 106 |
-
capped = kick_source.renditions('https://edge.example/master.m3u8')
|
| 107 |
-
finally:
|
| 108 |
-
kick_source._get = _orig_get
|
| 109 |
-
os.environ.pop('KICK_MAX_HEIGHT', None)
|
| 110 |
-
check('KICK_MAX_HEIGHT=720 يُسقط 1080', capped[0]['quality_name'] == '720p60')
|
| 111 |
-
|
| 112 |
-
# --------------------------------------------------------------------------- #
|
| 113 |
-
# 3. القرار الحاسم: نسخ مباشر بلا إعادة ترميز للصورة
|
| 114 |
-
# --------------------------------------------------------------------------- #
|
| 115 |
-
check('copy_is_safe على h264 المُعلَن', Sender.copy_is_safe('h264', None) is True)
|
| 116 |
-
check('copy_is_safe يرفض h265', Sender.copy_is_safe('h265', None) is False)
|
| 117 |
-
check('مرشّح كيك ليس codec_unusable', Sender.codec_unusable(rend[0]) is False)
|
| 118 |
-
check('مرشّح كيك ليس hevc_payload', Sender.hevc_payload(rend[0]) is False)
|
| 119 |
-
|
| 120 |
-
snd = Sender(os.environ['FFMPEG'], lambda u, m: None, lambda u: kick_source.media_headers(u))
|
| 121 |
-
snd.mode_override = 'copy'
|
| 122 |
-
cand = {**rend[0], 'user': 'kick:absi'}
|
| 123 |
-
args = snd.command('rtmps://a.rtmps.youtube.com:443/live2/KEY', cand)
|
| 124 |
-
check('الفيديو نسخ لا ترميز', '-c:v' in args and args[args.index('-c:v') + 1] == 'copy')
|
| 125 |
-
check('لا libx264 في الأمر', 'libx264' not in args)
|
| 126 |
-
check('لا مرشّح scale/pad', not any('scale=' in str(a) for a in args))
|
| 127 |
-
check('الصوت AAC 48k ستيريو (سياسة المشروع القائمة)',
|
| 128 |
-
'-c:a' in args and args[args.index('-c:a') + 1] == 'aac' and '48000' in args)
|
| 129 |
-
|
| 130 |
-
ia = snd.input_args(cand)
|
| 131 |
-
check('HLS بلا أنبوب stdin', ia['stdin'] is None)
|
| 132 |
-
check('خيارات إعادة الاتصال مفعّلة', '-reconnect' in ia['input'])
|
| 133 |
-
check('seg_max_retry مفعّل لكيك (يبتلع عثرة CDN لحظية)',
|
| 134 |
-
'-seg_max_retry' in ia['input'] and ia['input'][ia['input'].index('-seg_max_retry')+1] == '2')
|
| 135 |
-
check('لا خيارات بلا أثر أو أضعف من الافتراضي',
|
| 136 |
-
not any(o in ia['input'] for o in ('-http_persistent', '-m3u8_hold_counters',
|
| 137 |
-
'-max_reload', '-http_multiple')))
|
| 138 |
-
check('ترويسات Referer كيك تُمرَّر',
|
| 139 |
-
'-headers' in ia['input'] and 'kick.com' in ia['input'][ia['input'].index('-headers') + 1])
|
| 140 |
-
check('لا يُرسل Referer تيك توك مع كيك',
|
| 141 |
-
'tiktok' not in ia['input'][ia['input'].index('-headers') + 1])
|
| 142 |
-
|
| 143 |
-
# مرشّح تيك توك (FLV) لم يتغيّر سلوكه
|
| 144 |
-
tt = {'media': 'flv', 'url': 'https://x/y.flv', 'user': 'someone', 'codec': 'h264'}
|
| 145 |
-
ia_tt = snd.input_args(tt)
|
| 146 |
-
check('تيك توك FLV ما زال على stdin', ia_tt['stdin'] is not None)
|
| 147 |
-
check('تيك توك لا يأخذ خيارات كيك', '-seg_max_retry' not in ia_tt['input'])
|
| 148 |
-
|
| 149 |
-
# --------------------------------------------------------------------------- #
|
| 150 |
-
# 3b. الجودة القصوى لا تسقط تحت الحمل (Kick أفقي كان يقع تحت قاعدة تيك توك العمودية)
|
| 151 |
-
# --------------------------------------------------------------------------- #
|
| 152 |
-
import youtube_manager as _ym
|
| 153 |
-
from youtube_manager import ManagedYouTube
|
| 154 |
-
|
| 155 |
-
|
| 156 |
-
class _Hub:
|
| 157 |
-
def __init__(self, busy):
|
| 158 |
-
self.b = busy
|
| 159 |
-
|
| 160 |
-
def active_count(self):
|
| 161 |
-
return self.b
|
| 162 |
-
|
| 163 |
-
def light_count(self, except_user=None):
|
| 164 |
-
return 0
|
| 165 |
-
|
| 166 |
-
def light_available(self, except_user=None):
|
| 167 |
-
return True
|
| 168 |
-
|
| 169 |
-
|
| 170 |
-
_orig_hub = _ym.hub
|
| 171 |
-
_kick_ladder = [dict(r) for r in rend]
|
| 172 |
-
try:
|
| 173 |
-
picks = {}
|
| 174 |
-
for _busy in (0, 1, 2, 3, 5):
|
| 175 |
-
_ym.hub = _Hub(_busy)
|
| 176 |
-
_sel = ManagedYouTube.video_sources(_kick_ladder)
|
| 177 |
-
picks[_busy] = _sel[0]['quality_name'] if _sel else None
|
| 178 |
-
check('Kick يبقى 1080p60 تحت أي عدد من البثوث',
|
| 179 |
-
all(v == '1080p60' for v in picks.values()), picks)
|
| 180 |
-
|
| 181 |
-
_tt = [{'codec': 'h264', 'width': 720, 'height': 1280, 'resolution': '720x1280',
|
| 182 |
-
'label': 'origin', 'brief': 'origin 1280p H264', 'media': 'flv'},
|
| 183 |
-
{'codec': 'h264', 'width': 1440, 'height': 2560, 'resolution': '1440x2560',
|
| 184 |
-
'label': 'uhd', 'brief': 'uhd 2560p H264', 'media': 'flv'},
|
| 185 |
-
{'codec': 'h264', 'width': 1920, 'height': 1080, 'resolution': '1920x1080',
|
| 186 |
-
'label': 'hd', 'brief': 'hd 1080p H264', 'media': 'flv'}]
|
| 187 |
-
_ym.hub = _Hub(0)
|
| 188 |
-
_free = [c['brief'] for c in ManagedYouTube.video_sources(_tt)]
|
| 189 |
-
_ym.hub = _Hub(2)
|
| 190 |
-
_busysel = [c['brief'] for c in ManagedYouTube.video_sources(_tt)]
|
| 191 |
-
check('تيك توك بلا حمل: كل المرشّحات كما كانت', len(_free) == 3, _free)
|
| 192 |
-
check('تيك توك تحت الحمل: 1440p و1080p الأفقي ما زالا يُخفَّضان',
|
| 193 |
-
_busysel == ['origin 1280p H264'], _busysel)
|
| 194 |
-
|
| 195 |
-
_hevc = {'codec': 'h265', 'width': 1920, 'height': 1080, 'platform': 'kick'}
|
| 196 |
-
_h264 = {'codec': 'h264', 'width': 1280, 'height': 720, 'platform': 'kick'}
|
| 197 |
-
check('الإعفاء مشروط بالنسخ (_copyable يفرّق H264 عن HEVC)',
|
| 198 |
-
ManagedYouTube._copyable(_h264) and not ManagedYouTube._copyable(_hevc))
|
| 199 |
-
finally:
|
| 200 |
-
_ym.hub = _orig_hub
|
| 201 |
-
|
| 202 |
-
# --------------------------------------------------------------------------- #
|
| 203 |
-
# 3c. الطبقة «المجوّعة»: دقة أعلى ببتريت أقل تُزاح عن الصدارة
|
| 204 |
-
# --------------------------------------------------------------------------- #
|
| 205 |
-
class _Resp:
|
| 206 |
-
def __init__(self, text):
|
| 207 |
-
self.text = text
|
| 208 |
-
|
| 209 |
-
|
| 210 |
-
def _master(rows):
|
| 211 |
-
base = 'https://ivs.example/v1/'
|
| 212 |
-
out = ['#EXTM3U']
|
| 213 |
-
for name, grp, w, h, f, bw in rows:
|
| 214 |
-
out.append('#EXT-X-MEDIA:TYPE=VIDEO,GROUP-ID="%s",NAME="%s"' % (grp, name))
|
| 215 |
-
out.append('#EXT-X-STREAM-INF:BANDWIDTH=%d,CODECS="avc1.4D401F,mp4a.40.2",'
|
| 216 |
-
'RESOLUTION=%dx%d,VIDEO="%s",FRAME-RATE=%.3f' % (bw, w, h, grp, f))
|
| 217 |
-
out.append(base + grp + '/playlist.m3u8')
|
| 218 |
-
return '\n'.join(out)
|
| 219 |
-
|
| 220 |
-
|
| 221 |
-
def _ladder(rows):
|
| 222 |
-
orig = kick_source._get
|
| 223 |
-
kick_source._get = lambda u, hdrs=None, tries=2, _t=_master(rows): _Resp(_t)
|
| 224 |
-
try:
|
| 225 |
-
return kick_source.renditions('https://x/master.m3u8')
|
| 226 |
-
finally:
|
| 227 |
-
kick_source._get = orig
|
| 228 |
-
|
| 229 |
-
|
| 230 |
-
# سلّم emadpes الحقيقي (VOD 2026-10-06): 1080p30 بـ943k مقابل 720p30 بـ2379k
|
| 231 |
-
_emad = _ladder([('1080p', '1080p', 1920, 1080, 30, 943209),
|
| 232 |
-
('720p', '720p30', 1280, 720, 30, 2378958),
|
| 233 |
-
('480p', '480p30', 852, 480, 30, 1433958),
|
| 234 |
-
('360p', '360p30', 640, 360, 30, 630000)])
|
| 235 |
-
check('سلّم مجوّع: 720p يتصدّر لا 1080p', _emad[0]['height'] == 720,
|
| 236 |
-
_emad[0]['brief'])
|
| 237 |
-
check('سلّم مجوّع: 1080p موسوم starved', _emad[-1]['height'] == 1080 and _emad[-1]['starved'])
|
| 238 |
-
check('سلّم مجوّع: 1080p يبقى احتياطيًا لا يُحذف',
|
| 239 |
-
any(c['height'] == 1080 for c in _emad) and len(_emad) == 4)
|
| 240 |
-
check('تقدير bpp صحيح', abs(_emad[-1]['bpp'] - 0.0152) < 0.001 and _emad[-1]['bpp_grade'] == 'poor',
|
| 241 |
-
str(_emad[-1]['bpp']))
|
| 242 |
-
|
| 243 |
-
# سلّم سليم: البتريت يرتفع مع الدقة ⇒ القاعدة لا تتفعّل إطلاقًا
|
| 244 |
-
_ok = _ladder([('1080p60', '1080p60', 1920, 1080, 60, 4797000),
|
| 245 |
-
('720p60', '720p60', 1280, 720, 60, 3480000),
|
| 246 |
-
('480p', '480p30', 852, 480, 30, 1485000)])
|
| 247 |
-
check('سلّم سليم: 1080p60 يتصدّر', _ok[0]['height'] == 1080 and _ok[0]['fps'] == 60,
|
| 248 |
-
_ok[0]['brief'])
|
| 249 |
-
check('سلّم سليم: لا طبقة موسومة starved', not any(c['starved'] for c in _ok))
|
| 250 |
-
|
| 251 |
-
# سلّم chunked سليم (absi): مسار المصدر الأصلي يبقى متصدّرًا
|
| 252 |
-
_chunk = _ladder([('1080p60', 'chunked', 1920, 1080, 60, 9015000),
|
| 253 |
-
('720p60', '720p60', 1280, 720, 60, 3423000),
|
| 254 |
-
('480p', '480p30', 852, 480, 30, 1428000)])
|
| 255 |
-
check('سلّم chunked: 1080p60 يتصدّر', _chunk[0]['height'] == 1080 and _chunk[0]['source_ladder'])
|
| 256 |
-
|
| 257 |
-
# بلا بيانات بتريت ⇒ السلوك القديم حرفيًا (الدقة وحدها)
|
| 258 |
-
_nobw = _ladder([('1080p', '1080p', 1920, 1080, 30, 0),
|
| 259 |
-
('720p', '720p30', 1280, 720, 30, 0)])
|
| 260 |
-
check('بلا بتريت: الترتيب بالدقة كالسابق',
|
| 261 |
-
_nobw[0]['height'] == 1080 and not any(c['starved'] for c in _nobw))
|
| 262 |
-
|
| 263 |
-
# --------------------------------------------------------------------------- #
|
| 264 |
-
# 4. عقد الرصد مطابق لتيك توك
|
| 265 |
-
# --------------------------------------------------------------------------- #
|
| 266 |
-
off = kick_source._offline('', 'Emad', '')
|
| 267 |
-
check('عقد offline مطابق', set(['status', 'room_id', 'sources', 'nickname', 'live_title']) <= set(off))
|
| 268 |
-
check('offline بلا مصادر', off['status'] == 'offline' and off['sources'] == [])
|
| 269 |
-
|
| 270 |
-
# --------------------------------------------------------------------------- #
|
| 271 |
-
# 5. وصف يوتيوب يربط المنصة الصحيحة
|
| 272 |
-
# --------------------------------------------------------------------------- #
|
| 273 |
-
from youtube_manager import ManagedYouTube
|
| 274 |
-
d_kick = ManagedYouTube.description_with_links('بث', 'kick:emadpes', '')
|
| 275 |
-
d_tt = ManagedYouTube.description_with_links('بث', 'emadpes', '')
|
| 276 |
-
check('وصف كيك يضع رابط kick.com', 'https://kick.com/emadpes' in d_kick and 'tiktok' not in d_kick)
|
| 277 |
-
check('وصف تيك توك لم يتغيّر', 'https://www.tiktok.com/@emadpes' in d_tt and 'kick.com' not in d_tt)
|
| 278 |
-
check('Referer ديناميكي', ManagedYouTube._referer('kick:x') == 'https://kick.com/'
|
| 279 |
-
and ManagedYouTube._referer('abc') == 'https://www.tiktok.com/')
|
| 280 |
-
|
| 281 |
-
# قالب كُتب في زمن المنصة الواحدة ويثبّت رابط تيك توك يدويًا: لا يجوز أن يُنشر
|
| 282 |
-
# «https://www.tiktok.com/@kick:emadpes» علنًا في وصف كل بث كيك.
|
| 283 |
-
LEGACY = '📺 {name}\n👤 @{username}\n🎵 https://www.tiktok.com/@{username}\n\n📅 {date}'
|
| 284 |
-
rendered_k = ManagedYouTube.description_with_links(
|
| 285 |
-
LEGACY.format(name='Emad', username='kick:emadpes', date='2026-10-06'), 'kick:emadpes', '')
|
| 286 |
-
check('قالب قديم: لا رابط تيك توك مكسور لحساب كيك',
|
| 287 |
-
'tiktok.com/@kick' not in rendered_k, rendered_k)
|
| 288 |
-
check('قالب قديم: الرابط صُحّح إلى kick.com',
|
| 289 |
-
'https://kick.com/emadpes' in rendered_k)
|
| 290 |
-
check('قالب قديم: المعرّف بلا بادئة kick:',
|
| 291 |
-
'@emadpes' in rendered_k and '@kick:emadpes' not in rendered_k)
|
| 292 |
-
rendered_t = ManagedYouTube.description_with_links(
|
| 293 |
-
LEGACY.format(name='Emad', username='c_emad3', date='2026-10-06'), 'c_emad3', '')
|
| 294 |
-
check('قالب قديم: ناتج تيك توك لم يتغيّر',
|
| 295 |
-
'https://www.tiktok.com/@c_emad3' in rendered_t and 'kick' not in rendered_t)
|
| 296 |
-
|
| 297 |
-
# متغيّرات القالب الجديدة يجب أن يقبلها التحقق عند الحفظ، وإلا رُفض كل قالب يستعملها
|
| 298 |
-
import inspect as _insp
|
| 299 |
-
_settings_src = _insp.getsource(ManagedYouTube.settings)
|
| 300 |
-
check('التحقق عند الحفظ يعرف {handle}/{profile_url}/{platform}',
|
| 301 |
-
all(k in _settings_src for k in ("'handle'", "'profile_url'", "'platform'")))
|
| 302 |
-
|
| 303 |
-
# --------------------------------------------------------------------------- #
|
| 304 |
-
# 6. حيّ (اختياري)
|
| 305 |
-
# --------------------------------------------------------------------------- #
|
| 306 |
-
if str(os.getenv('KICK_LIVE', '')).strip() in ('1', 'on', 'true', 'yes'):
|
| 307 |
-
target = 'kick:' + (sys.argv[1] if len(sys.argv) > 1 else 'absi')
|
| 308 |
-
print('\n--- اختبار حيّ على %s ---' % target)
|
| 309 |
-
try:
|
| 310 |
-
obs = kick_source.observe(target)
|
| 311 |
-
if obs['status'] != 'live':
|
| 312 |
-
print('INFO القناة غير مباشرة الآن؛ تخطّي الاختبار الحيّ')
|
| 313 |
-
else:
|
| 314 |
-
check('حيّ: الحالة live', obs['status'] == 'live')
|
| 315 |
-
check('حيّ: room_id موجود', bool(obs['room_id']))
|
| 316 |
-
check('حيّ: مصادر مرتَّبة', len(obs['sources']) >= 2)
|
| 317 |
-
check('حيّ: لا مرشّح ABR/auto',
|
| 318 |
-
all(c['quality_name'] != 'auto' for c in obs['sources']))
|
| 319 |
-
check('حيّ: كل الجودات H264', all(c['codec'] == 'h264' for c in obs['sources']))
|
| 320 |
-
top = {**obs['sources'][0], 'user': target}
|
| 321 |
-
import subprocess, time
|
| 322 |
-
snd2 = Sender(os.environ['FFMPEG'], lambda u, m: None,
|
| 323 |
-
lambda u: kick_source.media_headers(u))
|
| 324 |
-
snd2.mode_override = 'copy'
|
| 325 |
-
out = '/tmp/kick_live_test.flv'
|
| 326 |
-
p = subprocess.Popen(snd2.command(out, top), stdout=subprocess.DEVNULL,
|
| 327 |
-
stderr=subprocess.PIPE)
|
| 328 |
-
time.sleep(25)
|
| 329 |
-
p.terminate()
|
| 330 |
-
err = p.stderr.read().decode('utf-8', 'replace')
|
| 331 |
-
p.wait(10)
|
| 332 |
-
size = os.path.getsize(out) if os.path.exists(out) else 0
|
| 333 |
-
check('حيّ: FFmpeg أنتج بايتات بالنسخ المباشر', size > 1_000_000, '%d bytes' % size)
|
| 334 |
-
check('حيّ: بلا أخطاء FFmpeg', 'Error' not in err and 'Non-monotonous' not in err,
|
| 335 |
-
err[-200:])
|
| 336 |
-
try:
|
| 337 |
-
os.remove(out)
|
| 338 |
-
except OSError:
|
| 339 |
-
pass
|
| 340 |
-
except Exception as exc:
|
| 341 |
-
print('INFO تعذّر الاختبار الحيّ: %s: %s' % (type(exc).__name__, exc))
|
| 342 |
-
|
| 343 |
-
print('\n%d passed, %d failed' % (len(passed), len(failed)))
|
| 344 |
-
if failed:
|
| 345 |
-
print('فاشل:', failed)
|
| 346 |
-
sys.exit(1 if failed else 0)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
test_lifecycle.py
CHANGED
|
@@ -165,6 +165,13 @@ mgr.journal.change(lambda d: d['events'].update({key: {
|
|
| 165 |
'phase': 'live', 'youtube_status': 'live', 'created_at': time.time(), 'was_live': True,
|
| 166 |
'create_pending': False, 'note': '', 'last_poll': time.time()}}))
|
| 167 |
mgr.destinations['u7'] = 'rtmps://example.invalid/y' # وجهة وهمية عمدًا: لا نريد اتصال يوتيوب
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 168 |
# لماذا لا نطلب out_time هنا: مقياس محلي — مع وجهة لا تُفتح، `-timeshift 10` كان يُقدّم
|
| 169 |
# out_time_us من مخزن fifo (8.4 ث في 8 ث) بينما `-timeshift 0` يبقى على 0.0. أي أن تقدّم
|
| 170 |
# الوقت كان يخبر عن «كم حُجز» لا عن «كم سُلّم». فالأمانة في هذه الحالة هي الصفر.
|
|
@@ -204,8 +211,8 @@ check('J: out_time لا يتقدّم حين لا شيء يُسلَّم (كان t
|
|
| 204 |
# مطلوبًا أن يقفز المدير فوق الكاش — والأثر المطلوب هو إعادة الرصد والجلسة الجديدة.
|
| 205 |
watchdog_logged = any('[WATCHDOG]' in m for m in logs[-25:])
|
| 206 |
check('J: عطل التدفق أُعلِن في السجل وأُعيد الرصد/الجلسة (خيط حيّ لا يحتاج قفز الكاش)',
|
| 207 |
-
watchdog_logged and (
|
| 208 |
-
'attended=%s force=%s log=%s' % (attended, seen_force[:2], watchdog_logged))
|
| 209 |
# الدورة كاملة تُقرأ من السجل وحده — هذا ما طلبه المستخدم: صمت ⇒ حارس ⇒ تنظيف ⇒ مراقبة ⇒
|
| 210 |
# LIVE ⇒ جلسة جديدة. الترتيب أدناه مقيس من logs نفسها، لا مفترض.
|
| 211 |
def _first(tag, after=-1):
|
|
@@ -243,16 +250,19 @@ mgr.observe = lambda u, force=False: {'status': 'offline', 'room_id': '7', 'sour
|
|
| 243 |
'nickname': 'n', 'live_title': ''}
|
| 244 |
mgr.drive_event(key)
|
| 245 |
ev = mgr.journal.read()['events'].get(key)
|
| 246 |
-
check('K: offline
|
| 247 |
-
(not ev or not ev.get('closing')) and
|
| 248 |
_dead = time.monotonic() + 8
|
| 249 |
-
while time.monotonic() < _dead and not any('[OFFLINE]' in m for m in logs):
|
| 250 |
time.sleep(0.3)
|
| 251 |
-
check('K:
|
| 252 |
-
any('[OFFLINE]' in m for m in logs), logs[-1][:90])
|
| 253 |
for e in list(mgr.senders.values()):
|
| 254 |
e['stop'].set()
|
| 255 |
e['sender'].terminate()
|
|
|
|
|
|
|
|
|
|
| 256 |
|
| 257 |
# ── L) التطبيق يستورد، ونقاط الحالة تعمل بعد التعديل ───────────────────────────────
|
| 258 |
r = subprocess.run([sys.executable, '-c',
|
|
@@ -291,13 +301,11 @@ try:
|
|
| 291 |
except ImportError as e:
|
| 292 |
check('L: TestClient غير متاح (httpx ناقص) — فحص الاستيراد يكفي', True, str(e)[:60])
|
| 293 |
|
| 294 |
-
#
|
| 295 |
-
# upstream) — فحص الصحة الفعلي هو /api/state و/api/youtube. نؤكد ذلك في الاختبار حتى لا يُقرأ
|
| 296 |
-
# مطلب «بقاء Flask /api/health عاملًا» على أنه شيء عُدِّل أو وُجد.
|
| 297 |
_src = (DIR / 'app.py').read_text(encoding='utf-8')
|
| 298 |
_routes = [seg.split(chr(39))[1] for seg in _src.splitlines() if seg.startswith('@app.') and chr(39) in seg]
|
| 299 |
-
check('L:
|
| 300 |
-
|
| 301 |
and 'flask' not in (DIR / 'requirements.txt').read_text(encoding='utf-8').lower(),
|
| 302 |
'routes=%d' % len(_routes))
|
| 303 |
|
|
@@ -498,10 +506,10 @@ check('N7: التطابق داخل دقيقتين يُكتم (لا سطر)، و
|
|
| 498 |
check('N7: عند أول كتابة بعد الكتم يُلحق عدد ما كُتم، وحساب آخر لا يتأثر',
|
| 499 |
'كُتمت 1' in str(_m3) and 'كُتمت' not in str(_m4) and str(_o1) == 'تيك توك رفض الجلسة (403)',
|
| 500 |
'm3=%r m4=%r o1=%r' % (_m3, _m4, _o1))
|
| 501 |
-
_src7 =
|
| 502 |
check('N7: worker يستعمل الكتم والحالة تبقى صادقة (التحديث خارج الكتم)',
|
| 503 |
'out=throttle_failure(user,msg)' in _src7
|
| 504 |
-
and "
|
| 505 |
'الاستدعاء أو تحديث الحالة مفقود')
|
| 506 |
_app._failure_notes.clear()# N8: نافذة تأجيل منتهية تمسح قفلها وملاحظتها المجمدة («مؤجّلة 17 ث») عند أول start_sender
|
| 507 |
mgr.journal.change(lambda dd: dd['events'].update({'ex:9': {
|
|
@@ -617,7 +625,7 @@ check('N11: بعد انتهاء النافذة تُكتب وتُلحق عدد م
|
|
| 617 |
len(logs11) == 2 and 'كُتمت 1' in logs11[-1], 'last=%r' % logs11[-1][:60])
|
| 618 |
mgr._log_throttled('hz', 'رسالة أخرى مختلفة')
|
| 619 |
check('N11: رسالة غير متطابقة تُكتب فورًا', len(logs11) == 3, 'logs=%d' % len(logs11))
|
| 620 |
-
mgr._hold_notes.pop('hz', None)# N12: حجب المصادر ⇒ ملاحظة صادقة
|
| 621 |
import threading as _th
|
| 622 |
mgr.journal.change(lambda dd: dd['events'].update({'bl:1': {
|
| 623 |
'session_key': 'bl:1', 'username': 'blocked', 'nickname': 'b', 'room_id': '5', 'title': 't',
|
|
@@ -625,17 +633,17 @@ mgr.journal.change(lambda dd: dd['events'].update({'bl:1': {
|
|
| 625 |
'bound': True, 'closing': False, 'phase': 'live', 'youtube_status': 'active',
|
| 626 |
'created_at': time.time(), 'was_live': True, 'create_pending': False, 'last_poll': time.time(),
|
| 627 |
'note': 'يوتيوب يستقبل؛ طُلب بدء الحدث للعامة حسب الخصوصية'}}))
|
| 628 |
-
mgr._observe = lambda u: {'status': 'unknown', 'room_id': '', 'sources': [], 'nickname': 'b', 'live_title': 't'}
|
| 629 |
_stop12 = _th.Event()
|
| 630 |
_sd12 = _FeedingSender()
|
| 631 |
_th12 = _th.Thread(target=mgr.sender_loop, args=('bl:1', 'blocked', '5', 'rtmps://x/k', _stop12, _sd12), daemon=True)
|
| 632 |
-
_th12.start();
|
| 633 |
_ev12 = mgr.journal.read()['events'].get('bl:1') or {}
|
| 634 |
-
check('N12: حجب المصادر — الم
|
| 635 |
-
_th12.is_alive() is
|
| 636 |
and str(_ev12.get('note') or '') == 'تيك توك لا يرجع مصادر لهذا الخادم الآن؛ الحدث محفوظ والمحاولة كل دورة رصد',
|
| 637 |
'alive=%s note=%r' % (_th12.is_alive(), str(_ev12.get('note'))[:50]))
|
| 638 |
-
_stop12.set()
|
| 639 |
mgr.journal.change(lambda dd: dd['events'].pop('bl:1', None))# N13: المسار الصامت مغلق — «غير مباشر» يُكتب عند التحوّل فقط، وstreak جديد يعيده
|
| 640 |
st13 = []
|
| 641 |
mgr.max_events = 9 # استرجاع N9 أعاد أحداث N4 — بلا رفع السقف تُقطع حلقة الرصد قبل 'pa'
|
|
@@ -1035,130 +1043,47 @@ check('N23: بث liveStarting لم يُشغَّل أبدًا يُحذف ويُؤ
|
|
| 1035 |
mgr.api, mgr.log, mgr.stop_sender = _pre23_api, _pre23_log, _pre23_stop
|
| 1036 |
mgr.journal.change(_restore23)
|
| 1037 |
|
| 1038 |
-
# N25:
|
| 1039 |
-
|
| 1040 |
-
|
| 1041 |
-
|
| 1042 |
-
|
| 1043 |
-
|
| 1044 |
-
|
| 1045 |
-
import
|
| 1046 |
-
_mod24 = types.ModuleType('huggingface_hub')
|
| 1047 |
-
_mod24.upload_file = _FakeHF.upload_file
|
| 1048 |
-
_sys24.modules['huggingface_hub'] = _mod24
|
| 1049 |
-
_orig_tok24 = os.environ.get('HF_UPLOAD_TOKEN')
|
| 1050 |
-
os.environ['HF_UPLOAD_TOKEN'] = 'TESTTOK24'
|
| 1051 |
-
_tmp24 = pathlib.Path(tempfile.mkdtemp()) / 'x.mp4'
|
| 1052 |
-
_tmp24.write_bytes(b'0' * 128)
|
| 1053 |
-
_app._bucket_upload(_tmp24, 'rj1')
|
| 1054 |
-
_deadline24 = time.time() + 5
|
| 1055 |
-
while time.time() < _deadline24 and not _fake_hf['calls']:
|
| 1056 |
-
time.sleep(0.05)
|
| 1057 |
-
_app._bucket_upload(pathlib.Path(tempfile.mkdtemp()) / 'missing.mp4', 'rj1')
|
| 1058 |
-
_ok24 = bool(_fake_hf['calls']) and _fake_hf['calls'][0][0] == 'Reoo88/Tktktk-archive' \
|
| 1059 |
-
and _fake_hf['calls'][0][1] == 'recordings/x.mp4' and _fake_hf['calls'][0][2] == 'dataset' \
|
| 1060 |
-
and _fake_hf['calls'][0][3] == 'TESTTOK24'
|
| 1061 |
-
if _orig_tok24 is None:
|
| 1062 |
-
os.environ.pop('HF_UPLOAD_TOKEN', None)
|
| 1063 |
-
else:
|
| 1064 |
-
os.environ['HF_UPLOAD_TOKEN'] = _orig_tok24
|
| 1065 |
-
check('N25: إقفال MP4 يرفع الأرشيف إلى dataset دائم خارج الـbucket (المستودع/المسار/النوع/التوكن صحيحة) والمفقود لا يكسر شيئًا',
|
| 1066 |
-
_ok24, 'calls=%s' % (_fake_hf['calls'],))
|
| 1067 |
-
|
| 1068 |
-
# N19: رفض توكن الحساب (403) ⇒ محاولة تلقائية واحدة بـTIKTOK_SESSIONID العام قبل
|
| 1069 |
-
# إعلان الرفض — تحديث السر العام يشفِي كل الحسابات رغم توكنات الملف القديمة، والحساب
|
| 1070 |
-
# بلا توكن ملفي يستعمل العام مباشرة من أول نداء
|
| 1071 |
-
_tk19 = {'cookies': []}
|
| 1072 |
-
class _Resp19:
|
| 1073 |
-
status_code = 200
|
| 1074 |
-
def raise_for_status(self):
|
| 1075 |
-
pass
|
| 1076 |
-
def json(self):
|
| 1077 |
-
return {'data': {'ok': True}}
|
| 1078 |
-
class _Rej19:
|
| 1079 |
-
status_code = 403
|
| 1080 |
-
def raise_for_status(self):
|
| 1081 |
-
_e = OSError('http 403')
|
| 1082 |
-
_e.response = type('R', (), {'status_code': 403})()
|
| 1083 |
-
raise _e
|
| 1084 |
-
def _fake_get19(url, params=None, impersonate=None, headers=None, timeout=None):
|
| 1085 |
-
cookie = (headers or {}).get('Cookie', '')
|
| 1086 |
-
_tk19['cookies'].append(cookie)
|
| 1087 |
-
return _Rej19() if 'OLDSID' in cookie and 'GLOBALSID' not in cookie else _Resp19()
|
| 1088 |
-
_orig_get19 = _app.requests.get
|
| 1089 |
_orig_env19 = os.environ.get('TIKTOK_SESSIONID')
|
| 1090 |
-
_app.requests.get = _fake_get19
|
| 1091 |
-
os.environ['TIKTOK_SESSIONID'] = 'GLOBALSID'
|
| 1092 |
try:
|
| 1093 |
-
|
| 1094 |
-
|
| 1095 |
-
|
| 1096 |
-
|
| 1097 |
-
_tk19['cookies'].clear()
|
| 1098 |
-
_app._tokens.pop('oldacc', None)
|
| 1099 |
-
_r19b = _app.get_json('https://www.tiktok.com/api-live/user/room', {'aid': 1988}, 'oldacc')
|
| 1100 |
-
_ok19b = _r19b.get('data', {}).get('ok') is True and len(_tk19['cookies']) == 1 \
|
| 1101 |
-
and 'GLOBALSID' in _tk19['cookies'][0]
|
| 1102 |
finally:
|
| 1103 |
-
|
| 1104 |
-
if _orig_env19 is None:
|
| 1105 |
-
|
| 1106 |
-
|
| 1107 |
-
|
| 1108 |
-
|
| 1109 |
-
|
| 1110 |
-
|
| 1111 |
-
|
| 1112 |
-
|
| 1113 |
-
# N20: بعد موت كل الكوكيز — محاولة مجهولة أخيرة: تُرجع الجسد إن كان صالحًا للاكتشاف
|
| 1114 |
-
# (غير مباشر، أو حي بمصادر مرئية مجهولًا)؛ حيّ بلا مصادر مجهولًا يبقى «رفض الجلسة» الأصلي
|
| 1115 |
-
_body20 = {'v': 0}
|
| 1116 |
class _Resp20:
|
| 1117 |
status_code = 200
|
| 1118 |
-
def raise_for_status(self):
|
| 1119 |
-
|
| 1120 |
-
def json(self):
|
| 1121 |
-
return _body20
|
| 1122 |
-
class _Rej20:
|
| 1123 |
-
status_code = 403
|
| 1124 |
-
def raise_for_status(self):
|
| 1125 |
-
_e = OSError('http 403')
|
| 1126 |
-
_e.response = type('R', (), {'status_code': 403})()
|
| 1127 |
-
raise _e
|
| 1128 |
-
_calls20 = {'anon': 0}
|
| 1129 |
-
def _fake_get20(url, params=None, impersonate=None, headers=None, timeout=None):
|
| 1130 |
-
if (headers or {}).get('Cookie'):
|
| 1131 |
-
return _Rej20()
|
| 1132 |
-
_calls20['anon'] += 1
|
| 1133 |
-
return _Resp20()
|
| 1134 |
_orig_get20 = _app.requests.get
|
| 1135 |
-
|
|
|
|
| 1136 |
_app.requests.get = _fake_get20
|
| 1137 |
-
_app._tokens['old20'] = 'OLDSID'
|
| 1138 |
-
_URL20 = 'https://www.tiktok.com/api-live/user/room'
|
| 1139 |
try:
|
| 1140 |
-
|
| 1141 |
-
|
| 1142 |
-
|
| 1143 |
-
_sd20 = json.dumps({'data': {'origin': {'main': {'flv': 'https://pull/x.flv'}}}})
|
| 1144 |
-
_body20.clear()
|
| 1145 |
-
_body20.update({'data': {'liveRoom': {'status': 2, 'streamData': {'pull_data': {'stream_data': _sd20}}}}})
|
| 1146 |
-
_r20b = _app.get_json(_URL20, {'aid': 1988}, 'old20')
|
| 1147 |
-
_ok20b = _r20b.get('data', {}).get('liveRoom', {}).get('status') == 2
|
| 1148 |
-
_body20.clear(); _body20.update({'data': {'liveRoom': {'status': 2}}})
|
| 1149 |
-
_raise20 = False
|
| 1150 |
-
try:
|
| 1151 |
-
_app.get_json(_URL20, {'aid': 1988}, 'old20')
|
| 1152 |
-
except RuntimeError as e:
|
| 1153 |
-
_raise20 = 'رفض الجلسة' in str(e)
|
| 1154 |
finally:
|
| 1155 |
_app.requests.get = _orig_get20
|
| 1156 |
-
|
| 1157 |
-
|
| 1158 |
-
os.environ['TIKTOK_SESSIONID'] = _orig_env20
|
| 1159 |
-
check('N20: بعد رفض الكوكيز، المحاولة المجهولة تُرجع الرصد الصالح (غير مباشر/حي بمصادر) — وحيّ بلا مصادر مجهولًا يبقى رفض جلسة بلا كذب',
|
| 1160 |
-
_ok20a and _ok20b and _raise20,
|
| 1161 |
-
'offline=%r live_src=%r no_src_raises=%r' % (_ok20a, _ok20b, _raise20))
|
| 1162 |
|
| 1163 |
# N21: القالب الفخم (V9) — ترحيل '{title}' غير المعدّل تلقائيًا، القوالب المخصصة لا تُمس،
|
| 1164 |
# وعنوان الحدث بلا live_title يبقى اسم المذيع داخل الغلاف الفخم بلا تكرار «بث مباشر»
|
|
@@ -1207,11 +1132,11 @@ mgr.journal.change(lambda dd: dd.update(enabled=True, events={}, history=[]))
|
|
| 1207 |
mgr.tick()
|
| 1208 |
_ev21 = (mgr.journal.read().get('events') or {}).get('rj1:R21') or {}
|
| 1209 |
_t21 = str(_ev21.get('title') or '')
|
| 1210 |
-
check('N21: القالب ال
|
| 1211 |
-
|
| 1212 |
and _j21c['settings']['title'] == 'قالبي {name} الخاص'
|
| 1213 |
-
and
|
| 1214 |
-
and _t21.startswith('
|
| 1215 |
'migrated=%r custom=%r nick=%r title=%r' % (_j21['settings']['title'], _j21c['settings']['title'], _j21n['settings']['title'], _t21))
|
| 1216 |
# N22: سجل البثوث يصل اللوحة بعناوينه — الأحدث أولًا مع معرف البث لرابط المشاهدة
|
| 1217 |
mgr.journal.change(lambda dd: dd.update(history=[
|
|
@@ -1221,11 +1146,9 @@ mgr.journal.change(lambda dd: dd.update(history=[
|
|
| 1221 |
'nickname': 'ر', 'outcome': 'live_ended', 'ended_at': 2.0}]))
|
| 1222 |
_sn22 = mgr.snapshot()
|
| 1223 |
_h22 = _sn22.get('history') or []
|
| 1224 |
-
check('N22: /api/youtube يع
|
| 1225 |
-
_h22
|
| 1226 |
-
|
| 1227 |
-
and _h22[0].get('outcome') == 'live_ended',
|
| 1228 |
-
'hist=%s count=%s' % ([(h.get('title'), h.get('broadcast_id')) for h in _h22], _sn22.get('history_count')))
|
| 1229 |
mgr.api, mgr._observe, mgr.ensure_stream, mgr.open_event, mgr.drive_event, mgr.probe = _pre21
|
| 1230 |
mgr.accounts = _pre21_acc
|
| 1231 |
mgr.journal.change(lambda dd: dd.clear() or dd.update(_jb21))
|
|
@@ -1292,7 +1215,8 @@ mgr.remote = _remote23
|
|
| 1292 |
def _no_open23(u, o):
|
| 1293 |
raise RuntimeError('open_event should not run on resume')
|
| 1294 |
mgr.open_event = _no_open23
|
| 1295 |
-
mgr.journal.change(lambda dd: dd.update(enabled=True, events={},
|
|
|
|
| 1296 |
'session_key': 'u23:R23', 'broadcast_id': 'b23', 'title': 'same', 'username': 'u23',
|
| 1297 |
'nickname': 'u23', 'outcome': 'live_ended', 'ended_at': time.time() - 400}]))
|
| 1298 |
mgr.tick()
|
|
@@ -1309,6 +1233,7 @@ mgr.accounts, mgr._observe, mgr.ensure_stream, mgr.drive_event, mgr.remote, mgr.
|
|
| 1309 |
mgr.log = _orig_log23
|
| 1310 |
mgr.journal.change(lambda dd: dd.update(
|
| 1311 |
events={k: v for k, v in (dd.get('events') or {}).items() if k != 'u23:R23'},
|
|
|
|
| 1312 |
history=[h for h in (dd.get('history') or []) if h.get('session_key') != 'u23:R23']))
|
| 1313 |
|
| 1314 |
check('M: لا ffmpeg/قارئ متسرب بعد كل الجلسات', not stray, 'stray=%s' % stray[:1])
|
|
|
|
| 165 |
'phase': 'live', 'youtube_status': 'live', 'created_at': time.time(), 'was_live': True,
|
| 166 |
'create_pending': False, 'note': '', 'last_poll': time.time()}}))
|
| 167 |
mgr.destinations['u7'] = 'rtmps://example.invalid/y' # وجهة وهمية عمدًا: لا نريد اتصال يوتيوب
|
| 168 |
+
# Publishing failure now invalidates the cached ingest. Keep this local media lifecycle
|
| 169 |
+
# fixture isolated: restoring that fake ingest must never call the real OAuth API.
|
| 170 |
+
_lifecycle_ensure_stream = mgr.ensure_stream
|
| 171 |
+
def _local_lifecycle_ingest(user):
|
| 172 |
+
mgr.destinations[user] = 'rtmps://example.invalid/y'
|
| 173 |
+
return {}
|
| 174 |
+
mgr.ensure_stream = _local_lifecycle_ingest
|
| 175 |
# لماذا لا نطلب out_time هنا: مقياس محلي — مع وجهة لا تُفتح، `-timeshift 10` كان يُقدّم
|
| 176 |
# out_time_us من مخزن fifo (8.4 ث في 8 ث) بينما `-timeshift 0` يبقى على 0.0. أي أن تقدّم
|
| 177 |
# الوقت كان يخبر عن «كم حُجز» لا عن «كم سُلّم». فالأمانة في هذه الحالة هي الصفر.
|
|
|
|
| 211 |
# مطلوبًا أن يقفز المدير فوق الكاش — والأثر المطلوب هو إعادة الرصد والجلسة الجديدة.
|
| 212 |
watchdog_logged = any('[WATCHDOG]' in m for m in logs[-25:])
|
| 213 |
check('J: عطل التدفق أُعلِن في السجل وأُعيد الرصد/الجلسة (خيط حيّ لا يحتاج قفز الكاش)',
|
| 214 |
+
watchdog_logged and bool(seen_force) and src2 > 0,
|
| 215 |
+
'attended=%s force=%s src=%.0f log=%s' % (attended, seen_force[:2], src2, watchdog_logged))
|
| 216 |
# الدورة كاملة تُقرأ من السجل وحده — هذا ما طلبه المستخدم: صمت ⇒ حارس ⇒ تنظيف ⇒ مراقبة ⇒
|
| 217 |
# LIVE ⇒ جلسة جديدة. الترتيب أدناه مقيس من logs نفسها، لا مفترض.
|
| 218 |
def _first(tag, after=-1):
|
|
|
|
| 250 |
'nickname': 'n', 'live_title': ''}
|
| 251 |
mgr.drive_event(key)
|
| 252 |
ev = mgr.journal.read()['events'].get(key)
|
| 253 |
+
check('K: أول offline لا يغلق الحدث ولا يحذف المشرف (تأكيد قبل الإنهاء)',
|
| 254 |
+
(not ev or not ev.get('closing')) and key in mgr.senders)
|
| 255 |
_dead = time.monotonic() + 8
|
| 256 |
+
while time.monotonic() < _dead and not any('[OFFLINE]' in m or 'TikTok offline' in m for m in logs):
|
| 257 |
time.sleep(0.3)
|
| 258 |
+
check('K: إشارة offline الأولى مميزة في السجل عن صمت المصدر (والإنهاء ينتظر التأكيد)',
|
| 259 |
+
any('[OFFLINE]' in m or 'TikTok offline' in m for m in logs), logs[-1][:90])
|
| 260 |
for e in list(mgr.senders.values()):
|
| 261 |
e['stop'].set()
|
| 262 |
e['sender'].terminate()
|
| 263 |
+
for _lifecycle_key in list(mgr.senders):
|
| 264 |
+
mgr.stop_sender(_lifecycle_key)
|
| 265 |
+
mgr.ensure_stream = _lifecycle_ensure_stream
|
| 266 |
|
| 267 |
# ── L) التطبيق يستورد، ونقاط الحالة تعمل بعد التعديل ───────────────────────────────
|
| 268 |
r = subprocess.run([sys.executable, '-c',
|
|
|
|
| 301 |
except ImportError as e:
|
| 302 |
check('L: TestClient غير متاح (httpx ناقص) — فحص الاستيراد يكفي', True, str(e)[:60])
|
| 303 |
|
| 304 |
+
# Public liveness is deliberately minimal; authenticated diagnostics remain available.
|
|
|
|
|
|
|
| 305 |
_src = (DIR / 'app.py').read_text(encoding='utf-8')
|
| 306 |
_routes = [seg.split(chr(39))[1] for seg in _src.splitlines() if seg.startswith('@app.') and chr(39) in seg]
|
| 307 |
+
check('L: FastAPI exposes minimal /health plus authenticated state/youtube diagnostics',
|
| 308 |
+
all(r in _routes for r in ('/health','/api/health','/api/state','/api/youtube'))
|
| 309 |
and 'flask' not in (DIR / 'requirements.txt').read_text(encoding='utf-8').lower(),
|
| 310 |
'routes=%d' % len(_routes))
|
| 311 |
|
|
|
|
| 506 |
check('N7: عند أول كتابة بعد الكتم يُلحق عدد ما كُتم، وحساب آخر لا يتأثر',
|
| 507 |
'كُتمت 1' in str(_m3) and 'كُتمت' not in str(_m4) and str(_o1) == 'تيك توك رفض الجلسة (403)',
|
| 508 |
'm3=%r m4=%r o1=%r' % (_m3, _m4, _o1))
|
| 509 |
+
_src7 = (DIR / 'app.py').read_text(encoding='utf-8')
|
| 510 |
check('N7: worker يستعمل الكتم والحالة تبقى صادقة (التحديث خارج الكتم)',
|
| 511 |
'out=throttle_failure(user,msg)' in _src7
|
| 512 |
+
and "_set_state(user,'ERROR' if 'رفض' in msg else 'BACKOFF'" in _src7,
|
| 513 |
'الاستدعاء أو تحديث الحالة مفقود')
|
| 514 |
_app._failure_notes.clear()# N8: نافذة تأجيل منتهية تمسح قفلها وملاحظتها المجمدة («مؤجّلة 17 ث») عند أول start_sender
|
| 515 |
mgr.journal.change(lambda dd: dd['events'].update({'ex:9': {
|
|
|
|
| 625 |
len(logs11) == 2 and 'كُتمت 1' in logs11[-1], 'last=%r' % logs11[-1][:60])
|
| 626 |
mgr._log_throttled('hz', 'رسالة أخرى مختلفة')
|
| 627 |
check('N11: رسالة غير متطابقة تُكتب فورًا', len(logs11) == 3, 'logs=%d' % len(logs11))
|
| 628 |
+
mgr._hold_notes.pop('hz', None)# N12: حجب المصادر ⇒ ملاحظة صادقة مع إبقاء مشرف الحدث للمحاولة
|
| 629 |
import threading as _th
|
| 630 |
mgr.journal.change(lambda dd: dd['events'].update({'bl:1': {
|
| 631 |
'session_key': 'bl:1', 'username': 'blocked', 'nickname': 'b', 'room_id': '5', 'title': 't',
|
|
|
|
| 633 |
'bound': True, 'closing': False, 'phase': 'live', 'youtube_status': 'active',
|
| 634 |
'created_at': time.time(), 'was_live': True, 'create_pending': False, 'last_poll': time.time(),
|
| 635 |
'note': 'يوتيوب يستقبل؛ طُلب بدء الحدث للعامة حسب الخصوصية'}}))
|
| 636 |
+
mgr._observe = lambda u, **kw: {'status': 'unknown', 'room_id': '', 'sources': [], 'nickname': 'b', 'live_title': 't'}
|
| 637 |
_stop12 = _th.Event()
|
| 638 |
_sd12 = _FeedingSender()
|
| 639 |
_th12 = _th.Thread(target=mgr.sender_loop, args=('bl:1', 'blocked', '5', 'rtmps://x/k', _stop12, _sd12), daemon=True)
|
| 640 |
+
_th12.start(); time.sleep(2)
|
| 641 |
_ev12 = mgr.journal.read()['events'].get('bl:1') or {}
|
| 642 |
+
check('N12: حجب المصادر — الحدث محفوظ والمشرف يبقى للمحاولة بدل وميض جلسات جديدة',
|
| 643 |
+
_th12.is_alive() is True
|
| 644 |
and str(_ev12.get('note') or '') == 'تيك توك لا يرجع مصادر لهذا الخادم الآن؛ الحدث محفوظ والمحاولة كل دورة رصد',
|
| 645 |
'alive=%s note=%r' % (_th12.is_alive(), str(_ev12.get('note'))[:50]))
|
| 646 |
+
_stop12.set();_th12.join(timeout=4)
|
| 647 |
mgr.journal.change(lambda dd: dd['events'].pop('bl:1', None))# N13: المسار الصامت مغلق — «غير مباشر» يُكتب عند التحوّل فقط، وstreak جديد يعيده
|
| 648 |
st13 = []
|
| 649 |
mgr.max_events = 9 # استرجاع N9 أعاد أحداث N4 — بلا رفع السقف تُقطع حلقة الرصد قبل 'pa'
|
|
|
|
| 1043 |
mgr.api, mgr.log, mgr.stop_sender = _pre23_api, _pre23_log, _pre23_stop
|
| 1044 |
mgr.journal.change(_restore23)
|
| 1045 |
|
| 1046 |
+
# N25: هذا المشروع Relay فقط. لا تسجيل MP4 ولا رفع أرشيف أو اعتماد huggingface_hub.
|
| 1047 |
+
_src25 = (DIR / 'app.py').read_text(encoding='utf-8') + (DIR / 'relay.py').read_text(encoding='utf-8')
|
| 1048 |
+
check('N25: مسار التنفيذ بلا تسجيل/رفع أرشيف وبلا HF upload token',
|
| 1049 |
+
'_bucket_upload' not in _src25 and 'HF_UPLOAD_TOKEN' not in _src25
|
| 1050 |
+
and 'huggingface_hub' not in (DIR / 'requirements.txt').read_text(encoding='utf-8'), '')
|
| 1051 |
+
|
| 1052 |
+
# N19: Secrets must beat an older UI token. This is deterministic and does not hit TikTok.
|
| 1053 |
+
import tiktok_auth as _ta19
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1054 |
_orig_env19 = os.environ.get('TIKTOK_SESSIONID')
|
|
|
|
|
|
|
| 1055 |
try:
|
| 1056 |
+
_ta19.save('oldacc', 'sessionid=' + 'O' * 40)
|
| 1057 |
+
os.environ['TIKTOK_SESSIONID'] = 'G' * 40
|
| 1058 |
+
_s19 = _ta19.session_for('oldacc')
|
| 1059 |
+
_ok19 = _s19.get('source') == 'TIKTOK_SESSIONID' and _s19.get('sessionid') == 'G' * 40
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1060 |
finally:
|
| 1061 |
+
_ta19.delete('oldacc')
|
| 1062 |
+
if _orig_env19 is None: os.environ.pop('TIKTOK_SESSIONID', None)
|
| 1063 |
+
else: os.environ['TIKTOK_SESSIONID'] = _orig_env19
|
| 1064 |
+
check('N19: Secret TIKTOK_SESSIONID يتقدم على توكن UI قديم للحساب',
|
| 1065 |
+
_ok19, 'source=%r' % _s19.get('source'))
|
| 1066 |
+
|
| 1067 |
+
|
| 1068 |
+
# N20: public-first avoids burning an expiring cookie for rooms visible anonymously.
|
| 1069 |
+
_body20 = {'data': {'liveRoom': {'status': 4}}}
|
| 1070 |
+
_calls20 = []
|
|
|
|
|
|
|
|
|
|
| 1071 |
class _Resp20:
|
| 1072 |
status_code = 200
|
| 1073 |
+
def raise_for_status(self): pass
|
| 1074 |
+
def json(self): return _body20
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1075 |
_orig_get20 = _app.requests.get
|
| 1076 |
+
def _fake_get20(url, params=None, impersonate=None, headers=None, timeout=None):
|
| 1077 |
+
_calls20.append(dict(headers or {}));return _Resp20()
|
| 1078 |
_app.requests.get = _fake_get20
|
|
|
|
|
|
|
| 1079 |
try:
|
| 1080 |
+
_r20a = _app.get_json('https://www.tiktok.com/api-live/user/room', {'aid':1988}, 'old20')
|
| 1081 |
+
_ok20a = _r20a.get('data',{}).get('liveRoom',{}).get('status') == 4
|
| 1082 |
+
_ok20b = len(_calls20) == 1 and not _calls20[0].get('Cookie')
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1083 |
finally:
|
| 1084 |
_app.requests.get = _orig_get20
|
| 1085 |
+
check('N20: الغرفة العامة تُفحص بلا Cookie أولًا ولا تُستهلك الجلسة',
|
| 1086 |
+
_ok20a and _ok20b, 'calls=%r' % _calls20)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1087 |
|
| 1088 |
# N21: القالب الفخم (V9) — ترحيل '{title}' غير المعدّل تلقائيًا، القوالب المخصصة لا تُمس،
|
| 1089 |
# وعنوان الحدث بلا live_title يبقى اسم المذيع داخل الغلاف الفخم بلا تكرار «بث مباشر»
|
|
|
|
| 1132 |
mgr.tick()
|
| 1133 |
_ev21 = (mgr.journal.read().get('events') or {}).get('rj1:R21') or {}
|
| 1134 |
_t21 = str(_ev21.get('title') or '')
|
| 1135 |
+
check('N21: القوالب القديمة العامة تُرحَّل للقالب البسيط، والمخصص لا يُمس، واسم المذيع يبقى في العنوان',
|
| 1136 |
+
_j21['settings']['title'] == _DS21['title']
|
| 1137 |
and _j21c['settings']['title'] == 'قالبي {name} الخاص'
|
| 1138 |
+
and _j21n['settings']['title'] == _DS21['title']
|
| 1139 |
+
and _t21.startswith('rj1 | ') and 'rj1' in _t21,
|
| 1140 |
'migrated=%r custom=%r nick=%r title=%r' % (_j21['settings']['title'], _j21c['settings']['title'], _j21n['settings']['title'], _t21))
|
| 1141 |
# N22: سجل البثوث يصل اللوحة بعناوينه — الأحدث أولًا مع معرف البث لرابط المشاهدة
|
| 1142 |
mgr.journal.change(lambda dd: dd.update(history=[
|
|
|
|
| 1146 |
'nickname': 'ر', 'outcome': 'live_ended', 'ended_at': 2.0}]))
|
| 1147 |
_sn22 = mgr.snapshot()
|
| 1148 |
_h22 = _sn22.get('history') or []
|
| 1149 |
+
check('N22: /api/youtube لا يعرض سجل الأحداث القديمة أو روابطها (المشروع Relay بلا لوحة أرشيف)',
|
| 1150 |
+
_h22 == [] and _sn22.get('history_count') == 0,
|
| 1151 |
+
'hist=%s count=%s' % (_h22, _sn22.get('history_count')))
|
|
|
|
|
|
|
| 1152 |
mgr.api, mgr._observe, mgr.ensure_stream, mgr.open_event, mgr.drive_event, mgr.probe = _pre21
|
| 1153 |
mgr.accounts = _pre21_acc
|
| 1154 |
mgr.journal.change(lambda dd: dd.clear() or dd.update(_jb21))
|
|
|
|
| 1215 |
def _no_open23(u, o):
|
| 1216 |
raise RuntimeError('open_event should not run on resume')
|
| 1217 |
mgr.open_event = _no_open23
|
| 1218 |
+
mgr.journal.change(lambda dd: dd.update(enabled=True, events={},
|
| 1219 |
+
streams={**(dd.get('streams') or {}), 'u23': {'id': 's1'}}, history=[{
|
| 1220 |
'session_key': 'u23:R23', 'broadcast_id': 'b23', 'title': 'same', 'username': 'u23',
|
| 1221 |
'nickname': 'u23', 'outcome': 'live_ended', 'ended_at': time.time() - 400}]))
|
| 1222 |
mgr.tick()
|
|
|
|
| 1233 |
mgr.log = _orig_log23
|
| 1234 |
mgr.journal.change(lambda dd: dd.update(
|
| 1235 |
events={k: v for k, v in (dd.get('events') or {}).items() if k != 'u23:R23'},
|
| 1236 |
+
streams={k: v for k, v in (dd.get('streams') or {}).items() if k != 'u23'},
|
| 1237 |
history=[h for h in (dd.get('history') or []) if h.get('session_key') != 'u23:R23']))
|
| 1238 |
|
| 1239 |
check('M: لا ffmpeg/قارئ متسرب بعد كل الجلسات', not stray, 'stray=%s' % stray[:1])
|
test_regressions.py
ADDED
|
@@ -0,0 +1,146 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Fast regressions for the production noData/auth/privacy fixes."""
|
| 2 |
+
import os, pathlib, stat, sys, tempfile, threading, time
|
| 3 |
+
|
| 4 |
+
DIR = pathlib.Path(sys.argv[1]).resolve() if len(sys.argv) > 1 else pathlib.Path(__file__).resolve().parent
|
| 5 |
+
os.environ.setdefault('PASSWORD', 'audit-password')
|
| 6 |
+
os.environ.setdefault('DATA_DIR', tempfile.mkdtemp())
|
| 7 |
+
os.environ.setdefault('FFMPEG_PATH', os.getenv('FFMPEG_PATH') or '/bin/true')
|
| 8 |
+
sys.path.insert(0, str(DIR))
|
| 9 |
+
|
| 10 |
+
failed=[];passed=0
|
| 11 |
+
def check(name, cond, detail=''):
|
| 12 |
+
global passed
|
| 13 |
+
if cond:
|
| 14 |
+
passed+=1;print('PASS ',name)
|
| 15 |
+
else:
|
| 16 |
+
failed.append(name);print('FAIL ',name,detail)
|
| 17 |
+
|
| 18 |
+
# UI regression: refresh() used to throw because these two elements did not exist.
|
| 19 |
+
html=(DIR/'index.html').read_text(encoding='utf-8')
|
| 20 |
+
for ident in ('login-panel','admin-password','accounts-panel','youtube-panel','system-panel','ncpu','nram'):
|
| 21 |
+
check('dashboard contains #'+ident, ('id="%s"'%ident) in html)
|
| 22 |
+
check('dashboard API sends the in-page Basic credential', 'headers.Authorization=authHeader' in html)
|
| 23 |
+
|
| 24 |
+
from youtube_manager import ManagedYouTube
|
| 25 |
+
from relay import Sender, ffmpeg_output_failure, source_http_headers
|
| 26 |
+
from ingest import hub
|
| 27 |
+
|
| 28 |
+
# Login cookies belong to tiktok.com. Signed media CDN hosts must receive the public Referer
|
| 29 |
+
# only; manually forwarding sessionid cross-domain both leaks it and can upset CDN edges.
|
| 30 |
+
header_calls=[]
|
| 31 |
+
def account_headers(user):
|
| 32 |
+
header_calls.append(user)
|
| 33 |
+
return {'Cookie':'sessionid=secret; sid_tt=secret','X-Account':'private','Host':'wrong.example'}
|
| 34 |
+
cdn=source_http_headers('https://pull-flv-l1-va01.tiktokcdn-us.com/stage/stream.flv',
|
| 35 |
+
'alice',account_headers)
|
| 36 |
+
check('signed CDN gets Referer but no account cookie',
|
| 37 |
+
cdn=={'Referer':'https://www.tiktok.com/'} and header_calls==[],str(cdn))
|
| 38 |
+
tiktok=source_http_headers('https://www.tiktok.com/@alice/live','alice',account_headers)
|
| 39 |
+
check('real tiktok.com host retains its account cookie',
|
| 40 |
+
tiktok.get('Cookie','').startswith('sessionid=') and tiktok.get('X-Account')=='private',str(tiktok))
|
| 41 |
+
check('caller cannot override the HTTP Host header', 'Host' not in tiktok,str(tiktok))
|
| 42 |
+
evil=source_http_headers('https://tiktok.com.attacker.example/stream.flv','alice',account_headers)
|
| 43 |
+
check('lookalike hostname cannot receive TikTok credentials', 'Cookie' not in evil,str(evil))
|
| 44 |
+
hls_blob=Sender('/bin/true',lambda *a:None,account_headers).headers_blob(
|
| 45 |
+
{'url':'https://pull.example/stream.m3u8','user':'alice'})
|
| 46 |
+
check('FFmpeg HLS headers enforce the same CDN cookie boundary',
|
| 47 |
+
'Referer: https://www.tiktok.com/\r\n' in hls_blob and 'sessionid' not in hls_blob,hls_blob)
|
| 48 |
+
|
| 49 |
+
# Production evidence was "Error opening output files: End of file" after 10 seconds.
|
| 50 |
+
# Once RTMPS blocks, FFmpeg stops reading stdin and the source meter ages as a consequence;
|
| 51 |
+
# that must not be misdiagnosed as TikTok/CDN starvation.
|
| 52 |
+
check('FFmpeg output-open EOF is classified as publishing-side failure',
|
| 53 |
+
ffmpeg_output_failure('Error opening output files: End of file'))
|
| 54 |
+
check('an HLS input 403 is not mislabeled as an RTMPS output failure',
|
| 55 |
+
not ffmpeg_output_failure('Error opening input files: Server returned 403 Forbidden'))
|
| 56 |
+
|
| 57 |
+
old_forced=os.environ.get('YOUTUBE_FORCE_TRANSCODE_USERS')
|
| 58 |
+
os.environ['YOUTUBE_FORCE_TRANSCODE_USERS']='@alice, bob'
|
| 59 |
+
check('forced reliability mode is scoped per account',
|
| 60 |
+
ManagedYouTube.forced_mode('alice')=='matchgop' and ManagedYouTube.forced_mode('carol')=='')
|
| 61 |
+
if old_forced is None:os.environ.pop('YOUTUBE_FORCE_TRANSCODE_USERS',None)
|
| 62 |
+
else:os.environ['YOUTUBE_FORCE_TRANSCODE_USERS']=old_forced
|
| 63 |
+
|
| 64 |
+
out_logs=[]
|
| 65 |
+
tmp_out=pathlib.Path(tempfile.mkdtemp())
|
| 66 |
+
mgr_out=ManagedYouTube(os.environ['FFMPEG_PATH'],lambda u:{'status':'offline','sources':[]},
|
| 67 |
+
lambda u,m:out_logs.append(str(m)),lambda:[],tmp_out/'yt-output.json')
|
| 68 |
+
refreshed=[]
|
| 69 |
+
mgr_out.destinations['alice']='rtmps://a.rtmps.youtube.com/live2/old'
|
| 70 |
+
def refresh_ingest(user):
|
| 71 |
+
refreshed.append(user);mgr_out.destinations[user]='rtmps://a.rtmps.youtube.com/live2/current';return {}
|
| 72 |
+
mgr_out.ensure_stream=refresh_ingest
|
| 73 |
+
class OutputRejected:
|
| 74 |
+
last_exit_code=187;last_source_gap=12;last_failure_side='output'
|
| 75 |
+
def __init__(self):self.sticky=[]
|
| 76 |
+
def snapshot(self):return {'source_bytes':262144,'send_mode':'copy'}
|
| 77 |
+
def send_mode(self):return 'copy'
|
| 78 |
+
def request_sticky(self,mode,user,reason):self.sticky.append((mode,user,reason));return True
|
| 79 |
+
out_sender=OutputRejected()
|
| 80 |
+
mgr_out._note_early_exit('alice',out_sender,300)
|
| 81 |
+
check('output rejection after a long run still refreshes ingest and is not called TikTok starvation',
|
| 82 |
+
refreshed==['alice'] and mgr_out.hammer.get('alice')==1 and 'alice' not in mgr_out.starve)
|
| 83 |
+
mgr_out._note_early_exit('alice',out_sender,10)
|
| 84 |
+
check('second output rejection normalizes that publisher instead of reconnect storming COPY',
|
| 85 |
+
bool(out_sender.sticky) and mgr_out._sender_sticky.get('alice')=='matchgop',str(out_sender.sticky))
|
| 86 |
+
|
| 87 |
+
# The manager's normal sleep lands on every full scan. The old `if/else` therefore never
|
| 88 |
+
# called restart_dead_senders() for a live supervisor whose FFmpeg child was gone.
|
| 89 |
+
tmp=pathlib.Path(tempfile.mkdtemp())
|
| 90 |
+
mgr=ManagedYouTube(os.environ['FFMPEG_PATH'], lambda u,force=False:{'status':'offline','sources':[]},
|
| 91 |
+
lambda *a:None, lambda:[], tmp/'yt.json')
|
| 92 |
+
called=[]
|
| 93 |
+
mgr.check_channel=lambda *a,**k:None
|
| 94 |
+
mgr.tick=lambda:called.append('tick')
|
| 95 |
+
def restart_once():
|
| 96 |
+
called.append('restart');mgr.manager_stop.set();return 0
|
| 97 |
+
mgr.restart_dead_senders=restart_once
|
| 98 |
+
mgr.run_manager()
|
| 99 |
+
check('fast sender watchdog runs in the same pass as the full tick', called[:2]==['tick','restart'], str(called))
|
| 100 |
+
|
| 101 |
+
# A network reader can ignore the three-second join. Once its stop flag is set and FFmpeg is
|
| 102 |
+
# terminated, the stale slot must not block a replacement forever.
|
| 103 |
+
key='alice:1'
|
| 104 |
+
mgr2=ManagedYouTube(os.environ['FFMPEG_PATH'], lambda u:{'status':'offline','sources':[]},
|
| 105 |
+
lambda *a:None, lambda:['alice'], tmp/'yt2.json')
|
| 106 |
+
mgr2.journal.change(lambda d:d['events'].update({key:{'username':'alice','room_id':'1'}}))
|
| 107 |
+
class StuckThread:
|
| 108 |
+
def is_alive(self):return True
|
| 109 |
+
def join(self,timeout=None):return None
|
| 110 |
+
class DeadSender:
|
| 111 |
+
def __init__(self):self.terminated=0
|
| 112 |
+
def alive(self):return False
|
| 113 |
+
def terminate(self):self.terminated+=1
|
| 114 |
+
def snapshot(self):return {'last_source_at':time.monotonic()-30}
|
| 115 |
+
snd=DeadSender();th=StuckThread();stop=threading.Event()
|
| 116 |
+
mgr2.senders[key]={'thread':th,'sender':snd,'stop':stop}
|
| 117 |
+
with hub.lock:hub.slots.clear()
|
| 118 |
+
hub.occupy('alice','oauth',sender=snd,thread=th)
|
| 119 |
+
check('stuck stopped supervisor is detached', mgr2.stop_sender(key) and key not in mgr2.senders)
|
| 120 |
+
check('detached supervisor releases RelayHub slot', not hub.snapshot('alice'))
|
| 121 |
+
check('stuck supervisor was fenced and terminated', stop.is_set() and snd.terminated==1)
|
| 122 |
+
|
| 123 |
+
# Real ASGI boundary: public shell + minimal liveness, protected operational APIs.
|
| 124 |
+
import app as appmod
|
| 125 |
+
from fastapi.testclient import TestClient
|
| 126 |
+
with TestClient(appmod.app) as client:
|
| 127 |
+
root=client.get('/')
|
| 128 |
+
health=client.get('/health').json()
|
| 129 |
+
unauth=client.get('/api/state')
|
| 130 |
+
wrong=client.get('/api/state',auth=('admin','wrong'))
|
| 131 |
+
right=client.get('/api/state',auth=('admin',os.environ['PASSWORD']))
|
| 132 |
+
stream_events=client.get('/api/stream-events',auth=('admin',os.environ['PASSWORD']))
|
| 133 |
+
check('embedded root shows login instead of raw 401', root.status_code==200 and 'login-panel' in root.text)
|
| 134 |
+
check('public health contains no broadcaster/account details', set(health)<= {'status','application','monitor','version'}, str(health))
|
| 135 |
+
check('operational API rejects anonymous access', unauth.status_code==401)
|
| 136 |
+
check('operational API rejects a wrong password', wrong.status_code==401)
|
| 137 |
+
check('operational API accepts the configured password', right.status_code==200)
|
| 138 |
+
check('authenticated stream-event API exposes the bounded JSON log',
|
| 139 |
+
stream_events.status_code==200 and stream_events.json().get('file')=='logs/stream_events.json')
|
| 140 |
+
|
| 141 |
+
appmod.set_token('alice','sessionid='+'x'*32)
|
| 142 |
+
mode=stat.S_IMODE(appmod.TOKENS.stat().st_mode)
|
| 143 |
+
check('legacy token store is owner-only (0600)', mode==0o600, oct(mode))
|
| 144 |
+
|
| 145 |
+
print('%d passed, %d failed'%(passed,len(failed)))
|
| 146 |
+
if failed:sys.exit(1)
|
test_relay.py
CHANGED
|
@@ -86,6 +86,11 @@ top = ranked[0]
|
|
| 86 |
check('prefers H264 over HEVC origin', '264' in (top.get('codec') or '').lower(), 'top=%s codec=%s'%(top.get('quality_name'), top.get('codec')))
|
| 87 |
check('still lists HEVC as fallback', any('265' in (c.get('codec') or '').lower() or 'hevc' in (c.get('codec') or '').lower() for c in ranked))
|
| 88 |
check('sd not dropped', any(c.get('quality_name')=='sd' for c in ranked))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 89 |
|
| 90 |
# ---------- title template ----------
|
| 91 |
tpl = os.environ['YOUTUBE_TITLE_TEMPLATE']
|
|
@@ -110,7 +115,8 @@ check('requirements has no huggingface_hub', 'huggingface_hub' not in (ROOT/'req
|
|
| 110 |
# ---------- health + monitor isolation ----------
|
| 111 |
h = app.health_public()
|
| 112 |
check('TEST public /health', h.get('application')=='running', str(h))
|
| 113 |
-
check('health
|
|
|
|
| 114 |
# TEST 1: offline account does not start ffmpeg
|
| 115 |
app.tasks['offlineuser'] = app._blank_task()
|
| 116 |
app.tasks['offlineuser']['enabled'] = True
|
|
@@ -232,6 +238,31 @@ yt.retry['a']=yt._backoff('a')*2
|
|
| 232 |
check('TEST 11 backoff increases', yt._backoff('a')>=2, str(yt._backoff('a')))
|
| 233 |
yt.retry['a']=9999
|
| 234 |
check('TEST 11 backoff capped', yt._backoff('a')<=yt.retry_max)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 235 |
|
| 236 |
# ---------- unstable source fallback bookkeeping ----------
|
| 237 |
yt.mark_unstable('bob', {'quality_name':'origin','media':'flv','codec':'h265','resolution':'1080x1920','brief':'origin 1080p HEVC'}, 'stalled')
|
|
@@ -284,8 +315,8 @@ check('active_count is ffmpeg not idle threads', hub.active_count()==2)
|
|
| 284 |
hub.release('e1'); hub.release('e2')
|
| 285 |
check('env free after release', not hub.env_key_busy())
|
| 286 |
h=app.health_public()
|
| 287 |
-
check('health
|
| 288 |
-
check('health
|
| 289 |
check('health has version', bool(h.get('version')))
|
| 290 |
|
| 291 |
# Null TikTok payloads must be Offline, not AttributeError → sticky last_error
|
|
@@ -313,11 +344,11 @@ try:
|
|
| 313 |
app._check_account('staleerr')
|
| 314 |
check('offline clears last_error', app.tasks['staleerr'].get('last_error')=='', str(app.tasks['staleerr']))
|
| 315 |
check('offline after error is OFFLINE', app.tasks['staleerr']['state']=='OFFLINE')
|
|
|
|
|
|
|
| 316 |
h=app.health_public()
|
| 317 |
-
check('health
|
| 318 |
-
|
| 319 |
-
check('health lists broadcasters', isinstance(h.get('broadcasters'), list))
|
| 320 |
-
check('health metadata_automation field', 'metadata_automation' in h)
|
| 321 |
finally:
|
| 322 |
app.observe_session = orig
|
| 323 |
app.tasks.pop('staleerr', None)
|
|
@@ -381,7 +412,14 @@ yt.journal.change(lambda d: d['events'].pop('bob:1', None))
|
|
| 381 |
|
| 382 |
df=(ROOT/'Dockerfile').read_text()
|
| 383 |
check('Dockerfile stall default 12', 'SOURCE_STALL_TIMEOUT=12' in df and 'YOUTUBE_SOURCE_STALL_SECONDS=12' in df)
|
| 384 |
-
check('Dockerfile concurrent cap
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 385 |
mgr_src=(ROOT/'youtube_manager.py').read_text()
|
| 386 |
check('run_manager calls restart_dead_senders', 'restart_dead_senders' in mgr_src.split('def run_manager')[1])
|
| 387 |
pump=(ROOT/'relay.py').read_text()
|
|
@@ -391,7 +429,11 @@ check('empty FLV chunks do not refresh last', empty_i!=-1 and last_i!=-1 and emp
|
|
| 391 |
td=pump.split('def _teardown')[1].split('def send')[0]
|
| 392 |
check('teardown does not stop supervisor Event', 'stop.set()' not in td and "sess['force_stop']" in td)
|
| 393 |
check('send keeps FFmpeg via refresh reattach', 'def _try_reattach' in pump and 'def send(self, user, candidate, destination, stop, refresh=None)' in pump)
|
| 394 |
-
check('sender_loop
|
|
|
|
|
|
|
|
|
|
|
|
|
| 395 |
from flv_bridge import FLVBridge
|
| 396 |
def _flv_avc(ts=0, seq=False, payload=b'\x00'):
|
| 397 |
if seq:
|
|
|
|
| 86 |
check('prefers H264 over HEVC origin', '264' in (top.get('codec') or '').lower(), 'top=%s codec=%s'%(top.get('quality_name'), top.get('codec')))
|
| 87 |
check('still lists HEVC as fallback', any('265' in (c.get('codec') or '').lower() or 'hevc' in (c.get('codec') or '').lower() for c in ranked))
|
| 88 |
check('sd not dropped', any(c.get('quality_name')=='sd' for c in ranked))
|
| 89 |
+
# TikTok webcast/room/info returns hls_pull_url as one string on current live rooms.
|
| 90 |
+
# Calling .items() on it used to throw, so the fallback disappeared exactly when needed.
|
| 91 |
+
string_hls=rank_sources({'hls_pull_url':'https://pull.example/live.m3u8'})
|
| 92 |
+
check('single-string HLS fallback is accepted',
|
| 93 |
+
len(string_hls)==1 and string_hls[0].get('media')=='hls',str(string_hls))
|
| 94 |
|
| 95 |
# ---------- title template ----------
|
| 96 |
tpl = os.environ['YOUTUBE_TITLE_TEMPLATE']
|
|
|
|
| 115 |
# ---------- health + monitor isolation ----------
|
| 116 |
h = app.health_public()
|
| 117 |
check('TEST public /health', h.get('application')=='running', str(h))
|
| 118 |
+
check('public health is minimal (no account/relay details)',
|
| 119 |
+
set(h)<= {'status','application','monitor','version'}, str(h))
|
| 120 |
# TEST 1: offline account does not start ffmpeg
|
| 121 |
app.tasks['offlineuser'] = app._blank_task()
|
| 122 |
app.tasks['offlineuser']['enabled'] = True
|
|
|
|
| 238 |
check('TEST 11 backoff increases', yt._backoff('a')>=2, str(yt._backoff('a')))
|
| 239 |
yt.retry['a']=9999
|
| 240 |
check('TEST 11 backoff capped', yt._backoff('a')<=yt.retry_max)
|
| 241 |
+
check('reliability selection keeps lower H264 after preferred 720-class source',
|
| 242 |
+
any(c.get('quality_name')=='sd' for c in yt.video_sources(ranked)),
|
| 243 |
+
str([c.get('quality_name') for c in yt.video_sources(ranked)]))
|
| 244 |
+
|
| 245 |
+
# Same-codec lower rendition is spliced without reopening RTMP; quality is restored only on a
|
| 246 |
+
# later natural refresh after the stable hold interval.
|
| 247 |
+
high={'url':'https://x/high.flv','media':'flv','codec':'h264','quality_name':'hd',
|
| 248 |
+
'resolution':'720x1280','width':720,'height':1280,'label':'hd','brief':'hd 720p H264'}
|
| 249 |
+
low={'url':'https://x/low.flv','media':'flv','codec':'h264','quality_name':'sd',
|
| 250 |
+
'resolution':'480x854','width':480,'height':854,'label':'sd','brief':'sd 480p H264'}
|
| 251 |
+
_saved_observe,_saved_select=yt._observe,yt._select_source
|
| 252 |
+
yt._observe=lambda *a,**k: {'status':'live','room_id':'1','sources':[high,low]}
|
| 253 |
+
yt._select_source=lambda user,obs: [dict(high,user=user),dict(low,user=user)]
|
| 254 |
+
yt._rendition_pin['adaptive']=yt._source_pin(high)
|
| 255 |
+
chosen=yt._refresh_flv('adaptive',high)
|
| 256 |
+
check('stalled high FLV falls to lower same-codec source in the same publisher',
|
| 257 |
+
chosen and chosen.get('quality_name')=='sd' and yt._quality_fallback.get('adaptive'),str(chosen))
|
| 258 |
+
os.environ['YOUTUBE_SOURCE_UPGRADE_SECONDS']='60'
|
| 259 |
+
yt._quality_fallback['adaptive']['since']=time.monotonic()-61
|
| 260 |
+
yt._rendition_pin['adaptive']=yt._source_pin(low)
|
| 261 |
+
restored=yt._refresh_flv('adaptive',low)
|
| 262 |
+
check('stable lower source restores preferred quality on a later natural refresh',
|
| 263 |
+
restored and restored.get('quality_name')=='hd' and 'adaptive' not in yt._quality_fallback,str(restored))
|
| 264 |
+
yt._observe,yt._select_source=_saved_observe,_saved_select
|
| 265 |
+
os.environ.pop('YOUTUBE_SOURCE_UPGRADE_SECONDS',None)
|
| 266 |
|
| 267 |
# ---------- unstable source fallback bookkeeping ----------
|
| 268 |
yt.mark_unstable('bob', {'quality_name':'origin','media':'flv','codec':'h265','resolution':'1080x1920','brief':'origin 1080p HEVC'}, 'stalled')
|
|
|
|
| 315 |
hub.release('e1'); hub.release('e2')
|
| 316 |
check('env free after release', not hub.env_key_busy())
|
| 317 |
h=app.health_public()
|
| 318 |
+
check('public health hides last_error', 'last_error' not in h, str(h.keys()))
|
| 319 |
+
check('public health hides last_error_user', 'last_error_user' not in h, str(h.keys()))
|
| 320 |
check('health has version', bool(h.get('version')))
|
| 321 |
|
| 322 |
# Null TikTok payloads must be Offline, not AttributeError → sticky last_error
|
|
|
|
| 344 |
app._check_account('staleerr')
|
| 345 |
check('offline clears last_error', app.tasks['staleerr'].get('last_error')=='', str(app.tasks['staleerr']))
|
| 346 |
check('offline after error is OFFLINE', app.tasks['staleerr']['state']=='OFFLINE')
|
| 347 |
+
h=app.health_detail()
|
| 348 |
+
check('authenticated detail last_error empty after offline', not h.get('last_error'), str(h))
|
| 349 |
h=app.health_public()
|
| 350 |
+
check('public health does not list broadcasters', 'broadcasters' not in h)
|
| 351 |
+
check('public health hides metadata automation', 'metadata_automation' not in h)
|
|
|
|
|
|
|
| 352 |
finally:
|
| 353 |
app.observe_session = orig
|
| 354 |
app.tasks.pop('staleerr', None)
|
|
|
|
| 412 |
|
| 413 |
df=(ROOT/'Dockerfile').read_text()
|
| 414 |
check('Dockerfile stall default 12', 'SOURCE_STALL_TIMEOUT=12' in df and 'YOUTUBE_SOURCE_STALL_SECONDS=12' in df)
|
| 415 |
+
check('Dockerfile concurrent cap 4', 'MAX_CONCURRENT_RELAYS=4' in df and 'YOUTUBE_MAX_EVENTS=4' in df)
|
| 416 |
+
check('Dockerfile defaults to byte-copy AVC/Enhanced-HEVC without forced x264',
|
| 417 |
+
'YOUTUBE_LIGHT_MAX=0' in df and
|
| 418 |
+
'YOUTUBE_AUTO_TRANSCODE=0' in df and
|
| 419 |
+
'YOUTUBE_FORCE_TRANSCODE_USERS=' not in df and
|
| 420 |
+
'YOUTUBE_ENHANCED_RTMP=auto' in df and
|
| 421 |
+
'stream_monitor.py' in df and 'YOUTUBE_HEALTH_INTERVAL=20' in df and
|
| 422 |
+
'STREAM_EVENT_MAX=10000' in df)
|
| 423 |
mgr_src=(ROOT/'youtube_manager.py').read_text()
|
| 424 |
check('run_manager calls restart_dead_senders', 'restart_dead_senders' in mgr_src.split('def run_manager')[1])
|
| 425 |
pump=(ROOT/'relay.py').read_text()
|
|
|
|
| 429 |
td=pump.split('def _teardown')[1].split('def send')[0]
|
| 430 |
check('teardown does not stop supervisor Event', 'stop.set()' not in td and "sess['force_stop']" in td)
|
| 431 |
check('send keeps FFmpeg via refresh reattach', 'def _try_reattach' in pump and 'def send(self, user, candidate, destination, stop, refresh=None)' in pump)
|
| 432 |
+
check('sender_loop pins codec family during refresh',
|
| 433 |
+
"refresh=lambda: self._refresh_flv(user,getattr(sender,'current_candidate',None))" in mgr_src and
|
| 434 |
+
'def _refresh_flv(self,user,current=None)' in mgr_src)
|
| 435 |
+
check('no runtime caller restarts output on FormatChanged',
|
| 436 |
+
all('FormatChanged' not in (ROOT/name).read_text() for name in ('app.py','relay.py','youtube_manager.py')))
|
| 437 |
from flv_bridge import FLVBridge
|
| 438 |
def _flv_avc(ts=0, seq=False, payload=b'\x00'):
|
| 439 |
if seq:
|
test_smart_mode.py
ADDED
|
@@ -0,0 +1,213 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Smart mode-governor contract.
|
| 3 |
+
|
| 4 |
+
The production failures behind these tests: a health-triggered matchgop
|
| 5 |
+
stayed latched for a whole event (journal re-applied it to every FFmpeg),
|
| 6 |
+
HEVC sources were excluded from copy recovery, a pure data-starved verdict
|
| 7 |
+
prescribed CPU-burning transcoding, and a 960x1920 transcode saturated the
|
| 8 |
+
host. The governor must copy what YouTube can ingest, transcode only what
|
| 9 |
+
copy cannot fix, cap the fallback canvas, and earn its way back to copy.
|
| 10 |
+
"""
|
| 11 |
+
import os
|
| 12 |
+
import pathlib
|
| 13 |
+
import sys
|
| 14 |
+
import tempfile
|
| 15 |
+
import time
|
| 16 |
+
import unittest
|
| 17 |
+
from unittest.mock import patch
|
| 18 |
+
|
| 19 |
+
ROOT = pathlib.Path(__file__).resolve().parent
|
| 20 |
+
sys.path.insert(0, str(ROOT))
|
| 21 |
+
from relay import Sender
|
| 22 |
+
from youtube_manager import ManagedYouTube
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
class CopyRecoveryTests(unittest.TestCase):
|
| 26 |
+
def make_sender(self, candidate):
|
| 27 |
+
sender = Sender('/bin/true', lambda *a: None)
|
| 28 |
+
sender.sticky_mode = 'matchgop'
|
| 29 |
+
sender.sticky_since = time.monotonic() - 600
|
| 30 |
+
sender._last_light_output = 120.0
|
| 31 |
+
sender.current_candidate = candidate
|
| 32 |
+
return sender
|
| 33 |
+
|
| 34 |
+
def env(self):
|
| 35 |
+
return patch.dict(os.environ, {
|
| 36 |
+
'YOUTUBE_SEND_MODE': 'auto', 'YOUTUBE_COPY_RECOVERY_SECONDS': '60',
|
| 37 |
+
'YOUTUBE_COPY_RECOVERY_MAX_FAILS': '2',
|
| 38 |
+
})
|
| 39 |
+
|
| 40 |
+
def test_hevc_source_may_probe_copy(self):
|
| 41 |
+
with self.env():
|
| 42 |
+
sender = self.make_sender({'codec': 'h265', 'label': 'origin · 960x1920 · HEVC'})
|
| 43 |
+
self.assertEqual(sender.send_mode(), 'copy')
|
| 44 |
+
self.assertTrue(sender._recovering_copy)
|
| 45 |
+
|
| 46 |
+
def test_h264_source_may_probe_copy(self):
|
| 47 |
+
with self.env():
|
| 48 |
+
sender = self.make_sender({'codec': 'h264', 'label': 'hd · 720x1280 · H264'})
|
| 49 |
+
self.assertEqual(sender.send_mode(), 'copy')
|
| 50 |
+
|
| 51 |
+
def test_unknown_codec_never_probes_copy(self):
|
| 52 |
+
with self.env():
|
| 53 |
+
sender = self.make_sender({'codec': 'vp9', 'label': 'vp9'})
|
| 54 |
+
self.assertEqual(sender.send_mode(), 'matchgop')
|
| 55 |
+
|
| 56 |
+
def test_operator_locked_mode_never_probes_copy(self):
|
| 57 |
+
with self.env():
|
| 58 |
+
sender = self.make_sender({'codec': 'h264', 'label': 'h264'})
|
| 59 |
+
sender.sticky_operator_locked = True
|
| 60 |
+
self.assertEqual(sender.send_mode(), 'matchgop')
|
| 61 |
+
|
| 62 |
+
def test_recent_or_unproven_light_run_does_not_probe(self):
|
| 63 |
+
with self.env():
|
| 64 |
+
sender = self.make_sender({'codec': 'h264', 'label': 'h264'})
|
| 65 |
+
sender.sticky_since = time.monotonic()
|
| 66 |
+
self.assertEqual(sender.send_mode(), 'matchgop')
|
| 67 |
+
sender = self.make_sender({'codec': 'h264', 'label': 'h264'})
|
| 68 |
+
sender._last_light_output = 3.0
|
| 69 |
+
self.assertEqual(sender.send_mode(), 'matchgop')
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
class CanvasCapTests(unittest.TestCase):
|
| 73 |
+
def test_matchgop_canvas_is_capped_at_720_class(self):
|
| 74 |
+
# 960x1920 must fit inside the 720x1280 box (aspect preserved -> the
|
| 75 |
+
# canvas is 640x1280), never re-encode at the full 1920 height.
|
| 76 |
+
sender = Sender('/bin/true', lambda *a: None)
|
| 77 |
+
sender.mode_override = 'matchgop'
|
| 78 |
+
args = sender.command('out.flv', {'codec': 'h265', 'width': 960, 'height': 1920})
|
| 79 |
+
vf = args[args.index('-vf') + 1]
|
| 80 |
+
self.assertIn('pad=640:1280', vf)
|
| 81 |
+
self.assertNotIn('1920', vf)
|
| 82 |
+
|
| 83 |
+
def test_safe_size_mapping_still_applies(self):
|
| 84 |
+
# Pre-existing rule: a 640x1280 picture is normalized onto the
|
| 85 |
+
# YouTube-healthy 720x1280 canvas (640-wide copy measured Studio-black).
|
| 86 |
+
sender = Sender('/bin/true', lambda *a: None)
|
| 87 |
+
sender.mode_override = 'matchgop'
|
| 88 |
+
args = sender.command('out.flv', {'codec': 'h264', 'width': 640, 'height': 1280})
|
| 89 |
+
vf = args[args.index('-vf') + 1]
|
| 90 |
+
self.assertIn('scale=w=720:h=1280', vf)
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
class FakeThread:
|
| 94 |
+
def is_alive(self):
|
| 95 |
+
return True
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
class FakeSender:
|
| 99 |
+
def __init__(self, candidate):
|
| 100 |
+
self.sticky_mode = None
|
| 101 |
+
self.current_candidate = candidate
|
| 102 |
+
self.sticky_requests = []
|
| 103 |
+
self.telemetry_key = None
|
| 104 |
+
|
| 105 |
+
def snapshot(self):
|
| 106 |
+
return {'output_seconds': 60.0, 'source_bytes': 500000, 'send_mode': 'copy'}
|
| 107 |
+
|
| 108 |
+
def send_mode(self):
|
| 109 |
+
return 'copy'
|
| 110 |
+
|
| 111 |
+
def request_sticky(self, mode, user, reason):
|
| 112 |
+
self.sticky_requests.append((mode, user, reason))
|
| 113 |
+
self.sticky_mode = mode
|
| 114 |
+
return True
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
class HealthGovernorTests(unittest.TestCase):
|
| 118 |
+
def setUp(self):
|
| 119 |
+
self.tmp = tempfile.TemporaryDirectory(prefix='smart-health-')
|
| 120 |
+
self.addCleanup(self.tmp.cleanup)
|
| 121 |
+
self.manager = ManagedYouTube('/bin/true', lambda u: None, lambda *a: None,
|
| 122 |
+
lambda: ['alice'], pathlib.Path(self.tmp.name) / 'journal.json')
|
| 123 |
+
self.key = 'alice:room'
|
| 124 |
+
self.manager.journal.change(lambda d: d['streams'].update({'alice': {'id': 'STREAM'}}))
|
| 125 |
+
|
| 126 |
+
def run_health(self, status, issues, candidate):
|
| 127 |
+
sender = FakeSender(candidate)
|
| 128 |
+
self.manager.senders[self.key] = {'thread': FakeThread(), 'sender': sender}
|
| 129 |
+
self.manager.remote = lambda resource, rid: {
|
| 130 |
+
'status': {'healthStatus': {'status': status, 'configurationIssues': issues}}}
|
| 131 |
+
self.manager.stream_health(self.key, 'alice', {'last_health': 0})
|
| 132 |
+
return sender
|
| 133 |
+
|
| 134 |
+
def test_pure_starved_does_not_prescribe_transcode(self):
|
| 135 |
+
sender = self.run_health('bad', [
|
| 136 |
+
{'type': 'videoIngestionStarved', 'severity': 'error', 'reason': 'Video output low'}],
|
| 137 |
+
{'codec': 'h264', 'width': 640, 'height': 1280, 'bitrate': 1200})
|
| 138 |
+
self.assertEqual(sender.sticky_requests, [])
|
| 139 |
+
|
| 140 |
+
def test_oversized_signalled_copy_may_transcode(self):
|
| 141 |
+
sender = self.run_health('bad', [
|
| 142 |
+
{'type': 'videoIngestionStarved', 'severity': 'error', 'reason': 'Video output low'}],
|
| 143 |
+
{'codec': 'h264', 'width': 720, 'height': 1440, 'bitrate': 1000})
|
| 144 |
+
self.assertEqual(len(sender.sticky_requests), 1)
|
| 145 |
+
|
| 146 |
+
def test_gop_fault_still_transcodes(self):
|
| 147 |
+
sender = self.run_health('bad', [
|
| 148 |
+
{'type': 'gopSizeLong', 'severity': 'error', 'reason': 'GOP too long'}],
|
| 149 |
+
{'codec': 'h264', 'width': 640, 'height': 1280, 'bitrate': 1200})
|
| 150 |
+
self.assertEqual(len(sender.sticky_requests), 1)
|
| 151 |
+
|
| 152 |
+
|
| 153 |
+
class ManagerClearTests(unittest.TestCase):
|
| 154 |
+
def test_verified_copy_clears_journaled_mode(self):
|
| 155 |
+
tmp = tempfile.TemporaryDirectory(prefix='smart-clear-')
|
| 156 |
+
self.addCleanup(tmp.cleanup)
|
| 157 |
+
manager = ManagedYouTube('/bin/true', lambda u: None, lambda *a: None,
|
| 158 |
+
lambda: ['alice'], pathlib.Path(tmp.name) / 'journal.json')
|
| 159 |
+
key = 'alice:room'
|
| 160 |
+
event = {'username': 'alice', 'session_key': key, 'room_id': 'room',
|
| 161 |
+
'broadcast_id': 'VIDEO', 'title': 't', 'nickname': 'Alice',
|
| 162 |
+
'phase': 'live', 'youtube_status': 'live', 'closing': False}
|
| 163 |
+
manager.journal.change(lambda d: d['events'].update({key: event}))
|
| 164 |
+
manager._remember_sender_mode('alice', 'matchgop', 960, 1920)
|
| 165 |
+
self.assertEqual(manager.journal.read()['events'][key]['sender_mode'], 'matchgop')
|
| 166 |
+
manager._clear_sender_mode('alice')
|
| 167 |
+
ev = manager.journal.read()['events'][key]
|
| 168 |
+
self.assertEqual(ev['sender_mode'], '')
|
| 169 |
+
self.assertNotIn('alice', manager._sender_sticky)
|
| 170 |
+
self.assertNotIn('alice', manager._sender_gop)
|
| 171 |
+
|
| 172 |
+
|
| 173 |
+
class FormatLockTests(unittest.TestCase):
|
| 174 |
+
"""مصدر بفاصل إطارات مفتاحية مضطرب (قياس الجسر) لا يُنسخ: يُطبَّع حتى نهاية
|
| 175 |
+
جلسة الناشر، لأن يوتيوب يشترط GOP ثابتًا ~2 ث والنسخ يمرّر الاضطراب كما هو."""
|
| 176 |
+
|
| 177 |
+
def test_keyframe_instability_locks_auto_to_matchgop(self):
|
| 178 |
+
sender = Sender('/bin/true', lambda *a: None)
|
| 179 |
+
sender.current_candidate = {'codec': 'h264', 'label': 'hd · 720x1440 · H264'}
|
| 180 |
+
with patch.dict(os.environ, {'YOUTUBE_SEND_MODE': 'auto'}):
|
| 181 |
+
self.assertEqual(sender.send_mode(), 'copy')
|
| 182 |
+
sender.format_unstable = True
|
| 183 |
+
self.assertEqual(sender.send_mode(), 'matchgop')
|
| 184 |
+
|
| 185 |
+
def test_bridge_keyframe_change_sets_the_lock(self):
|
| 186 |
+
sender = Sender('/bin/true', lambda *a: None)
|
| 187 |
+
with patch('relay.log_event', lambda *a, **k: None):
|
| 188 |
+
sender._bridge_event('alice', 'KEYFRAME_CHANGE',
|
| 189 |
+
{'old_interval_ms': 1900.0, 'new_interval_ms': 400.0})
|
| 190 |
+
self.assertTrue(sender.format_unstable)
|
| 191 |
+
|
| 192 |
+
def test_lock_blocks_copy_recovery_probe(self):
|
| 193 |
+
sender = Sender('/bin/true', lambda *a: None)
|
| 194 |
+
sender.sticky_mode = 'matchgop'
|
| 195 |
+
sender.sticky_since = time.monotonic() - 600
|
| 196 |
+
sender._last_light_output = 120.0
|
| 197 |
+
sender.current_candidate = {'codec': 'h264', 'label': 'hd · 720x1280 · H264'}
|
| 198 |
+
sender.format_unstable = True
|
| 199 |
+
with patch.dict(os.environ, {'YOUTUBE_SEND_MODE': 'auto',
|
| 200 |
+
'YOUTUBE_COPY_RECOVERY_SECONDS': '60'}):
|
| 201 |
+
self.assertEqual(sender.send_mode(), 'matchgop')
|
| 202 |
+
|
| 203 |
+
def test_operator_forced_copy_is_respected(self):
|
| 204 |
+
sender = Sender('/bin/true', lambda *a: None)
|
| 205 |
+
sender.mode_override = 'copy'
|
| 206 |
+
sender.format_unstable = True
|
| 207 |
+
sender.current_candidate = {'codec': 'h264', 'label': 'hd · 720x1440 · H264'}
|
| 208 |
+
with patch.dict(os.environ, {'YOUTUBE_SEND_MODE': 'auto'}):
|
| 209 |
+
self.assertEqual(sender.send_mode(), 'copy')
|
| 210 |
+
|
| 211 |
+
|
| 212 |
+
if __name__ == '__main__':
|
| 213 |
+
unittest.main(argv=[sys.argv[0]], verbosity=2)
|
test_source_reconnect.py
ADDED
|
@@ -0,0 +1,295 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Regression for live source handover; no real TikTok/YouTube requests.
|
| 3 |
+
|
| 4 |
+
Starting a replacement pump while swap_source=True made the new thread exit before
|
| 5 |
+
reading a single byte. FFmpeg was kept alive but YouTube received no replacement media.
|
| 6 |
+
"""
|
| 7 |
+
import io
|
| 8 |
+
import http.server
|
| 9 |
+
import json
|
| 10 |
+
import shutil
|
| 11 |
+
import subprocess
|
| 12 |
+
import tempfile
|
| 13 |
+
import os
|
| 14 |
+
import pathlib
|
| 15 |
+
import sys
|
| 16 |
+
import threading
|
| 17 |
+
import time
|
| 18 |
+
import unittest
|
| 19 |
+
from unittest.mock import Mock, patch
|
| 20 |
+
|
| 21 |
+
ROOT = pathlib.Path(sys.argv[1]).resolve() if len(sys.argv) > 1 else pathlib.Path(__file__).parent
|
| 22 |
+
sys.path.insert(0, str(ROOT))
|
| 23 |
+
os.environ.setdefault('DATA_DIR', tempfile.mkdtemp(prefix='handover-test-data-'))
|
| 24 |
+
from relay import Sender
|
| 25 |
+
from youtube_manager import ManagedYouTube
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
class InlineThread:
|
| 29 |
+
"""Deterministic scheduler: the new pump runs immediately when start() is called."""
|
| 30 |
+
def __init__(self, target, args=(), daemon=False):
|
| 31 |
+
self.target = target
|
| 32 |
+
self.args = args
|
| 33 |
+
self.daemon = daemon
|
| 34 |
+
self.started = False
|
| 35 |
+
|
| 36 |
+
def start(self):
|
| 37 |
+
self.started = True
|
| 38 |
+
self.target(*self.args)
|
| 39 |
+
|
| 40 |
+
def join(self, timeout=None):
|
| 41 |
+
pass
|
| 42 |
+
|
| 43 |
+
def is_alive(self):
|
| 44 |
+
return False
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
class Response:
|
| 48 |
+
def __init__(self, chunks=(b'replacement media',)):
|
| 49 |
+
self.chunks = chunks
|
| 50 |
+
self.closed = False
|
| 51 |
+
self.reads = 0
|
| 52 |
+
|
| 53 |
+
def raise_for_status(self):
|
| 54 |
+
pass
|
| 55 |
+
|
| 56 |
+
def iter_content(self, chunk_size=None):
|
| 57 |
+
for chunk in self.chunks:
|
| 58 |
+
self.reads += 1
|
| 59 |
+
yield chunk
|
| 60 |
+
|
| 61 |
+
def close(self):
|
| 62 |
+
self.closed = True
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
class HandoverTests(unittest.TestCase):
|
| 66 |
+
def setUp(self):
|
| 67 |
+
self.env = patch.dict(os.environ, {'SOURCE_STALL_TIMEOUT': '0'})
|
| 68 |
+
self.env.start()
|
| 69 |
+
self.addCleanup(self.env.stop)
|
| 70 |
+
self.sender = Sender('/bin/true', lambda *a: None)
|
| 71 |
+
self.p = Mock()
|
| 72 |
+
self.p.poll.return_value = None
|
| 73 |
+
self.p.stdin = io.BytesIO()
|
| 74 |
+
self.old_pump = Mock()
|
| 75 |
+
self.old_pump.is_alive.return_value = False
|
| 76 |
+
self.old_response = Response()
|
| 77 |
+
self.new_response = Response()
|
| 78 |
+
self.stop = threading.Event()
|
| 79 |
+
self.sess = {'last': time.monotonic() - 4, 'max_seconds': 180,
|
| 80 |
+
'force_stop': False, 'timeouts': 0, 'error': '', 'ended': True}
|
| 81 |
+
self.bridge = Mock()
|
| 82 |
+
self.bridge.feed.side_effect = lambda chunk: chunk
|
| 83 |
+
self.refresh = Mock(return_value={'url': 'https://example.invalid/source.flv', 'codec': 'h264', 'label': 'hd'})
|
| 84 |
+
|
| 85 |
+
def attach(self, refresh=None):
|
| 86 |
+
with patch('relay.requests.get', return_value=self.new_response), patch('relay.threading.Thread', InlineThread):
|
| 87 |
+
return self.sender._try_reattach('alice', self.p, self.bridge, self.sess,
|
| 88 |
+
self.stop, refresh or self.refresh, 10, 3, self.old_response, self.old_pump)
|
| 89 |
+
|
| 90 |
+
def test_new_pump_reads_media_even_when_scheduled_immediately(self):
|
| 91 |
+
attached = self.attach()
|
| 92 |
+
self.assertIsNotNone(attached)
|
| 93 |
+
self.assertEqual(self.new_response.reads, 1)
|
| 94 |
+
self.assertEqual(self.p.stdin.getvalue(), b'replacement media')
|
| 95 |
+
self.assertEqual(self.sender.snapshot()['source_bytes'], len(b'replacement media'))
|
| 96 |
+
self.assertFalse(self.sess['swap_source'])
|
| 97 |
+
|
| 98 |
+
def test_old_pump_must_stop_before_bridge_is_reused(self):
|
| 99 |
+
self.old_pump.is_alive.return_value = True
|
| 100 |
+
self.assertIsNone(self.attach())
|
| 101 |
+
self.bridge.reconnect.assert_not_called()
|
| 102 |
+
self.refresh.assert_not_called()
|
| 103 |
+
self.assertEqual(self.new_response.reads, 0)
|
| 104 |
+
|
| 105 |
+
def test_stop_during_resolution_does_not_resurrect_the_reader(self):
|
| 106 |
+
def stop_then_refresh():
|
| 107 |
+
self.stop.set()
|
| 108 |
+
return self.refresh()
|
| 109 |
+
self.assertIsNone(self.attach(stop_then_refresh))
|
| 110 |
+
self.bridge.reconnect.assert_not_called()
|
| 111 |
+
self.assertEqual(self.new_response.reads, 0)
|
| 112 |
+
|
| 113 |
+
def test_refresh_does_not_fabricate_source_heartbeat(self):
|
| 114 |
+
self.new_response = Response(chunks=())
|
| 115 |
+
previous = self.sess['last']
|
| 116 |
+
self.assertIsNotNone(self.attach())
|
| 117 |
+
self.assertEqual(self.sess['last'], previous)
|
| 118 |
+
self.assertEqual(self.sender.snapshot()['source_bytes'], 0)
|
| 119 |
+
|
| 120 |
+
def test_opened_source_has_bounded_first_byte_grace(self):
|
| 121 |
+
previous = self.sess['last']
|
| 122 |
+
now = time.monotonic()
|
| 123 |
+
self.new_response = Response(chunks=())
|
| 124 |
+
self.attach()
|
| 125 |
+
self.assertGreater(self.sess['reattach_not_before'], now)
|
| 126 |
+
self.assertLessEqual(self.sess['reattach_not_before'], time.monotonic() + 5)
|
| 127 |
+
self.assertEqual(self.sess['last'], previous)
|
| 128 |
+
|
| 129 |
+
def test_cancelled_reader_cannot_deliver_a_late_chunk(self):
|
| 130 |
+
cancel = threading.Event()
|
| 131 |
+
response = Response()
|
| 132 |
+
def late_chunk(_size=None):
|
| 133 |
+
cancel.set()
|
| 134 |
+
yield b'old reader late packet'
|
| 135 |
+
response.iter_content = late_chunk
|
| 136 |
+
with patch('relay.threading.Thread', InlineThread):
|
| 137 |
+
self.sender._pump_source(response, self.p, self.bridge, self.stop,
|
| 138 |
+
self.sess, 10, 3, cancel)
|
| 139 |
+
self.assertEqual(self.p.stdin.getvalue(), b'')
|
| 140 |
+
self.assertEqual(self.sender.snapshot()['source_bytes'], 0)
|
| 141 |
+
|
| 142 |
+
def test_no_source_is_a_failed_handover_not_a_fake_success(self):
|
| 143 |
+
self.refresh.return_value = None
|
| 144 |
+
self.assertIsNone(self.attach())
|
| 145 |
+
self.bridge.reconnect.assert_not_called()
|
| 146 |
+
|
| 147 |
+
|
| 148 |
+
class CanvasTests(unittest.TestCase):
|
| 149 |
+
def test_placeholder_16x16_does_not_pin_the_live_canvas(self):
|
| 150 |
+
sender = Sender('/bin/true', lambda *a: None)
|
| 151 |
+
self.assertEqual(sender.lock_gold({'width': 16, 'height': 16}), (0, 0))
|
| 152 |
+
self.assertEqual(sender.lock_gold({'width': 720, 'height': 1440}), (720, 1280))
|
| 153 |
+
|
| 154 |
+
def test_unknown_or_placeholder_matchgop_uses_safe_constant_canvas(self):
|
| 155 |
+
for candidate in ({}, {'width': 16, 'height': 16}):
|
| 156 |
+
sender = Sender('/bin/true', lambda *a: None)
|
| 157 |
+
sender.mode_override = 'matchgop'
|
| 158 |
+
args = sender.command('test.flv', candidate)
|
| 159 |
+
vf = args[args.index('-vf') + 1]
|
| 160 |
+
self.assertIn('scale=w=720:h=1280:', vf)
|
| 161 |
+
# A later real configuration does not mutate the encoder canvas.
|
| 162 |
+
sender.lock_gold({'width': 960, 'height': 1920})
|
| 163 |
+
self.assertEqual((sender._gop_w, sender._gop_h), (720, 1280))
|
| 164 |
+
|
| 165 |
+
def test_normal_and_real_1080_source_dimensions_remain_supported(self):
|
| 166 |
+
for size in ((160, 120), (320, 240), (1080, 1920)):
|
| 167 |
+
sender = Sender('/bin/true', lambda *a: None)
|
| 168 |
+
self.assertEqual(sender.lock_gold({'width': size[0], 'height': size[1]}), size)
|
| 169 |
+
|
| 170 |
+
|
| 171 |
+
class CachedSourceTests(unittest.TestCase):
|
| 172 |
+
def setUp(self):
|
| 173 |
+
self.tmp = tempfile.TemporaryDirectory()
|
| 174 |
+
self.addCleanup(self.tmp.cleanup)
|
| 175 |
+
self.manager = ManagedYouTube('/bin/true', lambda u, force=False: None,
|
| 176 |
+
lambda *a: None, lambda: ['alice'], pathlib.Path(self.tmp.name) / 'journal.json')
|
| 177 |
+
self.manager.video_sources = lambda sources: list(sources)
|
| 178 |
+
self.hd = {'url': 'https://example.invalid/hd.flv', 'media': 'flv', 'codec': 'h264',
|
| 179 |
+
'quality_name': 'hd', 'width': 720, 'height': 1280, 'label': 'hd'}
|
| 180 |
+
self.sd = dict(self.hd, url='https://example.invalid/sd.flv', quality_name='sd',
|
| 181 |
+
width=480, height=854, label='sd')
|
| 182 |
+
self.obs = {'status': 'live', 'room_id': 'same-room', 'sources': [self.hd, self.sd]}
|
| 183 |
+
self.manager._observe = Mock(return_value=self.obs)
|
| 184 |
+
|
| 185 |
+
def test_recent_compatible_source_is_reused_without_blocking_metadata_lookup(self):
|
| 186 |
+
self.manager._held['alice'] = (time.monotonic(), self.obs)
|
| 187 |
+
chosen = self.manager._refresh_flv('alice', self.hd)
|
| 188 |
+
self.assertEqual(chosen['url'], self.sd['url'])
|
| 189 |
+
self.manager._observe.assert_not_called()
|
| 190 |
+
|
| 191 |
+
def test_stale_source_snapshot_requires_fresh_lookup(self):
|
| 192 |
+
self.manager._held['alice'] = (time.monotonic() - 60, self.obs)
|
| 193 |
+
self.assertEqual(self.manager._refresh_flv('alice', self.hd)['url'], self.sd['url'])
|
| 194 |
+
self.manager._observe.assert_called_once_with('alice', force=True, bypass_throttle=True, allow_hold=False)
|
| 195 |
+
|
| 196 |
+
def test_cache_with_wrong_codec_cannot_be_spliced_into_open_publisher(self):
|
| 197 |
+
self.manager._held['alice'] = (time.monotonic(), dict(self.obs, sources=[dict(self.sd, codec='h265')]))
|
| 198 |
+
chosen = self.manager._refresh_flv('alice', self.hd)
|
| 199 |
+
self.assertEqual(chosen['codec'], 'h264')
|
| 200 |
+
self.manager._observe.assert_called_once()
|
| 201 |
+
|
| 202 |
+
|
| 203 |
+
@unittest.skipUnless(shutil.which('ffmpeg') and shutil.which('ffprobe'), 'FFmpeg required')
|
| 204 |
+
class RealHTTPContinuityTests(unittest.TestCase):
|
| 205 |
+
def run_continuity(self, mode):
|
| 206 |
+
with tempfile.TemporaryDirectory(prefix='source-handover-media-') as tmp:
|
| 207 |
+
root = pathlib.Path(tmp)
|
| 208 |
+
source = root / 'generated.flv'
|
| 209 |
+
output = root / 'output.flv'
|
| 210 |
+
subprocess.run([shutil.which('ffmpeg'), '-v', 'error', '-y', '-f', 'lavfi',
|
| 211 |
+
'-i', 'testsrc2=size=160x120:rate=20', '-f', 'lavfi', '-i', 'sine=sample_rate=48000',
|
| 212 |
+
'-t', '2', '-c:v', 'libx264', '-preset', 'ultrafast', '-pix_fmt', 'yuv420p',
|
| 213 |
+
'-g', '20', '-c:a', 'aac', '-f', 'flv', str(source)], check=True, capture_output=True)
|
| 214 |
+
media = source.read_bytes()
|
| 215 |
+
calls = []
|
| 216 |
+
class Handler(http.server.BaseHTTPRequestHandler):
|
| 217 |
+
def log_message(self, *a):
|
| 218 |
+
pass
|
| 219 |
+
def do_GET(self):
|
| 220 |
+
calls.append(time.monotonic())
|
| 221 |
+
self.send_response(200)
|
| 222 |
+
self.send_header('Content-Type', 'video/x-flv')
|
| 223 |
+
self.send_header('Content-Length', str(len(media)))
|
| 224 |
+
self.end_headers()
|
| 225 |
+
# Header arrives immediately; replacements wait before their first byte.
|
| 226 |
+
# Without startup grace the supervisor closes them before this media arrives.
|
| 227 |
+
if len(calls) > 1:
|
| 228 |
+
time.sleep(1)
|
| 229 |
+
try:
|
| 230 |
+
self.wfile.write(media)
|
| 231 |
+
self.wfile.flush()
|
| 232 |
+
except (OSError, BrokenPipeError):
|
| 233 |
+
pass
|
| 234 |
+
server = http.server.ThreadingHTTPServer(('127.0.0.1', 0), Handler)
|
| 235 |
+
server.daemon_threads = True
|
| 236 |
+
server_thread = threading.Thread(target=server.serve_forever, daemon=True)
|
| 237 |
+
server_thread.start()
|
| 238 |
+
stop = threading.Event()
|
| 239 |
+
errors = []
|
| 240 |
+
candidate = {'url': 'http://127.0.0.1:%d/source.flv' % server.server_port,
|
| 241 |
+
'media': 'flv', 'codec': 'h264', 'label': 'fixture', 'width': 160, 'height': 120}
|
| 242 |
+
sender = Sender(shutil.which('ffmpeg'), lambda *a: None)
|
| 243 |
+
sender.mode_override = mode
|
| 244 |
+
spawned = []
|
| 245 |
+
from relay import subprocess as relay_subprocess
|
| 246 |
+
real_popen = relay_subprocess.Popen
|
| 247 |
+
def track_process(*a, **kw):
|
| 248 |
+
child = real_popen(*a, **kw)
|
| 249 |
+
spawned.append(child)
|
| 250 |
+
return child
|
| 251 |
+
def send():
|
| 252 |
+
try:
|
| 253 |
+
sender.send('fixture', candidate, str(output), stop, refresh=lambda: dict(candidate))
|
| 254 |
+
except Exception as exc:
|
| 255 |
+
errors.append(exc)
|
| 256 |
+
env = {'SOURCE_STALL_TIMEOUT': '3', 'YOUTUBE_REATTACH_GRACE_SECONDS': '2',
|
| 257 |
+
'YOUTUBE_SOURCE_READ_TIMEOUT': '5', 'YOUTUBE_PUMP_JOIN_SECONDS': '2',
|
| 258 |
+
'YOUTUBE_SEND_MODE': mode, 'YOUTUBE_VIDEO_MODE': 'original',
|
| 259 |
+
'YOUTUBE_AUTO_TRANSCODE': '0', 'YOUTUBE_X264_PRESET': 'ultrafast'}
|
| 260 |
+
thread = None
|
| 261 |
+
try:
|
| 262 |
+
with patch.dict(os.environ, env), patch('relay.subprocess.Popen', side_effect=track_process):
|
| 263 |
+
thread = threading.Thread(target=send, daemon=True)
|
| 264 |
+
thread.start()
|
| 265 |
+
time.sleep(7.5)
|
| 266 |
+
alive = thread.is_alive() and sender.alive()
|
| 267 |
+
snapshot = sender.snapshot()
|
| 268 |
+
stop.set()
|
| 269 |
+
thread.join(6)
|
| 270 |
+
self.assertTrue(alive, 'Publisher ended instead of reusing the delayed replacement source: %r' % errors)
|
| 271 |
+
self.assertFalse(errors, repr(errors))
|
| 272 |
+
self.assertEqual(len(spawned), 1, 'Source reconnect must keep the same FFmpeg process')
|
| 273 |
+
self.assertGreaterEqual(len(calls), 3)
|
| 274 |
+
self.assertGreater(snapshot.get('output_seconds', 0), 4)
|
| 275 |
+
self.assertFalse(thread.is_alive(), 'Sender did not stop cleanly')
|
| 276 |
+
probe = subprocess.run([shutil.which('ffprobe'), '-v', 'error', '-show_entries',
|
| 277 |
+
'format=duration', '-of', 'json', str(output)], check=True, capture_output=True, text=True)
|
| 278 |
+
self.assertGreater(float(json.loads(probe.stdout)['format']['duration']), 4)
|
| 279 |
+
finally:
|
| 280 |
+
stop.set()
|
| 281 |
+
sender.terminate()
|
| 282 |
+
if thread:
|
| 283 |
+
thread.join(5)
|
| 284 |
+
server.shutdown()
|
| 285 |
+
server.server_close()
|
| 286 |
+
|
| 287 |
+
def test_eof_and_delayed_replacements_keep_same_copy_publisher(self):
|
| 288 |
+
self.run_continuity('copy')
|
| 289 |
+
|
| 290 |
+
def test_eof_and_delayed_replacements_keep_same_matchgop_publisher(self):
|
| 291 |
+
self.run_continuity('matchgop')
|
| 292 |
+
|
| 293 |
+
|
| 294 |
+
if __name__ == '__main__':
|
| 295 |
+
unittest.main(argv=[sys.argv[0]], verbosity=2)
|
test_telemetry.py
ADDED
|
@@ -0,0 +1,134 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Telemetry safety contract: append-only, fail-open, and control-path neutral.
|
| 3 |
+
|
| 4 |
+
No live services and no FFmpeg. The important production guarantee is not
|
| 5 |
+
that storage can never fail, but that telemetry can fail/drop its own records
|
| 6 |
+
without raising into, blocking, or steering a stream.
|
| 7 |
+
"""
|
| 8 |
+
import json
|
| 9 |
+
import os
|
| 10 |
+
import pathlib
|
| 11 |
+
import sys
|
| 12 |
+
import tempfile
|
| 13 |
+
import time
|
| 14 |
+
|
| 15 |
+
ROOT = pathlib.Path(__file__).resolve().parent
|
| 16 |
+
sys.path.insert(0, str(ROOT))
|
| 17 |
+
|
| 18 |
+
from telemetry import Telemetry, http_status_from_exception
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
passed = failed = 0
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def check(name, condition, detail=""):
|
| 25 |
+
global passed, failed
|
| 26 |
+
if condition:
|
| 27 |
+
passed += 1
|
| 28 |
+
print("PASS %s" % name)
|
| 29 |
+
else:
|
| 30 |
+
failed += 1
|
| 31 |
+
print("FAIL %s %s" % (name, detail))
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def wait_records(store, count, timeout=3.0):
|
| 35 |
+
deadline = time.time() + timeout
|
| 36 |
+
rows = []
|
| 37 |
+
while time.time() < deadline:
|
| 38 |
+
rows = store.read_records(100)
|
| 39 |
+
if len(rows) >= count:
|
| 40 |
+
return rows
|
| 41 |
+
time.sleep(0.02)
|
| 42 |
+
return rows
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
with tempfile.TemporaryDirectory() as tmp:
|
| 46 |
+
path = pathlib.Path(tmp) / "telemetry" / "telemetry.jsonl"
|
| 47 |
+
store = Telemetry(path)
|
| 48 |
+
key = store.start_session("alice", {
|
| 49 |
+
"mode": "copy",
|
| 50 |
+
"url": "https://signed.example/private?token=should-not-persist",
|
| 51 |
+
"nested": {"stream_key": "should-not-persist", "room_id": "123"},
|
| 52 |
+
})
|
| 53 |
+
check("session starts", bool(key))
|
| 54 |
+
check("observe accepts ffmpeg progress", store.observe(key, {
|
| 55 |
+
"ffmpeg_speed": 0.80, "ffmpeg_fps": 30.0, "source_bps": 900_000,
|
| 56 |
+
"output_seconds": 12.0,
|
| 57 |
+
}))
|
| 58 |
+
check("observe accepts recovered speed", store.observe(key, {
|
| 59 |
+
"ffmpeg_speed": 1.01, "ffmpeg_fps": 30.0, "source_bps": 2_400_000,
|
| 60 |
+
"output_seconds": 27.0,
|
| 61 |
+
}))
|
| 62 |
+
|
| 63 |
+
class Response:
|
| 64 |
+
status_code = 403
|
| 65 |
+
|
| 66 |
+
class HttpFailure(Exception):
|
| 67 |
+
response = Response()
|
| 68 |
+
|
| 69 |
+
check("http status extracted without message", http_status_from_exception(HttpFailure()) == 403)
|
| 70 |
+
check("source-open event accepted", store.event(key, "alice", "SOURCE_OPEN_ERROR", {
|
| 71 |
+
"stage": "initial_open", "error_type": "HTTPError", "http_status": 403,
|
| 72 |
+
"url": "https://signed.example/do-not-store",
|
| 73 |
+
}))
|
| 74 |
+
check("resolution event accepted", store.event(key, "alice", "RESOLUTION_CHANGE", {
|
| 75 |
+
"old_width": 720, "old_height": 1280, "new_width": 428, "new_height": 856,
|
| 76 |
+
}))
|
| 77 |
+
check("checkpoint accepted", store.checkpoint(key, "unit-test"))
|
| 78 |
+
check("finish accepted", store.finish(key, "unit finished", {"output_seconds": 27.0}))
|
| 79 |
+
|
| 80 |
+
rows = wait_records(store, 5)
|
| 81 |
+
kinds = [row.get("type") for row in rows]
|
| 82 |
+
check("writer persisted all record kinds", kinds == [
|
| 83 |
+
"session_start", "event", "event", "checkpoint", "session_finish"
|
| 84 |
+
], str(kinds))
|
| 85 |
+
raw = path.read_text(encoding="utf-8")
|
| 86 |
+
check("signed URL is not persisted", "signed.example" not in raw and "should-not-persist" not in raw)
|
| 87 |
+
finish = [row for row in rows if row.get("type") == "session_finish"][-1]
|
| 88 |
+
summary = finish["summary"]
|
| 89 |
+
check("summary identifies broadcaster", summary["broadcaster"] == "alice")
|
| 90 |
+
check("summary counts source-open status", summary["counters"].get("source_open_http_403") == 1,
|
| 91 |
+
str(summary["counters"]))
|
| 92 |
+
check("summary counts slow ffmpeg samples", summary["counters"].get("ffmpeg_speed_below_0_95_samples") == 1,
|
| 93 |
+
str(summary["counters"]))
|
| 94 |
+
check("summary averages ffmpeg speed", abs(summary["stats"]["ffmpeg_speed"]["avg"] - 0.905) < 0.0001,
|
| 95 |
+
str(summary["stats"].get("ffmpeg_speed")))
|
| 96 |
+
check("summary keeps minute buckets", len(summary["minutes"]) == 1, str(summary["minutes"]))
|
| 97 |
+
|
| 98 |
+
before = path.read_bytes()
|
| 99 |
+
reopened = Telemetry(path)
|
| 100 |
+
check("reopening telemetry does not truncate", path.read_bytes() == before)
|
| 101 |
+
check("reopened store reads old records", len(reopened.read_records(10)) == len(rows))
|
| 102 |
+
check("no delete/rotate/truncate API", not any(
|
| 103 |
+
hasattr(Telemetry, name) for name in ("delete", "rotate", "truncate", "clear", "purge")
|
| 104 |
+
))
|
| 105 |
+
|
| 106 |
+
os.environ["TELEMETRY_ENABLED"] = "0"
|
| 107 |
+
try:
|
| 108 |
+
disabled_path = pathlib.Path(tmp) / "disabled" / "telemetry.jsonl"
|
| 109 |
+
disabled = Telemetry(disabled_path)
|
| 110 |
+
check("disabled telemetry is a no-op", disabled.start_session("bob") is None and not disabled_path.exists())
|
| 111 |
+
finally:
|
| 112 |
+
os.environ.pop("TELEMETRY_ENABLED", None)
|
| 113 |
+
|
| 114 |
+
blocker = pathlib.Path(tmp) / "blocker"
|
| 115 |
+
blocker.write_text("not a directory", encoding="utf-8")
|
| 116 |
+
broken = Telemetry(blocker / "telemetry" / "telemetry.jsonl")
|
| 117 |
+
broken_key = broken.start_session("carol")
|
| 118 |
+
broken.observe(broken_key, {"ffmpeg_speed": 1.0})
|
| 119 |
+
broken.finish(broken_key, "storage unavailable")
|
| 120 |
+
deadline = time.time() + 3.0
|
| 121 |
+
while time.time() < deadline and broken.write_errors < 2:
|
| 122 |
+
time.sleep(0.02)
|
| 123 |
+
check("storage failure stays inside telemetry", broken.write_errors >= 2,
|
| 124 |
+
"write_errors=%s" % broken.write_errors)
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
relay_source = (ROOT / "relay.py").read_text(encoding="utf-8")
|
| 128 |
+
check("telemetry result is never a streaming condition", "if telemetry_" not in relay_source and
|
| 129 |
+
"while telemetry_" not in relay_source)
|
| 130 |
+
check("relay records HTTP status at initial open", "'stage':'initial_open'" in relay_source and
|
| 131 |
+
"http_status_from_exception" in relay_source)
|
| 132 |
+
|
| 133 |
+
print("\n%d passed, %d failed" % (passed, failed))
|
| 134 |
+
sys.exit(1 if failed else 0)
|
test_transition_ingest.py
ADDED
|
@@ -0,0 +1,68 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Keep media flowing while YouTube completes liveStarting/testStarting.
|
| 3 |
+
No cloud calls or real ingest URLs.
|
| 4 |
+
"""
|
| 5 |
+
import os, pathlib, sys, tempfile, time, unittest
|
| 6 |
+
from unittest.mock import Mock
|
| 7 |
+
ROOT=pathlib.Path(sys.argv[1]).resolve() if len(sys.argv)>1 else pathlib.Path(__file__).parent
|
| 8 |
+
sys.path.insert(0,str(ROOT))
|
| 9 |
+
from youtube_manager import ManagedYouTube
|
| 10 |
+
|
| 11 |
+
class TransitionTests(unittest.TestCase):
|
| 12 |
+
def setup_event(self,life,poll=True):
|
| 13 |
+
tmp=tempfile.TemporaryDirectory();self.addCleanup(tmp.cleanup)
|
| 14 |
+
m=ManagedYouTube('/bin/true',lambda u:None,lambda *a:None,lambda:['alice'],
|
| 15 |
+
pathlib.Path(tmp.name)/'journal.json')
|
| 16 |
+
key='alice:room1'
|
| 17 |
+
event={'username':'alice','room_id':'room1','session_key':key,'marker':'OWNED-MARKER',
|
| 18 |
+
'bound':True,'broadcast_id':'OWNED-VIDEO','youtube_status':life,'phase':'starting',
|
| 19 |
+
'was_live':False,'closing':False,'created_at':time.time(),
|
| 20 |
+
'last_poll':0 if poll else time.time(),'note':''}
|
| 21 |
+
m.journal.change(lambda d:d.update(channel={'id':'CHANNEL'},streams={'alice':{'id':'OWNED-STREAM'}},events={key:event}))
|
| 22 |
+
source={'url':'https://example.invalid/source.flv','media':'flv','codec':'h264','label':'fixture'}
|
| 23 |
+
m._observe=Mock(return_value={'status':'live','room_id':'room1','sources':[source]})
|
| 24 |
+
m.video_sources=lambda sources:list(sources)
|
| 25 |
+
m.destinations['alice']='rtmps://example.invalid/test-only'
|
| 26 |
+
m.remote=Mock(return_value={'id':'OWNED-VIDEO','status':{'lifeCycleStatus':life},
|
| 27 |
+
'snippet':{'description':'OWNED-MARKER'},'contentDetails':{'boundStreamId':'OWNED-STREAM'}})
|
| 28 |
+
m.start_sender=Mock();m.stop_sender=Mock();m.finish_event=Mock();m.stream_health=Mock()
|
| 29 |
+
m.api.call=Mock(side_effect=AssertionError('Transitional observation must not create or re-transition the event'))
|
| 30 |
+
return m,key
|
| 31 |
+
|
| 32 |
+
def check_transition(self,life,poll):
|
| 33 |
+
m,key=self.setup_event(life,poll)
|
| 34 |
+
m.drive_event(key)
|
| 35 |
+
m.start_sender.assert_called_once_with(key)
|
| 36 |
+
m.stop_sender.assert_not_called()
|
| 37 |
+
m.finish_event.assert_not_called()
|
| 38 |
+
m.api.call.assert_not_called()
|
| 39 |
+
self.assertFalse(m.journal.read()['events'][key]['was_live'])
|
| 40 |
+
self.assertEqual(m.journal.read()['events'][key]['broadcast_id'],'OWNED-VIDEO')
|
| 41 |
+
|
| 42 |
+
def test_live_starting_fresh_poll_keeps_publisher(self):self.check_transition('liveStarting',True)
|
| 43 |
+
def test_live_starting_cached_status_keeps_publisher(self):self.check_transition('liveStarting',False)
|
| 44 |
+
def test_test_starting_fresh_poll_keeps_publisher(self):self.check_transition('testStarting',True)
|
| 45 |
+
def test_test_starting_cached_status_keeps_publisher(self):self.check_transition('testStarting',False)
|
| 46 |
+
|
| 47 |
+
def test_accepted_transition_is_not_cancelled_by_prestart_timeout(self):
|
| 48 |
+
m,key=self.setup_event('liveStarting')
|
| 49 |
+
m.journal.change(lambda d:d['events'][key].update(created_at=time.time()-3600))
|
| 50 |
+
m.drive_event(key)
|
| 51 |
+
m.start_sender.assert_called_once_with(key)
|
| 52 |
+
m.finish_event.assert_not_called()
|
| 53 |
+
m.api.call.assert_not_called()
|
| 54 |
+
|
| 55 |
+
def test_terminal_states_never_restart_publisher(self):
|
| 56 |
+
for life in ('complete','revoked'):
|
| 57 |
+
m,key=self.setup_event(life)
|
| 58 |
+
m.drive_event(key)
|
| 59 |
+
m.start_sender.assert_not_called()
|
| 60 |
+
m.finish_event.assert_called_once_with(key)
|
| 61 |
+
|
| 62 |
+
def test_created_state_is_still_gated(self):
|
| 63 |
+
m,key=self.setup_event('created')
|
| 64 |
+
m.drive_event(key)
|
| 65 |
+
m.start_sender.assert_not_called()
|
| 66 |
+
m.stop_sender.assert_called_once_with(key)
|
| 67 |
+
|
| 68 |
+
if __name__=='__main__':unittest.main(argv=[sys.argv[0]],verbosity=2)
|
test_watchdog.py
CHANGED
|
@@ -299,11 +299,27 @@ check('A2: نسخة h264 لا تُعلن hvc1 على حافة الاستقبال
|
|
| 299 |
'-rtmp_enhanced_codecs' not in ' '.join(_s_h264), ' '.join(_s_h264)[:120])
|
| 300 |
check('A2: نسخة h265 تُعلن hvc1 (الإعلان لجمهور النسخ المعزّز فعلًا)',
|
| 301 |
'-rtmp_enhanced_codecs' in ' '.join(_s_h265), ' '.join(_s_h265)[:120])
|
|
|
|
|
|
|
| 302 |
check('A2: YOUTUBE_ENHANCED_RTMP=off يلغي الإعلان حتى مع h265',
|
| 303 |
'-rtmp_enhanced_codecs' not in ' '.join(_s_off), ' '.join(_s_off)[:120])
|
| 304 |
check('A2: ملف محلي لا يأخذ خيارات بروتوكول rtmp',
|
| 305 |
'-rtmp_enhanced_codecs' not in ' '.join(new_sender(logs).command(str(tmp / 'z.flv'), {'codec': 'hevc'})), '')
|
| 306 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 307 |
# ── H) مرصد سبب الإغلاق: stderr من FFmpeg الحقيقي يصل مصنَّفًا ومُخفًى ─────────────
|
| 308 |
# الإنتاج قال «لم يظهر سبب مصنّف» لست جلسات متتالية. هذه الفحوصات تُثبت أن ما يقوله FFmpeg
|
| 309 |
# فعلًا يُصنَّف ويُخزَّن ويُطبع، وأن المفتاح والرابط لا يخرجان من الإخفاء أبدًا.
|
|
@@ -406,9 +422,9 @@ os.environ.pop('YOUTUBE_FIFO_TIMESHIFT', None)
|
|
| 406 |
_joined = ' '.join(_s_slow)
|
| 407 |
check('I: مع الحجز يبقى الطابور صريحًا وإهدار الحزم مفعّلًا (تركيب مدروس لا نصف إصلاح)',
|
| 408 |
'-timeshift 12' in _joined and '-queue_size' in _joined and '-drop_pkts_on_overflow 1' in _joined, '')
|
| 409 |
-
check('I: بلا حجز ي
|
| 410 |
-
'-timeshift' not in ' '.join(_s_fast) and '-queue_size
|
| 411 |
-
and '-drop_pkts_on_overflow
|
| 412 |
|
| 413 |
|
| 414 |
# ── K) مُبلِّغ الاستقرار: يُخبر المدير أن الحافة قبلتنا، مرة واحدة، وهو حيّ ──────────
|
|
|
|
| 299 |
'-rtmp_enhanced_codecs' not in ' '.join(_s_h264), ' '.join(_s_h264)[:120])
|
| 300 |
check('A2: نسخة h265 تُعلن hvc1 (الإعلان لجمهور النسخ المعزّز فعلًا)',
|
| 301 |
'-rtmp_enhanced_codecs' in ' '.join(_s_h265), ' '.join(_s_h265)[:120])
|
| 302 |
+
check('A2: HEVC يمر stream-copy ولا يدخل libx264',
|
| 303 |
+
'-c:v copy' in ' '.join(_s_h265) and 'libx264' not in _s_h265, ' '.join(_s_h265)[:160])
|
| 304 |
check('A2: YOUTUBE_ENHANCED_RTMP=off يلغي الإعلان حتى مع h265',
|
| 305 |
'-rtmp_enhanced_codecs' not in ' '.join(_s_off), ' '.join(_s_off)[:120])
|
| 306 |
check('A2: ملف محلي لا يأخذ خيارات بروتوكول rtmp',
|
| 307 |
'-rtmp_enhanced_codecs' not in ' '.join(new_sender(logs).command(str(tmp / 'z.flv'), {'codec': 'hevc'})), '')
|
| 308 |
|
| 309 |
+
# ── A3) معدل حي ثابت حقيقي: لا CRF مقنّعًا بعنوان 4500k ───────────────────────────
|
| 310 |
+
# قياس الأمر السابق على لون ساكن 720x1280/30: 14.12 kbit/s فقط رغم -b:v 4500k، ثم
|
| 311 |
+
# videoIngestionStarved من يوتيوب للحسابين. nal-hrd=cbr + minrate أعطيا 4443.72 kbit/s.
|
| 312 |
+
_s_cbr = new_sender(logs, mode_override='matchgop').command(
|
| 313 |
+
'rtmps://x/live/K', {'codec': 'h264', 'label': 'hd · h264', 'width': 720, 'height': 1280})
|
| 314 |
+
_j_cbr = ' '.join(_s_cbr)
|
| 315 |
+
check('A3: التحويل يطلب CBR صريحًا: bitrate=minrate=maxrate ولا CRF متعارض',
|
| 316 |
+
'-b:v 4500k -minrate 4500k -maxrate 4500k' in _j_cbr and '-crf' not in _s_cbr,
|
| 317 |
+
_j_cbr[:180])
|
| 318 |
+
check('A3: x264 يملأ المشاهد الساكنة ويحافظ على CFR عند بوابة يوتيوب',
|
| 319 |
+
any(a.startswith('nal-hrd=cbr:force-cfr=1:') for a in _s_cbr),
|
| 320 |
+
next((a for a in _s_cbr if 'nal-hrd' in a), 'missing'))
|
| 321 |
+
_os.environ['YOUTUBE_SEND_MODE'] = 'copy'
|
| 322 |
+
|
| 323 |
# ── H) مرصد سبب الإغلاق: stderr من FFmpeg الحقيقي يصل مصنَّفًا ومُخفًى ─────────────
|
| 324 |
# الإنتاج قال «لم يظهر سبب مصنّف» لست جلسات متتالية. هذه الفحوصات تُثبت أن ما يقوله FFmpeg
|
| 325 |
# فعلًا يُصنَّف ويُخزَّن ويُطبع، وأن المفتاح والرابط لا يخرجان من الإخفاء أبدًا.
|
|
|
|
| 422 |
_joined = ' '.join(_s_slow)
|
| 423 |
check('I: مع الحجز يبقى الطابور صريحًا وإهدار الحزم مفعّلًا (تركيب مدروس لا نصف إصلاح)',
|
| 424 |
'-timeshift 12' in _joined and '-queue_size' in _joined and '-drop_pkts_on_overflow 1' in _joined, '')
|
| 425 |
+
check('I: بلا حجز يكون الخرج FLV مباشرًا؛ لا fifo مخفي يكذب في out_time أو يحبس المصدر',
|
| 426 |
+
'-timeshift' not in ' '.join(_s_fast) and '-queue_size' not in ' '.join(_s_fast)
|
| 427 |
+
and '-drop_pkts_on_overflow' not in ' '.join(_s_fast) and '-f flv' in ' '.join(_s_fast), '')
|
| 428 |
|
| 429 |
|
| 430 |
# ── K) مُبلِّغ الاستقرار: يُخبر المدير أن الحافة قبلتنا، مرة واحدة، وهو حيّ ──────────
|
tiktok_auth.py
CHANGED
|
@@ -24,7 +24,7 @@ Secrets handling
|
|
| 24 |
Tokens are never logged, never returned by any API response, and never written
|
| 25 |
into the recordings directory. Every outward-facing string is masked.
|
| 26 |
"""
|
| 27 |
-
import json, os, re, threading
|
| 28 |
from pathlib import Path
|
| 29 |
|
| 30 |
# Account data-centre cookie; only used when a session id is present.
|
|
@@ -95,6 +95,39 @@ def _env(name):
|
|
| 95 |
# --------------------------------------------------------------------------- #
|
| 96 |
# parsing
|
| 97 |
# --------------------------------------------------------------------------- #
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 98 |
def parse_token(raw):
|
| 99 |
"""Accept whatever the user can realistically copy, return (sessionid, extra_cookies).
|
| 100 |
|
|
@@ -103,6 +136,7 @@ def parse_token(raw):
|
|
| 103 |
* `sessionid=1a2b3c...`
|
| 104 |
* full Cookie header `sessionid=x; sid_tt=x; ttwid=y; tt-target-idc=useast1a`
|
| 105 |
* Netscape cookies.txt line `.tiktok.com\tTRUE\t/\tTRUE\t0\tsessionid\tx`
|
|
|
|
| 106 |
* several of the above separated by newlines / commas / semicolons
|
| 107 |
Unknown cookie names are preserved (e.g. ttwid, msToken) and sent as-is.
|
| 108 |
"""
|
|
@@ -110,9 +144,10 @@ def parse_token(raw):
|
|
| 110 |
if not text:
|
| 111 |
return '', {}
|
| 112 |
text = text.replace('\r', '\n')
|
| 113 |
-
|
|
|
|
| 114 |
sessionid = ''
|
| 115 |
-
for line in text.split('\n'):
|
| 116 |
line = line.strip()
|
| 117 |
if not line or line.startswith('#'):
|
| 118 |
continue
|
|
@@ -268,7 +303,7 @@ def _pack(sessionid, pairs, source, user):
|
|
| 268 |
|
| 269 |
|
| 270 |
def headers(user=None, extra=None):
|
| 271 |
-
"""
|
| 272 |
result = {'Referer': 'https://www.tiktok.com/'}
|
| 273 |
sess = session_for(user)
|
| 274 |
if sess['cookie']:
|
|
|
|
| 24 |
Tokens are never logged, never returned by any API response, and never written
|
| 25 |
into the recordings directory. Every outward-facing string is masked.
|
| 26 |
"""
|
| 27 |
+
import json, os, re, threading, time
|
| 28 |
from pathlib import Path
|
| 29 |
|
| 30 |
# Account data-centre cookie; only used when a session id is present.
|
|
|
|
| 95 |
# --------------------------------------------------------------------------- #
|
| 96 |
# parsing
|
| 97 |
# --------------------------------------------------------------------------- #
|
| 98 |
+
def _json_cookie_pairs(text):
|
| 99 |
+
"""Flatten a browser cookie export for TikTok's www endpoints, not other sites.
|
| 100 |
+
|
| 101 |
+
Expired cookies are discarded. Where the export contains two cookies with the
|
| 102 |
+
same name, prefer www.tiktok.com's more specific cookie (e.g. msToken).
|
| 103 |
+
"""
|
| 104 |
+
try:
|
| 105 |
+
exported=json.loads(text)
|
| 106 |
+
except (ValueError,TypeError):
|
| 107 |
+
return {}
|
| 108 |
+
if isinstance(exported,dict):exported=exported.get('cookies')
|
| 109 |
+
if not isinstance(exported,list):return {}
|
| 110 |
+
pairs={};priority={};now=time.time()
|
| 111 |
+
for item in exported:
|
| 112 |
+
if not isinstance(item,dict):continue
|
| 113 |
+
name=item.get('name');value=item.get('value')
|
| 114 |
+
if not isinstance(name,str) or not isinstance(value,str) or not value:continue
|
| 115 |
+
if not re.fullmatch(r"[!#$%&'*+\-.^_`|~0-9A-Za-z]+",name):continue
|
| 116 |
+
if any(c in value for c in ('\r','\n','\x00',';')):continue
|
| 117 |
+
domain=str(item.get('domain') or '').lower().lstrip('.')
|
| 118 |
+
if domain and domain not in ('tiktok.com','www.tiktok.com'):continue
|
| 119 |
+
# These headers serve several TikTok API paths; do not flatten path-specific cookies.
|
| 120 |
+
if str(item.get('path') or '/')!='/':continue
|
| 121 |
+
expiry=item.get('expirationDate',item.get('expires'))
|
| 122 |
+
try:expired=not item.get('session') and expiry is not None and 0<float(expiry)<=now
|
| 123 |
+
except (TypeError,ValueError):expired=False
|
| 124 |
+
if expired:continue
|
| 125 |
+
rank=(int(domain=='www.tiktok.com'),int(bool(item.get('hostOnly'))))
|
| 126 |
+
if name not in pairs or rank>=priority[name]:
|
| 127 |
+
pairs[name]=value;priority[name]=rank
|
| 128 |
+
return pairs
|
| 129 |
+
|
| 130 |
+
|
| 131 |
def parse_token(raw):
|
| 132 |
"""Accept whatever the user can realistically copy, return (sessionid, extra_cookies).
|
| 133 |
|
|
|
|
| 136 |
* `sessionid=1a2b3c...`
|
| 137 |
* full Cookie header `sessionid=x; sid_tt=x; ttwid=y; tt-target-idc=useast1a`
|
| 138 |
* Netscape cookies.txt line `.tiktok.com\tTRUE\t/\tTRUE\t0\tsessionid\tx`
|
| 139 |
+
* JSON browser export `[{"name":"sessionid","value":"...",...}]`
|
| 140 |
* several of the above separated by newlines / commas / semicolons
|
| 141 |
Unknown cookie names are preserved (e.g. ttwid, msToken) and sent as-is.
|
| 142 |
"""
|
|
|
|
| 144 |
if not text:
|
| 145 |
return '', {}
|
| 146 |
text = text.replace('\r', '\n')
|
| 147 |
+
json_input = text.startswith(('[', '{'))
|
| 148 |
+
pairs = _json_cookie_pairs(text) if json_input else {}
|
| 149 |
sessionid = ''
|
| 150 |
+
for line in (() if json_input else text.split('\n')):
|
| 151 |
line = line.strip()
|
| 152 |
if not line or line.startswith('#'):
|
| 153 |
continue
|
|
|
|
| 303 |
|
| 304 |
|
| 305 |
def headers(user=None, extra=None):
|
| 306 |
+
"""Build first-party TikTok headers; never forward this Cookie to a media CDN host."""
|
| 307 |
result = {'Referer': 'https://www.tiktok.com/'}
|
| 308 |
sess = session_for(user)
|
| 309 |
if sess['cookie']:
|
verify.sh
CHANGED
|
@@ -18,7 +18,22 @@ print('PASS no recorder / no video download API')
|
|
| 18 |
PY
|
| 19 |
|
| 20 |
python3 test_concurrency.py "$ROOT"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 21 |
python3 test_completion.py "$ROOT"
|
|
|
|
|
|
|
| 22 |
# Optional heavy tests when ffmpeg exists
|
| 23 |
if command -v ffmpeg >/dev/null 2>&1; then
|
| 24 |
python3 test_watchdog.py "$ROOT"
|
|
|
|
| 18 |
PY
|
| 19 |
|
| 20 |
python3 test_concurrency.py "$ROOT"
|
| 21 |
+
python3 test_channel_switch.py "$ROOT"
|
| 22 |
+
if command -v node >/dev/null 2>&1; then
|
| 23 |
+
node test_dashboard.js "$ROOT"
|
| 24 |
+
else
|
| 25 |
+
echo "SKIP dashboard JavaScript regressions (Node.js not installed)"
|
| 26 |
+
fi
|
| 27 |
+
python3 test_regressions.py "$ROOT"
|
| 28 |
+
python3 test_relay.py "$ROOT"
|
| 29 |
+
python3 test_source_reconnect.py "$ROOT"
|
| 30 |
+
python3 test_ingest_routes.py "$ROOT"
|
| 31 |
+
python3 test_transition_ingest.py "$ROOT"
|
| 32 |
+
python3 test_flv_bridge.py "$ROOT"
|
| 33 |
+
python3 test_adaptive_format.py "$ROOT"
|
| 34 |
python3 test_completion.py "$ROOT"
|
| 35 |
+
python3 test_telemetry.py "$ROOT"
|
| 36 |
+
python3 test_smart_mode.py "$ROOT"
|
| 37 |
# Optional heavy tests when ffmpeg exists
|
| 38 |
if command -v ffmpeg >/dev/null 2>&1; then
|
| 39 |
python3 test_watchdog.py "$ROOT"
|
youtube_manager.py
CHANGED
|
@@ -5,10 +5,11 @@ Fail closed on ambiguous remote creates."""
|
|
| 5 |
import os, re, subprocess, threading, time, uuid
|
| 6 |
from datetime import datetime, timezone, timedelta
|
| 7 |
from zoneinfo import ZoneInfo
|
| 8 |
-
from urllib.parse import urlparse
|
| 9 |
from curl_cffi import requests
|
| 10 |
-
from relay import RelayStartError, Sender, SourceStalled
|
| 11 |
-
from
|
|
|
|
| 12 |
import inspect
|
| 13 |
|
| 14 |
from youtube_api import GoogleAPI, Journal, APIError
|
|
@@ -23,6 +24,9 @@ class ManagedYouTube:
|
|
| 23 |
# Supervisor backoff: 1s after a healthy run, doubling to a cap while a fault persists.
|
| 24 |
self.retry_min=max(1.0,float(os.getenv('YOUTUBE_RETRY_MIN','1')))
|
| 25 |
self.retry_max=max(self.retry_min,float(os.getenv('YOUTUBE_RETRY_MAX','60')))
|
|
|
|
|
|
|
|
|
|
| 26 |
self.retry={} # username -> current backoff seconds
|
| 27 |
self.shutdown=threading.Event()
|
| 28 |
self.headers_for=headers_for or (lambda user:{})
|
|
@@ -31,13 +35,21 @@ class ManagedYouTube:
|
|
| 31 |
self.manager_thread=None;self.manager_stop=threading.Event()
|
| 32 |
self.senders={} # session_key -> {'thread','stop','sender'}
|
| 33 |
self.destinations={} # username -> rtmps url (in-memory only, never persisted)
|
|
|
|
|
|
|
|
|
|
| 34 |
self.scan=max(8,int(os.getenv('YOUTUBE_SCAN_SECONDS') or os.getenv('CHECK_INTERVAL','20')))
|
| 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,6 +76,15 @@ class ManagedYouTube:
|
|
| 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
|
|
@@ -133,23 +154,27 @@ class ManagedYouTube:
|
|
| 133 |
"""
|
| 134 |
try:return str((self.journal.read()['settings'].get('send_mode') or '')).strip().lower()
|
| 135 |
except Exception:return ''
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 136 |
def audio_mode_note(self):
|
| 137 |
"""What the audience actually receives, for the UI line."""
|
| 138 |
try:d=self.journal.read()
|
| 139 |
except Exception:return ''
|
| 140 |
return str(d['settings'].get('send_mode') or '')
|
| 141 |
@staticmethod
|
| 142 |
-
def _copyable(candidate):
|
| 143 |
-
"""هل يُنسخ هذا المرشّح بلا إعادة ترميز؟ (H.264 مُعلَن) — نفس قاعدة Sender.copy_is_safe."""
|
| 144 |
-
codec=str((candidate or {}).get('codec') or '').strip().lower()
|
| 145 |
-
return any(k in codec for k in ('h264','avc','264'))
|
| 146 |
-
@staticmethod
|
| 147 |
def video_sources(sources):
|
| 148 |
"""Renditions the relay may use, best first.
|
| 149 |
|
| 150 |
Two hard rules, both learned from the live source of this Space:
|
| 151 |
-
1.
|
| 152 |
-
|
| 153 |
2. the list is not truncated to one item — a TikTok rendition URL is signed and expires
|
| 154 |
before the broadcast ends, and the next rendition must be reachable in the same tick.
|
| 155 |
"""
|
|
@@ -168,17 +193,13 @@ class ManagedYouTube:
|
|
| 168 |
try:w=int(c.get('width') or 0);h=int(c.get('height') or 0)
|
| 169 |
except (TypeError,ValueError):w=h=0
|
| 170 |
return min(w,h) if w and h else 0
|
| 171 |
-
#
|
| 172 |
-
#
|
| 173 |
decent=[c for c in h264 if _short(c)>=720]
|
| 174 |
-
|
| 175 |
-
|
| 176 |
-
|
| 177 |
-
|
| 178 |
-
if lights_full and (decent or h264):
|
| 179 |
-
supported=decent or h264
|
| 180 |
-
elif decent:
|
| 181 |
-
supported=decent
|
| 182 |
out=supported
|
| 183 |
else:
|
| 184 |
raise RuntimeError('YOUTUBE_VIDEO_MODE يجب أن يكون original أو h264')
|
|
@@ -192,16 +213,6 @@ class ManagedYouTube:
|
|
| 192 |
try:w=int(c.get('width') or 0); h=int(c.get('height') or 0)
|
| 193 |
except (TypeError,ValueError):w=h=0
|
| 194 |
if w and h:
|
| 195 |
-
# قاعدة البكسلات أدناه كُتبت لمصادر تيك توك وهي **عمودية**: 720x1440 يمرّ
|
| 196 |
-
# (~1 مليون بكسل) بينما أي ماستر 1440p+ يُرفض. لكن Kick **أفقي**: 1920x1080
|
| 197 |
-
# = 2.07 مليون بكسل ⇒ كان يسقط تحت القاعدة دائمًا، فينزل البث من 1080p60
|
| 198 |
-
# إلى 720p60 بمجرد وجود ناشرَين — وهو ما لا يشتريه أحد شيئًا هنا:
|
| 199 |
-
# مرشّح Kick يُنسخ بلا إعادة ترميز، ومقيسٌ على نفس صورة الإنتاج
|
| 200 |
-
# (ffmpeg 7.1.5، @luchodku 1080p60): 4.9% من نواة واحدة = 2.4% من حصة
|
| 201 |
-
# الـ2.0 CPU. ما فوق 1080p يبقى خاضعًا للقاعدة.
|
| 202 |
-
if (str(c.get('platform') or '')=='kick'
|
| 203 |
-
and ManagedYouTube._copyable(c) and max(w,h)<=1920 and min(w,h)<=1080):
|
| 204 |
-
return False
|
| 205 |
# 720x1440 vertical is 720-class (~1 Mbps), not a 1440p master.
|
| 206 |
return min(w,h)>=1440 or (w*h)>=(1600*900)
|
| 207 |
text=str(c.get('label') or c.get('brief') or '')
|
|
@@ -228,38 +239,13 @@ class ManagedYouTube:
|
|
| 228 |
if len(out)>=12:break
|
| 229 |
return ' '.join(out)[:400]
|
| 230 |
@staticmethod
|
| 231 |
-
def _referer(user):
|
| 232 |
-
"""Referer حسب المنصة — تيك توك يحتفظ بقيمته التاريخية حرفيًا."""
|
| 233 |
-
try:
|
| 234 |
-
import kick_source
|
| 235 |
-
if kick_source.is_kick(user):return 'https://kick.com/'
|
| 236 |
-
except Exception:pass
|
| 237 |
-
return 'https://www.tiktok.com/'
|
| 238 |
-
@staticmethod
|
| 239 |
def description_with_links(text,user,hashtags):
|
| 240 |
"""Per-account footer: the broadcaster's own TikTok profile + hashtags of this live.
|
| 241 |
No cross-account links, so concurrent events never mix attributions."""
|
| 242 |
text=text.rstrip()
|
| 243 |
-
|
| 244 |
-
|
| 245 |
-
|
| 246 |
-
except Exception:
|
| 247 |
-
kick=False
|
| 248 |
-
if kick:
|
| 249 |
-
slug=kick_source.channel(user)
|
| 250 |
-
link=kick_source.profile_url(user)
|
| 251 |
-
# قالب كُتب في زمن المنصة الواحدة يثبّت «https://www.tiktok.com/@{username}»،
|
| 252 |
-
# و{username} لحساب كيك هو «kick:slug» ⇒ رابط مكسور يُنشر علنًا في كل بث.
|
| 253 |
-
# نصلحه في الناتج بدل إجبار المشغّل على تعطيل الأتمتة لتحرير القالب.
|
| 254 |
-
for host in ('https://www.tiktok.com/@', 'https://tiktok.com/@'):
|
| 255 |
-
text=text.replace(host+user, link)
|
| 256 |
-
text=text.replace('@'+user, '@'+slug)
|
| 257 |
-
if link not in text:
|
| 258 |
-
text+=f'\n\n🟢 قناة المذيع على كيك\n{slug}\n{link}'
|
| 259 |
-
else:
|
| 260 |
-
link=f'https://www.tiktok.com/@{user}'
|
| 261 |
-
if link not in text:
|
| 262 |
-
text+=f'\n\n🎵 حساب المذيع على تيك توك\n@{user}\n{link}'
|
| 263 |
if hashtags and hashtags not in text:text+='\n\n'+hashtags
|
| 264 |
return re.sub(r'\n{3,}','\n\n',text)
|
| 265 |
|
|
@@ -338,6 +324,10 @@ class ManagedYouTube:
|
|
| 338 |
channels=result.get('items',[])
|
| 339 |
if len(channels)!=1:raise RuntimeError('لم نجد قناة واحدة مفوضة؛ أعد OAuth واختر قناة يوتيوب الصحيحة')
|
| 340 |
channel={'id':channels[0]['id'],'title':channels[0]['snippet']['title']}
|
|
|
|
|
|
|
|
|
|
|
|
|
| 341 |
old=self.journal.read()['channel']
|
| 342 |
if old and old['id']!=channel['id']:
|
| 343 |
# التبديل المتعمد فقط: تمرير معرف القناة الجديدة نفسه في /api/youtube/start
|
|
@@ -355,24 +345,42 @@ class ManagedYouTube:
|
|
| 355 |
self.journal.change(lambda d:d.update(channel=channel))
|
| 356 |
return channel
|
| 357 |
def _migrate_channel(self,old,new):
|
| 358 |
-
#
|
| 359 |
-
#
|
| 360 |
-
|
|
|
|
|
|
|
| 361 |
d=self.journal.read();_n=len(d['events'])
|
| 362 |
def change(dd):
|
|
|
|
|
|
|
|
|
|
|
|
|
| 363 |
for ev in dd['events'].values():
|
| 364 |
dd['history'].append({'session_key':ev.get('session_key',''),'broadcast_id':ev.get('broadcast_id'),
|
|
|
|
| 365 |
'title':ev.get('title',''),'username':ev.get('username',''),'nickname':ev.get('nickname',''),
|
| 366 |
-
'note':'تبديل القناة المفوضة؛ الحدث كان يخص القناة السابقة ('+str(
|
| 367 |
'outcome':'local_cancelled_channel_switch','ended_at':time.time()})
|
| 368 |
-
dd
|
| 369 |
-
|
| 370 |
self.journal.change(change)
|
| 371 |
-
|
| 372 |
-
self.
|
|
|
|
|
|
|
|
|
|
| 373 |
def check(self):
|
| 374 |
# الفحص بلاغٌ لا اعتماد: يعيد القناة الجديدة (+ السابقة) ويبقي التوقف الآمن قائمًا
|
| 375 |
with self.operations:return self.check_channel(report_only=True)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 376 |
def settings(self,values):
|
| 377 |
with self.operations:
|
| 378 |
d=self.journal.read()
|
|
@@ -399,8 +407,7 @@ class ManagedYouTube:
|
|
| 399 |
raise ValueError('عطّل الأتمتة وانتظر إغلاق الأحداث قبل تعديل قوالب الأحداث')
|
| 400 |
if len(clean['name'])>80:raise ValueError('الاسم الاحتياطي حتى 80 حرفًا (الاسم الفعلي يُجلب من حساب تيك توك)')
|
| 401 |
test={'name':'فلان','title':'بث تجريبي','hashtags':'#تجربة','date':'2026-09-23','time':'14:35','username':'example','room_id':'123',
|
| 402 |
-
'nickname':'فلان','live_title':'بث تجريبي','broadcaster':'فلان'
|
| 403 |
-
'handle':'example','profile_url':'https://www.tiktok.com/@example','platform':'تيك توك'}
|
| 404 |
try:title=clean['title'].format(**test);desc=clean['description'].format(**test)
|
| 405 |
except (KeyError,ValueError,IndexError,AttributeError):raise ValueError('متغير قالب غير مدعوم')
|
| 406 |
if not title or len(title)>100 or any(c in title+desc for c in '<>') or len(desc)>4500:
|
|
@@ -424,10 +431,13 @@ class ManagedYouTube:
|
|
| 424 |
'closing':bool(ev.get('closing')),'broadcast_id':ev.get('broadcast_id',''),'note':ev.get('note',''),
|
| 425 |
'adult_only':bool(ev.get('adult_only')),
|
| 426 |
'status':s.get('status',''),'source':s.get('source',''),'output_seconds':s.get('output_seconds',0),
|
|
|
|
|
|
|
| 427 |
# عمر آخر بايت من المصدر + حدّ الحارس: اللوحة تُظهر «المصدر صامت 12 ث» بدل أن
|
| 428 |
# يظن المشاهد أن البث ميت بينما الجلسة تعمل (ما حدث في تجمّد @viggoo313).
|
| 429 |
# صمت المصدر لحظة آخر قفل: يشرح في اللوحة سبب 187 (جوع تغذية لا رفض مستقبِل).
|
| 430 |
'source_age_seconds':s.get('source_age'),'source_gap':s.get('source_gap'),
|
|
|
|
| 431 |
# آخر سطور stderr من FFmpeg بعد إخفاء الرابط والمفتاح: «لماذا أُغلقت الجلسة» لا يُترك تخمينًا
|
| 432 |
'ffmpeg_errors':list(s.get('ffmpeg_errors') or []),
|
| 433 |
'ffmpeg_diagnostics':list(s.get('ffmpeg_diagnostics') or []),
|
|
@@ -511,6 +521,93 @@ class ManagedYouTube:
|
|
| 511 |
markers=[self.marker()+'-STREAM-'+user]
|
| 512 |
if legacy:markers.append(self.marker()+'-STREAM') # stream migrated from V6/V7
|
| 513 |
return markers
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 514 |
def ensure_stream(self,user):
|
| 515 |
d=self.journal.read();st=d['streams'].get(user) or {}
|
| 516 |
markers=self.stream_markers(user,bool(st.get('legacy')))
|
|
@@ -548,13 +645,30 @@ class ManagedYouTube:
|
|
| 548 |
if not secure:
|
| 549 |
# YouTube's secure endpoint; streamName remains in memory only.
|
| 550 |
secure='rtmps://a.rtmps.youtube.com:443/live2'
|
| 551 |
-
|
| 552 |
-
|
| 553 |
-
|
| 554 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 555 |
return stream
|
| 556 |
|
| 557 |
# ---------- events ----------
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 558 |
def open_event(self,user,observation):
|
| 559 |
d=self.journal.read();key=user+':'+observation['room_id']
|
| 560 |
# قفل رفض 403 يُفحص أولًا: بعد الإغلاق يبقى المفتاح في history والفحص اللاحق كان
|
|
@@ -563,29 +677,16 @@ class ManagedYouTube:
|
|
| 563 |
if block and time.monotonic()-block<float(os.getenv('YOUTUBE_403_BLOCK_SECONDS','600')):
|
| 564 |
self._skip_note(user,'يوتيوب رفض إنشاء حدث لهذه الجلسة (403) مؤخرًا؛ ننتظر %d ث قبل المحاولة من جديد'%int(float(os.getenv('YOUTUBE_403_BLOCK_SECONDS','600'))-(time.monotonic()-block)))
|
| 565 |
return False
|
| 566 |
-
if key in d['events'] or
|
| 567 |
dt=datetime.now(ZoneInfo('Asia/Baghdad'));settings=d['settings']
|
| 568 |
nickname=str(observation.get('nickname') or '').strip()
|
| 569 |
live_title=str(observation.get('live_title') or '').strip()
|
| 570 |
name=nickname or user
|
| 571 |
title_value=live_title or name
|
| 572 |
hashtags=self.extract_hashtags(live_title)
|
| 573 |
-
# handle/profile_url/platform: متغيّرات قالب واعية بالمنصة. بدونها كان قالب الوصف
|
| 574 |
-
# الذي يكتب رابط تيك توك يدويًا يُنتج لحساب كيك رابطًا مكسورًا يُنشر علنًا:
|
| 575 |
-
# «https://www.tiktok.com/@kick:emadpes». {username} يبقى المفتاح الداخلي كما كان
|
| 576 |
-
# حتى لا يتغيّر أي قالب قائم، و{handle} هو الاسم المعروض بلا بادئة.
|
| 577 |
-
handle, profile = user, 'https://www.tiktok.com/@%s'%user
|
| 578 |
-
platform = 'تيك توك'
|
| 579 |
-
try:
|
| 580 |
-
import kick_source
|
| 581 |
-
if kick_source.is_kick(user):
|
| 582 |
-
handle, profile, platform = kick_source.channel(user), kick_source.profile_url(user), 'كيك'
|
| 583 |
-
except Exception:
|
| 584 |
-
pass
|
| 585 |
values={'name':name,'title':title_value,'hashtags':hashtags,'date':dt.strftime('%Y-%m-%d'),
|
| 586 |
'time':dt.strftime('%H:%M'),'username':user,'room_id':observation['room_id'],
|
| 587 |
-
'nickname':name,'live_title':live_title,'broadcaster':name
|
| 588 |
-
'handle':handle,'profile_url':profile,'platform':platform}
|
| 589 |
title_tpl=(os.getenv('YOUTUBE_TITLE_TEMPLATE','').strip() or settings.get('title') or '{broadcaster} | {date} {time}')
|
| 590 |
try:title=title_tpl.format(**values)[:100]
|
| 591 |
except (KeyError,ValueError,IndexError,AttributeError):
|
|
@@ -632,16 +733,23 @@ class ManagedYouTube:
|
|
| 632 |
self.event_update(key,bound=True,phase='bound')
|
| 633 |
return remote
|
| 634 |
def archive_event(self,key,outcome):
|
|
|
|
|
|
|
| 635 |
def change(d):
|
| 636 |
ev=d['events'].pop(key,None)
|
| 637 |
if ev is None:return
|
| 638 |
d['history'].append({'session_key':ev['session_key'],'broadcast_id':ev['broadcast_id'],
|
| 639 |
'title':ev['title'],'username':ev['username'],'nickname':ev.get('nickname',''),
|
| 640 |
-
'note':ev.get('note','')})
|
| 641 |
d['history'][-1].update(outcome=outcome,ended_at=time.time())
|
| 642 |
del d['history'][:-40]
|
| 643 |
self.journal.change(change)
|
| 644 |
self.stop_sender(key)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 645 |
def finish_event(self,key):
|
| 646 |
ev=self.journal.read()['events'].get(key)
|
| 647 |
if not ev:return True
|
|
@@ -711,6 +819,130 @@ class ManagedYouTube:
|
|
| 711 |
self.log(user or 'system', '[WATCHDOG] أُلغي تأجيل إعادة الاتصال (%d حدث) — %s' % (dropped, why))
|
| 712 |
return dropped
|
| 713 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 714 |
def start_sender(self,key):
|
| 715 |
# عقاب الوتيرة يجب أن يصمد أمام نقرات tick(): أي أن إعادة الاتصال المؤجّلة بسبب رفض
|
| 716 |
# الوجهة (187) لا تُبطلها دورة رصد جاءت بعد 15 ث. بدون هذا القفل يبقى التأجيل شكليًا
|
|
@@ -785,16 +1017,59 @@ class ManagedYouTube:
|
|
| 785 |
# والمرسل نفسه يحفظ مرشّحه الحالي في Sender.current_candidate — لا حاجة للقيد.
|
| 786 |
stop=threading.Event();sender=Sender(self.ffmpeg,self.log,self.headers_for)
|
| 787 |
u=ev['username']
|
| 788 |
-
|
| 789 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 790 |
sender.sticky_since=time.monotonic()
|
| 791 |
-
|
| 792 |
-
|
|
|
|
|
|
|
| 793 |
sender._gop_w,sender._gop_h=int(gw or 0),int(gh or 0)
|
|
|
|
|
|
|
| 794 |
sender.set_probe(self.codec_probe)
|
| 795 |
# حين تبدأ الحافة بقبولنا فعلًا يُمسح العقاب وأثره — لا يُتركان حتى أول انقطاع لاحق
|
| 796 |
sender.on_stable=lambda u=ev['username']: self.mark_stream_stable(u)
|
| 797 |
sender.mode_override=self.send_mode_setting() or None
|
|
|
|
|
|
|
| 798 |
thread=threading.Thread(target=self.sender_loop,
|
| 799 |
args=(key,ev['username'],ev['room_id'],destination,stop,sender),daemon=True)
|
| 800 |
self.senders[key]={'thread':thread,'stop':stop,'sender':sender}
|
|
@@ -828,10 +1103,21 @@ class ManagedYouTube:
|
|
| 828 |
if not since:
|
| 829 |
entry['idle_since']=time.monotonic()
|
| 830 |
continue
|
| 831 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 832 |
continue
|
| 833 |
self.log(ev.get('username') or key,
|
| 834 |
-
'[RELAY] @%s sender thread without FFmpeg; recycle'%
|
|
|
|
| 835 |
if not self.stop_sender(key):
|
| 836 |
continue
|
| 837 |
self.start_sender(key); n+=1
|
|
@@ -860,7 +1146,13 @@ class ManagedYouTube:
|
|
| 860 |
user=(self.journal.read()['events'].get(key) or {}).get('username')
|
| 861 |
if entry['thread'].is_alive():
|
| 862 |
entry['thread'].join(timeout=3)
|
| 863 |
-
if entry['thread'].is_alive():
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 864 |
self.senders.pop(key,None)
|
| 865 |
if user:hub.release(user,'oauth')
|
| 866 |
return True
|
|
@@ -869,7 +1161,6 @@ class ManagedYouTube:
|
|
| 869 |
failure, refresh the ranked sources when a signed URL has expired, and reconnect at
|
| 870 |
once when the source resolution changed. Exponential backoff replaces the fixed 15s
|
| 871 |
loop so a persistent fault stops hammering TikTok and YouTube."""
|
| 872 |
-
restart_at=0.0
|
| 873 |
while not stop.is_set() and not self.shutdown.is_set():
|
| 874 |
try:
|
| 875 |
try:obs=self._observe(user, allow_hold=user not in self._skip_hold)
|
|
@@ -917,19 +1208,21 @@ class ManagedYouTube:
|
|
| 917 |
session_started=time.monotonic()
|
| 918 |
candidates=self._select_source(user,obs)
|
| 919 |
prev=getattr(sender,'current_candidate',None) or {}
|
| 920 |
-
|
| 921 |
-
return '|'.join([str(c.get('quality_name') or c.get('label') or '').strip().lower(),
|
| 922 |
-
str(c.get('width') or ''), str(c.get('height') or ''),
|
| 923 |
-
str(c.get('media') or '')])
|
| 924 |
-
pin=_pin(prev) if any(_pin(prev).split('|')) else (self._rendition_pin.get(user) or '')
|
| 925 |
if pin.strip('|') and candidates:
|
| 926 |
-
same=[c for c in candidates if
|
| 927 |
if same:
|
| 928 |
rest=[c for c in candidates if c not in same]
|
| 929 |
candidates=same+rest
|
| 930 |
else:
|
| 931 |
-
|
| 932 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 933 |
if not candidates:
|
| 934 |
self.log(user,'لا مرشح فيديو صالح لهذه الدورة؛ سيُحدَّث المصدر تلقائيًا')
|
| 935 |
stop.wait(self._backoff(user));continue
|
|
@@ -942,9 +1235,12 @@ class ManagedYouTube:
|
|
| 942 |
destination = self.destinations.get(user) or destination
|
| 943 |
try:
|
| 944 |
self.log(user,'[RELAY] @%s starting (%s)'%(user,self._source_brief(candidate)))
|
| 945 |
-
|
|
|
|
|
|
|
|
|
|
| 946 |
sent=True
|
| 947 |
-
self._rendition_pin[user]=
|
| 948 |
sender.lock_gold(candidate)
|
| 949 |
gw,gh=int(getattr(sender,'_gop_w',0) or 0), int(getattr(sender,'_gop_h',0) or 0)
|
| 950 |
if gw>=16 and gh>=16:
|
|
@@ -956,6 +1252,14 @@ class ManagedYouTube:
|
|
| 956 |
if candidate is not None:self.mark_unstable(user,candidate,'start failed')
|
| 957 |
continue
|
| 958 |
except SourceStalled as e:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 959 |
# Signed URLs in the hold cache are stale once bytes stop. Drop the
|
| 960 |
# hold so the next observe is honest (real Offline vs PK blip).
|
| 961 |
self._held.pop(user, None)
|
|
@@ -967,35 +1271,26 @@ class ManagedYouTube:
|
|
| 967 |
self._skip_probe_once[user]=True
|
| 968 |
self.retry[user]=self.retry_min
|
| 969 |
break
|
| 970 |
-
except FormatChanged:
|
| 971 |
-
prev=sender.current_candidate or candidate or {}
|
| 972 |
-
sender.note_format_change()
|
| 973 |
-
sender.lock_gold(prev)
|
| 974 |
-
sender.request_sticky('matchgop', user, 'PK/layout size change — keep YouTube canvas')
|
| 975 |
-
self._sender_sticky[user]='matchgop'
|
| 976 |
-
gw,gh=int(getattr(sender,'_gop_w',0) or 0), int(getattr(sender,'_gop_h',0) or 0)
|
| 977 |
-
if gw>=16 and gh>=16:
|
| 978 |
-
self._sender_gop[user]=(gw,gh)
|
| 979 |
-
self.log(user,'تغيرت أبعاد المصدر (جولة PK رباعية)؛ نثبت matchgop على نفس حدث يوتيوب')
|
| 980 |
-
restart_at=time.monotonic();sent=True;break
|
| 981 |
except Exception as e:
|
| 982 |
self.log(user,'تعثر إرسال الفيديو؛ نفس الحدث سيُستخدم — '+self.safe_error(e)[:160])
|
| 983 |
-
if sent:break
|
| 984 |
self._note_early_exit(user, sender, time.monotonic() - session_started)
|
| 985 |
if stalled:
|
| 986 |
# المصدر صامت الآن: دورة قصيرة ثم رصد جديد، لا نقر متواصل على CDN ميت.
|
| 987 |
if stop.wait(0.5):return
|
| 988 |
continue
|
| 989 |
-
|
|
|
|
|
|
|
|
|
|
| 990 |
if sent and sender.alive():
|
| 991 |
# FFmpeg owns the connection now; only watch for it ending.
|
| 992 |
sender.wait_until(lambda:sender.alive(),stop)
|
| 993 |
self.retry[user]=self.retry_min
|
| 994 |
except Exception as e:self.log(user,'تعذر تحديث مصدر الإرسال؛ لا ننشئ حدثًا إضافيًا — '+self.safe_error(e)[:160])
|
| 995 |
-
# Skip the idle wait right after a resolution change; otherwise keep polling.
|
| 996 |
-
if restart_at and time.monotonic()-restart_at<30:restart_at=0.0;continue
|
| 997 |
gap=float(getattr(sender,'last_source_gap',0) or 0)
|
| 998 |
-
|
|
|
|
| 999 |
if stop.wait(wait):return
|
| 1000 |
def mark_stream_stable(self, user):
|
| 1001 |
"""الحافة تقبل التدفق: تُرمى نافذة العقاب وملاحظتها وعدّادها. تُستدعى من المرسل عند أول
|
|
@@ -1005,6 +1300,10 @@ class ManagedYouTube:
|
|
| 1005 |
# 25 ث مُسلَّمة تُثبت أن المسار الحالي يكفي: يُلغى تناوب النقل الذي فرضه الجوع
|
| 1006 |
self.starve.pop(user, None)
|
| 1007 |
self._skip_hold.discard(user)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1008 |
cleared = 0
|
| 1009 |
for k in list(self.retry_at):
|
| 1010 |
if self.journal.read()['events'].get(k, {}).get('username') == user:
|
|
@@ -1028,10 +1327,11 @@ class ManagedYouTube:
|
|
| 1028 |
كان يُبقي الحدث «noData» ويحرق الوقت بلا فائدة. نُبطئ النقر تصاعديًا حتى 120ث، ونُصفّر
|
| 1029 |
العدّ عند أول جلسة دامت ≥25ث (الاستقبال صار يقبلنا). صمت المصدر له مسار آخر: `stalled`."""
|
| 1030 |
code = getattr(sender, 'last_exit_code', None)
|
| 1031 |
-
|
|
|
|
| 1032 |
return # لم تخرج العملية وحدَها: لا حكم على الوجهة
|
| 1033 |
gap = float(getattr(sender, 'last_source_gap', 0.0) or 0.0)
|
| 1034 |
-
if gap >= float(os.getenv('YOUTUBE_SOURCE_GAP_SUSPECT_SECONDS', '8')):
|
| 1035 |
# جوع مصدر لا رفض وجهة: التأجيل هنا يطيل أمد الصمت الذي يراه المشاهدون. نُسرّع
|
| 1036 |
# الرصد بدل ذلك (رابط FLV موقّع جديد) ونُبقي الوتيرة الطبيعية.
|
| 1037 |
# جوعٌ موثّق بالقياس يزيد عدّاد التناوب: بعد جوعين يُقدَّم مرشح غير FLV (انظر _select_source)
|
|
@@ -1045,12 +1345,60 @@ class ManagedYouTube:
|
|
| 1045 |
% (gap, code, '؛ أُلغي تأجيل سابق' if was is not None else ''))
|
| 1046 |
self.retry[user] = self.retry_min
|
| 1047 |
return
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1048 |
if lasted >= 25:
|
| 1049 |
-
# نفس الدالة التي يستدعيها المرسل وهو يعمل: نسخة واحدة من التعافي لا نسختان
|
|
|
|
|
|
|
|
|
|
| 1050 |
self.mark_stream_stable(user)
|
| 1051 |
-
|
|
|
|
| 1052 |
n = self.hammer.get(user, 0) + 1
|
| 1053 |
self.hammer[user] = n
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1054 |
# حالة الحدث تُبدّل الحكم: إن لم يكن قد شُغِّل بعد (ready/created) فالحافة لا تقبل نشرًا
|
| 1055 |
# على حدث متوقف — الإغلاق عند ~12 ث هنا عرض لا علة، وتجديد المفتاح لن يغيّر شيئًا.
|
| 1056 |
_evs = [ev for ev in self.journal.read()['events'].values() if ev.get('username') == user]
|
|
@@ -1067,7 +1415,7 @@ class ManagedYouTube:
|
|
| 1067 |
self.log(user, '[WATCHDOG] الحدث لم يبدأ بعد (youtube_status=%s): لا نُجدّد المفتاح — النشر '
|
| 1068 |
'لا يُقبل قبل تشغيل الحدث؛ سيُعاد المحاولة بوتيرة أبطأ حتى يبدأ'
|
| 1069 |
% (_evs[0].get('youtube_status') if _evs else '؟'))
|
| 1070 |
-
if n == 3 and not not_started and gap < float(os.getenv('YOUTUBE_SOURCE_GAP_SUSPECT_SECONDS', '8')):
|
| 1071 |
# المصدر يرسل والوجهة ما زالت تقفل: الشكّ في المفتاح لا في البث. نُجه��ل العنوان ليُعاد
|
| 1072 |
# قراءته من YouTube API في start_sender — قراءة واحدة، بلا إنشاء ولا تعديل حالة الحدث.
|
| 1073 |
if self.destinations.pop(user, None):
|
|
@@ -1081,15 +1429,14 @@ class ManagedYouTube:
|
|
| 1081 |
except Exception as e:
|
| 1082 |
self.log(user, '[WATCHDOG] تعذر تجديد عنوان الاستقبال: ' + self.safe_error(e)[:120])
|
| 1083 |
if n >= 3:
|
| 1084 |
-
#
|
| 1085 |
-
#
|
| 1086 |
-
wait =
|
| 1087 |
-
self.retry[user] = max(self.retry.get(user, 0) or 0, wait)
|
| 1088 |
-
for k in [k for k, ev in self.journal.read()['events'].items() if ev.get('username') == user]:
|
| 1089 |
-
self.retry_at[k] = time.monotonic() + wait # يقفل start_sender من tick() نفسه
|
| 1090 |
self.log(user, '[WATCHDOG] الوجهة أغلقت الاتصال بعد %.0f ث (رمز %s) — المرة %d: تأجيل إعادة الاتصال إلى %d ث بدل النقر على حافة ترفض%s'
|
| 1091 |
% (lasted, code, n, int(self._backoff(user)),
|
| 1092 |
'؛ السبب المعلوم: الحدث لم يُشغَّل بعد' if not_started else ''))
|
|
|
|
|
|
|
| 1093 |
return
|
| 1094 |
|
| 1095 |
def _backoff(self,user):
|
|
@@ -1108,7 +1455,7 @@ class ManagedYouTube:
|
|
| 1108 |
media=(candidate or {}).get('media') or 'flv'
|
| 1109 |
want=self._source_magic(media);got=bytearray()
|
| 1110 |
r=requests.get(candidate['url'],impersonate='chrome',
|
| 1111 |
-
headers=
|
| 1112 |
try:
|
| 1113 |
r.raise_for_status()
|
| 1114 |
for chunk in r.iter_content():
|
|
@@ -1130,8 +1477,7 @@ class ManagedYouTube:
|
|
| 1130 |
# Local paths reject HTTP-only options, exactly like FFmpeg does.
|
| 1131 |
args+=['-reconnect','1','-rw_timeout','10000000']
|
| 1132 |
hdr=''.join('%s: %s\r\n'%(k,v) for k,v in
|
| 1133 |
-
|
| 1134 |
-
**self.headers_for((candidate or {}).get('user'))}.items() if v)
|
| 1135 |
if hdr:args+=['-headers',hdr]
|
| 1136 |
try:
|
| 1137 |
r=subprocess.run(args+['-i',url],capture_output=True,text=True,timeout=45)
|
|
@@ -1150,40 +1496,119 @@ class ManagedYouTube:
|
|
| 1150 |
return '|'.join([str(c.get('quality_name') or ''), str(c.get('media') or ''),
|
| 1151 |
str(c.get('codec') or ''), str(c.get('resolution') or '')])
|
| 1152 |
@staticmethod
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1153 |
def _source_brief(c):
|
| 1154 |
return str(c.get('brief') or c.get('label') or 'source')
|
| 1155 |
def mark_unstable(self,user,candidate,why=''):
|
| 1156 |
key=self._source_key(candidate)
|
| 1157 |
self._unstable.setdefault(user,set()).add(key)
|
| 1158 |
self.log(user,'[SOURCE] @%s source %s unstable%s'%(user,self._source_brief(candidate),(' — '+why) if why else ''))
|
| 1159 |
-
def _refresh_flv(self,user):
|
| 1160 |
-
"""
|
| 1161 |
|
| 1162 |
-
|
| 1163 |
-
|
|
|
|
|
|
|
| 1164 |
"""
|
| 1165 |
-
|
| 1166 |
-
|
| 1167 |
-
|
| 1168 |
-
|
| 1169 |
-
|
| 1170 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1171 |
if (obs or {}).get('status')!='live':
|
| 1172 |
return None
|
|
|
|
|
|
|
|
|
|
| 1173 |
ordered=self._select_source(user, obs) or []
|
| 1174 |
-
|
| 1175 |
-
|
| 1176 |
-
|
| 1177 |
-
|
| 1178 |
-
|
| 1179 |
-
|
| 1180 |
-
|
| 1181 |
-
|
| 1182 |
-
|
| 1183 |
-
|
| 1184 |
-
|
| 1185 |
-
|
| 1186 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1187 |
def _select_source(self,user,obs):
|
| 1188 |
"""All relayable renditions, stable first. Never drop a working lower-quality source."""
|
| 1189 |
candidates=self.video_sources(obs.get('sources') or [])
|
|
@@ -1224,6 +1649,7 @@ class ManagedYouTube:
|
|
| 1224 |
return usable
|
| 1225 |
def _republish_allowed(self,key,entry):
|
| 1226 |
"""True when the earlier broadcast of this very session is over (so re-publishing is right)."""
|
|
|
|
| 1227 |
if time.time()-float(entry.get('ended_at') or 0)<float(os.getenv('YOUTUBE_REPUBLISH_AFTER','120')):
|
| 1228 |
return False # too soon: the old session may still be settling
|
| 1229 |
bid=entry.get('broadcast_id')
|
|
@@ -1241,6 +1667,7 @@ class ManagedYouTube:
|
|
| 1241 |
_republish_allowed refuses a second event, and nobody reattaches a publisher.
|
| 1242 |
Restore the same broadcast_id so the watch URL does not change.
|
| 1243 |
"""
|
|
|
|
| 1244 |
if not obs.get('room_id'):return False
|
| 1245 |
key=user+':'+str(obs.get('room_id') or '')
|
| 1246 |
if self.journal.read()['events'].get(key):
|
|
@@ -1280,7 +1707,8 @@ class ManagedYouTube:
|
|
| 1280 |
'resume_trusted':True}
|
| 1281 |
def change(d):
|
| 1282 |
d['events'][key]=ev
|
| 1283 |
-
d['history']=[h for h in d['history'] if h.get('session_key')!=key
|
|
|
|
| 1284 |
self.journal.change(change)
|
| 1285 |
try:self.ensure_stream(user)
|
| 1286 |
except Exception as e:
|
|
@@ -1343,15 +1771,15 @@ class ManagedYouTube:
|
|
| 1343 |
if self.max_events>0 and len(d['events'])>=self.max_events:
|
| 1344 |
return False
|
| 1345 |
key=user+':'+str(obs['room_id'])
|
| 1346 |
-
entry=
|
| 1347 |
if entry is not None:
|
| 1348 |
if not self._republish_allowed(key,entry):
|
| 1349 |
if self._resume_archived_event(user,obs,entry):
|
| 1350 |
return True
|
| 1351 |
-
self.
|
| 1352 |
self.log(user,'[RELAY] @%s archived YouTube event not resumable; opening a new event'%user)
|
| 1353 |
else:
|
| 1354 |
-
self.
|
| 1355 |
found=self._find_open_broadcast(user)
|
| 1356 |
if found:
|
| 1357 |
fake={'broadcast_id':found.get('id'),'nickname':user,
|
|
@@ -1461,7 +1889,7 @@ class ManagedYouTube:
|
|
| 1461 |
self.last_seen_status[user]=obs['status']
|
| 1462 |
key=user+':'+obs['room_id']
|
| 1463 |
if key in d['events']:continue
|
| 1464 |
-
entry=
|
| 1465 |
if entry is not None:
|
| 1466 |
# The history entry stops a *duplicate* broadcast of one session. It must not
|
| 1467 |
# keep a broadcaster off the air after the earlier broadcast died: an app
|
|
@@ -1473,10 +1901,10 @@ class ManagedYouTube:
|
|
| 1473 |
continue
|
| 1474 |
# Resume failed (API error, missing marker). Do not leave TikTok LIVE
|
| 1475 |
# with no publisher: drop the history lock and open a new event.
|
| 1476 |
-
self.
|
| 1477 |
self.log(user,'[RELAY] @%s archived YouTube event not resumable; opening a new event'%user)
|
| 1478 |
else:
|
| 1479 |
-
self.
|
| 1480 |
self.log(user,'بثّ سابق لنفس الجلسة انتهى؛ نعيد نشر الجلسة الحالية على يوتيوب')
|
| 1481 |
# Fast confirmation: one extra fresh read in this same cycle (no extra interval).
|
| 1482 |
try:
|
|
@@ -1599,8 +2027,10 @@ class ManagedYouTube:
|
|
| 1599 |
self.log(user,'[RELAY] @%s stopping (TikTok LIVE ended)'%user)
|
| 1600 |
self._unstable.pop(user,None)
|
| 1601 |
self._rendition_pin.pop(user,None)
|
|
|
|
| 1602 |
self._sender_sticky.pop(user,None)
|
| 1603 |
self._sender_gop.pop(user,None)
|
|
|
|
| 1604 |
self._live_confirm.pop(user,None)
|
| 1605 |
self.finish_event(key)
|
| 1606 |
self.log(user,'[CLEANUP] @%s complete'%user)
|
|
@@ -1716,6 +2146,17 @@ class ManagedYouTube:
|
|
| 1716 |
self.stream_health(key,user,ev)
|
| 1717 |
return
|
| 1718 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1719 |
# life is expected to be 'ready' or 'testing' for a newly bound event
|
| 1720 |
if life not in ('ready','testing'):
|
| 1721 |
# 'created' etc. -> ingest not yet receivable, don't push (prevents 187)
|
|
@@ -1751,7 +2192,7 @@ class ManagedYouTube:
|
|
| 1751 |
(videoResolutionUnsupported / videoCodec) and why playback stalls (gopSizeLong /
|
| 1752 |
openGop). Surfacing it replaces guesswork with ground truth. Polled on a slower
|
| 1753 |
cadence than the life-cycle check so it stays inside the quota budget."""
|
| 1754 |
-
interval=max(
|
| 1755 |
if time.time()-float(ev.get('last_health') or 0)<interval:return
|
| 1756 |
stream_id=(self.journal.read()['streams'].get(user) or {}).get('id')
|
| 1757 |
if not stream_id:return
|
|
@@ -1767,23 +2208,53 @@ class ManagedYouTube:
|
|
| 1767 |
text=' | '.join(issues)
|
| 1768 |
prev=ev.get('last_issues')
|
| 1769 |
status=str(health.get('status') or '')
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1770 |
self.event_update(key,youtube_health=status,youtube_issues=text,last_issues=text)
|
| 1771 |
if text and text!=prev:
|
| 1772 |
self.log(user,'يوتيوب يشخّص البث: '+text)
|
| 1773 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1774 |
# Per-sender only; does not restart the Space or other publishers.
|
| 1775 |
blob=(text+' '+status).lower()
|
| 1776 |
gop_bad=any(k in blob for k in ('gopsizelong','gopsizeover','opengop'))
|
|
|
|
|
|
|
|
|
|
| 1777 |
nodata=status.lower()=='nodata'
|
| 1778 |
starved=any(k in blob for k in ('videoingestionstarved','videooutputlow','videobitratelow'))
|
| 1779 |
entry=self.senders.get(key)
|
| 1780 |
sender=entry['sender'] if entry and entry.get('thread') and entry['thread'].is_alive() else None
|
| 1781 |
-
if sender and (
|
| 1782 |
snap=sender.snapshot() or {}
|
| 1783 |
out=float(snap.get('output_seconds') or 0)
|
| 1784 |
mode=(snap.get('send_mode') or sender.send_mode() or '')
|
| 1785 |
if out>=20 and mode in ('','auto','copy') and not sender.sticky_mode:
|
| 1786 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1787 |
def run_manager(self):
|
| 1788 |
checked=False
|
| 1789 |
last_tick=0.0
|
|
@@ -1797,11 +2268,24 @@ class ManagedYouTube:
|
|
| 1797 |
if now-last_tick>=self.scan:
|
| 1798 |
self.tick()
|
| 1799 |
last_tick=now
|
| 1800 |
-
|
| 1801 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1802 |
d=self.journal.read()
|
| 1803 |
if not d['enabled'] and not d['events']:self.set_status('الأتمتة معطلة؛ لا إرسال ولا إنشاء أحداث')
|
| 1804 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1805 |
remain=self.scan-(time.monotonic()-last_tick)
|
| 1806 |
delay=2.0 if dead else max(1.0, min(self.scan, remain if remain>0 else self.scan))
|
| 1807 |
except Exception as e:
|
|
|
|
| 5 |
import os, re, subprocess, threading, time, uuid
|
| 6 |
from datetime import datetime, timezone, timedelta
|
| 7 |
from zoneinfo import ZoneInfo
|
| 8 |
+
from urllib.parse import urlparse, urlunparse, quote
|
| 9 |
from curl_cffi import requests
|
| 10 |
+
from relay import RelayStartError, Sender, SourceStalled, source_http_headers
|
| 11 |
+
from stream_monitor import log_event
|
| 12 |
+
from telemetry import record_event as telemetry_event
|
| 13 |
import inspect
|
| 14 |
|
| 15 |
from youtube_api import GoogleAPI, Journal, APIError
|
|
|
|
| 24 |
# Supervisor backoff: 1s after a healthy run, doubling to a cap while a fault persists.
|
| 25 |
self.retry_min=max(1.0,float(os.getenv('YOUTUBE_RETRY_MIN','1')))
|
| 26 |
self.retry_max=max(self.retry_min,float(os.getenv('YOUTUBE_RETRY_MAX','60')))
|
| 27 |
+
self._publish_wait={} # username -> انتظار نشر مفروض قبل المحاولة التالية (انضباط قبول مقعد يوتيوب)
|
| 28 |
+
self.publish_settle=max(0.0,float(os.getenv('YOUTUBE_PUBLISH_SETTLE_SECONDS','10')))
|
| 29 |
+
self.publish_max_defer=max(self.publish_settle,float(os.getenv('YOUTUBE_PUBLISH_MAX_DEFER_SECONDS','20')))
|
| 30 |
self.retry={} # username -> current backoff seconds
|
| 31 |
self.shutdown=threading.Event()
|
| 32 |
self.headers_for=headers_for or (lambda user:{})
|
|
|
|
| 35 |
self.manager_thread=None;self.manager_stop=threading.Event()
|
| 36 |
self.senders={} # session_key -> {'thread','stop','sender'}
|
| 37 |
self.destinations={} # username -> rtmps url (in-memory only, never persisted)
|
| 38 |
+
self._ingest_routes={};self._ingest_preferred={}
|
| 39 |
+
self._ingest_open_failures={} # username -> مرات متتالية لم يُفتح فيها الاتصال على المسار الحالي
|
| 40 |
+
self._ingest_route_blocked={} # username -> فهارس مسارات لم تفتح أصلًا؛ لا تُعاد تجربتها حتى يثبت مسار
|
| 41 |
self.scan=max(8,int(os.getenv('YOUTUBE_SCAN_SECONDS') or os.getenv('CHECK_INTERVAL','20')))
|
| 42 |
self.end_grace=max(15,int(os.getenv('YOUTUBE_END_GRACE','40')))
|
| 43 |
self._unstable={}
|
| 44 |
self._live_confirm={}
|
| 45 |
self._rendition_pin={}
|
| 46 |
+
# A stalled high rendition may fall back to a lower same-codec FLV without closing
|
| 47 |
+
# FFmpeg/RTMP. Keep the preferred pin so a later *natural* source refresh can restore it
|
| 48 |
+
# after a long stable interval; never churn a healthy connection merely to gain pixels.
|
| 49 |
+
self._quality_fallback={}
|
| 50 |
self._sender_sticky={}
|
| 51 |
self._sender_gop={}
|
| 52 |
+
self._sender_pending={}
|
| 53 |
# Reuse one YouTube broadcast when TikTok moves the streamer to a new session. The stream
|
| 54 |
# key is persistent (isReusable) and the broadcast is created with enableAutoStop=false,
|
| 55 |
# so the broadcast stays resumable and the watch URL does not change. YOUTUBE_REUSE_IDLE
|
|
|
|
| 76 |
# السقف، و0 يطفئ الاحتفاظ.
|
| 77 |
self.hold_seconds=max(0.0,float(os.getenv('YOUTUBE_OBS_HOLD_SECONDS','900')))
|
| 78 |
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={}
|
| 79 |
+
# تنظيف خامل تلقائي: بلا أي بث لفترة مستمرة تتراكم بقايا التكيّف (وضع ترميز
|
| 80 |
+
# لاصق matchgop ومقاسه، تثبيت جودة، عدّادات تأجيل، رصد محفوظ) فتبدأ الجلسة
|
| 81 |
+
# التالية من حالة متعبة بدل حالة نظيفة. بعد YOUTUBE_IDLE_RESET_SECONDS من
|
| 82 |
+
# غياب البث الكامل تُصفَّر هذه البقايا مرة واحدة في كل فترة خمول، والرصد
|
| 83 |
+
# لا يتوقف لحظة. 0 يعطّل الميزة.
|
| 84 |
+
self._idle_since=None;self._idle_cleaned=False
|
| 85 |
+
try:self.idle_reset_seconds=float(os.getenv('YOUTUBE_IDLE_RESET_SECONDS','600'))
|
| 86 |
+
except (TypeError,ValueError):self.idle_reset_seconds=600.0
|
| 87 |
+
if self.idle_reset_seconds<0:self.idle_reset_seconds=0.0
|
| 88 |
# هل تقبل دالة الرصد المحقونة force=؟ (app.py يفعّلها؛ الاختبارات قد لا تفعل)
|
| 89 |
try:self._observe_force='force' in inspect.signature(self.observe).parameters
|
| 90 |
except (TypeError,ValueError):self._observe_force=False
|
|
|
|
| 154 |
"""
|
| 155 |
try:return str((self.journal.read()['settings'].get('send_mode') or '')).strip().lower()
|
| 156 |
except Exception:return ''
|
| 157 |
+
@staticmethod
|
| 158 |
+
def forced_mode(user):
|
| 159 |
+
"""Optional per-account reliability mode; never forces every relay to burn CPU."""
|
| 160 |
+
users={x.strip().lower().lstrip('@') for x in
|
| 161 |
+
os.getenv('YOUTUBE_FORCE_TRANSCODE_USERS','').split(',') if x.strip()}
|
| 162 |
+
if str(user or '').lower().lstrip('@') not in users:
|
| 163 |
+
return ''
|
| 164 |
+
mode=os.getenv('YOUTUBE_FORCE_TRANSCODE_MODE','matchgop').strip().lower()
|
| 165 |
+
return mode if mode in ('matchgop','fixed720','fixed1080') else 'matchgop'
|
| 166 |
def audio_mode_note(self):
|
| 167 |
"""What the audience actually receives, for the UI line."""
|
| 168 |
try:d=self.journal.read()
|
| 169 |
except Exception:return ''
|
| 170 |
return str(d['settings'].get('send_mode') or '')
|
| 171 |
@staticmethod
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 172 |
def video_sources(sources):
|
| 173 |
"""Renditions the relay may use, best first.
|
| 174 |
|
| 175 |
Two hard rules, both learned from the live source of this Space:
|
| 176 |
+
1. H.264 remains the compatibility preference when the same useful resolution exists;
|
| 177 |
+
HEVC is nevertheless relayable through Enhanced RTMP hvc1 without re-encoding.
|
| 178 |
2. the list is not truncated to one item — a TikTok rendition URL is signed and expires
|
| 179 |
before the broadcast ends, and the next rendition must be reachable in the same tick.
|
| 180 |
"""
|
|
|
|
| 193 |
try:w=int(c.get('width') or 0);h=int(c.get('height') or 0)
|
| 194 |
except (TypeError,ValueError):w=h=0
|
| 195 |
return min(w,h) if w and h else 0
|
| 196 |
+
# Prefer 720-class+ AVC for widest player compatibility. HEVC remains a valid
|
| 197 |
+
# Enhanced-RTMP copy fallback when no useful AVC rendition exists.
|
| 198 |
decent=[c for c in h264 if _short(c)>=720]
|
| 199 |
+
if decent:
|
| 200 |
+
# Prefer useful AVC, but retain SD/LD and HEVC behind it. Dropping them
|
| 201 |
+
# removed the only working escape when a high rendition/CDN edge stalled.
|
| 202 |
+
supported=decent+[c for c in supported if c not in decent]
|
|
|
|
|
|
|
|
|
|
|
|
|
| 203 |
out=supported
|
| 204 |
else:
|
| 205 |
raise RuntimeError('YOUTUBE_VIDEO_MODE يجب أن يكون original أو h264')
|
|
|
|
| 213 |
try:w=int(c.get('width') or 0); h=int(c.get('height') or 0)
|
| 214 |
except (TypeError,ValueError):w=h=0
|
| 215 |
if w and h:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 216 |
# 720x1440 vertical is 720-class (~1 Mbps), not a 1440p master.
|
| 217 |
return min(w,h)>=1440 or (w*h)>=(1600*900)
|
| 218 |
text=str(c.get('label') or c.get('brief') or '')
|
|
|
|
| 239 |
if len(out)>=12:break
|
| 240 |
return ' '.join(out)[:400]
|
| 241 |
@staticmethod
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 242 |
def description_with_links(text,user,hashtags):
|
| 243 |
"""Per-account footer: the broadcaster's own TikTok profile + hashtags of this live.
|
| 244 |
No cross-account links, so concurrent events never mix attributions."""
|
| 245 |
text=text.rstrip()
|
| 246 |
+
link=f'https://www.tiktok.com/@{user}'
|
| 247 |
+
if link not in text:
|
| 248 |
+
text+=f'\n\n🎵 حساب المذيع على تيك توك\n@{user}\n{link}'
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 249 |
if hashtags and hashtags not in text:text+='\n\n'+hashtags
|
| 250 |
return re.sub(r'\n{3,}','\n\n',text)
|
| 251 |
|
|
|
|
| 324 |
channels=result.get('items',[])
|
| 325 |
if len(channels)!=1:raise RuntimeError('لم نجد قناة واحدة مفوضة؛ أعد OAuth واختر قناة يوتيوب الصحيحة')
|
| 326 |
channel={'id':channels[0]['id'],'title':channels[0]['snippet']['title']}
|
| 327 |
+
# Validate the explicit confirmation BEFORE changing any journal state, including
|
| 328 |
+
# first-time setup. A token rotated between check and confirm must fail closed.
|
| 329 |
+
if expected is not None and expected!=channel['id']:
|
| 330 |
+
raise ValueError('القناة المفوضة لا تطابق آخر فحص؛ افحص OAuth والقناة مجددًا وأكّد القناة الصحيحة')
|
| 331 |
old=self.journal.read()['channel']
|
| 332 |
if old and old['id']!=channel['id']:
|
| 333 |
# التبديل المتعمد فقط: تمرير معرف القناة الجديدة نفسه في /api/youtube/start
|
|
|
|
| 345 |
self.journal.change(lambda d:d.update(channel=channel))
|
| 346 |
return channel
|
| 347 |
def _migrate_channel(self,old,new):
|
| 348 |
+
# Stop before removing events: stop_sender needs their username to release the old
|
| 349 |
+
# RelayHub slot. Never carry an old channel's cached RTMPS destination into the new one.
|
| 350 |
+
for key in list(self.senders):
|
| 351 |
+
if not self.stop_sender(key):
|
| 352 |
+
raise RuntimeError('تعذر إيقاف مرسل القناة السابقة؛ لم تُعتمد القناة الجديدة')
|
| 353 |
d=self.journal.read();_n=len(d['events'])
|
| 354 |
def change(dd):
|
| 355 |
+
# Legacy history belonged to the channel recorded at the time of this switch.
|
| 356 |
+
# Retain it, but it must not block/resume the same TikTok room on a new channel.
|
| 357 |
+
for entry in dd['history']:
|
| 358 |
+
entry.setdefault('channel_id',old['id'])
|
| 359 |
for ev in dd['events'].values():
|
| 360 |
dd['history'].append({'session_key':ev.get('session_key',''),'broadcast_id':ev.get('broadcast_id'),
|
| 361 |
+
'channel_id':old['id'],
|
| 362 |
'title':ev.get('title',''),'username':ev.get('username',''),'nickname':ev.get('nickname',''),
|
| 363 |
+
'note':'تبديل القناة المفوضة؛ الحدث كان يخص القناة السابقة ('+str(old.get('title') or old['id'])+')',
|
| 364 |
'outcome':'local_cancelled_channel_switch','ended_at':time.time()})
|
| 365 |
+
dd.update(channel=dict(new),enabled=False,events={},streams={})
|
| 366 |
+
# One atomic journal replacement; no YouTube event update/delete/transition call.
|
| 367 |
self.journal.change(change)
|
| 368 |
+
self.destinations.clear();self._ingest_routes.clear();self._ingest_preferred.clear();self._ingest_open_failures.clear();self._ingest_route_blocked.clear();self._publish_wait.clear();self._blocked403.clear();self.retry.clear()
|
| 369 |
+
self.clear_pacing(None,'تبديل القناة المفوضة')
|
| 370 |
+
self.last_logged=None
|
| 371 |
+
self.set_status('القناة الجديدة معتمدة؛ الأتمتة معطلة حتى تفعيلها')
|
| 372 |
+
self.log('youtube','تم اعتماد قناة جديدة («%s» بدل «%s») بتأكيدك الصريح: أُرشفت %d حدثًا للقناة السابقة محليًا بلا أي تعديل بعيد، وأُسقطت مصادرها القديمة'%(new.get('title',''),old.get('title',''),_n))
|
| 373 |
def check(self):
|
| 374 |
# الفحص بلاغٌ لا اعتماد: يعيد القناة الجديدة (+ السابقة) ويبقي التوقف الآمن قائمًا
|
| 375 |
with self.operations:return self.check_channel(report_only=True)
|
| 376 |
+
def confirm_channel(self,expected_channel):
|
| 377 |
+
"""Explicitly adopt the checked channel without starting a broadcast.
|
| 378 |
+
|
| 379 |
+
Switching pauses automation; same-channel confirmation preserves its current state.
|
| 380 |
+
"""
|
| 381 |
+
if not expected_channel:raise ValueError('افحص OAuth والقناة أولًا')
|
| 382 |
+
with self.operations:
|
| 383 |
+
return self.check_channel(allow_switch=True,expected=expected_channel)
|
| 384 |
def settings(self,values):
|
| 385 |
with self.operations:
|
| 386 |
d=self.journal.read()
|
|
|
|
| 407 |
raise ValueError('عطّل الأتمتة وانتظر إغلاق الأحداث قبل تعديل قوالب الأحداث')
|
| 408 |
if len(clean['name'])>80:raise ValueError('الاسم الاحتياطي حتى 80 حرفًا (الاسم الفعلي يُجلب من حساب تيك توك)')
|
| 409 |
test={'name':'فلان','title':'بث تجريبي','hashtags':'#تجربة','date':'2026-09-23','time':'14:35','username':'example','room_id':'123',
|
| 410 |
+
'nickname':'فلان','live_title':'بث تجريبي','broadcaster':'فلان'}
|
|
|
|
| 411 |
try:title=clean['title'].format(**test);desc=clean['description'].format(**test)
|
| 412 |
except (KeyError,ValueError,IndexError,AttributeError):raise ValueError('متغير قالب غير مدعوم')
|
| 413 |
if not title or len(title)>100 or any(c in title+desc for c in '<>') or len(desc)>4500:
|
|
|
|
| 431 |
'closing':bool(ev.get('closing')),'broadcast_id':ev.get('broadcast_id',''),'note':ev.get('note',''),
|
| 432 |
'adult_only':bool(ev.get('adult_only')),
|
| 433 |
'status':s.get('status',''),'source':s.get('source',''),'output_seconds':s.get('output_seconds',0),
|
| 434 |
+
'send_mode':s.get('send_mode') or ev.get('sender_mode',''),
|
| 435 |
+
'pending_send_mode':s.get('pending_send_mode') or ev.get('sender_pending_mode',''),
|
| 436 |
# عمر آخر بايت من المصدر + حدّ الحارس: اللوحة تُظهر «المصدر صامت 12 ث» بدل أن
|
| 437 |
# يظن المشاهد أن البث ميت بينما الجلسة تعمل (ما حدث في تجمّد @viggoo313).
|
| 438 |
# صمت المصدر لحظة آخر قفل: يشرح في اللوحة سبب 187 (جوع تغذية لا رفض مستقبِل).
|
| 439 |
'source_age_seconds':s.get('source_age'),'source_gap':s.get('source_gap'),
|
| 440 |
+
'rtmp_phase':s.get('rtmp_phase',''),
|
| 441 |
# آخر سطور stderr من FFmpeg بعد إخفاء الرابط والمفتاح: «لماذا أُغلقت الجلسة» لا يُترك تخمينًا
|
| 442 |
'ffmpeg_errors':list(s.get('ffmpeg_errors') or []),
|
| 443 |
'ffmpeg_diagnostics':list(s.get('ffmpeg_diagnostics') or []),
|
|
|
|
| 521 |
markers=[self.marker()+'-STREAM-'+user]
|
| 522 |
if legacy:markers.append(self.marker()+'-STREAM') # stream migrated from V6/V7
|
| 523 |
return markers
|
| 524 |
+
@staticmethod
|
| 525 |
+
def secure_ingest_url(address,key):
|
| 526 |
+
p=urlparse(str(address or ''))
|
| 527 |
+
if (p.scheme!='rtmps' or not p.hostname or not p.hostname.endswith('.youtube.com')
|
| 528 |
+
or p.username or p.password or not key):
|
| 529 |
+
raise RuntimeError('لم يُرجع يوتيوب عنوان إرسال آمنًا صالحًا')
|
| 530 |
+
# Official backup addresses carry ?backup=1. The key belongs in the PATH,
|
| 531 |
+
# not after the query string, and neither endpoint nor key is persisted.
|
| 532 |
+
return urlunparse((p.scheme,p.netloc,p.path.rstrip('/')+'/'+quote(str(key),safe=''),'',p.query,''))
|
| 533 |
+
|
| 534 |
+
def switch_ingest_route(self,user):
|
| 535 |
+
routes=self._ingest_routes.get(user) or {}
|
| 536 |
+
d=self.journal.read()
|
| 537 |
+
if (routes.get('channel_id')!=(d.get('channel') or {}).get('id') or
|
| 538 |
+
routes.get('stream_id')!=(d.get('streams',{}).get(user) or {}).get('id')):
|
| 539 |
+
return False # Do not reuse a route across a channel/stream ownership change.
|
| 540 |
+
choices=routes.get('urls') or []
|
| 541 |
+
if len(choices)<2:return False
|
| 542 |
+
current=self.destinations.get(user)
|
| 543 |
+
blocked=self._ingest_route_blocked.get(user) or set()
|
| 544 |
+
alt=next((u for i,u in enumerate(choices) if u!=current and i not in blocked),None)
|
| 545 |
+
if not alt:return False
|
| 546 |
+
self._ingest_preferred[user]=choices.index(alt)
|
| 547 |
+
self.destinations[user]=alt
|
| 548 |
+
self._ingest_open_failures.pop(user,None) # مسار جديد: عدّاد فتح جديد
|
| 549 |
+
self.log(user,'[RECOVERY] تجربة مستقبل RTMPS البديل من يوتيوب بنفس المصدر والحدث؛ بلا إنشاء مفتاح جديد')
|
| 550 |
+
return True
|
| 551 |
+
|
| 552 |
+
@staticmethod
|
| 553 |
+
def _never_opened(sender):
|
| 554 |
+
"""الاتصال لم يُفتح أصلًا: لا ثانية خرج واحدة ولم نبلغ حتى أمر النشر.
|
| 555 |
+
هذا فشل وصول إلى العنوان (TLS/شبكة) لا رفض نشر — علاجه الرجوع عن العنوان
|
| 556 |
+
لا إعادة قراءة المفتاح ولا تغيير الترميز."""
|
| 557 |
+
try:snap=sender.snapshot() or {}
|
| 558 |
+
except Exception:snap={}
|
| 559 |
+
if 'output_seconds' not in snap:return False # لا حكم بلا دليل إيجابي
|
| 560 |
+
if float(snap.get('output_seconds') or 0)>0:return False
|
| 561 |
+
return str(snap.get('rtmp_phase') or '') in ('','opening','handshake')
|
| 562 |
+
|
| 563 |
+
def rotate_ingest_route(self,user):
|
| 564 |
+
"""المسار الحالي لم يفتح الاتصال أصلًا مرتين متتاليتين (لا إطار واحد): يُحظر
|
| 565 |
+
ويُنتقل إلى المسار الآخر بنفس المفتاح والحدث — بالاتجاهين. بلا هذا كان
|
| 566 |
+
ensure_stream يُعيد تثبيت العنوان غير القابل للوصول في كل تجديد فتموت كل
|
| 567 |
+
محاولة قبل أول إطار (حادثة 2026-10-14: بث حيّ لم يبدأ على يوتيوب أبدًا).
|
| 568 |
+
إن كان المساران محظورين فالانقطاع خارجي: يُعاد ضبط الحظر ويُكمل التناوب
|
| 569 |
+
البطيء المُهدَّأ بدل التوقف."""
|
| 570 |
+
routes=self._ingest_routes.get(user) or {}
|
| 571 |
+
d=self.journal.read()
|
| 572 |
+
if (routes.get('channel_id')!=(d.get('channel') or {}).get('id') or
|
| 573 |
+
routes.get('stream_id')!=(d.get('streams',{}).get(user) or {}).get('id')):
|
| 574 |
+
return False # نفس حارس ملكية switch_ingest_route
|
| 575 |
+
choices=routes.get('urls') or []
|
| 576 |
+
if len(choices)<2:return False
|
| 577 |
+
pref=int(self._ingest_preferred.get(user,0) or 0)
|
| 578 |
+
if pref<0 or pref>=len(choices):return False
|
| 579 |
+
blocked=self._ingest_route_blocked.setdefault(user,set())
|
| 580 |
+
blocked.add(pref)
|
| 581 |
+
others=[i for i in range(len(choices)) if i!=pref and i not in blocked]
|
| 582 |
+
if not others:
|
| 583 |
+
blocked.clear();blocked.add(pref)
|
| 584 |
+
others=[i for i in range(len(choices)) if i!=pref]
|
| 585 |
+
if not others:return False
|
| 586 |
+
target=others[0]
|
| 587 |
+
self._ingest_preferred[user]=target
|
| 588 |
+
self.destinations[user]=choices[target]
|
| 589 |
+
self._ingest_open_failures.pop(user,None)
|
| 590 |
+
self.log(user,'[RECOVERY] مسار الاستقبال الحالي لم يفتح الاتصال أصلًا مرتين (لا إطار واحد مُرسل)؛ '
|
| 591 |
+
'حُظر هذا المسار حتى يثبت آخر، وانتقلنا إلى المسار الآخر بنفس المفتاح والحدث')
|
| 592 |
+
return True
|
| 593 |
+
|
| 594 |
+
def fallback_ingest_route(self,user):
|
| 595 |
+
return self.rotate_ingest_route(user)
|
| 596 |
+
|
| 597 |
+
def _pace_publish(self,user,n):
|
| 598 |
+
"""تهدئة نشر بعد موت خرج: يوتيوب لا يحرّر مقعد استقبال البث لحظة اختفاء
|
| 599 |
+
المُرمِّز؛ اتصال جديد أسرع من التحرير يُرفض (EOF/187 عند ~11 ث) فيولّد حلقة
|
| 600 |
+
رفض لا نهائية — موثّق بتجارب مشغّلين وبقياسنا (إعادة اتصال بعد 2-3 ث = موت
|
| 601 |
+
مؤكد). الانتظار 10 ث +5 لكل موتة حتى سقف 20 ث: تهدئة كافية لتحرير المقعد،
|
| 602 |
+
وأقصر بكثير من تصاعد 20/40/80/120 القديم — عودة سريعة بلا عاصفة."""
|
| 603 |
+
desired=min(self.publish_max_defer,self.publish_settle+5.0*max(0,int(n)-1))
|
| 604 |
+
self._publish_wait[user]=desired
|
| 605 |
+
self.retry[user]=desired
|
| 606 |
+
ready=time.monotonic()+desired
|
| 607 |
+
for k,ev in self.journal.read()['events'].items():
|
| 608 |
+
if ev.get('username')==user:self.retry_at[k]=ready
|
| 609 |
+
return desired
|
| 610 |
+
|
| 611 |
def ensure_stream(self,user):
|
| 612 |
d=self.journal.read();st=d['streams'].get(user) or {}
|
| 613 |
markers=self.stream_markers(user,bool(st.get('legacy')))
|
|
|
|
| 645 |
if not secure:
|
| 646 |
# YouTube's secure endpoint; streamName remains in memory only.
|
| 647 |
secure='rtmps://a.rtmps.youtube.com:443/live2'
|
| 648 |
+
primary=self.secure_ingest_url(secure,key)
|
| 649 |
+
backup_address=ingest.get('rtmpsBackupIngestionAddress')
|
| 650 |
+
if not backup_address:
|
| 651 |
+
backup_address='rtmps://b.rtmps.youtube.com:443/live2?backup=1'
|
| 652 |
+
backup=self.secure_ingest_url(backup_address,key)
|
| 653 |
+
choices=list(dict.fromkeys((primary,backup)))
|
| 654 |
+
self._ingest_routes[user]={'urls':choices,'stream_id':sid,
|
| 655 |
+
'channel_id':(dnow.get('channel') or {}).get('id')}
|
| 656 |
+
index=min(int(self._ingest_preferred.get(user,0)),len(choices)-1)
|
| 657 |
+
self.destinations[user]=choices[index]
|
| 658 |
return stream
|
| 659 |
|
| 660 |
# ---------- events ----------
|
| 661 |
+
@staticmethod
|
| 662 |
+
def _history_on_channel(entry,channel):
|
| 663 |
+
# Untagged legacy entries belong to the current channel until the first switch.
|
| 664 |
+
return not entry.get('channel_id') or entry['channel_id']==(channel or {}).get('id')
|
| 665 |
+
def _history_entry(self,key,d=None):
|
| 666 |
+
if d is None:d=self.journal.read()
|
| 667 |
+
return next((h for h in d['history'] if h.get('session_key')==key
|
| 668 |
+
and self._history_on_channel(h,d.get('channel'))),None)
|
| 669 |
+
def _forget_history(self,key):
|
| 670 |
+
self.journal.change(lambda d:d.update(history=[h for h in d['history']
|
| 671 |
+
if h.get('session_key')!=key or not self._history_on_channel(h,d.get('channel'))]))
|
| 672 |
def open_event(self,user,observation):
|
| 673 |
d=self.journal.read();key=user+':'+observation['room_id']
|
| 674 |
# قفل رفض 403 يُفحص أولًا: بعد الإغلاق يبقى المفتاح في history والفحص اللاحق كان
|
|
|
|
| 677 |
if block and time.monotonic()-block<float(os.getenv('YOUTUBE_403_BLOCK_SECONDS','600')):
|
| 678 |
self._skip_note(user,'يوتيوب رفض إنشاء حدث لهذه الجلسة (403) مؤخرًا؛ ننتظر %d ث قبل المحاولة من جديد'%int(float(os.getenv('YOUTUBE_403_BLOCK_SECONDS','600'))-(time.monotonic()-block)))
|
| 679 |
return False
|
| 680 |
+
if key in d['events'] or self._history_entry(key,d) is not None:return False
|
| 681 |
dt=datetime.now(ZoneInfo('Asia/Baghdad'));settings=d['settings']
|
| 682 |
nickname=str(observation.get('nickname') or '').strip()
|
| 683 |
live_title=str(observation.get('live_title') or '').strip()
|
| 684 |
name=nickname or user
|
| 685 |
title_value=live_title or name
|
| 686 |
hashtags=self.extract_hashtags(live_title)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 687 |
values={'name':name,'title':title_value,'hashtags':hashtags,'date':dt.strftime('%Y-%m-%d'),
|
| 688 |
'time':dt.strftime('%H:%M'),'username':user,'room_id':observation['room_id'],
|
| 689 |
+
'nickname':name,'live_title':live_title,'broadcaster':name}
|
|
|
|
| 690 |
title_tpl=(os.getenv('YOUTUBE_TITLE_TEMPLATE','').strip() or settings.get('title') or '{broadcaster} | {date} {time}')
|
| 691 |
try:title=title_tpl.format(**values)[:100]
|
| 692 |
except (KeyError,ValueError,IndexError,AttributeError):
|
|
|
|
| 733 |
self.event_update(key,bound=True,phase='bound')
|
| 734 |
return remote
|
| 735 |
def archive_event(self,key,outcome):
|
| 736 |
+
owned=self.journal.read()['events'].get(key) or {}
|
| 737 |
+
user=owned.get('username')
|
| 738 |
def change(d):
|
| 739 |
ev=d['events'].pop(key,None)
|
| 740 |
if ev is None:return
|
| 741 |
d['history'].append({'session_key':ev['session_key'],'broadcast_id':ev['broadcast_id'],
|
| 742 |
'title':ev['title'],'username':ev['username'],'nickname':ev.get('nickname',''),
|
| 743 |
+
'channel_id':(d.get('channel') or {}).get('id'),'note':ev.get('note','')})
|
| 744 |
d['history'][-1].update(outcome=outcome,ended_at=time.time())
|
| 745 |
del d['history'][:-40]
|
| 746 |
self.journal.change(change)
|
| 747 |
self.stop_sender(key)
|
| 748 |
+
if user:
|
| 749 |
+
self._sender_sticky.pop(user,None)
|
| 750 |
+
self._sender_gop.pop(user,None)
|
| 751 |
+
self._sender_pending.pop(user,None)
|
| 752 |
+
hub.release_light(user)
|
| 753 |
def finish_event(self,key):
|
| 754 |
ev=self.journal.read()['events'].get(key)
|
| 755 |
if not ev:return True
|
|
|
|
| 819 |
self.log(user or 'system', '[WATCHDOG] أُلغي تأجيل إعادة الاتصال (%d حدث) — %s' % (dropped, why))
|
| 820 |
return dropped
|
| 821 |
|
| 822 |
+
def _broadcast_active(self):
|
| 823 |
+
"""هل يوجد بث فعلي الآن؟ عند الشك نجيب «نعم»: التنظيف لا يجوز أن يخمّن.
|
| 824 |
+
|
| 825 |
+
نشاط = حدث في السجل، أو خيط إشراف/FFmpeg حيّ، أو ناشر عند RelayHub.
|
| 826 |
+
حدث محفوظ بلا مرسل (بث يوتيوب قابل للاستئناف) يبقى نشاطًا: إنهاؤه شأن
|
| 827 |
+
دورة حياة الحدث نفسها، لا مكنسة الخمول.
|
| 828 |
+
"""
|
| 829 |
+
try:
|
| 830 |
+
if self.journal.read().get('events'):return True
|
| 831 |
+
except Exception:
|
| 832 |
+
return True
|
| 833 |
+
for entry in list(self.senders.values()):
|
| 834 |
+
try:
|
| 835 |
+
if entry.get('thread') and entry['thread'].is_alive():return True
|
| 836 |
+
snd=entry.get('sender')
|
| 837 |
+
if snd and snd.alive():return True
|
| 838 |
+
except Exception:
|
| 839 |
+
return True
|
| 840 |
+
try:
|
| 841 |
+
if hub.active_count():return True
|
| 842 |
+
except Exception:
|
| 843 |
+
pass
|
| 844 |
+
return False
|
| 845 |
+
|
| 846 |
+
def idle_housekeeping(self, now=None):
|
| 847 |
+
"""تصفير بقايا التكيّف المتراكمة بعد غياب بث كامل مستمر — مرة في كل خمول.
|
| 848 |
+
|
| 849 |
+
ما يُمسح: حالة ذاكرة متطايرة فقط (أوضاع ترميز لاصقة ومقاساتها، تثبيتات
|
| 850 |
+
جودة، قوائم مصادر غير مستقرة، رصد محفوظ، عدّادات تأجيل/جوع، وجهات RTMPS
|
| 851 |
+
المحفوظة في الذاكرة لتُعاد قراءتها طازجة من YouTube API عند البث التالي).
|
| 852 |
+
ما لا يُمسّ أبدًا: ربط القناة، مصادر الاستقبال القابلة لإعادة الاستخدام،
|
| 853 |
+
إعدادات المشغّل، سجل الأحداث، أو أي توكن — حذف ملف السجل نفسه كان سيضيّع
|
| 854 |
+
الربط ويحوّل «تنظيفًا» إلى كسر. الرصد يستمر أثناء ذلك وبعده بلا توقف.
|
| 855 |
+
"""
|
| 856 |
+
if self.idle_reset_seconds<=0:return False
|
| 857 |
+
now=time.monotonic() if now is None else float(now)
|
| 858 |
+
if self._broadcast_active():
|
| 859 |
+
self._idle_since=None;self._idle_cleaned=False
|
| 860 |
+
return False
|
| 861 |
+
if self._idle_since is None:
|
| 862 |
+
self._idle_since=now;return False
|
| 863 |
+
idle_for=now-self._idle_since
|
| 864 |
+
if self._idle_cleaned or idle_for<self.idle_reset_seconds:return False
|
| 865 |
+
cleared=[]
|
| 866 |
+
for name in ('_sender_sticky','_sender_gop','_sender_pending','_rendition_pin',
|
| 867 |
+
'_quality_fallback','_unstable','_held','_skip_hold','_loop_miss',
|
| 868 |
+
'starve','hammer','retry','retry_at','_offline_logged','_live_confirm'):
|
| 869 |
+
store=getattr(self,name,None)
|
| 870 |
+
if isinstance(store,(dict,set)) and store:
|
| 871 |
+
store.clear();cleared.append(name)
|
| 872 |
+
if self.destinations:
|
| 873 |
+
self.destinations.clear();cleared.append('destinations')
|
| 874 |
+
self._ingest_routes.clear();self._ingest_preferred.clear();self._ingest_open_failures.clear();self._ingest_route_blocked.clear();self._publish_wait.clear()
|
| 875 |
+
try:
|
| 876 |
+
for user in list(hub.light_reservations):
|
| 877 |
+
hub.release_light(user)
|
| 878 |
+
except Exception:
|
| 879 |
+
pass
|
| 880 |
+
try:self.journal.change(lambda d:d.update(last_idle_clean=time.time()))
|
| 881 |
+
except Exception:pass
|
| 882 |
+
self._idle_cleaned=True
|
| 883 |
+
try:log_event('system','IDLE_AUTOCLEAN',{'idle_seconds':int(idle_for),
|
| 884 |
+
'cleared_stores':len(cleared)})
|
| 885 |
+
except Exception:pass
|
| 886 |
+
self.log('system','[IDLE] لا بث منذ %.0f ث؛ نُظّفت بقايا حالة التكيّف المتراكمة '
|
| 887 |
+
'تلقائيًا (%d مخزنًا) والرصد مستمر 24/7 — ربط القناة والإع��ادات '
|
| 888 |
+
'والتوكنات لم تُمس'% (idle_for,len(cleared)))
|
| 889 |
+
return True
|
| 890 |
+
|
| 891 |
+
def _event_key_for_user(self,user):
|
| 892 |
+
for key,ev in self.journal.read()['events'].items():
|
| 893 |
+
if ev.get('username')==user and not ev.get('closing'):
|
| 894 |
+
return key
|
| 895 |
+
return None
|
| 896 |
+
|
| 897 |
+
def _remember_sender_mode(self,user,mode,width=0,height=0):
|
| 898 |
+
"""Persist a per-event adaptive mode/canvas across FFmpeg and Space recovery."""
|
| 899 |
+
user=str(user or '')
|
| 900 |
+
if not user:return
|
| 901 |
+
mode=str(mode or 'matchgop')
|
| 902 |
+
self._sender_sticky[user]=mode
|
| 903 |
+
self._sender_pending.pop(user,None)
|
| 904 |
+
try:width,height=int(width or 0),int(height or 0)
|
| 905 |
+
except (TypeError,ValueError):width=height=0
|
| 906 |
+
if width>=32 and height>=32:
|
| 907 |
+
self._sender_gop[user]=(width,height)
|
| 908 |
+
key=self._event_key_for_user(user)
|
| 909 |
+
if key:
|
| 910 |
+
fields={'sender_mode':mode,'sender_pending_mode':'','sender_pending_reason':''}
|
| 911 |
+
if width>=32 and height>=32:
|
| 912 |
+
fields.update(sender_canvas_width=width,sender_canvas_height=height)
|
| 913 |
+
self.event_update(key,**fields)
|
| 914 |
+
|
| 915 |
+
def _remember_pending_sender_mode(self,user,mode,reason):
|
| 916 |
+
"""Persist a requested format fallback while all bounded encode slots are busy."""
|
| 917 |
+
user=str(user or '')
|
| 918 |
+
if not user:return
|
| 919 |
+
mode=str(mode or 'matchgop');reason=str(reason or '')[:180]
|
| 920 |
+
self._sender_pending[user]=(mode,reason)
|
| 921 |
+
key=self._event_key_for_user(user)
|
| 922 |
+
if key:self.event_update(key,sender_pending_mode=mode,sender_pending_reason=reason)
|
| 923 |
+
|
| 924 |
+
def _clear_sender_mode(self,user):
|
| 925 |
+
"""A verified copy probe ended the transcode: forget it everywhere.
|
| 926 |
+
|
| 927 |
+
Without this, the journal's per-event sender_mode re-applied matchgop
|
| 928 |
+
to every later FFmpeg of the event, so one health-triggered transcode
|
| 929 |
+
burned CPU until the broadcast ended. An operator-forced mode is a
|
| 930 |
+
deliberate lock and is never cleared by a probe.
|
| 931 |
+
"""
|
| 932 |
+
user=str(user or '')
|
| 933 |
+
if not user:return
|
| 934 |
+
if self.forced_mode(user):return
|
| 935 |
+
self._sender_sticky.pop(user,None)
|
| 936 |
+
self._sender_pending.pop(user,None)
|
| 937 |
+
self._sender_gop.pop(user,None)
|
| 938 |
+
key=self._event_key_for_user(user)
|
| 939 |
+
if key:
|
| 940 |
+
self.event_update(key,sender_mode='',sender_pending_mode='',sender_pending_reason='',
|
| 941 |
+
sender_canvas_width=0,sender_canvas_height=0)
|
| 942 |
+
try:hub.release_light(user)
|
| 943 |
+
except Exception:pass
|
| 944 |
+
self.log(user,'[RECOVERY] عودة موثّقة إلى COPY — نُسي وضع الترميز لهذا الحدث')
|
| 945 |
+
|
| 946 |
def start_sender(self,key):
|
| 947 |
# عقاب الوتيرة يجب أن يصمد أمام نقرات tick(): أي أن إعادة الاتصال المؤجّلة بسبب رفض
|
| 948 |
# الوجهة (187) لا تُبطلها دورة رصد جاءت بعد 15 ث. بدون هذا القفل يبقى التأجيل شكليًا
|
|
|
|
| 1017 |
# والمرسل نفسه يحفظ مرشّحه الحالي في Sender.current_candidate — لا حاجة للقيد.
|
| 1018 |
stop=threading.Event();sender=Sender(self.ffmpeg,self.log,self.headers_for)
|
| 1019 |
u=ev['username']
|
| 1020 |
+
sender.on_sticky=self._remember_sender_mode
|
| 1021 |
+
sender.on_sticky_pending=self._remember_pending_sender_mode
|
| 1022 |
+
sender.on_sticky_clear=self._clear_sender_mode
|
| 1023 |
+
forced=self.forced_mode(u)
|
| 1024 |
+
saved_mode=str(ev.get('sender_mode') or self._sender_sticky.get(u) or '')
|
| 1025 |
+
pending=self._sender_pending.get(u)
|
| 1026 |
+
pending_mode=str(ev.get('sender_pending_mode') or (pending[0] if pending else '') or '')
|
| 1027 |
+
pending_reason=str(ev.get('sender_pending_reason') or (pending[1] if pending else '') or '')
|
| 1028 |
+
selected_mode=self.send_mode_setting() or os.getenv('YOUTUBE_SEND_MODE','auto').strip().lower()
|
| 1029 |
+
explicit_mode=selected_mode if selected_mode in ('matchgop','fixed720','fixed1080') else ''
|
| 1030 |
+
requested_mode=forced or saved_mode or explicit_mode
|
| 1031 |
+
use_pending=False
|
| 1032 |
+
if requested_mode:
|
| 1033 |
+
if not hub.reserve_light(u):
|
| 1034 |
+
self.event_note(key,'ينتظر خانة ترميز موثوقة؛ لن نرجع إلى COPY غير المستقر لهذا الحساب')
|
| 1035 |
+
self.log(u,'[RELAY] @%s waiting: %s needs a free YOUTUBE_LIGHT_MAX slot'%(u,requested_mode))
|
| 1036 |
+
return
|
| 1037 |
+
elif pending_mode:
|
| 1038 |
+
if hub.reserve_light(u):
|
| 1039 |
+
requested_mode=pending_mode
|
| 1040 |
+
use_pending=True
|
| 1041 |
+
else:
|
| 1042 |
+
sender.pending_sticky=(pending_mode,pending_reason)
|
| 1043 |
+
if forced:
|
| 1044 |
+
saved_mode=forced
|
| 1045 |
+
self._sender_sticky[u]=forced
|
| 1046 |
+
if pending_mode:
|
| 1047 |
+
self._sender_pending.pop(u,None)
|
| 1048 |
+
self.event_update(key,sender_pending_mode='',sender_pending_reason='')
|
| 1049 |
+
elif use_pending:
|
| 1050 |
+
saved_mode=pending_mode
|
| 1051 |
+
self._sender_pending.pop(u,None)
|
| 1052 |
+
self._remember_sender_mode(u,pending_mode,ev.get('sender_canvas_width',0),ev.get('sender_canvas_height',0))
|
| 1053 |
+
elif (explicit_mode or saved_mode) and pending_mode:
|
| 1054 |
+
self._sender_pending.pop(u,None)
|
| 1055 |
+
self.event_update(key,sender_pending_mode='',sender_pending_reason='')
|
| 1056 |
+
if saved_mode:
|
| 1057 |
+
self._sender_sticky[u]=saved_mode
|
| 1058 |
+
sender.sticky_mode=saved_mode
|
| 1059 |
sender.sticky_since=time.monotonic()
|
| 1060 |
+
# Only an operator-forced mode is locked against copy probes; a
|
| 1061 |
+
# health/format-triggered sticky must be able to earn its way back.
|
| 1062 |
+
sender.sticky_operator_locked=bool(forced)
|
| 1063 |
+
gw,gh=self._sender_gop.get(u,(ev.get('sender_canvas_width',0),ev.get('sender_canvas_height',0)))
|
| 1064 |
sender._gop_w,sender._gop_h=int(gw or 0),int(gh or 0)
|
| 1065 |
+
elif pending_mode and not use_pending and not explicit_mode:
|
| 1066 |
+
sender.pending_sticky=(pending_mode,pending_reason)
|
| 1067 |
sender.set_probe(self.codec_probe)
|
| 1068 |
# حين تبدأ الحافة بقبولنا فعلًا يُمسح العقاب وأثره — لا يُتركان حتى أول انقطاع لاحق
|
| 1069 |
sender.on_stable=lambda u=ev['username']: self.mark_stream_stable(u)
|
| 1070 |
sender.mode_override=self.send_mode_setting() or None
|
| 1071 |
+
if forced:
|
| 1072 |
+
self.log(u,'[RELAY] @%s forced reliability mode: %s (stable H.264/AAC/GOP)'%(u,forced))
|
| 1073 |
thread=threading.Thread(target=self.sender_loop,
|
| 1074 |
args=(key,ev['username'],ev['room_id'],destination,stop,sender),daemon=True)
|
| 1075 |
self.senders[key]={'thread':thread,'stop':stop,'sender':sender}
|
|
|
|
| 1103 |
if not since:
|
| 1104 |
entry['idle_since']=time.monotonic()
|
| 1105 |
continue
|
| 1106 |
+
# A brand-new supervisor may legitimately spend tens of seconds probing
|
| 1107 |
+
# several signed renditions before FFmpeg exists. A supervisor that has
|
| 1108 |
+
# already received media and then lost its child should recover quickly.
|
| 1109 |
+
try:snap=snd.snapshot() if snd else {}
|
| 1110 |
+
except Exception:snap={}
|
| 1111 |
+
had_media=bool(snap.get('last_source_at') or snap.get('output_seconds') or
|
| 1112 |
+
getattr(snd,'last_exit_code',None) is not None)
|
| 1113 |
+
idle_limit=(max(3.0,float(os.getenv('YOUTUBE_DEAD_FFMPEG_RECYCLE_SECONDS','5')))
|
| 1114 |
+
if had_media else
|
| 1115 |
+
max(30.0,float(os.getenv('YOUTUBE_SUPERVISOR_START_SECONDS','120'))))
|
| 1116 |
+
if time.monotonic()-since<idle_limit:
|
| 1117 |
continue
|
| 1118 |
self.log(ev.get('username') or key,
|
| 1119 |
+
'[RELAY] @%s sender thread without FFmpeg for %.0fs; recycle'%
|
| 1120 |
+
(ev.get('username'),idle_limit))
|
| 1121 |
if not self.stop_sender(key):
|
| 1122 |
continue
|
| 1123 |
self.start_sender(key); n+=1
|
|
|
|
| 1146 |
user=(self.journal.read()['events'].get(key) or {}).get('username')
|
| 1147 |
if entry['thread'].is_alive():
|
| 1148 |
entry['thread'].join(timeout=3)
|
| 1149 |
+
if entry['thread'].is_alive():
|
| 1150 |
+
# A network read can outlive its advertised timeout. Keeping that stopped
|
| 1151 |
+
# supervisor in `senders`/RelayHub blocked every replacement forever: the
|
| 1152 |
+
# production symptom was LIVE + YouTube noData + no FFmpeg PID for 14+ min.
|
| 1153 |
+
# The stop flag fences the old loop (it checks it before every new send), so
|
| 1154 |
+
# detach its dead FFmpeg slot and let a fresh supervisor recover the event.
|
| 1155 |
+
self.log(user or key,'[WATCHDOG] sender did not exit in 3s; detach stopped supervisor and recover')
|
| 1156 |
self.senders.pop(key,None)
|
| 1157 |
if user:hub.release(user,'oauth')
|
| 1158 |
return True
|
|
|
|
| 1161 |
failure, refresh the ranked sources when a signed URL has expired, and reconnect at
|
| 1162 |
once when the source resolution changed. Exponential backoff replaces the fixed 15s
|
| 1163 |
loop so a persistent fault stops hammering TikTok and YouTube."""
|
|
|
|
| 1164 |
while not stop.is_set() and not self.shutdown.is_set():
|
| 1165 |
try:
|
| 1166 |
try:obs=self._observe(user, allow_hold=user not in self._skip_hold)
|
|
|
|
| 1208 |
session_started=time.monotonic()
|
| 1209 |
candidates=self._select_source(user,obs)
|
| 1210 |
prev=getattr(sender,'current_candidate',None) or {}
|
| 1211 |
+
pin=self._source_pin(prev) if self._source_pin(prev).strip('|') else (self._rendition_pin.get(user) or '')
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1212 |
if pin.strip('|') and candidates:
|
| 1213 |
+
same=[c for c in candidates if self._source_pin(c)==pin]
|
| 1214 |
if same:
|
| 1215 |
rest=[c for c in candidates if c not in same]
|
| 1216 |
candidates=same+rest
|
| 1217 |
else:
|
| 1218 |
+
# The exact rendition vanished. Prefer same-or-lower pixels, but do not
|
| 1219 |
+
# leave YouTube with no publisher merely to preserve a quality label.
|
| 1220 |
+
old_pixels=self._source_pixels(prev)
|
| 1221 |
+
lower=[c for c in candidates if not old_pixels or
|
| 1222 |
+
(self._source_pixels(c) and self._source_pixels(c)<=old_pixels)]
|
| 1223 |
+
higher=[c for c in candidates if c not in lower]
|
| 1224 |
+
candidates=lower+higher
|
| 1225 |
+
self.log(user,'[SOURCE] المصدر المثبت اختفى؛ نجرب جودة مساوية/أقل بدل ترك يوتيوب متوقفًا')
|
| 1226 |
if not candidates:
|
| 1227 |
self.log(user,'لا مرشح فيديو صالح لهذه الدورة؛ سيُحدَّث المصدر تلقائيًا')
|
| 1228 |
stop.wait(self._backoff(user));continue
|
|
|
|
| 1235 |
destination = self.destinations.get(user) or destination
|
| 1236 |
try:
|
| 1237 |
self.log(user,'[RELAY] @%s starting (%s)'%(user,self._source_brief(candidate)))
|
| 1238 |
+
sender.telemetry_context={'event_key':key,'room_id':room_id,
|
| 1239 |
+
'broadcast_id':(self.journal.read()['events'].get(key) or {}).get('broadcast_id','')}
|
| 1240 |
+
if sender.send(user,candidate,destination,stop,
|
| 1241 |
+
refresh=lambda: self._refresh_flv(user,getattr(sender,'current_candidate',None))):
|
| 1242 |
sent=True
|
| 1243 |
+
self._rendition_pin[user]=self._source_pin(getattr(sender,'current_candidate',None) or candidate)
|
| 1244 |
sender.lock_gold(candidate)
|
| 1245 |
gw,gh=int(getattr(sender,'_gop_w',0) or 0), int(getattr(sender,'_gop_h',0) or 0)
|
| 1246 |
if gw>=16 and gh>=16:
|
|
|
|
| 1252 |
if candidate is not None:self.mark_unstable(user,candidate,'start failed')
|
| 1253 |
continue
|
| 1254 |
except SourceStalled as e:
|
| 1255 |
+
if getattr(sender,'last_failure_side','') == 'output':
|
| 1256 |
+
# The source meter also ages while FFmpeg is blocked opening/writing
|
| 1257 |
+
# RTMPS. Do not poison TikTok candidates or jump to HLS for a YouTube
|
| 1258 |
+
# output failure; _note_early_exit refreshes/normalizes that side.
|
| 1259 |
+
self.log(user,'[WATCHDOG] @%s RTMPS output stalled (%s)'%
|
| 1260 |
+
(user,self.safe_error(e)[:100]))
|
| 1261 |
+
stalled=False
|
| 1262 |
+
break
|
| 1263 |
# Signed URLs in the hold cache are stale once bytes stop. Drop the
|
| 1264 |
# hold so the next observe is honest (real Offline vs PK blip).
|
| 1265 |
self._held.pop(user, None)
|
|
|
|
| 1271 |
self._skip_probe_once[user]=True
|
| 1272 |
self.retry[user]=self.retry_min
|
| 1273 |
break
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1274 |
except Exception as e:
|
| 1275 |
self.log(user,'تعثر إرسال الفيديو؛ نفس الحدث سيُستخدم — '+self.safe_error(e)[:160])
|
| 1276 |
+
if sent or getattr(sender,'last_failure_side','') == 'output':break
|
| 1277 |
self._note_early_exit(user, sender, time.monotonic() - session_started)
|
| 1278 |
if stalled:
|
| 1279 |
# المصدر صامت الآن: دورة قصيرة ثم رصد جديد، لا نقر متواصل على CDN ميت.
|
| 1280 |
if stop.wait(0.5):return
|
| 1281 |
continue
|
| 1282 |
+
paced=float(self._publish_wait.get(user,0) or 0)
|
| 1283 |
+
# تهدئة النشر تسبق حتى «أُرسل بنجاح»: جلسة سلّمت ثم ماتت بخرج ميت تحتاج
|
| 1284 |
+
# تحرير مقعد يوتيوب مثلها مثل التي لم تُسلّم — وإلا عادت العاصفة من باب sent.
|
| 1285 |
+
self.retry[user]=paced if paced else (self.retry_min if sent else min(self.retry_max,self._backoff(user)*2))
|
| 1286 |
if sent and sender.alive():
|
| 1287 |
# FFmpeg owns the connection now; only watch for it ending.
|
| 1288 |
sender.wait_until(lambda:sender.alive(),stop)
|
| 1289 |
self.retry[user]=self.retry_min
|
| 1290 |
except Exception as e:self.log(user,'تعذر تحديث مصدر الإرسال؛ لا ننشئ حدثًا إضافيًا — '+self.safe_error(e)[:160])
|
|
|
|
|
|
|
| 1291 |
gap=float(getattr(sender,'last_source_gap',0) or 0)
|
| 1292 |
+
output_side=getattr(sender,'last_failure_side','') == 'output'
|
| 1293 |
+
wait=0.5 if gap>=8 and not output_side else self._backoff(user)
|
| 1294 |
if stop.wait(wait):return
|
| 1295 |
def mark_stream_stable(self, user):
|
| 1296 |
"""الحافة تقبل التدفق: تُرمى نافذة العقاب وملاحظتها وعدّادها. تُستدعى من المرسل عند أول
|
|
|
|
| 1300 |
# 25 ث مُسلَّمة تُثبت أن المسار الحالي يكفي: يُلغى تناوب النقل الذي فرضه الجوع
|
| 1301 |
self.starve.pop(user, None)
|
| 1302 |
self._skip_hold.discard(user)
|
| 1303 |
+
# مسار أثبت نفسه: تُنسى إخفاقات الفتح وحظر المسارات (قد يتعافى البديل لاحقًا)
|
| 1304 |
+
self._ingest_open_failures.pop(user, None)
|
| 1305 |
+
self._ingest_route_blocked.pop(user, None)
|
| 1306 |
+
self._publish_wait.pop(user, None)
|
| 1307 |
cleared = 0
|
| 1308 |
for k in list(self.retry_at):
|
| 1309 |
if self.journal.read()['events'].get(k, {}).get('username') == user:
|
|
|
|
| 1327 |
كان يُبقي الحدث «noData» ويحرق الوقت بلا فائدة. نُبطئ النقر تصاعديًا حتى 120ث، ونُصفّر
|
| 1328 |
العدّ عند أول جلسة دامت ≥25ث (الاستقبال صار يقبلنا). صمت المصدر له مسار آخر: `stalled`."""
|
| 1329 |
code = getattr(sender, 'last_exit_code', None)
|
| 1330 |
+
output_side = getattr(sender, 'last_failure_side', '') == 'output'
|
| 1331 |
+
if code is None and not output_side:
|
| 1332 |
return # لم تخرج العملية وحدَها: لا حكم على الوجهة
|
| 1333 |
gap = float(getattr(sender, 'last_source_gap', 0.0) or 0.0)
|
| 1334 |
+
if gap >= float(os.getenv('YOUTUBE_SOURCE_GAP_SUSPECT_SECONDS', '8')) and not output_side:
|
| 1335 |
# جوع مصدر لا رفض وجهة: التأجيل هنا يطيل أمد الصمت الذي يراه المشاهدون. نُسرّع
|
| 1336 |
# الرصد بدل ذلك (رابط FLV موقّع جديد) ونُبقي الوتيرة الطبيعية.
|
| 1337 |
# جوعٌ موثّق بالقياس يزيد عدّاد التناوب: بعد جوعين يُقدَّم مرشح غير FLV (انظر _select_source)
|
|
|
|
| 1345 |
% (gap, code, '؛ أُلغي تأجيل سابق' if was is not None else ''))
|
| 1346 |
self.retry[user] = self.retry_min
|
| 1347 |
return
|
| 1348 |
+
if not output_side:
|
| 1349 |
+
self._publish_wait.pop(user,None)
|
| 1350 |
+
if output_side and self._never_opened(sender):
|
| 1351 |
+
# مسار لم يفتح الاتصال أصلًا (TLS/وصول، لا إطار واحد): عقوبات «الوجهة أغلقت
|
| 1352 |
+
# بعد بدء النشر» لا تنطبق — العنوان غير قابل للوصول من هنا الآن. محاولة فتح
|
| 1353 |
+
# ثانية مُهدَّأة، ثم تدوير قسري إلى المسار الآخر وحظر هذا المسار.
|
| 1354 |
+
opens=int(self._ingest_open_failures.get(user,0) or 0)+1
|
| 1355 |
+
self._ingest_open_failures[user]=opens
|
| 1356 |
+
if opens>=2 and self.rotate_ingest_route(user):
|
| 1357 |
+
self.hammer.pop(user,None)
|
| 1358 |
+
for k,ev in self.journal.read()['events'].items():
|
| 1359 |
+
if ev.get('username')==user and str(ev.get('note') or '').startswith('إعادة الاتصال مؤجّلة'):
|
| 1360 |
+
self.event_note(k,'')
|
| 1361 |
+
self._pace_publish(user,2)
|
| 1362 |
+
return
|
| 1363 |
+
if opens==1:
|
| 1364 |
+
self._pace_publish(user,1)
|
| 1365 |
+
self.log(user,'[WATCHDOG] مسار الاستقبال الحالي لم يفتح الاتصال أصلًا (لا إطار مُرسل)؛ محاولة فتح ثانية مُهدَّأة قبل الحكم على المسار')
|
| 1366 |
+
return
|
| 1367 |
+
# تعذّر التدوير (تغيّرت الملكية؟): يكمل مسار العقوبات الطبيعي أدناه
|
| 1368 |
if lasted >= 25:
|
| 1369 |
+
# نفس الدالة التي يستدعيها المرسل وهو يعمل: نسخة واحدة من التعافي لا نسختان.
|
| 1370 |
+
# A confirmed output failure still becomes attempt #1 after clearing old history;
|
| 1371 |
+
# otherwise every receiver drop after a long run is forgotten and a 10-second
|
| 1372 |
+
# reconnect storm can never reach the normalization path.
|
| 1373 |
self.mark_stream_stable(user)
|
| 1374 |
+
if not output_side:
|
| 1375 |
+
return
|
| 1376 |
n = self.hammer.get(user, 0) + 1
|
| 1377 |
self.hammer[user] = n
|
| 1378 |
+
if output_side and n == 1:
|
| 1379 |
+
sender.trace_rtmp=True # Redacted handshake evidence on the next startup.
|
| 1380 |
+
# First confirmed output-side failure: re-read the API-owned ingest/key before
|
| 1381 |
+
# changing codecs. This is cheap, safe, and rules out stale in-memory routing.
|
| 1382 |
+
self.destinations.pop(user, None)
|
| 1383 |
+
try:
|
| 1384 |
+
self.ensure_stream(user)
|
| 1385 |
+
self.log(user, '[WATCHDOG] فشل خرج RTMPS؛ أُعيدت قراءة عنوان الاستقبال ومفتاحه من YouTube API')
|
| 1386 |
+
except Exception as e:
|
| 1387 |
+
self.log(user, '[WATCHDOG] تعذر تحديث عنوان الاستقبال بعد فشل الخرج: '+self.safe_error(e)[:100])
|
| 1388 |
+
if output_side and n == 2 and self.switch_ingest_route(user):
|
| 1389 |
+
self._pace_publish(user,2)
|
| 1390 |
+
return
|
| 1391 |
+
if output_side and (n == 2 or (n == 3 and self._ingest_preferred.get(user))):
|
| 1392 |
+
try:snap=sender.snapshot() or {}
|
| 1393 |
+
except Exception:snap={}
|
| 1394 |
+
mode=str(snap.get('send_mode') or sender.send_mode() or '')
|
| 1395 |
+
if float(snap.get('source_bytes') or 0) > 0 and mode in ('','auto','copy'):
|
| 1396 |
+
if sender.request_sticky('matchgop', user,
|
| 1397 |
+
'تكرر رفض/انسداد خرج RTMPS مع وصول المصدر — توحيد H.264/AAC وGOP قبل المحاولة التالية'):
|
| 1398 |
+
self._sender_sticky[user]='matchgop'
|
| 1399 |
+
self._pace_publish(user,n)
|
| 1400 |
+
self.log(user, '[RECOVERY] سيُعاد الإرسال فورًا بـ matchgop ثابت بدل تكرار COPY المرفوض')
|
| 1401 |
+
return
|
| 1402 |
# حالة الحدث تُبدّل الحكم: إن لم يكن قد شُغِّل بعد (ready/created) فالحافة لا تقبل نشرًا
|
| 1403 |
# على حدث متوقف — الإغلاق عند ~12 ث هنا عرض لا علة، وتجديد المفتاح لن يغيّر شيئًا.
|
| 1404 |
_evs = [ev for ev in self.journal.read()['events'].values() if ev.get('username') == user]
|
|
|
|
| 1415 |
self.log(user, '[WATCHDOG] الحدث لم يبدأ بعد (youtube_status=%s): لا نُجدّد المفتاح — النشر '
|
| 1416 |
'لا يُقبل قبل تشغيل الحدث؛ سيُعاد المحاولة بوتيرة أبطأ حتى يبدأ'
|
| 1417 |
% (_evs[0].get('youtube_status') if _evs else '؟'))
|
| 1418 |
+
if n == 3 and not not_started and (output_side or gap < float(os.getenv('YOUTUBE_SOURCE_GAP_SUSPECT_SECONDS', '8'))):
|
| 1419 |
# المصدر يرسل والوجهة ما زالت تقفل: الشكّ في المفتاح لا في البث. نُجه��ل العنوان ليُعاد
|
| 1420 |
# قراءته من YouTube API في start_sender — قراءة واحدة، بلا إنشاء ولا تعديل حالة الحدث.
|
| 1421 |
if self.destinations.pop(user, None):
|
|
|
|
| 1429 |
except Exception as e:
|
| 1430 |
self.log(user, '[WATCHDOG] تعذر تجديد عنوان الاستقبال: ' + self.safe_error(e)[:120])
|
| 1431 |
if n >= 3:
|
| 1432 |
+
# تهدئة مقعد الاستقبال بسقف 20 ث (كانت تتصاعد 20/40/80/120 فتطيل غياب
|
| 1433 |
+
# المشاهدين دقائق بعد أن يكون المصدر قد عاد منذ زمن).
|
| 1434 |
+
wait = self._pace_publish(user, n) # يقفل start_sender من tick() نفسه
|
|
|
|
|
|
|
|
|
|
| 1435 |
self.log(user, '[WATCHDOG] الوجهة أغلقت الاتصال بعد %.0f ث (رمز %s) — المرة %d: تأجيل إعادة الاتصال إلى %d ث بدل النقر على حافة ترفض%s'
|
| 1436 |
% (lasted, code, n, int(self._backoff(user)),
|
| 1437 |
'؛ السبب المعلوم: الحدث لم يُشغَّل بعد' if not_started else ''))
|
| 1438 |
+
elif output_side:
|
| 1439 |
+
self._pace_publish(user, n)
|
| 1440 |
return
|
| 1441 |
|
| 1442 |
def _backoff(self,user):
|
|
|
|
| 1455 |
media=(candidate or {}).get('media') or 'flv'
|
| 1456 |
want=self._source_magic(media);got=bytearray()
|
| 1457 |
r=requests.get(candidate['url'],impersonate='chrome',
|
| 1458 |
+
headers=source_http_headers(candidate.get('url'),user,self.headers_for),stream=True,timeout=20)
|
| 1459 |
try:
|
| 1460 |
r.raise_for_status()
|
| 1461 |
for chunk in r.iter_content():
|
|
|
|
| 1477 |
# Local paths reject HTTP-only options, exactly like FFmpeg does.
|
| 1478 |
args+=['-reconnect','1','-rw_timeout','10000000']
|
| 1479 |
hdr=''.join('%s: %s\r\n'%(k,v) for k,v in
|
| 1480 |
+
source_http_headers(url,(candidate or {}).get('user'),self.headers_for).items() if v)
|
|
|
|
| 1481 |
if hdr:args+=['-headers',hdr]
|
| 1482 |
try:
|
| 1483 |
r=subprocess.run(args+['-i',url],capture_output=True,text=True,timeout=45)
|
|
|
|
| 1496 |
return '|'.join([str(c.get('quality_name') or ''), str(c.get('media') or ''),
|
| 1497 |
str(c.get('codec') or ''), str(c.get('resolution') or '')])
|
| 1498 |
@staticmethod
|
| 1499 |
+
def _source_pin(c):
|
| 1500 |
+
c=c or {}
|
| 1501 |
+
return '|'.join([str(c.get('quality_name') or c.get('label') or '').strip().lower(),
|
| 1502 |
+
str(c.get('width') or ''),str(c.get('height') or ''),str(c.get('media') or '')])
|
| 1503 |
+
@staticmethod
|
| 1504 |
+
def _source_pixels(c):
|
| 1505 |
+
try:return max(0,int((c or {}).get('width') or 0))*max(0,int((c or {}).get('height') or 0))
|
| 1506 |
+
except (TypeError,ValueError):return 0
|
| 1507 |
+
@staticmethod
|
| 1508 |
+
def _codec_family(c):
|
| 1509 |
+
text=(str((c or {}).get('codec') or '')+' '+str((c or {}).get('label') or '')).lower()
|
| 1510 |
+
if any(x in text for x in ('h265','hevc','hvc1','265')):return 'h265'
|
| 1511 |
+
if any(x in text for x in ('h264','avc','264')):return 'h264'
|
| 1512 |
+
return ''
|
| 1513 |
+
@staticmethod
|
| 1514 |
def _source_brief(c):
|
| 1515 |
return str(c.get('brief') or c.get('label') or 'source')
|
| 1516 |
def mark_unstable(self,user,candidate,why=''):
|
| 1517 |
key=self._source_key(candidate)
|
| 1518 |
self._unstable.setdefault(user,set()).add(key)
|
| 1519 |
self.log(user,'[SOURCE] @%s source %s unstable%s'%(user,self._source_brief(candidate),(' — '+why) if why else ''))
|
| 1520 |
+
def _refresh_flv(self,user,current=None):
|
| 1521 |
+
"""Splice a fresh same-codec FLV into the existing FFmpeg/RTMP publisher.
|
| 1522 |
|
| 1523 |
+
Prefer a fresh URL for the pinned rendition. If TikTok still returns the exact stalled
|
| 1524 |
+
URL, fall down to the nearest lower rendition instead of freezing viewers or reopening
|
| 1525 |
+
YouTube. After a long stable interval, a later natural refresh may restore the preferred
|
| 1526 |
+
rendition. HLS and H.264↔H.265 changes cannot be spliced into this open FFmpeg map.
|
| 1527 |
"""
|
| 1528 |
+
# A normal CDN EOF is not evidence that its signed URL expired. The manager
|
| 1529 |
+
# already refreshes live observations continuously. Try a recent verified same-codec
|
| 1530 |
+
# source first instead of blocking this publisher on 20s metadata requests while
|
| 1531 |
+
# YouTube starves. Stale/absent/incompatible snapshots still force a fresh lookup.
|
| 1532 |
+
obs=None
|
| 1533 |
+
held=self._held.get(user)
|
| 1534 |
+
family=self._codec_family(current)
|
| 1535 |
+
if held and self.hold_seconds>0 and time.monotonic()-held[0]<=min(45.0,self.hold_seconds):
|
| 1536 |
+
cached=held[1] or {}
|
| 1537 |
+
if cached.get('status')=='live' and any(
|
| 1538 |
+
c.get('url') and c.get('media')!='hls' and
|
| 1539 |
+
(not family or self._codec_family(c)==family)
|
| 1540 |
+
for c in self.video_sources(cached.get('sources') or [])):
|
| 1541 |
+
obs=cached
|
| 1542 |
+
if obs is None:
|
| 1543 |
+
self._held.pop(user, None)
|
| 1544 |
+
self._skip_hold.add(user)
|
| 1545 |
+
try:
|
| 1546 |
+
obs=self._observe(user, force=True, bypass_throttle=True, allow_hold=False)
|
| 1547 |
+
except Exception:
|
| 1548 |
+
return None
|
| 1549 |
if (obs or {}).get('status')!='live':
|
| 1550 |
return None
|
| 1551 |
+
# We are already inside a three-second source gap. Probing every rendition serially can
|
| 1552 |
+
# add 15–60 seconds of black screen; the relay opens the selected URL immediately anyway.
|
| 1553 |
+
self._skip_probe_once[user]=True
|
| 1554 |
ordered=self._select_source(user, obs) or []
|
| 1555 |
+
family=self._codec_family(current)
|
| 1556 |
+
if family:
|
| 1557 |
+
ordered=[c for c in ordered if self._codec_family(c)==family]
|
| 1558 |
+
if not ordered:
|
| 1559 |
+
self.log(user,'[SOURCE] لا نُدخل تبدل H.264/H.265 في خريطة FFmpeg مفتوحة؛ ننتظر نفس الترميز')
|
| 1560 |
+
return None
|
| 1561 |
+
flv=[c for c in ordered if c.get('media')!='hls' and c.get('url')]
|
| 1562 |
+
if not flv:return None
|
| 1563 |
+
pin=self._source_pin(current)
|
| 1564 |
+
if not pin.strip('|'):pin=self._rendition_pin.get(user) or ''
|
| 1565 |
+
now=time.monotonic();state=self._quality_fallback.get(user) or {}
|
| 1566 |
+
try:upgrade_after=max(60.0,float(os.getenv('YOUTUBE_SOURCE_UPGRADE_SECONDS','300')))
|
| 1567 |
+
except (TypeError,ValueError):upgrade_after=300.0
|
| 1568 |
+
|
| 1569 |
+
# Restore quality only while we already have to refresh a source. Deliberately do not
|
| 1570 |
+
# close a healthy lower feed just to gain pixels: continuity has priority over sharpness.
|
| 1571 |
+
if state and now-float(state.get('since') or now)>=upgrade_after:
|
| 1572 |
+
better=[c for c in flv if self._source_pin(c)==state.get('preferred_pin')]
|
| 1573 |
+
if better:
|
| 1574 |
+
chosen=better[0];self._quality_fallback.pop(user,None)
|
| 1575 |
+
self._rendition_pin[user]=self._source_pin(chosen)
|
| 1576 |
+
log_event(user,'SOURCE_CHANGE',{'reason':'stable_quality_restore',
|
| 1577 |
+
'old_quality':str((current or {}).get('quality_name') or ''),
|
| 1578 |
+
'new_quality':str(chosen.get('quality_name') or ''),
|
| 1579 |
+
'old_width':(current or {}).get('width'),'old_height':(current or {}).get('height'),
|
| 1580 |
+
'new_width':chosen.get('width'),'new_height':chosen.get('height'),
|
| 1581 |
+
'codec':self._codec_family(chosen),'outbound_rtmp_reused':True})
|
| 1582 |
+
return chosen
|
| 1583 |
+
|
| 1584 |
+
same=[c for c in flv if self._source_pin(c)==pin] if pin.strip('|') else []
|
| 1585 |
+
current_url=str((current or {}).get('url') or '')
|
| 1586 |
+
fresh_same=[c for c in same if str(c.get('url') or '')!=current_url]
|
| 1587 |
+
if fresh_same:
|
| 1588 |
+
chosen=fresh_same[0];self._rendition_pin[user]=self._source_pin(chosen)
|
| 1589 |
+
return chosen
|
| 1590 |
+
|
| 1591 |
+
# The pinned URL itself is still the one that just stopped producing bytes. Choose the
|
| 1592 |
+
# best same-codec rendition that is no larger; only use a larger one when nothing else
|
| 1593 |
+
# exists, because some moving picture is safer than a dead publisher.
|
| 1594 |
+
alternatives=[c for c in flv if self._source_pin(c)!=pin]
|
| 1595 |
+
pixels=self._source_pixels(current)
|
| 1596 |
+
lower=[c for c in alternatives if not pixels or (self._source_pixels(c) and self._source_pixels(c)<pixels)]
|
| 1597 |
+
chosen=(lower or alternatives or same)[0] if (lower or alternatives or same) else None
|
| 1598 |
+
if not chosen:return None
|
| 1599 |
+
chosen_pin=self._source_pin(chosen)
|
| 1600 |
+
if chosen_pin!=pin:
|
| 1601 |
+
self._quality_fallback[user]={'preferred_pin':state.get('preferred_pin') or pin,
|
| 1602 |
+
'since':state.get('since') or now}
|
| 1603 |
+
self._rendition_pin[user]=chosen_pin
|
| 1604 |
+
log_event(user,'SOURCE_CHANGE',{'reason':'stalled_rendition_fallback',
|
| 1605 |
+
'old_quality':str((current or {}).get('quality_name') or ''),
|
| 1606 |
+
'new_quality':str(chosen.get('quality_name') or ''),
|
| 1607 |
+
'old_width':(current or {}).get('width'),'old_height':(current or {}).get('height'),
|
| 1608 |
+
'new_width':chosen.get('width'),'new_height':chosen.get('height'),
|
| 1609 |
+
'codec':self._codec_family(chosen),'outbound_rtmp_reused':True})
|
| 1610 |
+
self.log(user,'[SOURCE] المصدر المثبت صامت؛ هبوط إلى %s داخل جلسة يوتيوب نفسها'%self._source_brief(chosen))
|
| 1611 |
+
return chosen
|
| 1612 |
def _select_source(self,user,obs):
|
| 1613 |
"""All relayable renditions, stable first. Never drop a working lower-quality source."""
|
| 1614 |
candidates=self.video_sources(obs.get('sources') or [])
|
|
|
|
| 1649 |
return usable
|
| 1650 |
def _republish_allowed(self,key,entry):
|
| 1651 |
"""True when the earlier broadcast of this very session is over (so re-publishing is right)."""
|
| 1652 |
+
if not self._history_on_channel(entry,self.journal.read().get('channel')):return True
|
| 1653 |
if time.time()-float(entry.get('ended_at') or 0)<float(os.getenv('YOUTUBE_REPUBLISH_AFTER','120')):
|
| 1654 |
return False # too soon: the old session may still be settling
|
| 1655 |
bid=entry.get('broadcast_id')
|
|
|
|
| 1667 |
_republish_allowed refuses a second event, and nobody reattaches a publisher.
|
| 1668 |
Restore the same broadcast_id so the watch URL does not change.
|
| 1669 |
"""
|
| 1670 |
+
if not self._history_on_channel(entry,self.journal.read().get('channel')):return False
|
| 1671 |
if not obs.get('room_id'):return False
|
| 1672 |
key=user+':'+str(obs.get('room_id') or '')
|
| 1673 |
if self.journal.read()['events'].get(key):
|
|
|
|
| 1707 |
'resume_trusted':True}
|
| 1708 |
def change(d):
|
| 1709 |
d['events'][key]=ev
|
| 1710 |
+
d['history']=[h for h in d['history'] if h.get('session_key')!=key
|
| 1711 |
+
or not self._history_on_channel(h,d.get('channel'))]
|
| 1712 |
self.journal.change(change)
|
| 1713 |
try:self.ensure_stream(user)
|
| 1714 |
except Exception as e:
|
|
|
|
| 1771 |
if self.max_events>0 and len(d['events'])>=self.max_events:
|
| 1772 |
return False
|
| 1773 |
key=user+':'+str(obs['room_id'])
|
| 1774 |
+
entry=self._history_entry(key,d)
|
| 1775 |
if entry is not None:
|
| 1776 |
if not self._republish_allowed(key,entry):
|
| 1777 |
if self._resume_archived_event(user,obs,entry):
|
| 1778 |
return True
|
| 1779 |
+
self._forget_history(key)
|
| 1780 |
self.log(user,'[RELAY] @%s archived YouTube event not resumable; opening a new event'%user)
|
| 1781 |
else:
|
| 1782 |
+
self._forget_history(key)
|
| 1783 |
found=self._find_open_broadcast(user)
|
| 1784 |
if found:
|
| 1785 |
fake={'broadcast_id':found.get('id'),'nickname':user,
|
|
|
|
| 1889 |
self.last_seen_status[user]=obs['status']
|
| 1890 |
key=user+':'+obs['room_id']
|
| 1891 |
if key in d['events']:continue
|
| 1892 |
+
entry=self._history_entry(key,d)
|
| 1893 |
if entry is not None:
|
| 1894 |
# The history entry stops a *duplicate* broadcast of one session. It must not
|
| 1895 |
# keep a broadcaster off the air after the earlier broadcast died: an app
|
|
|
|
| 1901 |
continue
|
| 1902 |
# Resume failed (API error, missing marker). Do not leave TikTok LIVE
|
| 1903 |
# with no publisher: drop the history lock and open a new event.
|
| 1904 |
+
self._forget_history(key)
|
| 1905 |
self.log(user,'[RELAY] @%s archived YouTube event not resumable; opening a new event'%user)
|
| 1906 |
else:
|
| 1907 |
+
self._forget_history(key)
|
| 1908 |
self.log(user,'بثّ سابق لنفس الجلسة انتهى؛ نعيد نشر الجلسة الحالية على يوتيوب')
|
| 1909 |
# Fast confirmation: one extra fresh read in this same cycle (no extra interval).
|
| 1910 |
try:
|
|
|
|
| 2027 |
self.log(user,'[RELAY] @%s stopping (TikTok LIVE ended)'%user)
|
| 2028 |
self._unstable.pop(user,None)
|
| 2029 |
self._rendition_pin.pop(user,None)
|
| 2030 |
+
self._quality_fallback.pop(user,None)
|
| 2031 |
self._sender_sticky.pop(user,None)
|
| 2032 |
self._sender_gop.pop(user,None)
|
| 2033 |
+
self._sender_pending.pop(user,None)
|
| 2034 |
self._live_confirm.pop(user,None)
|
| 2035 |
self.finish_event(key)
|
| 2036 |
self.log(user,'[CLEANUP] @%s complete'%user)
|
|
|
|
| 2146 |
self.stream_health(key,user,ev)
|
| 2147 |
return
|
| 2148 |
|
| 2149 |
+
if life in ('liveStarting','testStarting'):
|
| 2150 |
+
# YouTube completes this transition only while ingest stays active. Stopping
|
| 2151 |
+
# FFmpeg here created a deadlock: liveStarting -> stop -> no frames -> never live.
|
| 2152 |
+
# Resume/keep the SAME owned publisher and poll; do not repeat transition POSTs
|
| 2153 |
+
# or apply the pre-start timeout to an already accepted transition.
|
| 2154 |
+
self.start_sender(key)
|
| 2155 |
+
self.event_update(key,phase='starting')
|
| 2156 |
+
self.event_note(key,'يوتيوب يُكمل مرحلة بدء الحدث؛ نُبقي الإرسال حتى تأكيد الحالة المباشرة')
|
| 2157 |
+
self.stream_health(key,user,ev)
|
| 2158 |
+
return
|
| 2159 |
+
|
| 2160 |
# life is expected to be 'ready' or 'testing' for a newly bound event
|
| 2161 |
if life not in ('ready','testing'):
|
| 2162 |
# 'created' etc. -> ingest not yet receivable, don't push (prevents 187)
|
|
|
|
| 2192 |
(videoResolutionUnsupported / videoCodec) and why playback stalls (gopSizeLong /
|
| 2193 |
openGop). Surfacing it replaces guesswork with ground truth. Polled on a slower
|
| 2194 |
cadence than the life-cycle check so it stays inside the quota budget."""
|
| 2195 |
+
interval=max(15,int(os.getenv('YOUTUBE_HEALTH_INTERVAL','20')))
|
| 2196 |
if time.time()-float(ev.get('last_health') or 0)<interval:return
|
| 2197 |
stream_id=(self.journal.read()['streams'].get(user) or {}).get('id')
|
| 2198 |
if not stream_id:return
|
|
|
|
| 2208 |
text=' | '.join(issues)
|
| 2209 |
prev=ev.get('last_issues')
|
| 2210 |
status=str(health.get('status') or '')
|
| 2211 |
+
log_event(user,'YOUTUBE_HEALTH',{'status':status or 'unknown','issues':issues,
|
| 2212 |
+
'issue_count':len(issues)})
|
| 2213 |
+
_health_entry=self.senders.get(key)
|
| 2214 |
+
_health_sender=_health_entry['sender'] if _health_entry and _health_entry.get('sender') else None
|
| 2215 |
+
if _health_sender is not None and getattr(_health_sender,'telemetry_key',None):
|
| 2216 |
+
telemetry_event(_health_sender.telemetry_key,user,'YOUTUBE_HEALTH',{
|
| 2217 |
+
'status':status or 'unknown','issues':issues,'issue_count':len(issues)},
|
| 2218 |
+
dedupe_key='youtube_health')
|
| 2219 |
self.event_update(key,youtube_health=status,youtube_issues=text,last_issues=text)
|
| 2220 |
if text and text!=prev:
|
| 2221 |
self.log(user,'يوتيوب يشخّص البث: '+text)
|
| 2222 |
+
# Mode governor: transcoding is prescribed only for faults it can
|
| 2223 |
+
# actually repair. GOP/codec/resolution faults and a noData that
|
| 2224 |
+
# persists while source bytes demonstrably flow are format faults.
|
| 2225 |
+
# videoIngestionStarved on its own is *data hunger* — re-encoding a
|
| 2226 |
+
# starved source cannot invent data and, measured live, it saturated
|
| 2227 |
+
# the CPU and made the starvation worse. The one starved exception
|
| 2228 |
+
# is a copy whose declared picture is far larger than its declared
|
| 2229 |
+
# bitrate can feed (a 1440-class signal at 720-class bitrate): a
|
| 2230 |
+
# capped constant canvas repairs exactly that mismatch.
|
| 2231 |
# Per-sender only; does not restart the Space or other publishers.
|
| 2232 |
blob=(text+' '+status).lower()
|
| 2233 |
gop_bad=any(k in blob for k in ('gopsizelong','gopsizeover','opengop'))
|
| 2234 |
+
format_bad=gop_bad or any(k in blob for k in (
|
| 2235 |
+
'videocodec','videodecoder','videoresolution','resolutionunsupported',
|
| 2236 |
+
'codecunsupported','unsupportedcodec','unsupportedresolution'))
|
| 2237 |
nodata=status.lower()=='nodata'
|
| 2238 |
starved=any(k in blob for k in ('videoingestionstarved','videooutputlow','videobitratelow'))
|
| 2239 |
entry=self.senders.get(key)
|
| 2240 |
sender=entry['sender'] if entry and entry.get('thread') and entry['thread'].is_alive() else None
|
| 2241 |
+
if sender and (format_bad or nodata or starved):
|
| 2242 |
snap=sender.snapshot() or {}
|
| 2243 |
out=float(snap.get('output_seconds') or 0)
|
| 2244 |
mode=(snap.get('send_mode') or sender.send_mode() or '')
|
| 2245 |
if out>=20 and mode in ('','auto','copy') and not sender.sticky_mode:
|
| 2246 |
+
source_flowing=float(snap.get('source_bytes') or 0)>0
|
| 2247 |
+
oversized_copy=False
|
| 2248 |
+
if starved and not format_bad:
|
| 2249 |
+
cand=getattr(sender,'current_candidate',None) or {}
|
| 2250 |
+
try:
|
| 2251 |
+
w=int(cand.get('width') or 0);h=int(cand.get('height') or 0)
|
| 2252 |
+
rate=float(cand.get('bitrate') or 0)
|
| 2253 |
+
except (TypeError,ValueError):
|
| 2254 |
+
w=h=0;rate=0.0
|
| 2255 |
+
oversized_copy=bool(w and h and max(w,h)>=1440 and 0<rate<3000)
|
| 2256 |
+
if format_bad or (nodata and source_flowing) or oversized_copy:
|
| 2257 |
+
sender.request_sticky('matchgop', user, 'YouTube %s (out=%.0fs copy not ingesting for viewers)'%(status or text[:40], out))
|
| 2258 |
def run_manager(self):
|
| 2259 |
checked=False
|
| 2260 |
last_tick=0.0
|
|
|
|
| 2268 |
if now-last_tick>=self.scan:
|
| 2269 |
self.tick()
|
| 2270 |
last_tick=now
|
| 2271 |
+
# Run the fast watchdog after *every* manager pass. Previously the
|
| 2272 |
+
# normal sleep landed exactly on the next scan, so this `else` branch
|
| 2273 |
+
# was skipped forever when a supervisor thread lived but its FFmpeg
|
| 2274 |
+
# child had died. The event then remained live/noData indefinitely.
|
| 2275 |
+
self.restart_dead_senders()
|
| 2276 |
+
# مكنسة الخمول: بلا بث لفترة مستمرة تُصفَّر بقايا التكيّف
|
| 2277 |
+
# المتراكمة مرة واحدة، والرصد نفسه لا يتوقف أبدًا (24/7).
|
| 2278 |
+
# أي فشل فيها لا يجوز أن يقتل المدير فيُبتلع بصمت تشغيلي.
|
| 2279 |
+
try:self.idle_housekeeping()
|
| 2280 |
+
except Exception:pass
|
| 2281 |
d=self.journal.read()
|
| 2282 |
if not d['enabled'] and not d['events']:self.set_status('الأتمتة معطلة؛ لا إرسال ولا إنشاء أحداث')
|
| 2283 |
+
def _dead_sender(e):
|
| 2284 |
+
th=e.get('thread');snd=e.get('sender')
|
| 2285 |
+
try:ff=bool(snd and snd.alive())
|
| 2286 |
+
except Exception:ff=False
|
| 2287 |
+
return not (th and th.is_alive() and ff)
|
| 2288 |
+
dead=any(_dead_sender(e) for e in list(self.senders.values()))
|
| 2289 |
remain=self.scan-(time.monotonic()-last_tick)
|
| 2290 |
delay=2.0 if dead else max(1.0, min(self.scan, remain if remain>0 else self.scan))
|
| 2291 |
except Exception as e:
|