1 from __future__ import unicode_literals
9 from .common import FileDownloader
10 from ..compat import (
14 from ..postprocessor.ffmpeg import FFmpegPostProcessor, EXT_TO_OUT_FORMATS
19 cli_configuration_args,
22 handle_youtubedl_headers,
25 process_communicate_or_kill,
29 class ExternalFD(FileDownloader):
30 def real_download(self, filename, info_dict):
31 self.report_destination(filename)
32 tmpfilename = self.temp_name(filename)
36 retval = self._call_downloader(tmpfilename, info_dict)
37 except KeyboardInterrupt:
38 if not info_dict.get('is_live'):
40 # Live stream downloading cancellation should be considered as
41 # correct and expected termination thus all postprocessing
44 self.to_screen('[%s] Interrupted by user' % self.get_basename())
50 'elapsed': time.time() - started,
53 fsize = os.path.getsize(encodeFilename(tmpfilename))
54 self.to_screen('\r[%s] Downloaded %s bytes' % (self.get_basename(), fsize))
55 self.try_rename(tmpfilename, filename)
57 'downloaded_bytes': fsize,
60 self._hook_progress(status)
64 self.report_error('%s exited with code %d' % (
65 self.get_basename(), retval))
69 def get_basename(cls):
70 return cls.__name__[:-2].lower()
74 return self.params.get('external_downloader')
78 return check_executable(cls.get_basename(), [cls.AVAILABLE_OPT])
81 def supports(cls, info_dict):
82 return info_dict['protocol'] in ('http', 'https', 'ftp', 'ftps')
85 def can_download(cls, info_dict):
86 return cls.available() and cls.supports(info_dict)
88 def _option(self, command_option, param):
89 return cli_option(self.params, command_option, param)
91 def _bool_option(self, command_option, param, true_value='true', false_value='false', separator=None):
92 return cli_bool_option(self.params, command_option, param, true_value, false_value, separator)
94 def _valueless_option(self, command_option, param, expected_value=True):
95 return cli_valueless_option(self.params, command_option, param, expected_value)
97 def _configuration_args(self, default=[]):
98 return cli_configuration_args(self.params, 'external_downloader_args', default)
100 def _call_downloader(self, tmpfilename, info_dict):
101 """ Either overwrite this or implement _make_cmd """
102 cmd = [encodeArgument(a) for a in self._make_cmd(tmpfilename, info_dict)]
106 p = subprocess.Popen(
107 cmd, stderr=subprocess.PIPE)
108 _, stderr = process_communicate_or_kill(p)
109 if p.returncode != 0:
110 self.to_stderr(stderr.decode('utf-8', 'replace'))
114 class CurlFD(ExternalFD):
117 def _make_cmd(self, tmpfilename, info_dict):
118 cmd = [self.exe, '--location', '-o', tmpfilename]
119 for key, val in info_dict['http_headers'].items():
120 cmd += ['--header', '%s: %s' % (key, val)]
121 cmd += self._bool_option('--continue-at', 'continuedl', '-', '0')
122 cmd += self._valueless_option('--silent', 'noprogress')
123 cmd += self._valueless_option('--verbose', 'verbose')
124 cmd += self._option('--limit-rate', 'ratelimit')
125 retry = self._option('--retry', 'retries')
127 if retry[1] in ('inf', 'infinite'):
128 retry[1] = '2147483647'
130 cmd += self._option('--max-filesize', 'max_filesize')
131 cmd += self._option('--interface', 'source_address')
132 cmd += self._option('--proxy', 'proxy')
133 cmd += self._valueless_option('--insecure', 'nocheckcertificate')
134 cmd += self._configuration_args()
135 cmd += ['--', info_dict['url']]
138 def _call_downloader(self, tmpfilename, info_dict):
139 cmd = [encodeArgument(a) for a in self._make_cmd(tmpfilename, info_dict)]
143 # curl writes the progress to stderr so don't capture it.
144 p = subprocess.Popen(cmd)
145 process_communicate_or_kill(p)
149 class AxelFD(ExternalFD):
152 def _make_cmd(self, tmpfilename, info_dict):
153 cmd = [self.exe, '-o', tmpfilename]
154 for key, val in info_dict['http_headers'].items():
155 cmd += ['-H', '%s: %s' % (key, val)]
156 cmd += self._configuration_args()
157 cmd += ['--', info_dict['url']]
161 class WgetFD(ExternalFD):
162 AVAILABLE_OPT = '--version'
164 def _make_cmd(self, tmpfilename, info_dict):
165 cmd = [self.exe, '-O', tmpfilename, '-nv', '--no-cookies']
166 for key, val in info_dict['http_headers'].items():
167 cmd += ['--header', '%s: %s' % (key, val)]
168 cmd += self._option('--limit-rate', 'ratelimit')
169 retry = self._option('--tries', 'retries')
171 if retry[1] in ('inf', 'infinite'):
174 cmd += self._option('--bind-address', 'source_address')
175 cmd += self._option('--proxy', 'proxy')
176 cmd += self._valueless_option('--no-check-certificate', 'nocheckcertificate')
177 cmd += self._configuration_args()
178 cmd += ['--', info_dict['url']]
182 class Aria2cFD(ExternalFD):
185 def _make_cmd(self, tmpfilename, info_dict):
186 cmd = [self.exe, '-c']
187 cmd += self._configuration_args([
188 '--min-split-size', '1M', '--max-connection-per-server', '4'])
189 dn = os.path.dirname(tmpfilename)
192 cmd += ['--out', os.path.basename(tmpfilename)]
193 for key, val in info_dict['http_headers'].items():
194 cmd += ['--header', '%s: %s' % (key, val)]
195 cmd += self._option('--interface', 'source_address')
196 cmd += self._option('--all-proxy', 'proxy')
197 cmd += self._bool_option('--check-certificate', 'nocheckcertificate', 'false', 'true', '=')
198 cmd += self._bool_option('--remote-time', 'updatetime', 'true', 'false', '=')
199 cmd += ['--', info_dict['url']]
203 class HttpieFD(ExternalFD):
206 return check_executable('http', ['--version'])
208 def _make_cmd(self, tmpfilename, info_dict):
209 cmd = ['http', '--download', '--output', tmpfilename, info_dict['url']]
210 for key, val in info_dict['http_headers'].items():
211 cmd += ['%s:%s' % (key, val)]
215 class FFmpegFD(ExternalFD):
217 def supports(cls, info_dict):
218 return info_dict['protocol'] in ('http', 'https', 'ftp', 'ftps', 'm3u8', 'rtsp', 'rtmp', 'mms')
222 return FFmpegPostProcessor().available
224 def _call_downloader(self, tmpfilename, info_dict):
225 url = info_dict['url']
226 ffpp = FFmpegPostProcessor(downloader=self)
227 if not ffpp.available:
228 self.report_error('m3u8 download detected but ffmpeg or avconv could not be found. Please install one.')
232 args = [ffpp.executable, '-y']
234 for log_level in ('quiet', 'verbose'):
235 if self.params.get(log_level, False):
236 args += ['-loglevel', log_level]
239 seekable = info_dict.get('_seekable')
240 if seekable is not None:
241 # setting -seekable prevents ffmpeg from guessing if the server
242 # supports seeking(by adding the header `Range: bytes=0-`), which
243 # can cause problems in some cases
244 # https://github.com/ytdl-org/youtube-dl/issues/11800#issuecomment-275037127
245 # http://trac.ffmpeg.org/ticket/6125#comment:10
246 args += ['-seekable', '1' if seekable else '0']
248 args += self._configuration_args()
250 # start_time = info_dict.get('start_time') or 0
252 # args += ['-ss', compat_str(start_time)]
253 # end_time = info_dict.get('end_time')
255 # args += ['-t', compat_str(end_time - start_time)]
257 if info_dict['http_headers'] and re.match(r'^https?://', url):
258 # Trailing \r\n after each HTTP header is important to prevent warning from ffmpeg/avconv:
259 # [http @ 00000000003d2fa0] No trailing CRLF found in HTTP header.
260 headers = handle_youtubedl_headers(info_dict['http_headers'])
263 ''.join('%s: %s\r\n' % (key, val) for key, val in headers.items())]
266 proxy = self.params.get('proxy')
268 if not re.match(r'^[\da-zA-Z]+://', proxy):
269 proxy = 'http://%s' % proxy
271 if proxy.startswith('socks'):
273 '%s does not support SOCKS proxies. Downloading is likely to fail. '
274 'Consider adding --hls-prefer-native to your command.' % self.get_basename())
276 # Since December 2015 ffmpeg supports -http_proxy option (see
277 # http://git.videolan.org/?p=ffmpeg.git;a=commit;h=b4eb1f29ebddd60c41a2eb39f5af701e38e0d3fd)
278 # We could switch to the following code if we are able to detect version properly
279 # args += ['-http_proxy', proxy]
280 env = os.environ.copy()
281 compat_setenv('HTTP_PROXY', proxy, env=env)
282 compat_setenv('http_proxy', proxy, env=env)
284 protocol = info_dict.get('protocol')
286 if protocol == 'rtmp':
287 player_url = info_dict.get('player_url')
288 page_url = info_dict.get('page_url')
289 app = info_dict.get('app')
290 play_path = info_dict.get('play_path')
291 tc_url = info_dict.get('tc_url')
292 flash_version = info_dict.get('flash_version')
293 live = info_dict.get('rtmp_live', False)
294 conn = info_dict.get('rtmp_conn')
295 if player_url is not None:
296 args += ['-rtmp_swfverify', player_url]
297 if page_url is not None:
298 args += ['-rtmp_pageurl', page_url]
300 args += ['-rtmp_app', app]
301 if play_path is not None:
302 args += ['-rtmp_playpath', play_path]
303 if tc_url is not None:
304 args += ['-rtmp_tcurl', tc_url]
305 if flash_version is not None:
306 args += ['-rtmp_flashver', flash_version]
308 args += ['-rtmp_live', 'live']
309 if isinstance(conn, list):
311 args += ['-rtmp_conn', entry]
312 elif isinstance(conn, compat_str):
313 args += ['-rtmp_conn', conn]
315 args += ['-i', url, '-c', 'copy']
317 if self.params.get('test', False):
318 args += ['-fs', compat_str(self._TEST_FILE_SIZE)]
320 if protocol in ('m3u8', 'm3u8_native'):
321 if self.params.get('hls_use_mpegts', False) or tmpfilename == '-':
322 args += ['-f', 'mpegts']
324 args += ['-f', 'mp4']
325 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')):
326 args += ['-bsf:a', 'aac_adtstoasc']
327 elif protocol == 'rtmp':
328 args += ['-f', 'flv']
330 args += ['-f', EXT_TO_OUT_FORMATS.get(info_dict['ext'], info_dict['ext'])]
332 args = [encodeArgument(opt) for opt in args]
333 args.append(encodeFilename(ffpp._ffmpeg_filename_argument(tmpfilename), True))
335 self._debug_cmd(args)
337 proc = subprocess.Popen(args, stdin=subprocess.PIPE, env=env)
340 except BaseException as e:
341 # subprocess.run would send the SIGKILL signal to ffmpeg and the
342 # mp4 file couldn't be played, but if we ask ffmpeg to quit it
343 # produces a file that is playable (this is mostly useful for live
344 # streams). Note that Windows is not affected and produces playable
345 # files (see https://github.com/ytdl-org/youtube-dl/issues/8300).
346 if isinstance(e, KeyboardInterrupt) and sys.platform != 'win32':
347 process_communicate_or_kill(proc, b'q')
355 class AVconvFD(FFmpegFD):
360 (klass.get_basename(), klass)
361 for name, klass in globals().items()
362 if name.endswith('FD') and name != 'ExternalFD'
366 def list_external_downloaders():
367 return sorted(_BY_NAME.keys())
370 def get_external_downloader(external_downloader):
371 """ Given the name of the executable, see whether we support the given
373 # Drop .exe extension on Windows
374 bn = os.path.splitext(os.path.basename(external_downloader))[0]