JAYNESTV commited on
Commit
2bf6aca
Β·
verified Β·
1 Parent(s): c44f93f

Upload 3 files

Browse files
Files changed (3) hide show
  1. app.py +290 -0
  2. packages.txt +1 -0
  3. requirements.txt +3 -0
app.py ADDED
@@ -0,0 +1,290 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ JAYNES MAX β€” HLS Bridge (Hugging Face Space, Gradio + FastAPI + ffmpeg)
3
+
4
+ Inapokea MPD + ClearKey kutoka kwenye app, inasimbua kwa ffmpeg (bila ku-encode video)
5
+ na kuhudumia HLS (.m3u8 + .ts) ambayo iPhone/Safari inacheza asili.
6
+
7
+ POST /start {"mpd": "...", "kid": "...", "key": "..."} -> {"url": ".../hls/<id>/index.m3u8"}
8
+ GET /hls/<id>/index.m3u8 (+ segments)
9
+ POST /stop/<id>
10
+ GET /health
11
+ """
12
+ import hashlib
13
+ import ipaddress
14
+ import os
15
+ import re
16
+ import shutil
17
+ import socket
18
+ import subprocess
19
+ import tempfile
20
+ import threading
21
+ import time
22
+ from urllib.parse import urlparse
23
+
24
+ import gradio as gr
25
+ import uvicorn
26
+ from fastapi import FastAPI, HTTPException
27
+ from fastapi.middleware.cors import CORSMiddleware
28
+ from fastapi.responses import FileResponse
29
+ from pydantic import BaseModel
30
+
31
+ # ── Mipangilio (weka kwenye Space β†’ Settings β†’ Variables and secrets) ──
32
+ MAX_SESSIONS = int(os.getenv("MAX_SESSIONS", "3")) # channel zinazoweza kuchezwa kwa wakati mmoja
33
+ IDLE_TIMEOUT = int(os.getenv("IDLE_TIMEOUT", "45")) # sekunde bila mtazamaji -> ffmpeg inazimwa
34
+ START_TOKEN = os.getenv("START_TOKEN", "") # (hiari) token ya kulinda /start
35
+ ID_SECRET = os.getenv("ID_SECRET", "change-me") # chumvi ya kutengeneza session id
36
+ ALLOWED_ORIGINS = [o.strip() for o in os.getenv("ALLOWED_ORIGINS", "*").split(",") if o.strip()]
37
+ READY_TIMEOUT = int(os.getenv("READY_TIMEOUT", "35")) # sekunde za kusubiri playlist ya kwanza
38
+
39
+ ROOT = os.path.join(tempfile.gettempdir(), "hls_bridge")
40
+ os.makedirs(ROOT, exist_ok=True)
41
+
42
+ UA = "Mozilla/5.0 (Linux; Android 13) AppleWebKit/537.36 Chrome/124.0 Mobile Safari/537.36"
43
+
44
+ sessions: dict = {}
45
+ lock = threading.Lock()
46
+ _key_opt_cache = None
47
+
48
+
49
+ # ─────────────────────────── ffmpeg helpers ───────────────────────────
50
+ def key_option() -> str:
51
+ """Jina la option ya ufunguo hutofautiana kati ya matoleo ya ffmpeg."""
52
+ global _key_opt_cache
53
+ if _key_opt_cache:
54
+ return _key_opt_cache
55
+ opt = "-decryption_key"
56
+ try:
57
+ out = subprocess.run(["ffmpeg", "-hide_banner", "-h", "demuxer=dash"],
58
+ capture_output=True, text=True, timeout=10).stdout
59
+ if "cenc_decryption_key" in out:
60
+ opt = "-cenc_decryption_key"
61
+ except Exception:
62
+ pass
63
+ _key_opt_cache = opt
64
+ return opt
65
+
66
+
67
+ def check_public_url(url: str) -> None:
68
+ p = urlparse(url)
69
+ if p.scheme not in ("http", "https") or not p.hostname:
70
+ raise HTTPException(400, "MPD lazima iwe URL ya http/https")
71
+ try:
72
+ for info in socket.getaddrinfo(p.hostname, None):
73
+ ip = ipaddress.ip_address(info[4][0])
74
+ if ip.is_private or ip.is_loopback or ip.is_link_local or ip.is_reserved:
75
+ raise HTTPException(400, "Anwani hairuhusiwi")
76
+ except socket.gaierror:
77
+ raise HTTPException(400, "Host haipatikani")
78
+
79
+
80
+ def clean_hex(s: str | None) -> str:
81
+ return re.sub(r"[^0-9a-fA-F]", "", s or "").lower()
82
+
83
+
84
+ def tail(path: str, n: int = 6) -> str:
85
+ try:
86
+ with open(path, "r", errors="ignore") as f:
87
+ return " | ".join(f.read().strip().splitlines()[-n:])
88
+ except Exception:
89
+ return ""
90
+
91
+
92
+ def spawn_ffmpeg(sid: str, mpd: str, key: str) -> dict:
93
+ d = os.path.join(ROOT, sid)
94
+ shutil.rmtree(d, ignore_errors=True)
95
+ os.makedirs(d, exist_ok=True)
96
+ log = os.path.join(d, "ffmpeg.log")
97
+ cmd = [
98
+ "ffmpeg", "-hide_banner", "-loglevel", "warning", "-nostdin",
99
+ "-protocol_whitelist", "http,https,tcp,tls,crypto",
100
+ "-user_agent", UA,
101
+ ]
102
+ if key:
103
+ cmd += [key_option(), key]
104
+ cmd += [
105
+ "-i", mpd,
106
+ "-c:v", "copy", # video haibadilishwi (CPU ndogo)
107
+ "-c:a", "aac", "-b:a", "128k", "-ac", "2", # sauti -> AAC kwa iPhone
108
+ "-f", "hls",
109
+ "-hls_time", "4",
110
+ "-hls_list_size", "8",
111
+ "-hls_flags", "delete_segments+independent_segments",
112
+ "-hls_segment_filename", os.path.join(d, "seg_%05d.ts"),
113
+ os.path.join(d, "index.m3u8"),
114
+ ]
115
+ proc = subprocess.Popen(cmd, stdout=subprocess.DEVNULL, stderr=open(log, "w"))
116
+ return {"proc": proc, "dir": d, "log": log, "last": time.time(), "mpd": mpd}
117
+
118
+
119
+ def wait_ready(sid: str) -> None:
120
+ s = sessions[sid]
121
+ playlist = os.path.join(s["dir"], "index.m3u8")
122
+ t0 = time.time()
123
+ while time.time() - t0 < READY_TIMEOUT:
124
+ if s["proc"].poll() is not None:
125
+ stop_session(sid)
126
+ raise HTTPException(502, "ffmpeg imeshindwa: " + (tail(s["log"]) or "hakuna maelezo"))
127
+ try:
128
+ with open(playlist) as f:
129
+ if f.read().count(".ts") >= 2:
130
+ return
131
+ except FileNotFoundError:
132
+ pass
133
+ time.sleep(0.5)
134
+ err = tail(s["log"])
135
+ stop_session(sid)
136
+ raise HTTPException(504, "Muda umeisha kusubiri stream. " + err)
137
+
138
+
139
+ # ���────────────────────────── sessions ───────────────────────────
140
+ def stop_session(sid: str) -> None:
141
+ with lock:
142
+ s = sessions.pop(sid, None)
143
+ if not s:
144
+ return
145
+ try:
146
+ s["proc"].terminate()
147
+ s["proc"].wait(timeout=5)
148
+ except Exception:
149
+ try:
150
+ s["proc"].kill()
151
+ except Exception:
152
+ pass
153
+ shutil.rmtree(s["dir"], ignore_errors=True)
154
+
155
+
156
+ def start_session(mpd: str, kid: str | None, key: str | None) -> str:
157
+ mpd = (mpd or "").strip()
158
+ check_public_url(mpd)
159
+ k = clean_hex(key)
160
+ if key and not re.fullmatch(r"[0-9a-f]{32}", k):
161
+ raise HTTPException(400, "Key lazima iwe hex ya herufi 32")
162
+ sid = hashlib.sha256(f"{ID_SECRET}|{mpd}|{k}".encode()).hexdigest()[:24]
163
+ with lock:
164
+ s = sessions.get(sid)
165
+ if s and s["proc"].poll() is None:
166
+ s["last"] = time.time()
167
+ fresh = False
168
+ else:
169
+ if s:
170
+ sessions.pop(sid, None)
171
+ live = sum(1 for x in sessions.values() if x["proc"].poll() is None)
172
+ if live >= MAX_SESSIONS:
173
+ raise HTTPException(503, "Server ina shughuli nyingi, jaribu tena baadaye")
174
+ sessions[sid] = spawn_ffmpeg(sid, mpd, k)
175
+ fresh = True
176
+ if fresh:
177
+ wait_ready(sid)
178
+ return sid
179
+
180
+
181
+ def reaper():
182
+ while True:
183
+ time.sleep(10)
184
+ now = time.time()
185
+ for sid, s in list(sessions.items()):
186
+ if now - s["last"] > IDLE_TIMEOUT or s["proc"].poll() is not None:
187
+ stop_session(sid)
188
+
189
+
190
+ threading.Thread(target=reaper, daemon=True).start()
191
+
192
+
193
+ def public_url(sid: str) -> str:
194
+ host = os.getenv("SPACE_HOST")
195
+ base = f"https://{host}" if host else "http://localhost:7860"
196
+ return f"{base}/hls/{sid}/index.m3u8"
197
+
198
+
199
+ # ─────────────────────────── API (FastAPI) ───────────────────────────
200
+ api = FastAPI(title="JAYNES MAX HLS Bridge")
201
+ api.add_middleware(
202
+ CORSMiddleware,
203
+ allow_origins=ALLOWED_ORIGINS,
204
+ allow_methods=["GET", "POST", "OPTIONS"],
205
+ allow_headers=["*"],
206
+ allow_credentials=False,
207
+ )
208
+
209
+
210
+ class StartReq(BaseModel):
211
+ mpd: str
212
+ kid: str | None = None
213
+ key: str | None = None
214
+ token: str | None = None
215
+
216
+
217
+ @api.post("/start")
218
+ def api_start(req: StartReq): # def (si async) -> inaendeshwa kwenye threadpool
219
+ if START_TOKEN and req.token != START_TOKEN:
220
+ raise HTTPException(401, "Token si sahihi")
221
+ sid = start_session(req.mpd, req.kid, req.key)
222
+ return {"id": sid, "url": public_url(sid)}
223
+
224
+
225
+ @api.post("/stop/{sid}")
226
+ def api_stop(sid: str):
227
+ if re.fullmatch(r"[a-f0-9]{24}", sid):
228
+ stop_session(sid)
229
+ return {"ok": True}
230
+
231
+
232
+ @api.get("/hls/{sid}/{name}")
233
+ def api_hls(sid: str, name: str):
234
+ if not re.fullmatch(r"[a-f0-9]{24}", sid) or not re.fullmatch(r"index\.m3u8|seg_\d{5}\.ts", name):
235
+ raise HTTPException(404)
236
+ s = sessions.get(sid)
237
+ if not s:
238
+ raise HTTPException(404, "Session haipo")
239
+ s["last"] = time.time()
240
+ path = os.path.join(s["dir"], name)
241
+ if not os.path.exists(path):
242
+ raise HTTPException(404)
243
+ if name.endswith(".m3u8"):
244
+ return FileResponse(path, media_type="application/vnd.apple.mpegurl",
245
+ headers={"Cache-Control": "no-store"})
246
+ return FileResponse(path, media_type="video/mp2t", headers={"Cache-Control": "max-age=30"})
247
+
248
+
249
+ @api.get("/health")
250
+ def api_health():
251
+ return {"ok": True, "sessions": len(sessions), "key_option": key_option()}
252
+
253
+
254
+ # ─────────────────────────── UI (Gradio) ───────────────────────────
255
+ def ui_start(mpd, kid, key):
256
+ try:
257
+ sid = start_session(mpd, kid, key)
258
+ return public_url(sid), "βœ… Imeanza"
259
+ except HTTPException as e:
260
+ return "", f"❌ {e.detail}"
261
+
262
+
263
+ def ui_list():
264
+ now = time.time()
265
+ return [[sid, s["mpd"][:60], f"{int(now - s['last'])}s", "ndio" if s["proc"].poll() is None else "hapana"]
266
+ for sid, s in sessions.items()]
267
+
268
+
269
+ def ui_stop_all():
270
+ for sid in list(sessions):
271
+ stop_session(sid)
272
+ return ui_list()
273
+
274
+
275
+ with gr.Blocks(title="JAYNES MAX HLS Bridge") as demo:
276
+ gr.Markdown("## JAYNES MAX β€” HLS Bridge\nMPD + ClearKey β†’ HLS kwa iPhone")
277
+ mpd_in = gr.Textbox(label="MPD URL")
278
+ kid_in = gr.Textbox(label="KID (hiari)")
279
+ key_in = gr.Textbox(label="KEY (hex 32)")
280
+ go = gr.Button("Anza", variant="primary")
281
+ out_url = gr.Textbox(label="HLS URL", interactive=False)
282
+ out_msg = gr.Markdown()
283
+ go.click(ui_start, [mpd_in, kid_in, key_in], [out_url, out_msg], api_name=False)
284
+ table = gr.Dataframe(headers=["id", "mpd", "idle", "hai"], value=ui_list, every=5, interactive=False)
285
+ gr.Button("Zima zote").click(ui_stop_all, None, table, api_name=False)
286
+
287
+ app = gr.mount_gradio_app(api, demo, path="/")
288
+
289
+ if __name__ == "__main__":
290
+ uvicorn.run(app, host="0.0.0.0", port=int(os.getenv("PORT", "7860")))
packages.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ ffmpeg
requirements.txt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ gradio>=4.44
2
+ fastapi
3
+ uvicorn