|
| 1 | +"""Helper methods for working with yt-dlp. |
| 2 | +
|
| 3 | +Currently ytp-dl is used to extract video URLs from various video sites, e.g. YouTube |
| 4 | +so they can be streamed via AirPlay. |
| 5 | +""" |
| 6 | +import asyncio |
| 7 | + |
| 8 | +from pyatv import exceptions |
| 9 | + |
| 10 | + |
| 11 | +def _extract_video_url(video_link: str) -> str: |
| 12 | + # TODO: For now, dynamic support for this feature. User must manually install |
| 13 | + # yt-dlp, it will not be pulled in by pyatv. |
| 14 | + try: |
| 15 | + import yt_dlp # pylint: disable=import-outside-toplevel |
| 16 | + except ModuleNotFoundError as ex: |
| 17 | + raise exceptions.NotSupportedError("package yt-dlp not installed") from ex |
| 18 | + |
| 19 | + with yt_dlp.YoutubeDL({"quiet": True, "no_warnings": True}) as ydl: |
| 20 | + info = ydl.sanitize_info(ydl.extract_info(video_link, download=False)) |
| 21 | + |
| 22 | + if "formats" not in info: |
| 23 | + raise exceptions.NotSupportedError( |
| 24 | + "formats are missing, maybe authentication is needed (not supported)?" |
| 25 | + ) |
| 26 | + |
| 27 | + best = None |
| 28 | + best_bitrate = 0 |
| 29 | + |
| 30 | + # Try to find supported video stream with highest bitrate. No way to customize |
| 31 | + # this in any way for now. |
| 32 | + for video_format in [ |
| 33 | + x for x in info["formats"] if x.get("protocol") == "m3u8_native" |
| 34 | + ]: |
| 35 | + if video_format["video_ext"] == "none": |
| 36 | + continue |
| 37 | + if video_format["has_drm"]: |
| 38 | + continue |
| 39 | + |
| 40 | + if video_format["vbr"] > best_bitrate: |
| 41 | + best = video_format |
| 42 | + best_bitrate = video_format["vbr"] |
| 43 | + |
| 44 | + if not best or "manifest_url" not in best: |
| 45 | + raise exceptions.NotSupportedError("manifest url could not be extracted") |
| 46 | + |
| 47 | + return best["manifest_url"] |
| 48 | + |
| 49 | + |
| 50 | +async def extract_video_url(video_link: str) -> str: |
| 51 | + """Extract video URL from external video service link. |
| 52 | +
|
| 53 | + This method takes a video link from a video service, e.g. YouTube, and extracts the |
| 54 | + underlying video URL that (hopefully) can be played via AirPlay. Currently yt-dlp |
| 55 | + is used to the extract the URL, thus all services supported by yt-dlp should be |
| 56 | + supported. No customization (e.g. resolution) nor authorization is supported at the |
| 57 | + moment, putting some restrictions on use case. |
| 58 | + """ |
| 59 | + loop = asyncio.get_event_loop() |
| 60 | + try: |
| 61 | + return await loop.run_in_executor(None, _extract_video_url, video_link) |
| 62 | + except Exception as ex: |
| 63 | + raise exceptions.InvalidFormatError(f"video {video_link} not supported") from ex |
0 commit comments