run streamlink with asyncio.to_thread

This commit is contained in:
Roy Olav Purser 2021-05-15 10:18:10 +02:00
parent df153d5a12
commit dd61429524
Signed by: roypur
GPG Key ID: E14D26A036F21656

View File

@ -4,6 +4,7 @@ import sys
import urllib.parse
import re
import os
import time
import base64
import logging
import asyncio
@ -98,6 +99,15 @@ class AsyncSession():
resp = await self.sdata.resp
return AsyncSessionData(resp, self.sdata.current)
class StreamRunner():
def __init__(self, upstream, proxy):
self.upstream = upstream
self.proxy = proxy
def stream(self):
return self.proxy.stream().streams(self.upstream)
async def run(self):
return await asyncio.to_thread(self.stream)
proxies = {}
for key in providers:
proxies[key] = []
@ -298,6 +308,7 @@ async def rewrite(current, proxy):
ndata += links.pop(0)
ndata += "\n"
return ndata
class MainHandler(tornado.web.RequestHandler):
async def handle_any(self, redir):
handler = UpstreamHandler()
@ -332,13 +343,17 @@ class MainHandler(tornado.web.RequestHandler):
async def handle_stream(self, handler, redir):
upstream = None
streams = None
runner = StreamRunner(handler.upstream, handler.proxy)
start_time = time.time_ns()
for i in range(5):
try:
streams = handler.proxy.stream().streams(handler.upstream)
streams = await runner.run()
except Exception as e:
logger.info(e)
else:
break
stop_time = time.time_ns()
logger.info((stop_time - start_time) // 1_000_000)
if streams is not None:
for key in reversed(streams):
stream = streams.get(key)