]> jfr.im git - yt-dlp.git/blob - yt_dlp/downloader/external.py
[aria2c] Fix IV for some AES-128 streams
[yt-dlp.git] / yt_dlp / downloader / external.py
1 from __future__ import unicode_literals
2
3 import os.path
4 import re
5 import subprocess
6 import sys
7 import time
8
9 from .common import FileDownloader
10 from ..aes import aes_cbc_decrypt_bytes
11 from ..compat import (
12 compat_setenv,
13 compat_str,
14 compat_struct_pack,
15 )
16 from ..postprocessor.ffmpeg import FFmpegPostProcessor, EXT_TO_OUT_FORMATS
17 from ..utils import (
18 cli_option,
19 cli_valueless_option,
20 cli_bool_option,
21 _configuration_args,
22 encodeFilename,
23 encodeArgument,
24 handle_youtubedl_headers,
25 check_executable,
26 is_outdated_version,
27 process_communicate_or_kill,
28 sanitized_Request,
29 sanitize_open,
30 )
31
32
33 class ExternalFD(FileDownloader):
34 SUPPORTED_PROTOCOLS = ('http', 'https', 'ftp', 'ftps')
35 can_download_to_stdout = False
36
37 def real_download(self, filename, info_dict):
38 self.report_destination(filename)
39 tmpfilename = self.temp_name(filename)
40
41 try:
42 started = time.time()
43 retval = self._call_downloader(tmpfilename, info_dict)
44 except KeyboardInterrupt:
45 if not info_dict.get('is_live'):
46 raise
47 # Live stream downloading cancellation should be considered as
48 # correct and expected termination thus all postprocessing
49 # should take place
50 retval = 0
51 self.to_screen('[%s] Interrupted by user' % self.get_basename())
52
53 if retval == 0:
54 status = {
55 'filename': filename,
56 'status': 'finished',
57 'elapsed': time.time() - started,
58 }
59 if filename != '-':
60 fsize = os.path.getsize(encodeFilename(tmpfilename))
61 self.to_screen('\r[%s] Downloaded %s bytes' % (self.get_basename(), fsize))
62 self.try_rename(tmpfilename, filename)
63 status.update({
64 'downloaded_bytes': fsize,
65 'total_bytes': fsize,
66 })
67 self._hook_progress(status, info_dict)
68 return True
69 else:
70 self.to_stderr('\n')
71 self.report_error('%s exited with code %d' % (
72 self.get_basename(), retval))
73 return False
74
75 @classmethod
76 def get_basename(cls):
77 return cls.__name__[:-2].lower()
78
79 @property
80 def exe(self):
81 return self.get_basename()
82
83 @classmethod
84 def available(cls, path=None):
85 path = check_executable(path or cls.get_basename(), [cls.AVAILABLE_OPT])
86 if path:
87 cls.exe = path
88 return path
89 return False
90
91 @classmethod
92 def supports(cls, info_dict):
93 return (
94 (cls.can_download_to_stdout or not info_dict.get('to_stdout'))
95 and info_dict['protocol'] in cls.SUPPORTED_PROTOCOLS)
96
97 @classmethod
98 def can_download(cls, info_dict, path=None):
99 return cls.available(path) and cls.supports(info_dict)
100
101 def _option(self, command_option, param):
102 return cli_option(self.params, command_option, param)
103
104 def _bool_option(self, command_option, param, true_value='true', false_value='false', separator=None):
105 return cli_bool_option(self.params, command_option, param, true_value, false_value, separator)
106
107 def _valueless_option(self, command_option, param, expected_value=True):
108 return cli_valueless_option(self.params, command_option, param, expected_value)
109
110 def _configuration_args(self, keys=None, *args, **kwargs):
111 return _configuration_args(
112 self.get_basename(), self.params.get('external_downloader_args'), self.get_basename(),
113 keys, *args, **kwargs)
114
115 def _call_downloader(self, tmpfilename, info_dict):
116 """ Either overwrite this or implement _make_cmd """
117 cmd = [encodeArgument(a) for a in self._make_cmd(tmpfilename, info_dict)]
118
119 self._debug_cmd(cmd)
120
121 if 'fragments' in info_dict:
122 fragment_retries = self.params.get('fragment_retries', 0)
123 skip_unavailable_fragments = self.params.get('skip_unavailable_fragments', True)
124
125 count = 0
126 while count <= fragment_retries:
127 p = subprocess.Popen(
128 cmd, stderr=subprocess.PIPE)
129 _, stderr = process_communicate_or_kill(p)
130 if p.returncode == 0:
131 break
132 # TODO: Decide whether to retry based on error code
133 # https://aria2.github.io/manual/en/html/aria2c.html#exit-status
134 self.to_stderr(stderr.decode('utf-8', 'replace'))
135 count += 1
136 if count <= fragment_retries:
137 self.to_screen(
138 '[%s] Got error. Retrying fragments (attempt %d of %s)...'
139 % (self.get_basename(), count, self.format_retries(fragment_retries)))
140 if count > fragment_retries:
141 if not skip_unavailable_fragments:
142 self.report_error('Giving up after %s fragment retries' % fragment_retries)
143 return -1
144
145 dest, _ = sanitize_open(tmpfilename, 'wb')
146 for frag_index, fragment in enumerate(info_dict['fragments']):
147 fragment_filename = '%s-Frag%d' % (tmpfilename, frag_index)
148 try:
149 src, _ = sanitize_open(fragment_filename, 'rb')
150 except IOError:
151 if skip_unavailable_fragments and frag_index > 1:
152 self.to_screen('[%s] Skipping fragment %d ...' % (self.get_basename(), frag_index))
153 continue
154 self.report_error('Unable to open fragment %d' % frag_index)
155 return -1
156 decrypt_info = fragment.get('decrypt_info')
157 if decrypt_info:
158 if decrypt_info['METHOD'] == 'AES-128':
159 iv = decrypt_info.get('IV') or compat_struct_pack('>8xq', fragment['media_sequence'])
160 decrypt_info['KEY'] = decrypt_info.get('KEY') or self.ydl.urlopen(
161 self._prepare_url(info_dict, info_dict.get('_decryption_key_url') or decrypt_info['URI'])).read()
162 encrypted_data = src.read()
163 decrypted_data = aes_cbc_decrypt_bytes(encrypted_data, decrypt_info['KEY'], iv)
164 dest.write(decrypted_data)
165 else:
166 fragment_data = src.read()
167 dest.write(fragment_data)
168 else:
169 fragment_data = src.read()
170 dest.write(fragment_data)
171 src.close()
172 if not self.params.get('keep_fragments', False):
173 os.remove(encodeFilename(fragment_filename))
174 dest.close()
175 os.remove(encodeFilename('%s.frag.urls' % tmpfilename))
176 else:
177 p = subprocess.Popen(
178 cmd, stderr=subprocess.PIPE)
179 _, stderr = process_communicate_or_kill(p)
180 if p.returncode != 0:
181 self.to_stderr(stderr.decode('utf-8', 'replace'))
182 return p.returncode
183
184 def _prepare_url(self, info_dict, url):
185 headers = info_dict.get('http_headers')
186 return sanitized_Request(url, None, headers) if headers else url
187
188
189 class CurlFD(ExternalFD):
190 AVAILABLE_OPT = '-V'
191
192 def _make_cmd(self, tmpfilename, info_dict):
193 cmd = [self.exe, '--location', '-o', tmpfilename]
194 if info_dict.get('http_headers') is not None:
195 for key, val in info_dict['http_headers'].items():
196 cmd += ['--header', '%s: %s' % (key, val)]
197
198 cmd += self._bool_option('--continue-at', 'continuedl', '-', '0')
199 cmd += self._valueless_option('--silent', 'noprogress')
200 cmd += self._valueless_option('--verbose', 'verbose')
201 cmd += self._option('--limit-rate', 'ratelimit')
202 retry = self._option('--retry', 'retries')
203 if len(retry) == 2:
204 if retry[1] in ('inf', 'infinite'):
205 retry[1] = '2147483647'
206 cmd += retry
207 cmd += self._option('--max-filesize', 'max_filesize')
208 cmd += self._option('--interface', 'source_address')
209 cmd += self._option('--proxy', 'proxy')
210 cmd += self._valueless_option('--insecure', 'nocheckcertificate')
211 cmd += self._configuration_args()
212 cmd += ['--', info_dict['url']]
213 return cmd
214
215 def _call_downloader(self, tmpfilename, info_dict):
216 cmd = [encodeArgument(a) for a in self._make_cmd(tmpfilename, info_dict)]
217
218 self._debug_cmd(cmd)
219
220 # curl writes the progress to stderr so don't capture it.
221 p = subprocess.Popen(cmd)
222 process_communicate_or_kill(p)
223 return p.returncode
224
225
226 class AxelFD(ExternalFD):
227 AVAILABLE_OPT = '-V'
228
229 def _make_cmd(self, tmpfilename, info_dict):
230 cmd = [self.exe, '-o', tmpfilename]
231 if info_dict.get('http_headers') is not None:
232 for key, val in info_dict['http_headers'].items():
233 cmd += ['-H', '%s: %s' % (key, val)]
234 cmd += self._configuration_args()
235 cmd += ['--', info_dict['url']]
236 return cmd
237
238
239 class WgetFD(ExternalFD):
240 AVAILABLE_OPT = '--version'
241
242 def _make_cmd(self, tmpfilename, info_dict):
243 cmd = [self.exe, '-O', tmpfilename, '-nv', '--no-cookies']
244 if info_dict.get('http_headers') is not None:
245 for key, val in info_dict['http_headers'].items():
246 cmd += ['--header', '%s: %s' % (key, val)]
247 cmd += self._option('--limit-rate', 'ratelimit')
248 retry = self._option('--tries', 'retries')
249 if len(retry) == 2:
250 if retry[1] in ('inf', 'infinite'):
251 retry[1] = '0'
252 cmd += retry
253 cmd += self._option('--bind-address', 'source_address')
254 cmd += self._option('--proxy', 'proxy')
255 cmd += self._valueless_option('--no-check-certificate', 'nocheckcertificate')
256 cmd += self._configuration_args()
257 cmd += ['--', info_dict['url']]
258 return cmd
259
260
261 class Aria2cFD(ExternalFD):
262 AVAILABLE_OPT = '-v'
263 SUPPORTED_PROTOCOLS = ('http', 'https', 'ftp', 'ftps', 'dash_frag_urls', 'm3u8_frag_urls')
264
265 @staticmethod
266 def supports_manifest(manifest):
267 UNSUPPORTED_FEATURES = [
268 r'#EXT-X-BYTERANGE', # playlists composed of byte ranges of media files [1]
269 # 1. https://tools.ietf.org/html/draft-pantos-http-live-streaming-17#section-4.3.2.2
270 ]
271 check_results = (not re.search(feature, manifest) for feature in UNSUPPORTED_FEATURES)
272 return all(check_results)
273
274 def _make_cmd(self, tmpfilename, info_dict):
275 cmd = [self.exe, '-c',
276 '--console-log-level=warn', '--summary-interval=0', '--download-result=hide',
277 '--file-allocation=none', '-x16', '-j16', '-s16']
278 if 'fragments' in info_dict:
279 cmd += ['--allow-overwrite=true', '--allow-piece-length-change=true']
280 else:
281 cmd += ['--min-split-size', '1M']
282
283 if info_dict.get('http_headers') is not None:
284 for key, val in info_dict['http_headers'].items():
285 cmd += ['--header', '%s: %s' % (key, val)]
286 cmd += self._option('--max-overall-download-limit', 'ratelimit')
287 cmd += self._option('--interface', 'source_address')
288 cmd += self._option('--all-proxy', 'proxy')
289 cmd += self._bool_option('--check-certificate', 'nocheckcertificate', 'false', 'true', '=')
290 cmd += self._bool_option('--remote-time', 'updatetime', 'true', 'false', '=')
291 cmd += self._configuration_args()
292
293 # aria2c strips out spaces from the beginning/end of filenames and paths.
294 # We work around this issue by adding a "./" to the beginning of the
295 # filename and relative path, and adding a "/" at the end of the path.
296 # See: https://github.com/yt-dlp/yt-dlp/issues/276
297 # https://github.com/ytdl-org/youtube-dl/issues/20312
298 # https://github.com/aria2/aria2/issues/1373
299 dn = os.path.dirname(tmpfilename)
300 if dn:
301 if not os.path.isabs(dn):
302 dn = '.%s%s' % (os.path.sep, dn)
303 cmd += ['--dir', dn + os.path.sep]
304 if 'fragments' not in info_dict:
305 cmd += ['--out', '.%s%s' % (os.path.sep, os.path.basename(tmpfilename))]
306 cmd += ['--auto-file-renaming=false']
307
308 if 'fragments' in info_dict:
309 cmd += ['--file-allocation=none', '--uri-selector=inorder']
310 url_list_file = '%s.frag.urls' % tmpfilename
311 url_list = []
312 for frag_index, fragment in enumerate(info_dict['fragments']):
313 fragment_filename = '%s-Frag%d' % (os.path.basename(tmpfilename), frag_index)
314 url_list.append('%s\n\tout=%s' % (fragment['url'], fragment_filename))
315 stream, _ = sanitize_open(url_list_file, 'wb')
316 stream.write('\n'.join(url_list).encode('utf-8'))
317 stream.close()
318 cmd += ['-i', url_list_file]
319 else:
320 cmd += ['--', info_dict['url']]
321 return cmd
322
323
324 class HttpieFD(ExternalFD):
325 AVAILABLE_OPT = '--version'
326
327 @classmethod
328 def available(cls, path=None):
329 return ExternalFD.available(cls, path or 'http')
330
331 def _make_cmd(self, tmpfilename, info_dict):
332 cmd = ['http', '--download', '--output', tmpfilename, info_dict['url']]
333
334 if info_dict.get('http_headers') is not None:
335 for key, val in info_dict['http_headers'].items():
336 cmd += ['%s:%s' % (key, val)]
337 return cmd
338
339
340 class FFmpegFD(ExternalFD):
341 SUPPORTED_PROTOCOLS = ('http', 'https', 'ftp', 'ftps', 'm3u8', 'm3u8_native', 'rtsp', 'rtmp', 'rtmp_ffmpeg', 'mms', 'http_dash_segments')
342 can_download_to_stdout = True
343
344 @classmethod
345 def available(cls, path=None):
346 # TODO: Fix path for ffmpeg
347 # Fixme: This may be wrong when --ffmpeg-location is used
348 return FFmpegPostProcessor().available
349
350 def on_process_started(self, proc, stdin):
351 """ Override this in subclasses """
352 pass
353
354 @classmethod
355 def can_merge_formats(cls, info_dict, params):
356 return (
357 info_dict.get('requested_formats')
358 and info_dict.get('protocol')
359 and not params.get('allow_unplayable_formats')
360 and 'no-direct-merge' not in params.get('compat_opts', [])
361 and cls.can_download(info_dict))
362
363 def _call_downloader(self, tmpfilename, info_dict):
364 urls = [f['url'] for f in info_dict.get('requested_formats', [])] or [info_dict['url']]
365 ffpp = FFmpegPostProcessor(downloader=self)
366 if not ffpp.available:
367 self.report_error('m3u8 download detected but ffmpeg could not be found. Please install')
368 return False
369 ffpp.check_version()
370
371 args = [ffpp.executable, '-y']
372
373 for log_level in ('quiet', 'verbose'):
374 if self.params.get(log_level, False):
375 args += ['-loglevel', log_level]
376 break
377 if not self.params.get('verbose'):
378 args += ['-hide_banner']
379
380 args += info_dict.get('_ffmpeg_args', [])
381
382 # This option exists only for compatibility. Extractors should use `_ffmpeg_args` instead
383 seekable = info_dict.get('_seekable')
384 if seekable is not None:
385 # setting -seekable prevents ffmpeg from guessing if the server
386 # supports seeking(by adding the header `Range: bytes=0-`), which
387 # can cause problems in some cases
388 # https://github.com/ytdl-org/youtube-dl/issues/11800#issuecomment-275037127
389 # http://trac.ffmpeg.org/ticket/6125#comment:10
390 args += ['-seekable', '1' if seekable else '0']
391
392 # start_time = info_dict.get('start_time') or 0
393 # if start_time:
394 # args += ['-ss', compat_str(start_time)]
395 # end_time = info_dict.get('end_time')
396 # if end_time:
397 # args += ['-t', compat_str(end_time - start_time)]
398
399 if info_dict.get('http_headers') is not None and re.match(r'^https?://', urls[0]):
400 # Trailing \r\n after each HTTP header is important to prevent warning from ffmpeg/avconv:
401 # [http @ 00000000003d2fa0] No trailing CRLF found in HTTP header.
402 headers = handle_youtubedl_headers(info_dict['http_headers'])
403 args += [
404 '-headers',
405 ''.join('%s: %s\r\n' % (key, val) for key, val in headers.items())]
406
407 env = None
408 proxy = self.params.get('proxy')
409 if proxy:
410 if not re.match(r'^[\da-zA-Z]+://', proxy):
411 proxy = 'http://%s' % proxy
412
413 if proxy.startswith('socks'):
414 self.report_warning(
415 '%s does not support SOCKS proxies. Downloading is likely to fail. '
416 'Consider adding --hls-prefer-native to your command.' % self.get_basename())
417
418 # Since December 2015 ffmpeg supports -http_proxy option (see
419 # http://git.videolan.org/?p=ffmpeg.git;a=commit;h=b4eb1f29ebddd60c41a2eb39f5af701e38e0d3fd)
420 # We could switch to the following code if we are able to detect version properly
421 # args += ['-http_proxy', proxy]
422 env = os.environ.copy()
423 compat_setenv('HTTP_PROXY', proxy, env=env)
424 compat_setenv('http_proxy', proxy, env=env)
425
426 protocol = info_dict.get('protocol')
427
428 if protocol == 'rtmp':
429 player_url = info_dict.get('player_url')
430 page_url = info_dict.get('page_url')
431 app = info_dict.get('app')
432 play_path = info_dict.get('play_path')
433 tc_url = info_dict.get('tc_url')
434 flash_version = info_dict.get('flash_version')
435 live = info_dict.get('rtmp_live', False)
436 conn = info_dict.get('rtmp_conn')
437 if player_url is not None:
438 args += ['-rtmp_swfverify', player_url]
439 if page_url is not None:
440 args += ['-rtmp_pageurl', page_url]
441 if app is not None:
442 args += ['-rtmp_app', app]
443 if play_path is not None:
444 args += ['-rtmp_playpath', play_path]
445 if tc_url is not None:
446 args += ['-rtmp_tcurl', tc_url]
447 if flash_version is not None:
448 args += ['-rtmp_flashver', flash_version]
449 if live:
450 args += ['-rtmp_live', 'live']
451 if isinstance(conn, list):
452 for entry in conn:
453 args += ['-rtmp_conn', entry]
454 elif isinstance(conn, compat_str):
455 args += ['-rtmp_conn', conn]
456
457 for i, url in enumerate(urls):
458 args += self._configuration_args((f'_i{i + 1}', '_i')) + ['-i', url]
459
460 args += ['-c', 'copy']
461 if info_dict.get('requested_formats') or protocol == 'http_dash_segments':
462 for (i, fmt) in enumerate(info_dict.get('requested_formats') or [info_dict]):
463 stream_number = fmt.get('manifest_stream_number', 0)
464 a_or_v = 'a' if fmt.get('acodec') != 'none' else 'v'
465 args.extend(['-map', f'{i}:{a_or_v}:{stream_number}'])
466
467 if self.params.get('test', False):
468 args += ['-fs', compat_str(self._TEST_FILE_SIZE)]
469
470 ext = info_dict['ext']
471 if protocol in ('m3u8', 'm3u8_native'):
472 use_mpegts = (tmpfilename == '-') or self.params.get('hls_use_mpegts')
473 if use_mpegts is None:
474 use_mpegts = info_dict.get('is_live')
475 if use_mpegts:
476 args += ['-f', 'mpegts']
477 else:
478 args += ['-f', 'mp4']
479 if (ffpp.basename == 'ffmpeg' and is_outdated_version(ffpp._versions['ffmpeg'], '3.2', False)) and (not info_dict.get('acodec') or info_dict['acodec'].split('.')[0] in ('aac', 'mp4a')):
480 args += ['-bsf:a', 'aac_adtstoasc']
481 elif protocol == 'rtmp':
482 args += ['-f', 'flv']
483 elif ext == 'mp4' and tmpfilename == '-':
484 args += ['-f', 'mpegts']
485 else:
486 args += ['-f', EXT_TO_OUT_FORMATS.get(ext, ext)]
487
488 args += self._configuration_args(('_o1', '_o', ''))
489
490 args = [encodeArgument(opt) for opt in args]
491 args.append(encodeFilename(ffpp._ffmpeg_filename_argument(tmpfilename), True))
492 self._debug_cmd(args)
493
494 proc = subprocess.Popen(args, stdin=subprocess.PIPE, env=env)
495 if url in ('-', 'pipe:'):
496 self.on_process_started(proc, proc.stdin)
497 try:
498 retval = proc.wait()
499 except BaseException as e:
500 # subprocces.run would send the SIGKILL signal to ffmpeg and the
501 # mp4 file couldn't be played, but if we ask ffmpeg to quit it
502 # produces a file that is playable (this is mostly useful for live
503 # streams). Note that Windows is not affected and produces playable
504 # files (see https://github.com/ytdl-org/youtube-dl/issues/8300).
505 if isinstance(e, KeyboardInterrupt) and sys.platform != 'win32' and url not in ('-', 'pipe:'):
506 process_communicate_or_kill(proc, b'q')
507 else:
508 proc.kill()
509 proc.wait()
510 raise
511 return retval
512
513
514 class AVconvFD(FFmpegFD):
515 pass
516
517
518 _BY_NAME = dict(
519 (klass.get_basename(), klass)
520 for name, klass in globals().items()
521 if name.endswith('FD') and name != 'ExternalFD'
522 )
523
524
525 def list_external_downloaders():
526 return sorted(_BY_NAME.keys())
527
528
529 def get_external_downloader(external_downloader):
530 """ Given the name of the executable, see whether we support the given
531 downloader . """
532 # Drop .exe extension on Windows
533 bn = os.path.splitext(os.path.basename(external_downloader))[0]
534 return _BY_NAME.get(bn)