-def download_hls_get_stream(url, hack_url_func):
- url = hack_url_func(url)
-
- def parse_bandwidth(line):
- params = line.split(":", 1)[1].split(",")
- for kv in params:
- k, v = kv.split("=", 1)
- if k == "BANDWIDTH":
- return int(v)
- return 0
-
- m3u8 = grab_text(url, 0)
- best_bandwidth = None
- best_url = None
- for line in m3u8.split("\n"):
- if line.startswith("#EXT-X-STREAM-INF:"):
- bandwidth = parse_bandwidth(line)
- if best_bandwidth is None or bandwidth > best_bandwidth:
- best_bandwidth = bandwidth
- best_url = None
- elif not line.startswith("#"):
- if best_url is None:
- best_url = line.strip()
-
- if not best_url:
- raise Exception("Failed to find best stream for HLS: " + url)
-
- return best_url
-
-def download_hls_segments(tmpdir, url, hack_url_func):
- m3u8 = grab_text(url, 0)
- result = []
-
- local_m3u8_filename = tmpdir + "/index.m3u8"
- local_m3u8 = open(local_m3u8_filename, "w")
-
- i = 1
- for line in m3u8.split("\n"):
- if not line.strip():
- continue
- if line.startswith("#"):
- local_m3u8.write(line + "\n")
- continue
-
- outfile = "%s/segment_%d.ts" % (tmpdir, i)
- i += 1
- local_m3u8.write(outfile + "\n")
- download_hls_fetch_segment(line, outfile)
- sys.stdout.write(".")
- sys.stdout.flush()
-
- sys.stdout.write("\n")
-
- local_m3u8.close()
- return local_m3u8_filename
-
-def download_hls_fetch_segment(segment, outfile):
- try:
- src = _urlopen(segment)
- dst = open(outfile, "w")
- shutil.copyfileobj(src, dst)
- finally:
- try:
- src.close()
- except:
- pass
- try:
- dst.close()
- except:
- pass