Last active
October 13, 2022 21:12
-
-
Save bbayles/d4df156ecbd4a162f279ed2f8465124e to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
"""Quick and dirty HLS transport stream downloader. | |
Give it a URI that points to a media playlist (one that contains transport stream URIs, | |
not a multivariant playlist that contains other playlist URIs). | |
It will read the playlist, download all the segments, and write them to your chosen | |
output location. | |
A single output file is created. This works because MPEG Transport Stream files | |
can be concatenated. | |
""" | |
from argparse import ArgumentParser | |
from concurrent.futures import ThreadPoolExecutor | |
from sys import argv | |
from m3u8 import loads as m3u8_loads | |
from requests import Session | |
def main(args=None): | |
args = args or argv[1:] | |
argument_parser = ArgumentParser(description='HLS transport stream downloader') | |
argument_parser.add_argument('playlist_uri', type=str, help='Playlist location') | |
argument_parser.add_argument( | |
'output_path', type=str, help='Output transport stream location' | |
) | |
argument_parser.add_argument( | |
'--threads', type=int, default=8, help='Number of concurrent downloads' | |
) | |
parsed_args = argument_parser.parse_args() | |
playlist_uri = parsed_args.playlist_uri | |
max_workers = parsed_args.threads | |
output_path = parsed_args.output_path | |
pool = ThreadPoolExecutor(max_workers=max_workers) | |
session = Session() | |
outfile = open(output_path, 'wb') | |
with pool, session, outfile: | |
playlist_text = session.get(playlist_uri).text | |
parsed_playlist = m3u8_loads(playlist_text, uri=playlist_uri) | |
all_uris = (s.absolute_uri for s in parsed_playlist.segments) | |
for data in pool.map(lambda uri: session.get(uri).content, all_uris): | |
outfile.write(data) | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You'll need to run
python -m pip install m3u8 requests
to download the required libraries for this script. Then run it withpython ./hls_ts_download.py
.