7 from .fragment
import FragmentFD
8 from ..compat
import compat_setenv
, compat_str
9 from ..postprocessor
.ffmpeg
import EXT_TO_OUT_FORMATS
, FFmpegPostProcessor
21 handle_youtubedl_headers
,
27 class ExternalFD(FragmentFD
):
28 SUPPORTED_PROTOCOLS
= ('http', 'https', 'ftp', 'ftps')
29 can_download_to_stdout
= False
31 def real_download(self
, filename
, info_dict
):
32 self
.report_destination(filename
)
33 tmpfilename
= self
.temp_name(filename
)
37 retval
= self
._call
_downloader
(tmpfilename
, info_dict
)
38 except KeyboardInterrupt:
39 if not info_dict
.get('is_live'):
41 # Live stream downloading cancellation should be considered as
42 # correct and expected termination thus all postprocessing
45 self
.to_screen('[%s] Interrupted by user' % self
.get_basename())
51 'elapsed': time
.time() - started
,
54 fsize
= os
.path
.getsize(encodeFilename(tmpfilename
))
55 self
.to_screen(f
'\r[{self.get_basename()}] Downloaded {fsize} bytes')
56 self
.try_rename(tmpfilename
, filename
)
58 'downloaded_bytes': fsize
,
61 self
._hook
_progress
(status
, info_dict
)
65 self
.report_error('%s exited with code %d' % (
66 self
.get_basename(), retval
))
70 def get_basename(cls
):
71 return cls
.__name
__[:-2].lower()
75 return cls
.get_basename()
82 def available(cls
, path
=None):
83 path
= check_executable(
84 cls
.EXE_NAME
if path
in (None, cls
.get_basename()) else path
,
92 def supports(cls
, info_dict
):
94 (cls
.can_download_to_stdout
or not info_dict
.get('to_stdout'))
95 and info_dict
['protocol'] in cls
.SUPPORTED_PROTOCOLS
)
98 def can_download(cls
, info_dict
, path
=None):
99 return cls
.available(path
) and cls
.supports(info_dict
)
101 def _option(self
, command_option
, param
):
102 return cli_option(self
.params
, command_option
, param
)
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
)
107 def _valueless_option(self
, command_option
, param
, expected_value
=True):
108 return cli_valueless_option(self
.params
, command_option
, param
, expected_value
)
110 def _configuration_args(self
, keys
=None, *args
, **kwargs
):
111 return _configuration_args(
112 self
.get_basename(), self
.params
.get('external_downloader_args'), self
.EXE_NAME
,
113 keys
, *args
, **kwargs
)
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
)]
121 if 'fragments' not in info_dict
:
122 p
= Popen(cmd
, stderr
=subprocess
.PIPE
)
123 _
, stderr
= p
.communicate_or_kill()
124 if p
.returncode
!= 0:
125 self
.to_stderr(stderr
.decode('utf-8', 'replace'))
128 fragment_retries
= self
.params
.get('fragment_retries', 0)
129 skip_unavailable_fragments
= self
.params
.get('skip_unavailable_fragments', True)
132 while count
<= fragment_retries
:
133 p
= Popen(cmd
, stderr
=subprocess
.PIPE
)
134 _
, stderr
= p
.communicate_or_kill()
135 if p
.returncode
== 0:
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'))
141 if count
<= fragment_retries
:
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
)
150 decrypt_fragment
= self
.decrypter(info_dict
)
151 dest
, _
= self
.sanitize_open(tmpfilename
, 'wb')
152 for frag_index
, fragment
in enumerate(info_dict
['fragments']):
153 fragment_filename
= '%s-Frag%d' % (tmpfilename
, frag_index
)
155 src
, _
= self
.sanitize_open(fragment_filename
, 'rb')
156 except OSError as err
:
157 if skip_unavailable_fragments
and frag_index
> 1:
158 self
.report_skip_fragment(frag_index
, err
)
160 self
.report_error(f
'Unable to open fragment {frag_index}; {err}')
162 dest
.write(decrypt_fragment(fragment
, src
.read()))
164 if not self
.params
.get('keep_fragments', False):
165 self
.try_remove(encodeFilename(fragment_filename
))
167 self
.try_remove(encodeFilename('%s.frag.urls' % tmpfilename
))
171 class CurlFD(ExternalFD
):
174 def _make_cmd(self
, tmpfilename
, info_dict
):
175 cmd
= [self
.exe
, '--location', '-o', tmpfilename
, '--compressed']
176 if info_dict
.get('http_headers') is not None:
177 for key
, val
in info_dict
['http_headers'].items():
178 cmd
+= ['--header', f
'{key}: {val}']
180 cmd
+= self
._bool
_option
('--continue-at', 'continuedl', '-', '0')
181 cmd
+= self
._valueless
_option
('--silent', 'noprogress')
182 cmd
+= self
._valueless
_option
('--verbose', 'verbose')
183 cmd
+= self
._option
('--limit-rate', 'ratelimit')
184 retry
= self
._option
('--retry', 'retries')
186 if retry
[1] in ('inf', 'infinite'):
187 retry
[1] = '2147483647'
189 cmd
+= self
._option
('--max-filesize', 'max_filesize')
190 cmd
+= self
._option
('--interface', 'source_address')
191 cmd
+= self
._option
('--proxy', 'proxy')
192 cmd
+= self
._valueless
_option
('--insecure', 'nocheckcertificate')
193 cmd
+= self
._configuration
_args
()
194 cmd
+= ['--', info_dict
['url']]
197 def _call_downloader(self
, tmpfilename
, info_dict
):
198 cmd
= [encodeArgument(a
) for a
in self
._make
_cmd
(tmpfilename
, info_dict
)]
202 # curl writes the progress to stderr so don't capture it.
204 p
.communicate_or_kill()
208 class AxelFD(ExternalFD
):
211 def _make_cmd(self
, tmpfilename
, info_dict
):
212 cmd
= [self
.exe
, '-o', tmpfilename
]
213 if info_dict
.get('http_headers') is not None:
214 for key
, val
in info_dict
['http_headers'].items():
215 cmd
+= ['-H', f
'{key}: {val}']
216 cmd
+= self
._configuration
_args
()
217 cmd
+= ['--', info_dict
['url']]
221 class WgetFD(ExternalFD
):
222 AVAILABLE_OPT
= '--version'
224 def _make_cmd(self
, tmpfilename
, info_dict
):
225 cmd
= [self
.exe
, '-O', tmpfilename
, '-nv', '--no-cookies', '--compression=auto']
226 if info_dict
.get('http_headers') is not None:
227 for key
, val
in info_dict
['http_headers'].items():
228 cmd
+= ['--header', f
'{key}: {val}']
229 cmd
+= self
._option
('--limit-rate', 'ratelimit')
230 retry
= self
._option
('--tries', 'retries')
232 if retry
[1] in ('inf', 'infinite'):
235 cmd
+= self
._option
('--bind-address', 'source_address')
236 proxy
= self
.params
.get('proxy')
238 for var
in ('http_proxy', 'https_proxy'):
239 cmd
+= ['--execute', f
'{var}={proxy}']
240 cmd
+= self
._valueless
_option
('--no-check-certificate', 'nocheckcertificate')
241 cmd
+= self
._configuration
_args
()
242 cmd
+= ['--', info_dict
['url']]
246 class Aria2cFD(ExternalFD
):
248 SUPPORTED_PROTOCOLS
= ('http', 'https', 'ftp', 'ftps', 'dash_frag_urls', 'm3u8_frag_urls')
251 def supports_manifest(manifest
):
252 UNSUPPORTED_FEATURES
= [
253 r
'#EXT-X-BYTERANGE', # playlists composed of byte ranges of media files [1]
254 # 1. https://tools.ietf.org/html/draft-pantos-http-live-streaming-17#section-4.3.2.2
256 check_results
= (not re
.search(feature
, manifest
) for feature
in UNSUPPORTED_FEATURES
)
257 return all(check_results
)
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 if not os
.path
.isabs(dn
):
288 dn
= f
'.{os.path.sep}{dn}'
289 cmd
+= ['--dir', dn
+ os
.path
.sep
]
290 if 'fragments' not in info_dict
:
291 cmd
+= ['--out', f
'.{os.path.sep}{os.path.basename(tmpfilename)}']
292 cmd
+= ['--auto-file-renaming=false']
294 if 'fragments' in info_dict
:
295 cmd
+= ['--file-allocation=none', '--uri-selector=inorder']
296 url_list_file
= '%s.frag.urls' % tmpfilename
298 for frag_index
, fragment
in enumerate(info_dict
['fragments']):
299 fragment_filename
= '%s-Frag%d' % (os
.path
.basename(tmpfilename
), frag_index
)
300 url_list
.append('%s\n\tout=%s' % (fragment
['url'], fragment_filename
))
301 stream
, _
= self
.sanitize_open(url_list_file
, 'wb')
302 stream
.write('\n'.join(url_list
).encode())
304 cmd
+= ['-i', url_list_file
]
306 cmd
+= ['--', info_dict
['url']]
310 class HttpieFD(ExternalFD
):
311 AVAILABLE_OPT
= '--version'
314 def _make_cmd(self
, tmpfilename
, info_dict
):
315 cmd
= ['http', '--download', '--output', tmpfilename
, info_dict
['url']]
317 if info_dict
.get('http_headers') is not None:
318 for key
, val
in info_dict
['http_headers'].items():
319 cmd
+= [f
'{key}:{val}']
323 class FFmpegFD(ExternalFD
):
324 SUPPORTED_PROTOCOLS
= ('http', 'https', 'ftp', 'ftps', 'm3u8', 'm3u8_native', 'rtsp', 'rtmp', 'rtmp_ffmpeg', 'mms', 'http_dash_segments')
325 can_download_to_stdout
= True
328 def available(cls
, path
=None):
329 # TODO: Fix path for ffmpeg
330 # Fixme: This may be wrong when --ffmpeg-location is used
331 return FFmpegPostProcessor().available
334 def supports(cls
, info_dict
):
335 return all(proto
in cls
.SUPPORTED_PROTOCOLS
for proto
in info_dict
['protocol'].split('+'))
337 def on_process_started(self
, proc
, stdin
):
338 """ Override this in subclasses """
342 def can_merge_formats(cls
, info_dict
, params
):
344 info_dict
.get('requested_formats')
345 and info_dict
.get('protocol')
346 and not params
.get('allow_unplayable_formats')
347 and 'no-direct-merge' not in params
.get('compat_opts', [])
348 and cls
.can_download(info_dict
))
350 def _call_downloader(self
, tmpfilename
, info_dict
):
351 urls
= [f
['url'] for f
in info_dict
.get('requested_formats', [])] or [info_dict
['url']]
352 ffpp
= FFmpegPostProcessor(downloader
=self
)
353 if not ffpp
.available
:
354 self
.report_error('m3u8 download detected but ffmpeg could not be found. Please install')
358 args
= [ffpp
.executable
, '-y']
360 for log_level
in ('quiet', 'verbose'):
361 if self
.params
.get(log_level
, False):
362 args
+= ['-loglevel', log_level
]
364 if not self
.params
.get('verbose'):
365 args
+= ['-hide_banner']
367 args
+= traverse_obj(info_dict
, ('downloader_options', 'ffmpeg_args'), default
=[])
369 # These exists only for compatibility. Extractors should use
370 # info_dict['downloader_options']['ffmpeg_args'] instead
371 args
+= info_dict
.get('_ffmpeg_args') or []
372 seekable
= info_dict
.get('_seekable')
373 if seekable
is not None:
374 # setting -seekable prevents ffmpeg from guessing if the server
375 # supports seeking(by adding the header `Range: bytes=0-`), which
376 # can cause problems in some cases
377 # https://github.com/ytdl-org/youtube-dl/issues/11800#issuecomment-275037127
378 # http://trac.ffmpeg.org/ticket/6125#comment:10
379 args
+= ['-seekable', '1' if seekable
else '0']
381 # start_time = info_dict.get('start_time') or 0
383 # args += ['-ss', compat_str(start_time)]
384 # end_time = info_dict.get('end_time')
386 # args += ['-t', compat_str(end_time - start_time)]
389 if info_dict
.get('http_headers'):
390 youtubedl_headers
= handle_youtubedl_headers(info_dict
['http_headers'])
392 # Trailing \r\n after each HTTP header is important to prevent warning from ffmpeg/avconv:
393 # [http @ 00000000003d2fa0] No trailing CRLF found in HTTP header.
395 ''.join(f
'{key}: {val}\r\n' for key
, val
in youtubedl_headers
.items())
399 proxy
= self
.params
.get('proxy')
401 if not re
.match(r
'^[\da-zA-Z]+://', proxy
):
402 proxy
= 'http://%s' % proxy
404 if proxy
.startswith('socks'):
406 '%s does not support SOCKS proxies. Downloading is likely to fail. '
407 'Consider adding --hls-prefer-native to your command.' % self
.get_basename())
409 # Since December 2015 ffmpeg supports -http_proxy option (see
410 # http://git.videolan.org/?p=ffmpeg.git;a=commit;h=b4eb1f29ebddd60c41a2eb39f5af701e38e0d3fd)
411 # We could switch to the following code if we are able to detect version properly
412 # args += ['-http_proxy', proxy]
413 env
= os
.environ
.copy()
414 compat_setenv('HTTP_PROXY', proxy
, env
=env
)
415 compat_setenv('http_proxy', proxy
, env
=env
)
417 protocol
= info_dict
.get('protocol')
419 if protocol
== 'rtmp':
420 player_url
= info_dict
.get('player_url')
421 page_url
= info_dict
.get('page_url')
422 app
= info_dict
.get('app')
423 play_path
= info_dict
.get('play_path')
424 tc_url
= info_dict
.get('tc_url')
425 flash_version
= info_dict
.get('flash_version')
426 live
= info_dict
.get('rtmp_live', False)
427 conn
= info_dict
.get('rtmp_conn')
428 if player_url
is not None:
429 args
+= ['-rtmp_swfverify', player_url
]
430 if page_url
is not None:
431 args
+= ['-rtmp_pageurl', page_url
]
433 args
+= ['-rtmp_app', app
]
434 if play_path
is not None:
435 args
+= ['-rtmp_playpath', play_path
]
436 if tc_url
is not None:
437 args
+= ['-rtmp_tcurl', tc_url
]
438 if flash_version
is not None:
439 args
+= ['-rtmp_flashver', flash_version
]
441 args
+= ['-rtmp_live', 'live']
442 if isinstance(conn
, list):
444 args
+= ['-rtmp_conn', entry
]
445 elif isinstance(conn
, compat_str
):
446 args
+= ['-rtmp_conn', conn
]
448 for i
, url
in enumerate(urls
):
449 # We need to specify headers for each http input stream
450 # otherwise, it will only be applied to the first.
451 # https://github.com/yt-dlp/yt-dlp/issues/2696
452 if http_headers
is not None and re
.match(r
'^https?://', url
):
454 args
+= self
._configuration
_args
((f
'_i{i + 1}', '_i')) + ['-i', url
]
456 args
+= ['-c', 'copy']
457 if info_dict
.get('requested_formats') or protocol
== 'http_dash_segments':
458 for (i
, fmt
) in enumerate(info_dict
.get('requested_formats') or [info_dict
]):
459 stream_number
= fmt
.get('manifest_stream_number', 0)
460 args
.extend(['-map', f
'{i}:{stream_number}'])
462 if self
.params
.get('test', False):
463 args
+= ['-fs', compat_str(self
._TEST
_FILE
_SIZE
)]
465 ext
= info_dict
['ext']
466 if protocol
in ('m3u8', 'm3u8_native'):
467 use_mpegts
= (tmpfilename
== '-') or self
.params
.get('hls_use_mpegts')
468 if use_mpegts
is None:
469 use_mpegts
= info_dict
.get('is_live')
471 args
+= ['-f', 'mpegts']
473 args
+= ['-f', 'mp4']
474 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')):
475 args
+= ['-bsf:a', 'aac_adtstoasc']
476 elif protocol
== 'rtmp':
477 args
+= ['-f', 'flv']
478 elif ext
== 'mp4' and tmpfilename
== '-':
479 args
+= ['-f', 'mpegts']
480 elif ext
== 'unknown_video':
481 ext
= determine_ext(remove_end(tmpfilename
, '.part'))
482 if ext
== 'unknown_video':
484 'The video format is unknown and cannot be downloaded by ffmpeg. '
485 'Explicitly set the extension in the filename to attempt download in that format')
487 self
.report_warning(f
'The video format is unknown. Trying to download as {ext} according to the filename')
488 args
+= ['-f', EXT_TO_OUT_FORMATS
.get(ext
, ext
)]
490 args
+= ['-f', EXT_TO_OUT_FORMATS
.get(ext
, ext
)]
492 args
+= self
._configuration
_args
(('_o1', '_o', ''))
494 args
= [encodeArgument(opt
) for opt
in args
]
495 args
.append(encodeFilename(ffpp
._ffmpeg
_filename
_argument
(tmpfilename
), True))
496 self
._debug
_cmd
(args
)
498 proc
= Popen(args
, stdin
=subprocess
.PIPE
, env
=env
)
499 if url
in ('-', 'pipe:'):
500 self
.on_process_started(proc
, proc
.stdin
)
503 except BaseException
as e
:
504 # subprocces.run would send the SIGKILL signal to ffmpeg and the
505 # mp4 file couldn't be played, but if we ask ffmpeg to quit it
506 # produces a file that is playable (this is mostly useful for live
507 # streams). Note that Windows is not affected and produces playable
508 # files (see https://github.com/ytdl-org/youtube-dl/issues/8300).
509 if isinstance(e
, KeyboardInterrupt) and sys
.platform
!= 'win32' and url
not in ('-', 'pipe:'):
510 proc
.communicate_or_kill(b
'q')
518 class AVconvFD(FFmpegFD
):
523 klass
.get_basename(): klass
524 for name
, klass
in globals().items()
525 if name
.endswith('FD') and name
not in ('ExternalFD', 'FragmentFD')
528 _BY_EXE
= {klass.EXE_NAME: klass for klass in _BY_NAME.values()}
531 def list_external_downloaders():
532 return sorted(_BY_NAME
.keys())
535 def get_external_downloader(external_downloader
):
536 """ Given the name of the executable, see whether we support the given
538 # Drop .exe extension on Windows
539 bn
= os
.path
.splitext(os
.path
.basename(external_downloader
))[0]
540 return _BY_NAME
.get(bn
, _BY_EXE
.get(bn
))