]> gitweb @ CieloNegro.org - youtube-dl.git/blob - youtube_dl/downloader/hls.py
[downloader/dash:hls] Respect --fragment-retries and --skip-unavailable-fragments...
[youtube-dl.git] / youtube_dl / downloader / hls.py
1 from __future__ import unicode_literals
2
3 import os.path
4 import re
5 import binascii
6 try:
7     from Crypto.Cipher import AES
8     can_decrypt_frag = True
9 except ImportError:
10     can_decrypt_frag = False
11
12 from .fragment import FragmentFD
13 from .external import FFmpegFD
14
15 from ..compat import (
16     compat_urllib_error,
17     compat_urlparse,
18     compat_struct_pack,
19 )
20 from ..utils import (
21     encodeFilename,
22     sanitize_open,
23     parse_m3u8_attributes,
24     update_url_query,
25 )
26
27
28 class HlsFD(FragmentFD):
29     """ A limited implementation that does not require ffmpeg """
30
31     FD_NAME = 'hlsnative'
32
33     @staticmethod
34     def can_download(manifest):
35         UNSUPPORTED_FEATURES = (
36             r'#EXT-X-KEY:METHOD=(?!NONE|AES-128)',  # encrypted streams [1]
37             r'#EXT-X-BYTERANGE',  # playlists composed of byte ranges of media files [2]
38
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)
41             # r'#EXT-X-MEDIA-SEQUENCE:(?!0$)',  # live streams [3]
42
43             # This heuristic also is not correct since segments may not be appended as well.
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.
46             # r'#EXT-X-PLAYLIST-TYPE:EVENT',  # media segments may be appended to the end of
47             #                                 # event media playlists [4]
48
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
52             # 4. https://tools.ietf.org/html/draft-pantos-http-live-streaming-17#section-4.3.3.5
53         )
54         check_results = [not re.search(feature, manifest) for feature in UNSUPPORTED_FEATURES]
55         check_results.append(can_decrypt_frag or '#EXT-X-KEY:METHOD=AES-128' not in manifest)
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         manifest = self.ydl.urlopen(man_url).read()
62
63         s = manifest.decode('utf-8', 'ignore')
64
65         if not self.can_download(s):
66             self.report_warning(
67                 'hlsnative has detected features it does not support, '
68                 'extraction will be delegated to ffmpeg')
69             fd = FFmpegFD(self.ydl, self.params)
70             for ph in self._progress_hooks:
71                 fd.add_progress_hook(ph)
72             return fd.real_download(filename, info_dict)
73
74         total_frags = 0
75         for line in s.splitlines():
76             line = line.strip()
77             if line and not line.startswith('#'):
78                 total_frags += 1
79
80         ctx = {
81             'filename': filename,
82             'total_frags': total_frags,
83         }
84
85         self._prepare_and_start_frag_download(ctx)
86
87         fragment_retries = self.params.get('fragment_retries', 0)
88         skip_unavailable_fragments = self.params.get('skip_unavailable_fragments', True)
89         test = self.params.get('test', False)
90
91         extra_query = None
92         extra_param_to_segment_url = info_dict.get('extra_param_to_segment_url')
93         if extra_param_to_segment_url:
94             extra_query = compat_urlparse.parse_qs(extra_param_to_segment_url)
95         i = 0
96         media_sequence = 0
97         decrypt_info = {'METHOD': 'NONE'}
98         frags_filenames = []
99         for line in s.splitlines():
100             line = line.strip()
101             if line:
102                 if not line.startswith('#'):
103                     frag_url = (
104                         line
105                         if re.match(r'^https?://', line)
106                         else compat_urlparse.urljoin(man_url, line))
107                     frag_name = 'Frag%d' % i
108                     frag_filename = '%s-%s' % (ctx['tmpfilename'], frag_name)
109                     if extra_query:
110                         frag_url = update_url_query(frag_url, extra_query)
111                     count = 0
112                     while count <= fragment_retries:
113                         try:
114                             success = ctx['dl'].download(frag_filename, {'url': frag_url})
115                             if not success:
116                                 return False
117                             down, frag_sanitized = sanitize_open(frag_filename, 'rb')
118                             frag_content = down.read()
119                             down.close()
120                             break
121                         except compat_urllib_error.HTTPError:
122                             # Unavailable (possibly temporary) fragments may be served.
123                             # First we try to retry then either skip or abort.
124                             # See https://github.com/rg3/youtube-dl/issues/10165,
125                             # https://github.com/rg3/youtube-dl/issues/10448).
126                             count += 1
127                             if count <= fragment_retries:
128                                 self.report_retry_fragment(frag_name, count, fragment_retries)
129                     if count > fragment_retries:
130                         if skip_unavailable_fragments:
131                             i += 1
132                             media_sequence += 1
133                             self.report_skip_fragment(frag_name)
134                             continue
135                         self.report_error(
136                             'giving up after %s fragment retries' % fragment_retries)
137                         return False
138                     if decrypt_info['METHOD'] == 'AES-128':
139                         iv = decrypt_info.get('IV') or compat_struct_pack('>8xq', media_sequence)
140                         frag_content = AES.new(
141                             decrypt_info['KEY'], AES.MODE_CBC, iv).decrypt(frag_content)
142                     ctx['dest_stream'].write(frag_content)
143                     frags_filenames.append(frag_sanitized)
144                     # We only download the first fragment during the test
145                     if test:
146                         break
147                     i += 1
148                     media_sequence += 1
149                 elif line.startswith('#EXT-X-KEY'):
150                     decrypt_info = parse_m3u8_attributes(line[11:])
151                     if decrypt_info['METHOD'] == 'AES-128':
152                         if 'IV' in decrypt_info:
153                             decrypt_info['IV'] = binascii.unhexlify(decrypt_info['IV'][2:].zfill(32))
154                         if not re.match(r'^https?://', decrypt_info['URI']):
155                             decrypt_info['URI'] = compat_urlparse.urljoin(
156                                 man_url, decrypt_info['URI'])
157                         if extra_query:
158                             decrypt_info['URI'] = update_url_query(decrypt_info['URI'], extra_query)
159                         decrypt_info['KEY'] = self.ydl.urlopen(decrypt_info['URI']).read()
160                 elif line.startswith('#EXT-X-MEDIA-SEQUENCE'):
161                     media_sequence = int(line[22:])
162
163         self._finish_frag_download(ctx)
164
165         for frag_file in frags_filenames:
166             os.remove(encodeFilename(frag_file))
167
168         return True