Repository navigation
Expand file tree
/
Copy pathytworker.py
More file actions
74 lines (63 loc) · 2.74 KB
/
Copy pathytworker.py
File metadata and controls
74 lines (63 loc) · 2.74 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
"""Worker yt-dlp yang nyala terus (dijalanin pakai Python bawaan yt-dlp).
Baca satu baris JSON {"vid": "..."} dari stdin, balas satu baris JSON berisi URL audio.
Karena prosesnya nggak mati, resolve lagu berikutnya cuma ~1 detik, bukan 4.
Di Android nggak bisa bikin proses Python baru, jadi server.py ngimpor modul ini
dan manggil make_ydl() + resolve() langsung di thread-nya sendiri.
"""
import json
import os
import sys
import yt_dlp
def make_ydl():
opts = {
'quiet': True,
'no_warnings': True,
'noprogress': True,
'noplaylist': True,
'format': 'bestaudio[ext=m4a]/bestaudio',
# Client bawaan yt-dlp baru (tv_samsung) ngasih URL yang 403 beberapa detik pertama
'extractor_args': {'youtube': {'player_client': ['visionos', 'web']}},
}
if os.environ.get('PUTAR_NO_JS'):
# Nggak ada runtime JS (Android): visionos nggak butuh JS player, cukup itu aja
opts['extractor_args']['youtube']['player_client'] = ['visionos']
if os.environ.get('PUTAR_COOKIES'):
opts['cookiesfrombrowser'] = (os.environ['PUTAR_COOKIES'],)
return yt_dlp.YoutubeDL(opts)
def videos(info):
"""Stream video-only H.264 per resolusi (diputar barengan audio yang udah ada)."""
best = {}
for f in info.get('formats') or []:
h = f.get('height')
if h not in (360, 480, 720, 1080) or f.get('acodec') not in ('none', None):
continue
if not str(f.get('vcodec', '')).startswith('avc1') or not str(f.get('protocol', '')).startswith('http'):
continue
if h not in best or (f.get('tbr') or 0) > (best[h].get('tbr') or 0):
best[h] = f
return {str(h): {'url': f['url'], 'headers': f.get('http_headers') or {}, 'size': f.get('filesize') or 0, 'tbr': f.get('tbr') or 0}
for h, f in best.items()}
def resolve(ydl, vid):
try:
info = ydl.extract_info(f'https://music.youtube.com/watch?v={vid}', download=False)
return {
'ok': True,
'url': info['url'],
'headers': info.get('http_headers') or {},
'ext': info.get('ext') or 'm4a',
'size': info.get('filesize') or info.get('filesize_approx') or 0,
'duration': info.get('duration') or 0,
'videos': videos(info),
}
except Exception as e:
msg = str(e).strip().splitlines()[-1] if str(e).strip() else 'yt-dlp gagal'
return {'ok': False, 'error': msg}
if __name__ == '__main__':
ydl = make_ydl()
for line in sys.stdin:
try:
out = resolve(ydl, json.loads(line)['vid'])
except Exception as e:
out = {'ok': False, 'error': str(e) or 'request rusak'}
sys.stdout.write(json.dumps(out) + '\n')
sys.stdout.flush()