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