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