]> jfr.im git - yt-dlp.git/blame - youtube_dl/downloader/hls.py
[odnoklassniki] update tests
[yt-dlp.git] / youtube_dl / downloader / hls.py
CommitLineData
f0b5d6af
PH
1from __future__ import unicode_literals
2
12b84ac8 3import os.path
f0b5d6af 4import re
e154c651 5import binascii
6try:
7 from Crypto.Cipher import AES
8 can_decrypt_frag = True
9except ImportError:
10 can_decrypt_frag = False
3bc2ddcc 11
f9a5affa 12from .fragment import FragmentFD
0d66bd0e 13from .external import FFmpegFD
f9a5affa 14
e154c651 15from ..compat import (
25afc2a7 16 compat_urllib_error,
e154c651 17 compat_urlparse,
18 compat_struct_pack,
19)
1cc79574 20from ..utils import (
3bc2ddcc 21 encodeFilename,
fcd9e423 22 sanitize_open,
e154c651 23 parse_m3u8_attributes,
aaf44a2f 24 update_url_query,
3bc2ddcc
JMF
25)
26
27
12b84ac8 28class HlsFD(FragmentFD):
29 """ A limited implementation that does not require ffmpeg """
f0b5d6af 30
f9a5affa
S
31 FD_NAME = 'hlsnative'
32
0d66bd0e 33 @staticmethod
6f126d90 34 def can_download(manifest, info_dict):
0d66bd0e 35 UNSUPPORTED_FEATURES = (
e154c651 36 r'#EXT-X-KEY:METHOD=(?!NONE|AES-128)', # encrypted streams [1]
f5974637 37 # r'#EXT-X-BYTERANGE', # playlists composed of byte ranges of media files [2]
1e236d7e 38
c15c47d1
S
39 # Live streams heuristic does not always work (e.g. geo restricted to Germany
40 # http://hls-geo.daserste.de/i/videoportal/Film/c_620000/622873/format,716451,716457,716450,716458,716459,.mp4.csmil/index_4_av.m3u8?null=0)
2937590e 41 # r'#EXT-X-MEDIA-SEQUENCE:(?!0$)', # live streams [3]
1e236d7e
S
42
43 # This heuristic also is not correct since segments may not be appended as well.
633b444f
S
44 # Twitch vods of finished streams have EXT-X-PLAYLIST-TYPE:EVENT despite
45 # no segments will definitely be appended to the end of the playlist.
1e236d7e 46 # r'#EXT-X-PLAYLIST-TYPE:EVENT', # media segments may be appended to the end of
51c4d85c 47 # # event media playlists [4]
1e236d7e 48
0d66bd0e
S
49 # 1. https://tools.ietf.org/html/draft-pantos-http-live-streaming-17#section-4.3.2.4
50 # 2. https://tools.ietf.org/html/draft-pantos-http-live-streaming-17#section-4.3.2.2
51 # 3. https://tools.ietf.org/html/draft-pantos-http-live-streaming-17#section-4.3.3.2
6104cc29 52 # 4. https://tools.ietf.org/html/draft-pantos-http-live-streaming-17#section-4.3.3.5
0d66bd0e 53 )
e154c651 54 check_results = [not re.search(feature, manifest) for feature in UNSUPPORTED_FEATURES]
f5974637
RA
55 is_aes128_enc = '#EXT-X-KEY:METHOD=AES-128' in manifest
56 check_results.append(can_decrypt_frag or not is_aes128_enc)
57 check_results.append(not (is_aes128_enc and r'#EXT-X-BYTERANGE' in manifest))
2bfaf89b 58 check_results.append(not info_dict.get('is_live'))
e154c651 59 return all(check_results)
0d66bd0e 60
f0b5d6af 61 def real_download(self, filename, info_dict):
f9a5affa
S
62 man_url = info_dict['url']
63 self.to_screen('[%s] Downloading m3u8 manifest' % self.FD_NAME)
69035555
S
64
65 manifest = self.ydl.urlopen(self._prepare_url(info_dict, man_url)).read()
f0b5d6af 66
f9a5affa 67 s = manifest.decode('utf-8', 'ignore')
0d66bd0e 68
6f126d90 69 if not self.can_download(s, info_dict):
bfa1073e
RA
70 if info_dict.get('extra_param_to_segment_url'):
71 self.report_error('pycrypto not found. Please install it.')
72 return False
2bfaf89b
RA
73 self.report_warning(
74 'hlsnative has detected features it does not support, '
75 'extraction will be delegated to ffmpeg')
76 fd = FFmpegFD(self.ydl, self.params)
77 for ph in self._progress_hooks:
78 fd.add_progress_hook(ph)
79 return fd.real_download(filename, info_dict)
0d66bd0e 80
e154c651 81 total_frags = 0
f0b5d6af
PH
82 for line in s.splitlines():
83 line = line.strip()
84 if line and not line.startswith('#'):
e154c651 85 total_frags += 1
f0b5d6af 86
f9a5affa 87 ctx = {
f0b5d6af 88 'filename': filename,
e154c651 89 'total_frags': total_frags,
f9a5affa
S
90 }
91
92 self._prepare_and_start_frag_download(ctx)
93
25afc2a7
S
94 fragment_retries = self.params.get('fragment_retries', 0)
95 skip_unavailable_fragments = self.params.get('skip_unavailable_fragments', True)
96 test = self.params.get('test', False)
97
b8079a40 98 extra_query = None
aaf44a2f 99 extra_param_to_segment_url = info_dict.get('extra_param_to_segment_url')
b8079a40
RA
100 if extra_param_to_segment_url:
101 extra_query = compat_urlparse.parse_qs(extra_param_to_segment_url)
e154c651 102 i = 0
103 media_sequence = 0
104 decrypt_info = {'METHOD': 'NONE'}
f5974637 105 byte_range = {}
f9a5affa 106 frags_filenames = []
e154c651 107 for line in s.splitlines():
108 line = line.strip()
109 if line:
110 if not line.startswith('#'):
111 frag_url = (
112 line
113 if re.match(r'^https?://', line)
114 else compat_urlparse.urljoin(man_url, line))
25afc2a7
S
115 frag_name = 'Frag%d' % i
116 frag_filename = '%s-%s' % (ctx['tmpfilename'], frag_name)
b8079a40
RA
117 if extra_query:
118 frag_url = update_url_query(frag_url, extra_query)
25afc2a7 119 count = 0
f5974637
RA
120 headers = info_dict.get('http_headers', {})
121 if byte_range:
122 headers['Range'] = 'bytes=%d-%d' % (byte_range['start'], byte_range['end'])
25afc2a7
S
123 while count <= fragment_retries:
124 try:
69035555
S
125 success = ctx['dl'].download(frag_filename, {
126 'url': frag_url,
f5974637 127 'http_headers': headers,
69035555 128 })
25afc2a7
S
129 if not success:
130 return False
131 down, frag_sanitized = sanitize_open(frag_filename, 'rb')
132 frag_content = down.read()
133 down.close()
134 break
2e99cd30 135 except compat_urllib_error.HTTPError as err:
25afc2a7
S
136 # Unavailable (possibly temporary) fragments may be served.
137 # First we try to retry then either skip or abort.
138 # See https://github.com/rg3/youtube-dl/issues/10165,
139 # https://github.com/rg3/youtube-dl/issues/10448).
140 count += 1
141 if count <= fragment_retries:
2e99cd30 142 self.report_retry_fragment(err, frag_name, count, fragment_retries)
25afc2a7
S
143 if count > fragment_retries:
144 if skip_unavailable_fragments:
145 i += 1
146 media_sequence += 1
147 self.report_skip_fragment(frag_name)
148 continue
149 self.report_error(
150 'giving up after %s fragment retries' % fragment_retries)
e154c651 151 return False
e154c651 152 if decrypt_info['METHOD'] == 'AES-128':
8369a4fe
S
153 iv = decrypt_info.get('IV') or compat_struct_pack('>8xq', media_sequence)
154 frag_content = AES.new(
155 decrypt_info['KEY'], AES.MODE_CBC, iv).decrypt(frag_content)
e154c651 156 ctx['dest_stream'].write(frag_content)
157 frags_filenames.append(frag_sanitized)
158 # We only download the first fragment during the test
25afc2a7 159 if test:
e154c651 160 break
161 i += 1
162 media_sequence += 1
163 elif line.startswith('#EXT-X-KEY'):
164 decrypt_info = parse_m3u8_attributes(line[11:])
165 if decrypt_info['METHOD'] == 'AES-128':
166 if 'IV' in decrypt_info:
07ea9c9b 167 decrypt_info['IV'] = binascii.unhexlify(decrypt_info['IV'][2:].zfill(32))
e154c651 168 if not re.match(r'^https?://', decrypt_info['URI']):
8369a4fe
S
169 decrypt_info['URI'] = compat_urlparse.urljoin(
170 man_url, decrypt_info['URI'])
b8079a40
RA
171 if extra_query:
172 decrypt_info['URI'] = update_url_query(decrypt_info['URI'], extra_query)
e154c651 173 decrypt_info['KEY'] = self.ydl.urlopen(decrypt_info['URI']).read()
174 elif line.startswith('#EXT-X-MEDIA-SEQUENCE'):
175 media_sequence = int(line[22:])
f5974637
RA
176 elif line.startswith('#EXT-X-BYTERANGE'):
177 splitted_byte_range = line[17:].split('@')
178 sub_range_start = int(splitted_byte_range[1]) if len(splitted_byte_range) == 2 else byte_range['end']
179 byte_range = {
180 'start': sub_range_start,
181 'end': sub_range_start + int(splitted_byte_range[0]),
182 }
f9a5affa
S
183
184 self._finish_frag_download(ctx)
185
186 for frag_file in frags_filenames:
fcd9e423 187 os.remove(encodeFilename(frag_file))
f9a5affa 188
f0b5d6af 189 return True