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
,
29 handle_youtubedl_headers
,
32 process_communicate_or_kill
,
38 class ExternalFD(FileDownloader
):
39 SUPPORTED_PROTOCOLS
= ('http', 'https', 'ftp', 'ftps')
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
)
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
.params
.get('external_downloader')
88 def available(cls
, path
=None):
89 return check_executable(path
or cls
.get_basename(), [cls
.AVAILABLE_OPT
])
92 def supports(cls
, info_dict
):
93 return info_dict
['protocol'] in cls
.SUPPORTED_PROTOCOLS
96 def can_download(cls
, info_dict
, path
=None):
97 return cls
.available(path
) and cls
.supports(info_dict
)
99 def _option(self
, command_option
, param
):
100 return cli_option(self
.params
, command_option
, param
)
102 def _bool_option(self
, command_option
, param
, true_value
='true', false_value
='false', separator
=None):
103 return cli_bool_option(self
.params
, command_option
, param
, true_value
, false_value
, separator
)
105 def _valueless_option(self
, command_option
, param
, expected_value
=True):
106 return cli_valueless_option(self
.params
, command_option
, param
, expected_value
)
108 def _configuration_args(self
, *args
, **kwargs
):
109 return cli_configuration_args(
110 self
.params
.get('external_downloader_args'),
111 [self
.get_basename(), 'default'],
114 def _call_downloader(self
, tmpfilename
, info_dict
):
115 """ Either overwrite this or implement _make_cmd """
116 cmd
= [encodeArgument(a
) for a
in self
._make
_cmd
(tmpfilename
, info_dict
)]
120 p
= subprocess
.Popen(
121 cmd
, stderr
=subprocess
.PIPE
)
122 _
, stderr
= process_communicate_or_kill(p
)
123 if p
.returncode
!= 0:
124 self
.to_stderr(stderr
.decode('utf-8', 'replace'))
126 if 'fragments' in info_dict
:
128 dest
, _
= sanitize_open(tmpfilename
, 'wb')
129 for i
, fragment
in enumerate(info_dict
['fragments']):
130 file = '%s-Frag%d' % (tmpfilename
, i
)
131 decrypt_info
= fragment
.get('decrypt_info')
132 src
, _
= sanitize_open(file, 'rb')
134 if decrypt_info
['METHOD'] == 'AES-128':
135 iv
= decrypt_info
.get('IV')
136 decrypt_info
['KEY'] = decrypt_info
.get('KEY') or self
.ydl
.urlopen(
137 self
._prepare
_url
(info_dict
, info_dict
.get('_decryption_key_url') or decrypt_info
['URI'])).read()
138 encrypted_data
= src
.read()
139 decrypted_data
= AES
.new(
140 decrypt_info
['KEY'], AES
.MODE_CBC
, iv
).decrypt(encrypted_data
)
141 dest
.write(decrypted_data
)
143 fragment_data
= src
.read()
144 dest
.write(fragment_data
)
146 fragment_data
= src
.read()
147 dest
.write(fragment_data
)
149 file_list
.append(file)
151 if not self
.params
.get('keep_fragments', False):
152 for file_path
in file_list
:
155 except OSError as ose
:
156 self
.report_error("Unable to delete file %s; %s" % (file_path
, error_to_compat_str(ose
)))
158 file_path
= '%s.frag.urls' % tmpfilename
160 except OSError as ose
:
161 self
.report_error("Unable to delete file %s; %s" % (file_path
, error_to_compat_str(ose
)))
165 def _prepare_url(self
, info_dict
, url
):
166 headers
= info_dict
.get('http_headers')
167 return sanitized_Request(url
, None, headers
) if headers
else url
170 class CurlFD(ExternalFD
):
173 def _make_cmd(self
, tmpfilename
, info_dict
):
174 cmd
= [self
.exe
, '--location', '-o', tmpfilename
]
175 if info_dict
.get('http_headers') is not None:
176 for key
, val
in info_dict
['http_headers'].items():
177 cmd
+= ['--header', '%s: %s' % (key
, val
)]
179 cmd
+= self
._bool
_option
('--continue-at', 'continuedl', '-', '0')
180 cmd
+= self
._valueless
_option
('--silent', 'noprogress')
181 cmd
+= self
._valueless
_option
('--verbose', 'verbose')
182 cmd
+= self
._option
('--limit-rate', 'ratelimit')
183 retry
= self
._option
('--retry', 'retries')
185 if retry
[1] in ('inf', 'infinite'):
186 retry
[1] = '2147483647'
188 cmd
+= self
._option
('--max-filesize', 'max_filesize')
189 cmd
+= self
._option
('--interface', 'source_address')
190 cmd
+= self
._option
('--proxy', 'proxy')
191 cmd
+= self
._valueless
_option
('--insecure', 'nocheckcertificate')
192 cmd
+= self
._configuration
_args
()
193 cmd
+= ['--', info_dict
['url']]
196 def _call_downloader(self
, tmpfilename
, info_dict
):
197 cmd
= [encodeArgument(a
) for a
in self
._make
_cmd
(tmpfilename
, info_dict
)]
201 # curl writes the progress to stderr so don't capture it.
202 p
= subprocess
.Popen(cmd
)
203 process_communicate_or_kill(p
)
207 class AxelFD(ExternalFD
):
210 def _make_cmd(self
, tmpfilename
, info_dict
):
211 cmd
= [self
.exe
, '-o', tmpfilename
]
212 if info_dict
.get('http_headers') is not None:
213 for key
, val
in info_dict
['http_headers'].items():
214 cmd
+= ['-H', '%s: %s' % (key
, val
)]
215 cmd
+= self
._configuration
_args
()
216 cmd
+= ['--', info_dict
['url']]
220 class WgetFD(ExternalFD
):
221 AVAILABLE_OPT
= '--version'
223 def _make_cmd(self
, tmpfilename
, info_dict
):
224 cmd
= [self
.exe
, '-O', tmpfilename
, '-nv', '--no-cookies']
225 if info_dict
.get('http_headers') is not None:
226 for key
, val
in info_dict
['http_headers'].items():
227 cmd
+= ['--header', '%s: %s' % (key
, val
)]
228 cmd
+= self
._option
('--limit-rate', 'ratelimit')
229 retry
= self
._option
('--tries', 'retries')
231 if retry
[1] in ('inf', 'infinite'):
234 cmd
+= self
._option
('--bind-address', 'source_address')
235 cmd
+= self
._option
('--proxy', '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', '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
)
255 def _make_cmd(self
, tmpfilename
, info_dict
):
256 cmd
= [self
.exe
, '-c']
257 dn
= os
.path
.dirname(tmpfilename
)
258 if 'fragments' not in info_dict
:
259 cmd
+= ['--out', os
.path
.basename(tmpfilename
)]
260 verbose_level_args
= ['--console-log-level=warn', '--summary-interval=0']
261 cmd
+= self
._configuration
_args
(['--file-allocation=none', '-x16', '-j16', '-s16'] + verbose_level_args
)
264 if info_dict
.get('http_headers') is not None:
265 for key
, val
in info_dict
['http_headers'].items():
266 cmd
+= ['--header', '%s: %s' % (key
, val
)]
267 cmd
+= self
._option
('--interface', 'source_address')
268 cmd
+= self
._option
('--all-proxy', 'proxy')
269 cmd
+= self
._bool
_option
('--check-certificate', 'nocheckcertificate', 'false', 'true', '=')
270 cmd
+= self
._bool
_option
('--remote-time', 'updatetime', 'true', 'false', '=')
271 cmd
+= ['--auto-file-renaming=false']
272 if 'fragments' in info_dict
:
273 cmd
+= verbose_level_args
274 cmd
+= ['--uri-selector', 'inorder', '--download-result=hide']
275 url_list_file
= '%s.frag.urls' % tmpfilename
277 for i
, fragment
in enumerate(info_dict
['fragments']):
278 tmpsegmentname
= '%s-Frag%d' % (os
.path
.basename(tmpfilename
), i
)
279 url_list
.append('%s\n\tout=%s' % (fragment
['url'], tmpsegmentname
))
280 stream
, _
= sanitize_open(url_list_file
, 'wb')
281 stream
.write('\n'.join(url_list
).encode('utf-8'))
284 cmd
+= ['-i', url_list_file
]
286 cmd
+= ['--', info_dict
['url']]
290 class HttpieFD(ExternalFD
):
292 def available(cls
, path
=None):
293 return check_executable(path
or 'http', ['--version'])
295 def _make_cmd(self
, tmpfilename
, info_dict
):
296 cmd
= ['http', '--download', '--output', tmpfilename
, info_dict
['url']]
298 if info_dict
.get('http_headers') is not None:
299 for key
, val
in info_dict
['http_headers'].items():
300 cmd
+= ['%s:%s' % (key
, val
)]
304 class FFmpegFD(ExternalFD
):
305 SUPPORTED_PROTOCOLS
= ('http', 'https', 'ftp', 'ftps', 'm3u8', 'rtsp', 'rtmp', 'mms')
308 def available(cls
, path
=None): # path is ignored for ffmpeg
309 return FFmpegPostProcessor().available
311 def _call_downloader(self
, tmpfilename
, info_dict
):
312 url
= info_dict
['url']
313 ffpp
= FFmpegPostProcessor(downloader
=self
)
314 if not ffpp
.available
:
315 self
.report_error('m3u8 download detected but ffmpeg could not be found. Please install')
319 args
= [ffpp
.executable
, '-y']
321 for log_level
in ('quiet', 'verbose'):
322 if self
.params
.get(log_level
, False):
323 args
+= ['-loglevel', log_level
]
326 seekable
= info_dict
.get('_seekable')
327 if seekable
is not None:
328 # setting -seekable prevents ffmpeg from guessing if the server
329 # supports seeking(by adding the header `Range: bytes=0-`), which
330 # can cause problems in some cases
331 # https://github.com/ytdl-org/youtube-dl/issues/11800#issuecomment-275037127
332 # http://trac.ffmpeg.org/ticket/6125#comment:10
333 args
+= ['-seekable', '1' if seekable
else '0']
335 args
+= self
._configuration
_args
()
337 # start_time = info_dict.get('start_time') or 0
339 # args += ['-ss', compat_str(start_time)]
340 # end_time = info_dict.get('end_time')
342 # args += ['-t', compat_str(end_time - start_time)]
344 if info_dict
.get('http_headers') is not None and re
.match(r
'^https?://', url
):
345 # Trailing \r\n after each HTTP header is important to prevent warning from ffmpeg/avconv:
346 # [http @ 00000000003d2fa0] No trailing CRLF found in HTTP header.
347 headers
= handle_youtubedl_headers(info_dict
['http_headers'])
350 ''.join('%s: %s\r\n' % (key
, val
) for key
, val
in headers
.items())]
353 proxy
= self
.params
.get('proxy')
355 if not re
.match(r
'^[\da-zA-Z]+://', proxy
):
356 proxy
= 'http://%s' % proxy
358 if proxy
.startswith('socks'):
360 '%s does not support SOCKS proxies. Downloading is likely to fail. '
361 'Consider adding --hls-prefer-native to your command.' % self
.get_basename())
363 # Since December 2015 ffmpeg supports -http_proxy option (see
364 # http://git.videolan.org/?p=ffmpeg.git;a=commit;h=b4eb1f29ebddd60c41a2eb39f5af701e38e0d3fd)
365 # We could switch to the following code if we are able to detect version properly
366 # args += ['-http_proxy', proxy]
367 env
= os
.environ
.copy()
368 compat_setenv('HTTP_PROXY', proxy
, env
=env
)
369 compat_setenv('http_proxy', proxy
, env
=env
)
371 protocol
= info_dict
.get('protocol')
373 if protocol
== 'rtmp':
374 player_url
= info_dict
.get('player_url')
375 page_url
= info_dict
.get('page_url')
376 app
= info_dict
.get('app')
377 play_path
= info_dict
.get('play_path')
378 tc_url
= info_dict
.get('tc_url')
379 flash_version
= info_dict
.get('flash_version')
380 live
= info_dict
.get('rtmp_live', False)
381 conn
= info_dict
.get('rtmp_conn')
382 if player_url
is not None:
383 args
+= ['-rtmp_swfverify', player_url
]
384 if page_url
is not None:
385 args
+= ['-rtmp_pageurl', page_url
]
387 args
+= ['-rtmp_app', app
]
388 if play_path
is not None:
389 args
+= ['-rtmp_playpath', play_path
]
390 if tc_url
is not None:
391 args
+= ['-rtmp_tcurl', tc_url
]
392 if flash_version
is not None:
393 args
+= ['-rtmp_flashver', flash_version
]
395 args
+= ['-rtmp_live', 'live']
396 if isinstance(conn
, list):
398 args
+= ['-rtmp_conn', entry
]
399 elif isinstance(conn
, compat_str
):
400 args
+= ['-rtmp_conn', conn
]
402 args
+= ['-i', url
, '-c', 'copy']
404 if self
.params
.get('test', False):
405 args
+= ['-fs', compat_str(self
._TEST
_FILE
_SIZE
)]
407 if protocol
in ('m3u8', 'm3u8_native'):
408 use_mpegts
= (tmpfilename
== '-') or self
.params
.get('hls_use_mpegts')
409 if use_mpegts
is None:
410 use_mpegts
= info_dict
.get('is_live')
412 args
+= ['-f', 'mpegts']
414 args
+= ['-f', 'mp4']
415 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')):
416 args
+= ['-bsf:a', 'aac_adtstoasc']
417 elif protocol
== 'rtmp':
418 args
+= ['-f', 'flv']
420 args
+= ['-f', EXT_TO_OUT_FORMATS
.get(info_dict
['ext'], info_dict
['ext'])]
422 args
= [encodeArgument(opt
) for opt
in args
]
423 args
.append(encodeFilename(ffpp
._ffmpeg
_filename
_argument
(tmpfilename
), True))
425 self
._debug
_cmd
(args
)
427 proc
= subprocess
.Popen(args
, stdin
=subprocess
.PIPE
, env
=env
)
430 except BaseException
as e
:
431 # subprocces.run would send the SIGKILL signal to ffmpeg and the
432 # mp4 file couldn't be played, but if we ask ffmpeg to quit it
433 # produces a file that is playable (this is mostly useful for live
434 # streams). Note that Windows is not affected and produces playable
435 # files (see https://github.com/ytdl-org/youtube-dl/issues/8300).
436 if isinstance(e
, KeyboardInterrupt) and sys
.platform
!= 'win32':
437 process_communicate_or_kill(proc
, b
'q')
445 class AVconvFD(FFmpegFD
):
450 (klass
.get_basename(), klass
)
451 for name
, klass
in globals().items()
452 if name
.endswith('FD') and name
!= 'ExternalFD'
456 def list_external_downloaders():
457 return sorted(_BY_NAME
.keys())
460 def get_external_downloader(external_downloader
):
461 """ Given the name of the executable, see whether we support the given
463 # Drop .exe extension on Windows
464 bn
= os
.path
.splitext(os
.path
.basename(external_downloader
))[0]