#!/usr/bin/env python3
"""dinnerplate optional local streaming bridge. CC0-1.0.
Install Python 3.10+, FFmpeg, then: python -m pip install websockets
Run: python stream-bridge.py
If browser blocks HTTPS-to-loopback, extract Download Local Version (HTML),
run `python -m http.server 8766 --bind 127.0.0.1` in that folder, and open
http://127.0.0.1:8766/recorder.html . Imported projects stay on that origin.
Stream keys are never printed or saved. FFmpeg and websockets retain their own
licenses; they are installed separately, not bundled in this bridge.
"""
import asyncio, json, secrets, shutil, subprocess
try:
 from websockets.asyncio.server import serve
except ImportError:
 raise SystemExit('Install the local dependency: python -m pip install websockets')
TOKEN=secrets.token_urlsafe(32)
ORIGINS=['https://dinnerplate.party','https://local-kit-monokai.chalkydaisy5.chatgpt.site','http://127.0.0.1:8766','http://localhost:8766','null']
active=asyncio.Lock()
def destination(platform,key):
 if not isinstance(key,str) or not key or len(key)>512 or any(c not in 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-' for c in key):
  raise ValueError('Use a valid platform stream key')
 if platform=='youtube':return 'rtmps://a.rtmps.youtube.com:443/live2/'+key
 if platform=='twitch':return 'rtmps://live.twitch.tv:443/app/'+key
 raise ValueError('Choose YouTube or Twitch')
async def client(ws):
 process=None
 try:
  config=json.loads(await asyncio.wait_for(ws.recv(),15))
  if not secrets.compare_digest(str(config.get('token','')),TOKEN):raise ValueError('Invalid bridge token')
  target=destination(config.get('platform'),config.get('key'))
  if active.locked():raise ValueError('Another stream is active')
  async with active:
   if not shutil.which('ffmpeg'):raise ValueError('Install FFmpeg on this computer first')
   process=await asyncio.create_subprocess_exec('ffmpeg','-loglevel','error','-i','pipe:0','-c:v','libx264','-preset','veryfast','-tune','zerolatency','-pix_fmt','yuv420p','-g','60','-c:a','aac','-b:a','160k','-f','flv',target,stdin=asyncio.subprocess.PIPE,stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL)
   await ws.send(json.dumps({'ready':True}))
   async for data in ws:
    if not isinstance(data,bytes):raise ValueError('Expected media bytes')
    process.stdin.write(data)
    await process.stdin.drain()
 except Exception:
  try:await ws.send(json.dumps({'error':'Live bridge stopped. Check the token, platform key, FFmpeg installation and platform streaming permissions.'}))
  except Exception:pass
 finally:
  if process:
   try:process.stdin.close();await asyncio.wait_for(process.wait(),5)
   except Exception:process.kill()
async def main():
 print('Local bridge: ws://127.0.0.1:8765\nSession token: '+TOKEN+'\nKeep this token private. Ctrl+C stops the bridge.')
 async with serve(client,'127.0.0.1',8765,origins=ORIGINS,max_size=16777216,max_queue=4,compression=None):await asyncio.Future()
if __name__=='__main__':
 try:asyncio.run(main())
 except KeyboardInterrupt:pass
