Advertisement
martastain

On the fly mp4 rewrapping server

Nov 4th, 2020
137
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.52 KB | None | 0 0
  1. #!/usr/bin/env python3
  2.  
  3. import asyncio
  4. import sanic
  5.  
  6. app = sanic.Sanic("VOD Downloader")
  7.  
  8. STREAM_TPL = "https://vod.nebulabroadcast.com/sport5/{key}/index-f1-v1-f4-a1.m3u8"
  9.  
  10. class Rewrapper():
  11.     def __init__(self, vod_key):
  12.         source_url = STREAM_TPL.format(key=vod_key)
  13.         self.args = [
  14.             "-i", source_url,
  15.             "-c:v", "copy",
  16.             "-c:a", "copy",
  17.             "-movflags", "frag_keyframe+empty_moov",
  18.             "-bsf:a", "aac_adtstoasc",
  19.             "-f", "mp4", "-"]
  20.  
  21.     async def start(self):
  22.         self.proc = await asyncio.create_subprocess_exec("ffmpeg", *self.args, stdout=asyncio.subprocess.PIPE)
  23.  
  24.     async def read(self):
  25.         return await self.proc.stdout.read(1024*1024)
  26.  
  27.     async def finish(self):
  28.         await self.proc.wait()
  29.         self.proc = None
  30.  
  31.     def __del__(self):
  32.         if self.proc:
  33.             print("Terminating rewrapper")
  34.             self.proc.kill()
  35.             asyncio.shield(self.proc.wait())
  36.  
  37. @app.route("/download/<vod_key:string>.mp4")
  38. async def test(request, vod_key):
  39.  
  40.     async def streaming_fn(response):
  41.         rewrapper = Rewrapper(vod_key)
  42.         await rewrapper.start()
  43.         while True:
  44.             buff = await rewrapper.read()
  45.             if not buff:
  46.                 break
  47.             await response.write(buff)
  48.         await rewrapper.finish()
  49.  
  50.     return sanic.response.stream(streaming_fn, content_type='video/mp4')
  51.  
  52. if __name__ == "__main__":
  53.     app.run(host="0.0.0.0", port=8910)
  54.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement