]> jfr.im git - yt-dlp.git/blame - yt_dlp/downloader/websocket.py
Fix `--skip-unavailable-fragments`
[yt-dlp.git] / yt_dlp / downloader / websocket.py
CommitLineData
f8271158 1import asyncio
e36d50c5 2import os
3import signal
e36d50c5 4import threading
5
6try:
7 import websockets
1e5d87be 8except (ImportError, SyntaxError):
9 # websockets 3.10 on python 3.6 causes SyntaxError
10 # See https://github.com/yt-dlp/yt-dlp/issues/2633
e36d50c5 11 has_websockets = False
1e5d87be 12else:
13 has_websockets = True
e36d50c5 14
15from .common import FileDownloader
16from .external import FFmpegFD
17
18
19class FFmpegSinkFD(FileDownloader):
20 """ A sink to ffmpeg for downloading fragments in any form """
21
22 def real_download(self, filename, info_dict):
23 info_copy = info_dict.copy()
24 info_copy['url'] = '-'
25
26 async def call_conn(proc, stdin):
27 try:
28 await self.real_connection(stdin, info_dict)
29 except (BrokenPipeError, OSError):
30 pass
31 finally:
32 try:
33 stdin.flush()
34 stdin.close()
35 except OSError:
36 pass
37 os.kill(os.getpid(), signal.SIGINT)
38
39 class FFmpegStdinFD(FFmpegFD):
40 @classmethod
41 def get_basename(cls):
42 return FFmpegFD.get_basename()
43
44 def on_process_started(self, proc, stdin):
45 thread = threading.Thread(target=asyncio.run, daemon=True, args=(call_conn(proc, stdin), ))
46 thread.start()
47
48 return FFmpegStdinFD(self.ydl, self.params or {}).download(filename, info_copy)
49
50 async def real_connection(self, sink, info_dict):
51 """ Override this in subclasses """
52 raise NotImplementedError('This method must be implemented by subclasses')
53
54
55class WebSocketFragmentFD(FFmpegSinkFD):
56 async def real_connection(self, sink, info_dict):
57 async with websockets.connect(info_dict['url'], extra_headers=info_dict.get('http_headers', {})) as ws:
58 while True:
59 recv = await ws.recv()
60 if isinstance(recv, str):
61 recv = recv.encode('utf8')
62 sink.write(recv)