Spaces:
Paused
Paused
Upload app.py
Browse files8 unmodified lines910111213149 unmodified lines242526272829303 unmodified lines34353637383929 unmodified lines6970717273746 unmodified lines818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381396 unmodified lines1461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582 unmodified lines2612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233242 unmodified lines3273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397408 unmodified linesimport queueimport uuid# Initialize Pygame headlesslyos.environ['SDL_VIDEODRIVER'] = 'dummy'pygame.init()9 unmodified linesapp = Flask(__name__)class ShaderRenderer:def __init__(self, width=640, height=480):self.width = widthself.height = heightself.mouse_x = width // 23 unmodified linesself.frame_count = 0self.last_frame_time = time.time()self.fps = 0# Sound sourcesself.sound_source = 'none'29 unmodified linesself.pygame_playing = Falseself.sound_amp = 0.0def render_frame(self):"""Render the pygame frame"""t = time.time() - self.start_time6 unmodified linesself.last_frame_time = time.time()# Clearself.surface.fill((20, 20, 30))# Draw TOP markerpygame.draw.rect(self.surface, (255, 100, 100), (10, 10, 100, 30))font = pygame.font.Font(None, 24)text = font.render("TOP", True, (255, 255, 255))self.surface.blit(text, (20, 15))# Draw BOTTOM markerpygame.draw.rect(self.surface, (100, 255, 100), (10, self.height-40, 100, 30))text = font.render("BOTTOM", True, (0, 0, 0))self.surface.blit(text, (20, self.height-35))# Draw moving circlecircle_size = 30 + int(20 * np.sin(t * 2))# Color code based on sound sourceif self.sound_source == 'pygame':color = (100, 255, 100) # Green for pygame soundelif self.sound_source == 'browser':color = (100, 100, 255) # Blue for browser soundelse:color = (255, 100, 100) # Red for no soundpygame.draw.circle(self.surface, color,(self.mouse_x, self.mouse_y), circle_size)# Draw gridfor x in range(0, self.width, 50):alpha = int(40 + 20 * np.sin(x * 0.1 + t))pygame.draw.line(self.surface, (alpha, alpha, 50),(x, 0), (x, self.height))for y in range(0, self.height, 50):alpha = int(40 + 20 * np.cos(y * 0.1 + t))pygame.draw.line(self.surface, (alpha, alpha, 50),(0, y), (self.width, y))# Sound metermeter_width = int(200 * self.sound_amp)pygame.draw.rect(self.surface, (60, 60, 60), (self.width-220, 10, 200, 20))pygame.draw.rect(self.surface, (100, 255, 100),(self.width-220, 10, meter_width, 20))# FPS counterfps_text = font.render(f"FPS: {self.fps}", True, (255, 255, 0))self.surface.blit(fps_text, (self.width-150, self.height-60))return pygame.image.tostring(self.surface, 'RGB')def get_frame(self):return self.render_frame()def get_frame_jpeg(self, quality=80):"""Return frame as JPEG"""frame = self.get_frame()# Convert to numpy array for OpenCV6 unmodified linesrenderer = ShaderRenderer()# Streaming managersclass StreamManager:def __init__(self):self.streams = {}def create_mjpeg_stream(self):stream_id = str(uuid.uuid4())self.streams[stream_id] = {'type': 'mjpeg','active': True,'clients': 0}return stream_iddef create_ffmpeg_stream(self, format_type='webm'):stream_id = str(uuid.uuid4())# FFmpeg command based on formatif format_type == 'webm':cmd = ['ffmpeg','-f', 'rawvideo','-pix_fmt', 'rgb24','-s', '640x480','-r', '30','-i', '-','-c:v', 'libvpx-vp9','-b:v', '1M','-cpu-used', '4','-deadline', 'realtime','-f', 'webm','-']mimetype = 'video/webm'else: # mp4cmd = ['ffmpeg','-f', 'rawvideo','-pix_fmt', 'rgb24','-s', '640x480','-r', '30','-i', '-','-c:v', 'libx264','-preset', 'ultrafast','-tune', 'zerolatency','-b:v', '1M','-f', 'mp4','-movflags', 'frag_keyframe+empty_moov','-']mimetype = 'video/mp4'# Start FFmpeg processprocess = subprocess.Popen(cmd,stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.DEVNULL,bufsize=0)frame_queue = queue.Queue(maxsize=30)self.streams[stream_id] = {'type': format_type,'mimetype': mimetype,'active': True,'process': process,'queue': frame_queue,'clients': 0}# Start frame pusher threaddef push_frames():while self.streams.get(stream_id, {}).get('active', False):try:frame = renderer.get_frame()process.stdin.write(frame)except:breakprocess.terminate()threading.Thread(target=push_frames, daemon=True).start()return stream_iddef get_stream(self, stream_id):return self.streams.get(stream_id)def close_stream(self, stream_id):if stream_id in self.streams:stream = self.streams[stream_id]if 'process' in stream:stream['process'].terminate()del self.streams[stream_id]stream_manager = StreamManager()@app.route('/')def index():return render_template_string('''<!DOCTYPE html><html><head><title>🎮 Pygame + Multi-format Streaming</title><style>body {margin: 0;background: #0a0a0a;color: white;2 unmodified linesjustify-content: center;align-items: center;min-height: 100vh;}.container {max-width: 900px;padding: 20px;text-align: center;}h1 {color: #4CAF50;margin-bottom: 20px;text-shadow: 0 0 10px rgba(76, 175, 80, 0.3);}.video-container {background: #000;border-radius: 12px;padding: 5px;margin: 20px 0;box-shadow: 0 0 30px rgba(76, 175, 80, 0.2);}#videoPlayer {width: 100%;max-width: 640px;height: auto;border-radius: 8px;display: block;margin: 0 auto;background: #111;}#mjpegImg {width: 100%;max-width: 640px;height: auto;border-radius: 8px;display: none;margin: 0 auto;background: #111;}.controls {background: #1a1a1a;border-radius: 12px;padding: 20px;margin-top: 20px;}.format-buttons {display: flex;gap: 10px;justify-content: center;margin: 20px 0;flex-wrap: wrap;}button {background: #333;color: white;border: none;2 unmodified linesborder-radius: 8px;cursor: pointer;transition: all 0.3s;min-width: 100px;font-weight: bold;border: 1px solid #444;}button:hover {transform: translateY(-2px);box-shadow: 0 5px 15px rgba(0,0,0,0.3);}button.active {background: #4CAF50;border-color: #4CAF50;box-shadow: 0 0 20px #4CAF50;}.status-panel {background: #222;border-radius: 8px;padding: 15px;margin-top: 20px;display: flex;justify-content: space-around;align-items: center;flex-wrap: wrap;gap: 15px;}.status-item {display: flex;align-items: center;gap: 10px;}.status-label {color: #888;font-size: 14px;}.status-value {background: #333;padding: 5px 12px;border-radius: 20px;font-size: 14px;font-weight: bold;}.browser-support {font-size: 12px;color: #666;margin-top: 15px;padding: 10px;border-top: 1px solid #333;}.badge {display: inline-block;padding: 3px 8px;border-radius: 4px;font-size: 11px;margin-left: 5px;}.badge.green {background: #4CAF50;}.badge.yellow {background: #ffaa00;color: black;}.badge.red {background: #ff4444;}.info-text {color: #666;font-size: 12px;margin-top: 10px;}</style></head><body><div class="container"><h1>🎮 Pygame + Multi-format Streaming</h1><div class="video-container"><video id="videoPlayer" autoplay controls muted></video><img id="mjpegImg" src=""></div><div class="controls"><h3>📡 Streaming Format</h3><div class="format-buttons"><button id="btnMjpeg" onclick="setFormat('mjpeg')" class="active">📸 MJPEG</button><button id="btnWebm" onclick="setFormat('webm')">🎥 WebM (VP9)</button><button id="btnMp4" onclick="setFormat('mp4')">🎬 MP4 (H.264)</button></div><div class="status-panel"><div class="status-item"><span class="status-label">Current Format:</span><span id="currentFormat" class="status-value">MJPEG</span></div><div class="status-item"><span class="status-label">Browser Support:</span><span id="browserSupport" class="status-value">Checking...</span></div><div class="status-item"><span class="status-label">Stream Status:</span><span id="streamStatus" class="status-value">🟢 Active</span></div></div><div class="browser-support" id="supportDetails">Testing browser capabilities...</div><div class="info-text">⚡ MJPEG: Lowest CPU, universal support<br>🎥 WebM: Efficient compression, best for Chrome/Firefox<br>🎬 MP4: Universal support, hardware accelerated</div></div></div><script>const videoPlayer = document.getElementById('videoPlayer');const mjpegImg = document.getElementById('mjpegImg');let currentFormat = 'mjpeg';let streamActive = true;// Check browser capabilitiesfunction checkBrowserSupport() {const video = document.createElement('video');const support = {webm: video.canPlayType('video/webm; codecs="vp9, vorbis"'),webmVP8: video.canPlayType('video/webm; codecs="vp8, vorbis"'),mp4: video.canPlayType('video/mp4; codecs="avc1.42E01E, mp4a.40.2"'),mp4H264: video.canPlayType('video/mp4; codecs="avc1.64001E"'),mjpeg: true};let supportText = '';let details = '';if (support.webm) {supportText += '✓ WebM VP9 ';details += 'WebM VP9: ' + support.webm + '<br>';}if (support.mp4) {supportText += '✓ MP4 H.264 ';details += 'MP4 H.264: ' + support.mp4 + '<br>';}supportText += '✓ MJPEG';document.getElementById('browserSupport').innerHTML = supportText;document.getElementById('supportDetails').innerHTML = details;return support;}function setFormat(format) {currentFormat = format;// Update button statesdocument.getElementById('btnMjpeg').className = format === 'mjpeg' ? 'active' : '';document.getElementById('btnWebm').className = format === 'webm' ? 'active' : '';document.getElementById('btnMp4').className = format === 'mp4' ? 'active' : '';document.getElementById('currentFormat').innerHTML = format.toUpperCase();// Hide both players firstvideoPlayer.style.display = 'none';mjpegImg.style.display = 'none';if (format === 'mjpeg') {// Use img tag for MJPEGmjpegImg.style.display = 'block';mjpegImg.src = '/video/mjpeg?' + Date.now(); // Add timestamp to prevent caching} else {// Use video tag for WebM/MP4videoPlayer.style.display = 'block';// Stop current playbackvideoPlayer.pause();videoPlayer.removeAttribute('src');videoPlayer.load();// Set new sourceconst source = document.createElement('source');if (format === 'webm') {source.src = '/video/webm?' + Date.now();source.type = 'video/webm';} else {source.src = '/video/mp4?' + Date.now();source.type = 'video/mp4';}videoPlayer.appendChild(source);videoPlayer.load();videoPlayer.play().catch(e => console.log('Playback error:', e));}}// Monitor stream healthfunction checkStreamHealth() {if (currentFormat === 'mjpeg') {// For MJPEG, check if image is loadingmjpegImg.onerror = function() {document.getElementById('streamStatus').innerHTML = '🔴 Error';streamActive = false;};mjpegImg.onload = function() {document.getElementById('streamStatus').innerHTML = '🟢 Active';streamActive = true;};} else {// For video, check if playingvideoPlayer.onerror = function() {document.getElementById('streamStatus').innerHTML = '🔴 Error';streamActive = false;};videoPlayer.onplaying = function() {document.getElementById('streamStatus').innerHTML = '🟢 Active';streamActive = true;};}}// InitializecheckBrowserSupport();setFormat('mjpeg'); // Start with MJPEG for reliabilitycheckStreamHealth();// Reconnect on errorsetInterval(() => {if (!streamActive) {console.log('Attempting to reconnect...');setFormat(currentFormat);}}, 5000);</script></body></html>''')@app.route('/video/mjpeg')def video_mjpeg():"""MJPEG streaming endpoint"""def generate():while True:frame = renderer.get_frame_jpeg(quality=70)yield (b'--frame\r\n'b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n')# Small delay to control frame ratetime.sleep(1/30)return Response(generate(),mimetype='multipart/x-mixed-replace; boundary=frame')@app.route('/video/webm')def video_webm():"""WebM streaming endpoint"""cmd = ['ffmpeg','-f', 'rawvideo','-pix_fmt', 'rgb24','-s', '640x480','-r', '30','-i', '-','-c:v', 'libvpx-vp9','-b:v', '1M','-cpu-used', '4','-deadline', 'realtime','-f', 'webm','-']process = subprocess.Popen(cmd,stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.DEVNULL,bufsize=0)def generate():# Frame pusher threaddef push_frames():while True:try:frame = renderer.get_frame()process.stdin.write(frame)except:breakthreading.Thread(target=push_frames, daemon=True).start()# Read and yield encoded datawhile True:data = process.stdout.read(4096)if not data:breakyield datareturn Response(generate(),mimetype='video/webm',headers={'Cache-Control': 'no-cache','Transfer-Encoding': 'chunked'})@app.route('/video/mp4')def video_mp4():"""MP4 streaming endpoint"""cmd = ['ffmpeg','-f', 'rawvideo','-pix_fmt', 'rgb24','-s', '640x480','-r', '30','-i', '-','-c:v', 'libx264','-preset', 'ultrafast','-tune', 'zerolatency','-b:v', '1M','-f', 'mp4','-movflags', 'frag_keyframe+empty_moov','-']process = subprocess.Popen(cmd,stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.DEVNULL,bufsize=0)def generate():def push_frames():while True:try:frame = renderer.get_frame()process.stdin.write(frame)except:breakthreading.Thread(target=push_frames, daemon=True).start()while True:data = process.stdout.read(4096)if not data:breakyield datareturn Response(generate(),mimetype='video/mp4',headers={'Cache-Control': 'no-cache','Transfer-Encoding': 'chunked'})@app.route('/mouse', methods=['POST'])def mouse():"""Keep mouse endpoint for interactivity"""data = request.jsonrenderer.set_mouse(data['x'], data['y'])return 'OK'@app.route('/sound/source', methods=['POST'])def sound_source():"""Keep sound source endpoint"""data = request.jsonrenderer.set_sound_source(data['source'])return 'OK'@app.route('/sound/amp')def sound_amp():"""Keep sound amp endpoint for compatibility"""return {'amp': renderer.sound_amp}@app.route('/static/sound.mp3')def serve_sound():"""Serve sound file"""if os.path.exists('sound.mp3'):with open('sound.mp3', 'rb') as f:return Response(f.read(), mimetype='audio/mpeg')return 'Sound not found', 404if __name__ == '__main__':print("\n" + "="*70)print("🎮 Pygame + Multi-format Streaming")print("="*70)print("📡 Streaming endpoints:")print(" • MJPEG: /video/mjpeg - Low CPU, universal")print(" • WebM: /video/webm - VP9 codec, efficient")print(" • MP4: /video/mp4 - H.264, hardware accelerated")print("\n🌐 Main page: /")print("="*70 + "\n")port = int(os.environ.get('PORT', 7860))app.run(host='0.0.0.0', port=port, debug=False, threaded=True)8 unmodified lines910111213141516171819202122232425262728293031323334353637383940419 unmodified lines515253545556573 unmodified lines6162636465666729 unmodified lines9798991001011021031041051061071081091101111126 unmodified lines1191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212226 unmodified lines2292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913922 unmodified lines3953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654662 unmodified lines4694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077088 unmodified linesimport queueimport uuid# ============ CONFIGURATION ============VIDEO_WIDTH = 1280VIDEO_HEIGHT = 720VIDEO_FPS = 30JPEG_QUALITY = 70STREAM_PORT = 7860# Colors (RGB)COLOR_TOP = (255, 100, 100)COLOR_BOTTOM = (100, 255, 100)COLOR_BG = (20, 20, 30)COLOR_GRID = (50, 50, 70)COLOR_FPS = (255, 255, 0)COLOR_CLOCK = (0, 255, 255)# Button colorsCOLOR_BUTTON_NORMAL = (80, 80, 80)COLOR_BUTTON_HOVER = (100, 100, 200)COLOR_BUTTON_CLICKED = (0, 200, 0)COLOR_BUTTON_BORDER = (200, 200, 200)# Sound source colorsCOLOR_SOUND_NONE = (255, 100, 100)COLOR_SOUND_PYGAME = (100, 255, 100)COLOR_SOUND_BROWSER = (100, 100, 255)# =======================================# Initialize Pygame headlesslyos.environ['SDL_VIDEODRIVER'] = 'dummy'pygame.init()9 unmodified linesapp = Flask(__name__)class ShaderRenderer:def __init__(self, width=VIDEO_WIDTH, height=VIDEO_HEIGHT):self.width = widthself.height = heightself.mouse_x = width // 23 unmodified linesself.frame_count = 0self.last_frame_time = time.time()self.fps = 0self.button_clicked = False# Sound sourcesself.sound_source = 'none'29 unmodified linesself.pygame_playing = Falseself.sound_amp = 0.0def handle_click(self, x, y):"""Handle mouse clicks on Pygame surface"""button_rect = pygame.Rect(self.width-250, 120, 220, 50)if button_rect.collidepoint(x, y):self.button_clicked = not self.button_clickedprint(f"🎯 Button {'clicked!' if self.button_clicked else 'unclicked!'}")return Truereturn Falsedef render_frame(self):"""Render the pygame frame"""t = time.time() - self.start_time6 unmodified linesself.last_frame_time = time.time()# Clearself.surface.fill(COLOR_BG)# Use larger font for 720pfont = pygame.font.Font(None, 36)small_font = pygame.font.Font(None, 24)# Draw TOP markerpygame.draw.rect(self.surface, COLOR_TOP, (10, 10, 150, 40))text = font.render("TOP", True, (255, 255, 255))self.surface.blit(text, (30, 15))# Draw BOTTOM markerpygame.draw.rect(self.surface, COLOR_BOTTOM, (10, self.height-50, 150, 40))text = font.render("BOTTOM", True, (0, 0, 0))self.surface.blit(text, (20, self.height-45))# ===== CLOCK DISPLAY =====current_time = time.time()seconds = int(current_time) % 60hundredths = int((current_time * 100) % 100)# Clock backgroundpygame.draw.rect(self.surface, (40, 40, 50), (self.width-250, 70, 220, 50))pygame.draw.rect(self.surface, (100, 100, 150), (self.width-250, 70, 220, 50), 2)# Clock texttime_str = f"{seconds:02d}.{hundredths:02d}s"clock_text = font.render(time_str, True, COLOR_CLOCK)self.surface.blit(clock_text, (self.width-230, 80))# ===== CLICKABLE BUTTON =====button_rect = pygame.Rect(self.width-250, 140, 220, 50)# Check if mouse is over buttonmouse_over = button_rect.collidepoint(self.mouse_x, self.mouse_y)# Button color based on state and hoverif self.button_clicked:button_color = COLOR_BUTTON_CLICKEDelif mouse_over:button_color = COLOR_BUTTON_HOVERelse:button_color = COLOR_BUTTON_NORMAL# Draw buttonpygame.draw.rect(self.surface, button_color, button_rect)pygame.draw.rect(self.surface, COLOR_BUTTON_BORDER, button_rect, 3)# Button textif self.button_clicked:btn_text = "✅ CLICKED!"else:btn_text = "🔘 CLICK ME"text_surf = font.render(btn_text, True, (255, 255, 255))text_rect = text_surf.get_rect(center=button_rect.center)self.surface.blit(text_surf, text_rect)# ===== MOVING CIRCLE =====circle_size = 40 + int(30 * np.sin(t * 2))# Color code based on sound sourceif self.sound_source == 'pygame':color = COLOR_SOUND_PYGAMEelif self.sound_source == 'browser':color = COLOR_SOUND_BROWSERelse:color = COLOR_SOUND_NONEpygame.draw.circle(self.surface, color,(self.mouse_x, self.mouse_y), circle_size)# ===== GRID =====for x in range(0, self.width, 70):alpha = int(40 + 20 * np.sin(x * 0.1 + t))pygame.draw.line(self.surface, (alpha, alpha, 50),(x, 0), (x, self.height))for y in range(0, self.height, 70):alpha = int(40 + 20 * np.cos(y * 0.1 + t))pygame.draw.line(self.surface, (alpha, alpha, 50),(0, y), (self.width, y))# ===== SOUND METER =====meter_width = int(250 * self.sound_amp)pygame.draw.rect(self.surface, (60, 60, 60), (self.width-270, 210, 250, 25))pygame.draw.rect(self.surface, (100, 255, 100),(self.width-270, 210, meter_width, 25))# ===== FPS COUNTER =====fps_text = small_font.render(f"FPS: {self.fps}", True, COLOR_FPS)self.surface.blit(fps_text, (self.width-200, self.height-80))return pygame.image.tostring(self.surface, 'RGB')def get_frame(self):return self.render_frame()def get_frame_jpeg(self, quality=JPEG_QUALITY):"""Return frame as JPEG"""frame = self.get_frame()# Convert to numpy array for OpenCV6 unmodified linesrenderer = ShaderRenderer()# ============ STREAMING ENDPOINTS ============@app.route('/video/mjpeg')def video_mjpeg():"""MJPEG streaming endpoint"""def generate():while True:frame = renderer.get_frame_jpeg()yield (b'--frame\r\n'b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n')time.sleep(1/VIDEO_FPS)return Response(generate(),mimetype='multipart/x-mixed-replace; boundary=frame')@app.route('/video/webm')def video_webm():"""WebM streaming endpoint"""cmd = ['ffmpeg','-f', 'rawvideo','-pix_fmt', 'rgb24','-s', f'{VIDEO_WIDTH}x{VIDEO_HEIGHT}','-r', str(VIDEO_FPS),'-i', '-','-c:v', 'libvpx-vp9','-b:v', '2M','-cpu-used', '4','-deadline', 'realtime','-f', 'webm','-']process = subprocess.Popen(cmd,stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.DEVNULL,bufsize=0)def generate():def push_frames():while True:try:frame = renderer.get_frame()process.stdin.write(frame)except:breakthreading.Thread(target=push_frames, daemon=True).start()while True:data = process.stdout.read(4096)if not data:breakyield datareturn Response(generate(),mimetype='video/webm',headers={'Cache-Control': 'no-cache', 'Transfer-Encoding': 'chunked'})@app.route('/video/mp4')def video_mp4():"""MP4 streaming endpoint"""cmd = ['ffmpeg','-f', 'rawvideo','-pix_fmt', 'rgb24','-s', f'{VIDEO_WIDTH}x{VIDEO_HEIGHT}','-r', str(VIDEO_FPS),'-i', '-','-c:v', 'libx264','-preset', 'ultrafast','-tune', 'zerolatency','-b:v', '2M','-f', 'mp4','-movflags', 'frag_keyframe+empty_moov','-']process = subprocess.Popen(cmd,stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.DEVNULL,bufsize=0)def generate():def push_frames():while True:try:frame = renderer.get_frame()process.stdin.write(frame)except:breakthreading.Thread(target=push_frames, daemon=True).start()while True:data = process.stdout.read(4096)if not data:breakyield datareturn Response(generate(),mimetype='video/mp4',headers={'Cache-Control': 'no-cache', 'Transfer-Encoding': 'chunked'})# ============ INTERACTIVITY ENDPOINTS ============@app.route('/mouse', methods=['POST'])def mouse():data = request.jsonrenderer.set_mouse(data['x'], data['y'])return 'OK'@app.route('/click', methods=['POST'])def click():data = request.jsonrenderer.handle_click(data['x'], data['y'])return 'OK'@app.route('/sound/source', methods=['POST'])def sound_source():data = request.jsonrenderer.set_sound_source(data['source'])return 'OK'@app.route('/sound/amp')def sound_amp():return {'amp': renderer.sound_amp}@app.route('/static/sound.mp3')def serve_sound():if os.path.exists('sound.mp3'):with open('sound.mp3', 'rb') as f:return Response(f.read(), mimetype='audio/mpeg')return 'Sound not found', 404# ============ HTML PAGE ============@app.route('/')def index():return render_template_string(f'''<!DOCTYPE html><html><head><title>🎮 Pygame 720p Streaming</title><style>body {{margin: 0;background: #0a0a0a;color: white;2 unmodified linesjustify-content: center;align-items: center;min-height: 100vh;}}.container {{max-width: 1400px;padding: 20px;text-align: center;}}h1 {{color: #4CAF50;margin-bottom: 20px;}}.video-container {{background: #000;border-radius: 12px;padding: 5px;margin: 20px 0;box-shadow: 0 0 30px rgba(76, 175, 80, 0.2);position: relative;}}#videoPlayer, #mjpegImg {{width: 100%;max-width: {VIDEO_WIDTH}px;height: auto;border-radius: 8px;display: block;margin: 0 auto;background: #111;cursor: crosshair;}}#mjpegImg {{display: none;}}.mouse-coords {{position: absolute;bottom: 10px;left: 10px;background: rgba(0,0,0,0.7);color: #4CAF50;padding: 5px 10px;border-radius: 20px;font-family: monospace;font-size: 14px;pointer-events: none;}}.controls {{background: #1a1a1a;border-radius: 12px;padding: 20px;margin-top: 20px;}}.format-buttons, .sound-controls {{display: flex;gap: 10px;justify-content: center;margin: 20px 0;flex-wrap: wrap;}}button {{background: #333;color: white;border: none;2 unmodified linesborder-radius: 8px;cursor: pointer;transition: all 0.3s;min-width: 120px;font-weight: bold;border: 1px solid #444;}}button:hover {{transform: translateY(-2px);box-shadow: 0 5px 15px rgba(0,0,0,0.3);}}button.active {{background: #4CAF50;border-color: #4CAF50;box-shadow: 0 0 20px #4CAF50;}}.status-panel {{background: #222;border-radius: 8px;padding: 15px;margin-top: 20px;display: flex;justify-content: space-around;flex-wrap: wrap;gap: 15px;}}.status-item {{display: flex;align-items: center;gap: 10px;}}.status-label {{color: #888;font-size: 14px;}}.status-value {{background: #333;padding: 5px 12px;border-radius: 20px;font-size: 14px;font-weight: bold;}}.meter {{width: 100%;height: 25px;background: #333;border-radius: 12px;overflow: hidden;margin: 10px 0;}}.meter-fill {{height: 100%;width: 0%;background: linear-gradient(90deg, #4CAF50, #2196F3);transition: width 0.05s;}}</style></head><body><div class="container"><h1>🎮 Pygame 720p Streaming</h1><div class="video-container"><video id="videoPlayer" autoplay controls muted></video><img id="mjpegImg" crossorigin="anonymous"><div id="mouseCoords" class="mouse-coords">X: 320, Y: 240</div></div><div class="controls"><div class="format-buttons"><button id="btnMjpeg" onclick="setFormat('mjpeg')" class="active">📸 MJPEG</button><button id="btnWebm" onclick="setFormat('webm')">🎥 WebM</button><button id="btnMp4" onclick="setFormat('mp4')">🎬 MP4</button></div><div class="sound-controls"><button id="btnNone" onclick="setSound('none')" class="active">🔇 None</button><button id="btnPygame" onclick="setSound('pygame')">🎮 Pygame</button><button id="btnBrowser" onclick="setSound('browser')">🌐 Browser</button></div><div class="meter"><div id="soundMeter" class="meter-fill"></div></div><div class="status-panel"><div class="status-item"><span class="status-label">Format:</span><span id="currentFormat" class="status-value">MJPEG</span></div><div class="status-item"><span class="status-label">Sound:</span><span id="currentSource" class="status-value">None</span></div><div class="status-item"><span class="status-label">Resolution:</span><span class="status-value">{VIDEO_WIDTH}x{VIDEO_HEIGHT}</span></div></div></div></div><audio id="browserAudio" loop style="display:none;"><source src="/static/sound.mp3" type="audio/mpeg"></audio><script>const videoPlayer = document.getElementById('videoPlayer');const mjpegImg = document.getElementById('mjpegImg');const browserAudio = document.getElementById('browserAudio');let currentFormat = 'mjpeg';let currentSource = 'none';let lastMouseSend = 0;// Mouse trackingfunction handleMouseMove(e) {{const rect = (currentFormat === 'mjpeg' ? mjpegImg : videoPlayer).getBoundingClientRect();const x = Math.round((e.clientX - rect.left) * {VIDEO_WIDTH} / rect.width);const y = Math.round((e.clientY - rect.top) * {VIDEO_HEIGHT} / rect.height);document.getElementById('mouseCoords').innerHTML = `X: ${{x}}, Y: ${{y}}`;const now = Date.now();if (now - lastMouseSend > 33) {{fetch('/mouse', {{method: 'POST',headers: {{'Content-Type': 'application/json'}},body: JSON.stringify({{x: x, y: y}})}});lastMouseSend = now;}}}}// Click handling for buttonfunction handleClick(e) {{const rect = (currentFormat === 'mjpeg' ? mjpegImg : videoPlayer).getBoundingClientRect();const x = Math.round((e.clientX - rect.left) * {VIDEO_WIDTH} / rect.width);const y = Math.round((e.clientY - rect.top) * {VIDEO_HEIGHT} / rect.height);fetch('/click', {{method: 'POST',headers: {{'Content-Type': 'application/json'}},body: JSON.stringify({{x: x, y: y}})}});}}videoPlayer.addEventListener('mousemove', handleMouseMove);mjpegImg.addEventListener('mousemove', handleMouseMove);videoPlayer.addEventListener('click', handleClick);mjpegImg.addEventListener('click', handleClick);// Sound handlingfunction setSound(source) {{currentSource = source;document.getElementById('btnNone').className = source === 'none' ? 'active' : '';document.getElementById('btnPygame').className = source === 'pygame' ? 'active' : '';document.getElementById('btnBrowser').className = source === 'browser' ? 'active' : '';document.getElementById('currentSource').innerHTML =source.charAt(0).toUpperCase() + source.slice(1);if (source === 'browser') {{browserAudio.play().catch(e => console.log('Audio error:', e));}} else {{browserAudio.pause();browserAudio.currentTime = 0;}}fetch('/sound/source', {{method: 'POST',headers: {{'Content-Type': 'application/json'}},body: JSON.stringify({{source: source}})}});}}// Sound meterfunction updateSoundMeter() {{fetch('/sound/amp').then(res => res.json()).then(data => {{document.getElementById('soundMeter').style.width = (data.amp * 100) + '%';}});setTimeout(updateSoundMeter, 100);}}updateSoundMeter();// Format switchingfunction setFormat(format) {{currentFormat = format;document.getElementById('btnMjpeg').className = format === 'mjpeg' ? 'active' : '';document.getElementById('btnWebm').className = format === 'webm' ? 'active' : '';document.getElementById('btnMp4').className = format === 'mp4' ? 'active' : '';document.getElementById('currentFormat').innerHTML = format.toUpperCase();videoPlayer.style.display = 'none';mjpegImg.style.display = 'none';if (format === 'mjpeg') {{mjpegImg.style.display = 'block';mjpegImg.src = '/video/mjpeg?' + Date.now();}} else {{videoPlayer.style.display = 'block';videoPlayer.src = `/video/${{format}}?` + Date.now();videoPlayer.play().catch(e => console.log('Playback error:', e));}}}}// InitializesetFormat('mjpeg');setSound('none');</script></body></html>''')if __name__ == '__main__':print("\n" + "="*70)print("🎮 Pygame 720p Streaming App")print("="*70)print(f"📡 Resolution: {VIDEO_WIDTH}x{VIDEO_HEIGHT} @ {VIDEO_FPS}fps")print("📡 Streaming endpoints:")print(" • /video/mjpeg - MJPEG stream")print(" • /video/webm - WebM stream")print(" • /video/mp4 - MP4 stream")print("🖱️ Interactive: mouse + clickable button")print(f"\n🌐 Main page: /")print("="*70 + "\n")port = int(os.environ.get('PORT', STREAM_PORT))app.run(host='0.0.0.0', port=port, debug=False, threaded=True)
app.py+417-449