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