1 from __future__
import unicode_literals
10 from Crypto
.Cipher
import AES
11 can_decrypt_frag
= True
13 can_decrypt_frag
= False
15 from .common
import FileDownloader
16 from ..compat
import (
20 from ..postprocessor
.ffmpeg
import FFmpegPostProcessor
, EXT_TO_OUT_FORMATS
25 cli_configuration_args
,
28 handle_youtubedl_headers
,
31 process_communicate_or_kill
,
37 class ExternalFD(FileDownloader
):
38 SUPPORTED_PROTOCOLS
= ('http', 'https', 'ftp', 'ftps')
39 can_download_to_stdout
= False
41 def real_download(self
, filename
, info_dict
):
42 self
.report_destination(filename
)
43 tmpfilename
= self
.temp_name(filename
)
47 retval
= self
._call
_downloader
(tmpfilename
, info_dict
)
48 except KeyboardInterrupt:
49 if not info_dict
.get('is_live'):
51 # Live stream downloading cancellation should be considered as
52 # correct and expected termination thus all postprocessing
55 self
.to_screen('[%s] Interrupted by user' % self
.get_basename())
61 'elapsed': time
.time() - started
,
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
)
68 'downloaded_bytes': fsize
,
71 self
._hook
_progress
(status
, info_dict
)
75 self
.report_error('%s exited with code %d' % (
76 self
.get_basename(), retval
))
80 def get_basename(cls
):
81 return cls
.__name
__[:-2].lower()
85 return self
.get_basename()
88 def available(cls
, path
=None):
89 path
= check_executable(path
or cls
.get_basename(), [cls
.AVAILABLE_OPT
])
96 def supports(cls
, info_dict
):
98 (cls
.can_download_to_stdout
or not info_dict
.get('to_stdout'))
99 and info_dict
['protocol'] in cls
.SUPPORTED_PROTOCOLS
)
102 def can_download(cls
, info_dict
, path
=None):
103 return cls
.available(path
) and cls
.supports(info_dict
)
105 def _option(self
, command_option
, param
):
106 return cli_option(self
.params
, command_option
, param
)
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
)
111 def _valueless_option(self
, command_option
, param
, expected_value
=True):
112 return cli_valueless_option(self
.params
, command_option
, param
, expected_value
)
114 def _configuration_args(self
, *args
, **kwargs
):
115 return cli_configuration_args(
116 self
.params
.get('external_downloader_args'),
117 [self
.get_basename(), 'default'],
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
)]
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)
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:
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 dest
, _
= sanitize_open(tmpfilename
, 'wb')
151 for frag_index
, fragment
in enumerate(info_dict
['fragments']):
152 fragment_filename
= '%s-Frag%d' % (tmpfilename
, frag_index
)
154 src
, _
= sanitize_open(fragment_filename
, 'rb')
156 if skip_unavailable_fragments
and frag_index
> 1:
157 self
.to_screen('[%s] Skipping fragment %d ...' % (self
.get_basename(), frag_index
))
159 self
.report_error('Unable to open fragment %d' % frag_index
)
161 decrypt_info
= fragment
.get('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
)
172 fragment_data
= src
.read()
173 dest
.write(fragment_data
)
175 fragment_data
= src
.read()
176 dest
.write(fragment_data
)
178 if not self
.params
.get('keep_fragments', False):
179 os
.remove(encodeFilename(fragment_filename
))
181 os
.remove(encodeFilename('%s.frag.urls' % tmpfilename
))
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'))
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
195 class CurlFD(ExternalFD
):
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
)]
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')
210 if retry
[1] in ('inf', 'infinite'):
211 retry
[1] = '2147483647'
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']]
221 def _call_downloader(self
, tmpfilename
, info_dict
):
222 cmd
= [encodeArgument(a
) for a
in self
._make
_cmd
(tmpfilename
, info_dict
)]
226 # curl writes the progress to stderr so don't capture it.
227 p
= subprocess
.Popen(cmd
)
228 process_communicate_or_kill(p
)
232 class AxelFD(ExternalFD
):
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']]
245 class WgetFD(ExternalFD
):
246 AVAILABLE_OPT
= '--version'
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')
256 if retry
[1] in ('inf', 'infinite'):
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']]
267 class Aria2cFD(ExternalFD
):
269 SUPPORTED_PROTOCOLS
= ('http', 'https', 'ftp', 'ftps', 'dash_frag_urls', 'm3u8_frag_urls')
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
277 check_results
= (not re
.search(feature
, manifest
) for feature
in UNSUPPORTED_FEATURES
)
278 return all(check_results
)
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']
287 cmd
+= ['--min-split-size', '1M']
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
()
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
)
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']
313 if 'fragments' in info_dict
:
314 cmd
+= ['--file-allocation=none', '--uri-selector=inorder']
315 url_list_file
= '%s.frag.urls' % tmpfilename
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'))
323 cmd
+= ['-i', url_list_file
]
325 cmd
+= ['--', info_dict
['url']]
329 class HttpieFD(ExternalFD
):
330 AVAILABLE_OPT
= '--version'
333 def available(cls
, path
=None):
334 return ExternalFD
.available(cls
, path
or 'http')
336 def _make_cmd(self
, tmpfilename
, info_dict
):
337 cmd
= ['http', '--download', '--output', tmpfilename
, info_dict
['url']]
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
)]
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
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
355 def on_process_started(self
, proc
, stdin
):
356 """ Override this in subclasses """
360 def can_merge_formats(cls
, info_dict
, params
={}):
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
))
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')
376 args
= [ffpp
.executable
, '-y']
378 for log_level
in ('quiet', 'verbose'):
379 if self
.params
.get(log_level
, False):
380 args
+= ['-loglevel', log_level
]
382 if not self
.params
.get('verbose'):
383 args
+= ['-hide_banner']
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']
394 # start_time = info_dict.get('start_time') or 0
396 # args += ['-ss', compat_str(start_time)]
397 # end_time = info_dict.get('end_time')
399 # args += ['-t', compat_str(end_time - start_time)]
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'])
407 ''.join('%s: %s\r\n' % (key
, val
) for key
, val
in headers
.items())]
410 proxy
= self
.params
.get('proxy')
412 if not re
.match(r
'^[\da-zA-Z]+://', proxy
):
413 proxy
= 'http://%s' % proxy
415 if proxy
.startswith('socks'):
417 '%s does not support SOCKS proxies. Downloading is likely to fail. '
418 'Consider adding --hls-prefer-native to your command.' % self
.get_basename())
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
)
428 protocol
= info_dict
.get('protocol')
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
]
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
]
452 args
+= ['-rtmp_live', 'live']
453 if isinstance(conn
, list):
455 args
+= ['-rtmp_conn', entry
]
456 elif isinstance(conn
, compat_str
):
457 args
+= ['-rtmp_conn', conn
]
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
])
470 if self
.params
.get('test', False):
471 args
+= ['-fs', compat_str(self
._TEST
_FILE
_SIZE
)]
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')
479 args
+= ['-f', 'mpegts']
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']
489 args
+= ['-f', EXT_TO_OUT_FORMATS
.get(ext
, ext
)]
491 args
= [encodeArgument(opt
) for opt
in args
]
492 args
.append(encodeFilename(ffpp
._ffmpeg
_filename
_argument
(tmpfilename
), True))
494 self
._debug
_cmd
(args
)
496 proc
= subprocess
.Popen(args
, stdin
=subprocess
.PIPE
, env
=env
)
497 if url
in ('-', 'pipe:'):
498 self
.on_process_started(proc
, proc
.stdin
)
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')
516 class AVconvFD(FFmpegFD
):
521 (klass
.get_basename(), klass
)
522 for name
, klass
in globals().items()
523 if name
.endswith('FD') and name
!= 'ExternalFD'
527 def list_external_downloaders():
528 return sorted(_BY_NAME
.keys())
531 def get_external_downloader(external_downloader
):
532 """ Given the name of the executable, see whether we support the given
534 # Drop .exe extension on Windows
535 bn
= os
.path
.splitext(os
.path
.basename(external_downloader
))[0]
536 return _BY_NAME
.get(bn
)