8 from .fragment
import FragmentFD
9 from ..compat
import functools
10 from ..postprocessor
.ffmpeg
import EXT_TO_OUT_FORMATS
, FFmpegPostProcessor
23 handle_youtubedl_headers
,
29 class Features(enum
.Enum
):
30 TO_STDOUT
= enum
.auto()
31 MULTIPLE_FORMATS
= enum
.auto()
34 class ExternalFD(FragmentFD
):
35 SUPPORTED_PROTOCOLS
= ('http', 'https', 'ftp', 'ftps')
36 SUPPORTED_FEATURES
= ()
37 _CAPTURE_STDERR
= True
39 def real_download(self
, filename
, info_dict
):
40 self
.report_destination(filename
)
41 tmpfilename
= self
.temp_name(filename
)
45 retval
= self
._call
_downloader
(tmpfilename
, info_dict
)
46 except KeyboardInterrupt:
47 if not info_dict
.get('is_live'):
49 # Live stream downloading cancellation should be considered as
50 # correct and expected termination thus all postprocessing
53 self
.to_screen('[%s] Interrupted by user' % self
.get_basename())
59 'elapsed': time
.time() - started
,
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
)
66 'downloaded_bytes': fsize
,
69 self
._hook
_progress
(status
, info_dict
)
73 self
.report_error('%s exited with code %d' % (
74 self
.get_basename(), retval
))
78 def get_basename(cls
):
79 return cls
.__name
__[:-2].lower()
83 return cls
.get_basename()
85 @functools.cached_property
90 def available(cls
, path
=None):
91 path
= check_executable(
92 cls
.EXE_NAME
if path
in (None, cls
.get_basename()) else path
,
100 def supports(cls
, info_dict
):
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('+')),
108 def can_download(cls
, info_dict
, path
=None):
109 return cls
.available(path
) and cls
.supports(info_dict
)
111 def _option(self
, command_option
, param
):
112 return cli_option(self
.params
, command_option
, param
)
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
)
117 def _valueless_option(self
, command_option
, param
, expected_value
=True):
118 return cli_valueless_option(self
.params
, command_option
, param
, expected_value
)
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
)
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
)]
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
)
138 skip_unavailable_fragments
= self
.params
.get('skip_unavailable_fragments', True)
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
)
146 # TODO: Decide whether to retry based on error code
147 # https://aria2.github.io/manual/en/html/aria2c.html#exit-status
149 self
.to_stderr(stderr
)
150 retry
.error
= Exception()
152 if not skip_unavailable_fragments
and retry_manager
.error
:
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
)
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
)
165 self
.report_error(f
'Unable to open fragment {frag_index}; {err}')
167 dest
.write(decrypt_fragment(fragment
, src
.read()))
169 if not self
.params
.get('keep_fragments', False):
170 self
.try_remove(encodeFilename(fragment_filename
))
172 self
.try_remove(encodeFilename('%s.frag.urls' % tmpfilename
))
176 class CurlFD(ExternalFD
):
178 _CAPTURE_STDERR
= False # curl writes the progress to stderr
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}']
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')
192 if retry
[1] in ('inf', 'infinite'):
193 retry
[1] = '2147483647'
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']]
204 class AxelFD(ExternalFD
):
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']]
217 class WgetFD(ExternalFD
):
218 AVAILABLE_OPT
= '--version'
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')
228 if retry
[1] in ('inf', 'infinite'):
231 cmd
+= self
._option
('--bind-address', 'source_address')
232 proxy
= self
.params
.get('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']]
242 class Aria2cFD(ExternalFD
):
244 SUPPORTED_PROTOCOLS
= ('http', 'https', 'ftp', 'ftps', 'dash_frag_urls', 'm3u8_frag_urls')
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
252 check_results
= (not re
.search(feature
, manifest
) for feature
in UNSUPPORTED_FEATURES
)
253 return all(check_results
)
256 def _aria2c_filename(fn
):
257 return fn
if os
.path
.isabs(fn
) else f
'.{os.path.sep}{fn}'
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']
266 cmd
+= ['--min-split-size', '1M']
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
()
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
)
287 cmd
+= ['--dir', self
._aria
2c
_filename
(dn
) + os
.path
.sep
]
288 if 'fragments' not in info_dict
:
289 cmd
+= ['--out', self
._aria
2c
_filename
(os
.path
.basename(tmpfilename
))]
290 cmd
+= ['--auto-file-renaming=false']
292 if 'fragments' in info_dict
:
293 cmd
+= ['--file-allocation=none', '--uri-selector=inorder']
294 url_list_file
= '%s.frag.urls' % tmpfilename
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
._aria
2c
_filename
(fragment_filename
)))
299 stream
, _
= self
.sanitize_open(url_list_file
, 'wb')
300 stream
.write('\n'.join(url_list
).encode())
302 cmd
+= ['-i', self
._aria
2c
_filename
(url_list_file
)]
304 cmd
+= ['--', info_dict
['url']]
308 class HttpieFD(ExternalFD
):
309 AVAILABLE_OPT
= '--version'
312 def _make_cmd(self
, tmpfilename
, info_dict
):
313 cmd
= ['http', '--download', '--output', tmpfilename
, info_dict
['url']]
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}']
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
)
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
331 def on_process_started(self
, proc
, stdin
):
332 """ Override this in subclasses """
336 def can_merge_formats(cls
, info_dict
, params
):
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
))
344 def _call_downloader(self
, tmpfilename
, info_dict
):
345 urls
= [f
['url'] for f
in info_dict
.get('requested_formats', [])] or [info_dict
['url']]
346 ffpp
= FFmpegPostProcessor(downloader
=self
)
347 if not ffpp
.available
:
348 self
.report_error('m3u8 download detected but ffmpeg could not be found. Please install')
352 args
= [ffpp
.executable
, '-y']
354 for log_level
in ('quiet', 'verbose'):
355 if self
.params
.get(log_level
, False):
356 args
+= ['-loglevel', log_level
]
358 if not self
.params
.get('verbose'):
359 args
+= ['-hide_banner']
361 args
+= traverse_obj(info_dict
, ('downloader_options', 'ffmpeg_args'), default
=[])
363 # These exists only for compatibility. Extractors should use
364 # info_dict['downloader_options']['ffmpeg_args'] instead
365 args
+= info_dict
.get('_ffmpeg_args') or []
366 seekable
= info_dict
.get('_seekable')
367 if seekable
is not None:
368 # setting -seekable prevents ffmpeg from guessing if the server
369 # supports seeking(by adding the header `Range: bytes=0-`), which
370 # can cause problems in some cases
371 # https://github.com/ytdl-org/youtube-dl/issues/11800#issuecomment-275037127
372 # http://trac.ffmpeg.org/ticket/6125#comment:10
373 args
+= ['-seekable', '1' if seekable
else '0']
376 if info_dict
.get('http_headers'):
377 youtubedl_headers
= handle_youtubedl_headers(info_dict
['http_headers'])
379 # Trailing \r\n after each HTTP header is important to prevent warning from ffmpeg/avconv:
380 # [http @ 00000000003d2fa0] No trailing CRLF found in HTTP header.
382 ''.join(f
'{key}: {val}\r\n' for key
, val
in youtubedl_headers
.items())
386 proxy
= self
.params
.get('proxy')
388 if not re
.match(r
'^[\da-zA-Z]+://', proxy
):
389 proxy
= 'http://%s' % proxy
391 if proxy
.startswith('socks'):
393 '%s does not support SOCKS proxies. Downloading is likely to fail. '
394 'Consider adding --hls-prefer-native to your command.' % self
.get_basename())
396 # Since December 2015 ffmpeg supports -http_proxy option (see
397 # http://git.videolan.org/?p=ffmpeg.git;a=commit;h=b4eb1f29ebddd60c41a2eb39f5af701e38e0d3fd)
398 # We could switch to the following code if we are able to detect version properly
399 # args += ['-http_proxy', proxy]
400 env
= os
.environ
.copy()
401 env
['HTTP_PROXY'] = proxy
402 env
['http_proxy'] = proxy
404 protocol
= info_dict
.get('protocol')
406 if protocol
== 'rtmp':
407 player_url
= info_dict
.get('player_url')
408 page_url
= info_dict
.get('page_url')
409 app
= info_dict
.get('app')
410 play_path
= info_dict
.get('play_path')
411 tc_url
= info_dict
.get('tc_url')
412 flash_version
= info_dict
.get('flash_version')
413 live
= info_dict
.get('rtmp_live', False)
414 conn
= info_dict
.get('rtmp_conn')
415 if player_url
is not None:
416 args
+= ['-rtmp_swfverify', player_url
]
417 if page_url
is not None:
418 args
+= ['-rtmp_pageurl', page_url
]
420 args
+= ['-rtmp_app', app
]
421 if play_path
is not None:
422 args
+= ['-rtmp_playpath', play_path
]
423 if tc_url
is not None:
424 args
+= ['-rtmp_tcurl', tc_url
]
425 if flash_version
is not None:
426 args
+= ['-rtmp_flashver', flash_version
]
428 args
+= ['-rtmp_live', 'live']
429 if isinstance(conn
, list):
431 args
+= ['-rtmp_conn', entry
]
432 elif isinstance(conn
, str):
433 args
+= ['-rtmp_conn', conn
]
435 start_time
, end_time
= info_dict
.get('section_start') or 0, info_dict
.get('section_end')
437 for i
, url
in enumerate(urls
):
438 if http_headers
is not None and re
.match(r
'^https?://', url
):
441 args
+= ['-ss', str(start_time
)]
443 args
+= ['-t', str(end_time
- start_time
)]
445 args
+= self
._configuration
_args
((f
'_i{i + 1}', '_i')) + ['-i', url
]
447 if not (start_time
or end_time
) or not self
.params
.get('force_keyframes_at_cuts'):
448 args
+= ['-c', 'copy']
450 if info_dict
.get('requested_formats') or protocol
== 'http_dash_segments':
451 for (i
, fmt
) in enumerate(info_dict
.get('requested_formats') or [info_dict
]):
452 stream_number
= fmt
.get('manifest_stream_number', 0)
453 args
.extend(['-map', f
'{i}:{stream_number}'])
455 if self
.params
.get('test', False):
456 args
+= ['-fs', str(self
._TEST
_FILE
_SIZE
)]
458 ext
= info_dict
['ext']
459 if protocol
in ('m3u8', 'm3u8_native'):
460 use_mpegts
= (tmpfilename
== '-') or self
.params
.get('hls_use_mpegts')
461 if use_mpegts
is None:
462 use_mpegts
= info_dict
.get('is_live')
464 args
+= ['-f', 'mpegts']
466 args
+= ['-f', 'mp4']
467 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')):
468 args
+= ['-bsf:a', 'aac_adtstoasc']
469 elif protocol
== 'rtmp':
470 args
+= ['-f', 'flv']
471 elif ext
== 'mp4' and tmpfilename
== '-':
472 args
+= ['-f', 'mpegts']
473 elif ext
== 'unknown_video':
474 ext
= determine_ext(remove_end(tmpfilename
, '.part'))
475 if ext
== 'unknown_video':
477 'The video format is unknown and cannot be downloaded by ffmpeg. '
478 'Explicitly set the extension in the filename to attempt download in that format')
480 self
.report_warning(f
'The video format is unknown. Trying to download as {ext} according to the filename')
481 args
+= ['-f', EXT_TO_OUT_FORMATS
.get(ext
, ext
)]
483 args
+= ['-f', EXT_TO_OUT_FORMATS
.get(ext
, ext
)]
485 args
+= self
._configuration
_args
(('_o1', '_o', ''))
487 args
= [encodeArgument(opt
) for opt
in args
]
488 args
.append(encodeFilename(ffpp
._ffmpeg
_filename
_argument
(tmpfilename
), True))
489 self
._debug
_cmd
(args
)
491 with Popen(args
, stdin
=subprocess
.PIPE
, env
=env
) as proc
:
492 if url
in ('-', 'pipe:'):
493 self
.on_process_started(proc
, proc
.stdin
)
496 except BaseException
as e
:
497 # subprocces.run would send the SIGKILL signal to ffmpeg and the
498 # mp4 file couldn't be played, but if we ask ffmpeg to quit it
499 # produces a file that is playable (this is mostly useful for live
500 # streams). Note that Windows is not affected and produces playable
501 # files (see https://github.com/ytdl-org/youtube-dl/issues/8300).
502 if isinstance(e
, KeyboardInterrupt) and sys
.platform
!= 'win32' and url
not in ('-', 'pipe:'):
503 proc
.communicate_or_kill(b
'q')
505 proc
.kill(timeout
=None)
510 class AVconvFD(FFmpegFD
):
515 klass
.get_basename(): klass
516 for name
, klass
in globals().items()
517 if name
.endswith('FD') and name
not in ('ExternalFD', 'FragmentFD')
521 def list_external_downloaders():
522 return sorted(_BY_NAME
.keys())
525 def get_external_downloader(external_downloader
):
526 """ Given the name of the executable, see whether we support the given downloader """
527 bn
= os
.path
.splitext(os
.path
.basename(external_downloader
))[0]
528 return _BY_NAME
.get(bn
) or next((
529 klass
for klass
in _BY_NAME
.values() if klass
.EXE_NAME
in bn