]> gitweb @ CieloNegro.org - youtube-dl.git/blob - youtube_dl/downloader/hls.py
[turner] fix secure m3u8 formats downloading
[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_urlparse,
17     compat_struct_pack,
18 )
19 from ..utils import (
20     encodeFilename,
21     sanitize_open,
22     parse_m3u8_attributes,
23     update_url_query,
24 )
25
26
27 class HlsFD(FragmentFD):
28     """ A limited implementation that does not require ffmpeg """
29
30     FD_NAME = 'hlsnative'
31
32     @staticmethod
33     def can_download(manifest):
34         UNSUPPORTED_FEATURES = (
35             r'#EXT-X-KEY:METHOD=(?!NONE|AES-128)',  # encrypted streams [1]
36             r'#EXT-X-BYTERANGE',  # playlists composed of byte ranges of media files [2]
37
38             # Live streams heuristic does not always work (e.g. geo restricted to Germany
39             # 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)
40             # r'#EXT-X-MEDIA-SEQUENCE:(?!0$)',  # live streams [3]
41
42             # This heuristic also is not correct since segments may not be appended as well.
43             # Twitch vods of finished streams have EXT-X-PLAYLIST-TYPE:EVENT despite
44             # no segments will definitely be appended to the end of the playlist.
45             # r'#EXT-X-PLAYLIST-TYPE:EVENT',  # media segments may be appended to the end of
46             #                                 # event media playlists [4]
47
48             # 1. https://tools.ietf.org/html/draft-pantos-http-live-streaming-17#section-4.3.2.4
49             # 2. https://tools.ietf.org/html/draft-pantos-http-live-streaming-17#section-4.3.2.2
50             # 3. https://tools.ietf.org/html/draft-pantos-http-live-streaming-17#section-4.3.3.2
51             # 4. https://tools.ietf.org/html/draft-pantos-http-live-streaming-17#section-4.3.3.5
52         )
53         check_results = [not re.search(feature, manifest) for feature in UNSUPPORTED_FEATURES]
54         check_results.append(can_decrypt_frag or '#EXT-X-KEY:METHOD=AES-128' not in manifest)
55         return all(check_results)
56
57     def real_download(self, filename, info_dict):
58         man_url = info_dict['url']
59         self.to_screen('[%s] Downloading m3u8 manifest' % self.FD_NAME)
60         manifest = self.ydl.urlopen(man_url).read()
61
62         s = manifest.decode('utf-8', 'ignore')
63
64         if not self.can_download(s):
65             self.report_warning(
66                 'hlsnative has detected features it does not support, '
67                 'extraction will be delegated to ffmpeg')
68             fd = FFmpegFD(self.ydl, self.params)
69             for ph in self._progress_hooks:
70                 fd.add_progress_hook(ph)
71             return fd.real_download(filename, info_dict)
72
73         total_frags = 0
74         for line in s.splitlines():
75             line = line.strip()
76             if line and not line.startswith('#'):
77                 total_frags += 1
78
79         ctx = {
80             'filename': filename,
81             'total_frags': total_frags,
82         }
83
84         self._prepare_and_start_frag_download(ctx)
85
86         extra_query = None
87         extra_param_to_segment_url = info_dict.get('extra_param_to_segment_url')
88         if extra_param_to_segment_url:
89             extra_query = compat_urlparse.parse_qs(extra_param_to_segment_url)
90         i = 0
91         media_sequence = 0
92         decrypt_info = {'METHOD': 'NONE'}
93         frags_filenames = []
94         for line in s.splitlines():
95             line = line.strip()
96             if line:
97                 if not line.startswith('#'):
98                     frag_url = (
99                         line
100                         if re.match(r'^https?://', line)
101                         else compat_urlparse.urljoin(man_url, line))
102                     frag_filename = '%s-Frag%d' % (ctx['tmpfilename'], i)
103                     if extra_query:
104                         frag_url = update_url_query(frag_url, extra_query)
105                     success = ctx['dl'].download(frag_filename, {'url': frag_url})
106                     if not success:
107                         return False
108                     down, frag_sanitized = sanitize_open(frag_filename, 'rb')
109                     frag_content = down.read()
110                     down.close()
111                     if decrypt_info['METHOD'] == 'AES-128':
112                         iv = decrypt_info.get('IV') or compat_struct_pack('>8xq', media_sequence)
113                         frag_content = AES.new(
114                             decrypt_info['KEY'], AES.MODE_CBC, iv).decrypt(frag_content)
115                     ctx['dest_stream'].write(frag_content)
116                     frags_filenames.append(frag_sanitized)
117                     # We only download the first fragment during the test
118                     if self.params.get('test', False):
119                         break
120                     i += 1
121                     media_sequence += 1
122                 elif line.startswith('#EXT-X-KEY'):
123                     decrypt_info = parse_m3u8_attributes(line[11:])
124                     if decrypt_info['METHOD'] == 'AES-128':
125                         if 'IV' in decrypt_info:
126                             decrypt_info['IV'] = binascii.unhexlify(decrypt_info['IV'][2:].zfill(32))
127                         if not re.match(r'^https?://', decrypt_info['URI']):
128                             decrypt_info['URI'] = compat_urlparse.urljoin(
129                                 man_url, decrypt_info['URI'])
130                         if extra_query:
131                             decrypt_info['URI'] = update_url_query(decrypt_info['URI'], extra_query)
132                         decrypt_info['KEY'] = self.ydl.urlopen(decrypt_info['URI']).read()
133                 elif line.startswith('#EXT-X-MEDIA-SEQUENCE'):
134                     media_sequence = int(line[22:])
135
136         self._finish_frag_download(ctx)
137
138         for frag_file in frags_filenames:
139             os.remove(encodeFilename(frag_file))
140
141         return True