-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathyoutube-live.py
65 lines (51 loc) · 2.06 KB
/
youtube-live.py
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
import subprocess
import json
import logging
from flask import Flask, request, Response, jsonify
app = Flask(__name__)
# Set up logging to only show warnings and errors
logging.basicConfig(level=logging.WARNING)
@app.route('/stream', methods=['GET'])
def stream():
url = request.args.get('url')
if not url:
return jsonify({'error': 'URL parameter is required'}), 400
# First, get stream info to detect stream type
try:
info_command = ['streamlink', '--json', url]
info_process = subprocess.Popen(info_command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
info_output, info_error = info_process.communicate()
if info_process.returncode != 0:
logging.error(f'Streamlink error: {info_error.decode()}')
return jsonify({'error': 'Failed to retrieve stream info'}), 500
# Parse the JSON output
stream_info = json.loads(info_output)
# Determine the best quality available
best_quality = stream_info['streams'].get('best')
if not best_quality:
return jsonify({'error': 'No valid streams found'}), 404
# Command to run Streamlink for the detected stream type
command = [
'streamlink',
url,
'best',
'--hls-live-restart',
'--stdout'
]
# Create a subprocess to run Streamlink and stream output
process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
def generate():
while True:
data = process.stdout.read(4096)
if not data:
break
yield data
process.stdout.close()
process.stderr.close()
process.wait()
return Response(generate(), content_type='video/mp2t')
except Exception as e:
logging.error(f'Error occurred: {str(e)}')
return jsonify({'error': str(e)}), 500
if __name__ == '__main__':
app.run(host='0.0.0.0', port=6095)