]> Raphaƫl G. Git Repositories - youtubedl/blob - youtube_dl/downloader/external.py
Initiate new release.
[youtubedl] / youtube_dl / downloader / external.py
1 from __future__ import unicode_literals
2
3 import os.path
4 import subprocess
5 import sys
6 import re
7
8 from .common import FileDownloader
9 from ..compat import compat_setenv
10 from ..postprocessor.ffmpeg import FFmpegPostProcessor, EXT_TO_OUT_FORMATS
11 from ..utils import (
12 cli_option,
13 cli_valueless_option,
14 cli_bool_option,
15 cli_configuration_args,
16 encodeFilename,
17 encodeArgument,
18 handle_youtubedl_headers,
19 check_executable,
20 is_outdated_version,
21 )
22
23
24 class ExternalFD(FileDownloader):
25 def real_download(self, filename, info_dict):
26 self.report_destination(filename)
27 tmpfilename = self.temp_name(filename)
28
29 retval = self._call_downloader(tmpfilename, info_dict)
30 if retval == 0:
31 fsize = os.path.getsize(encodeFilename(tmpfilename))
32 self.to_screen('\r[%s] Downloaded %s bytes' % (self.get_basename(), fsize))
33 self.try_rename(tmpfilename, filename)
34 self._hook_progress({
35 'downloaded_bytes': fsize,
36 'total_bytes': fsize,
37 'filename': filename,
38 'status': 'finished',
39 })
40 return True
41 else:
42 self.to_stderr('\n')
43 self.report_error('%s exited with code %d' % (
44 self.get_basename(), retval))
45 return False
46
47 @classmethod
48 def get_basename(cls):
49 return cls.__name__[:-2].lower()
50
51 @property
52 def exe(self):
53 return self.params.get('external_downloader')
54
55 @classmethod
56 def available(cls):
57 return check_executable(cls.get_basename(), [cls.AVAILABLE_OPT])
58
59 @classmethod
60 def supports(cls, info_dict):
61 return info_dict['protocol'] in ('http', 'https', 'ftp', 'ftps')
62
63 @classmethod
64 def can_download(cls, info_dict):
65 return cls.available() and cls.supports(info_dict)
66
67 def _option(self, command_option, param):
68 return cli_option(self.params, command_option, param)
69
70 def _bool_option(self, command_option, param, true_value='true', false_value='false', separator=None):
71 return cli_bool_option(self.params, command_option, param, true_value, false_value, separator)
72
73 def _valueless_option(self, command_option, param, expected_value=True):
74 return cli_valueless_option(self.params, command_option, param, expected_value)
75
76 def _configuration_args(self, default=[]):
77 return cli_configuration_args(self.params, 'external_downloader_args', default)
78
79 def _call_downloader(self, tmpfilename, info_dict):
80 """ Either overwrite this or implement _make_cmd """
81 cmd = [encodeArgument(a) for a in self._make_cmd(tmpfilename, info_dict)]
82
83 self._debug_cmd(cmd)
84
85 p = subprocess.Popen(
86 cmd, stderr=subprocess.PIPE)
87 _, stderr = p.communicate()
88 if p.returncode != 0:
89 self.to_stderr(stderr.decode('utf-8', 'replace'))
90 return p.returncode
91
92
93 class CurlFD(ExternalFD):
94 AVAILABLE_OPT = '-V'
95
96 def _make_cmd(self, tmpfilename, info_dict):
97 cmd = [self.exe, '--location', '-o', tmpfilename]
98 for key, val in info_dict['http_headers'].items():
99 cmd += ['--header', '%s: %s' % (key, val)]
100 cmd += self._bool_option('--continue-at', 'continuedl', '-', '0')
101 cmd += self._valueless_option('--silent', 'noprogress')
102 cmd += self._valueless_option('--verbose', 'verbose')
103 cmd += self._option('--limit-rate', 'ratelimit')
104 cmd += self._option('--retry', 'retries')
105 cmd += self._option('--max-filesize', 'max_filesize')
106 cmd += self._option('--interface', 'source_address')
107 cmd += self._option('--proxy', 'proxy')
108 cmd += self._valueless_option('--insecure', 'nocheckcertificate')
109 cmd += self._configuration_args()
110 cmd += ['--', info_dict['url']]
111 return cmd
112
113 def _call_downloader(self, tmpfilename, info_dict):
114 cmd = [encodeArgument(a) for a in self._make_cmd(tmpfilename, info_dict)]
115
116 self._debug_cmd(cmd)
117
118 # curl writes the progress to stderr so don't capture it.
119 p = subprocess.Popen(cmd)
120 p.communicate()
121 return p.returncode
122
123
124 class AxelFD(ExternalFD):
125 AVAILABLE_OPT = '-V'
126
127 def _make_cmd(self, tmpfilename, info_dict):
128 cmd = [self.exe, '-o', tmpfilename]
129 for key, val in info_dict['http_headers'].items():
130 cmd += ['-H', '%s: %s' % (key, val)]
131 cmd += self._configuration_args()
132 cmd += ['--', info_dict['url']]
133 return cmd
134
135
136 class WgetFD(ExternalFD):
137 AVAILABLE_OPT = '--version'
138
139 def _make_cmd(self, tmpfilename, info_dict):
140 cmd = [self.exe, '-O', tmpfilename, '-nv', '--no-cookies']
141 for key, val in info_dict['http_headers'].items():
142 cmd += ['--header', '%s: %s' % (key, val)]
143 cmd += self._option('--bind-address', 'source_address')
144 cmd += self._option('--proxy', 'proxy')
145 cmd += self._valueless_option('--no-check-certificate', 'nocheckcertificate')
146 cmd += self._configuration_args()
147 cmd += ['--', info_dict['url']]
148 return cmd
149
150
151 class Aria2cFD(ExternalFD):
152 AVAILABLE_OPT = '-v'
153
154 def _make_cmd(self, tmpfilename, info_dict):
155 cmd = [self.exe, '-c']
156 cmd += self._configuration_args([
157 '--min-split-size', '1M', '--max-connection-per-server', '4'])
158 dn = os.path.dirname(tmpfilename)
159 if dn:
160 cmd += ['--dir', dn]
161 cmd += ['--out', os.path.basename(tmpfilename)]
162 for key, val in info_dict['http_headers'].items():
163 cmd += ['--header', '%s: %s' % (key, val)]
164 cmd += self._option('--interface', 'source_address')
165 cmd += self._option('--all-proxy', 'proxy')
166 cmd += self._bool_option('--check-certificate', 'nocheckcertificate', 'false', 'true', '=')
167 cmd += ['--', info_dict['url']]
168 return cmd
169
170
171 class HttpieFD(ExternalFD):
172 @classmethod
173 def available(cls):
174 return check_executable('http', ['--version'])
175
176 def _make_cmd(self, tmpfilename, info_dict):
177 cmd = ['http', '--download', '--output', tmpfilename, info_dict['url']]
178 for key, val in info_dict['http_headers'].items():
179 cmd += ['%s:%s' % (key, val)]
180 return cmd
181
182
183 class FFmpegFD(ExternalFD):
184 @classmethod
185 def supports(cls, info_dict):
186 return info_dict['protocol'] in ('http', 'https', 'ftp', 'ftps', 'm3u8', 'rtsp', 'rtmp', 'mms')
187
188 @classmethod
189 def available(cls):
190 return FFmpegPostProcessor().available
191
192 def _call_downloader(self, tmpfilename, info_dict):
193 url = info_dict['url']
194 ffpp = FFmpegPostProcessor(downloader=self)
195 if not ffpp.available:
196 self.report_error('m3u8 download detected but ffmpeg or avconv could not be found. Please install one.')
197 return False
198 ffpp.check_version()
199
200 args = [ffpp.executable, '-y']
201
202 seekable = info_dict.get('_seekable')
203 if seekable is not None:
204 # setting -seekable prevents ffmpeg from guessing if the server
205 # supports seeking(by adding the header `Range: bytes=0-`), which
206 # can cause problems in some cases
207 # https://github.com/rg3/youtube-dl/issues/11800#issuecomment-275037127
208 # http://trac.ffmpeg.org/ticket/6125#comment:10
209 args += ['-seekable', '1' if seekable else '0']
210
211 args += self._configuration_args()
212
213 # start_time = info_dict.get('start_time') or 0
214 # if start_time:
215 # args += ['-ss', compat_str(start_time)]
216 # end_time = info_dict.get('end_time')
217 # if end_time:
218 # args += ['-t', compat_str(end_time - start_time)]
219
220 if info_dict['http_headers'] and re.match(r'^https?://', url):
221 # Trailing \r\n after each HTTP header is important to prevent warning from ffmpeg/avconv:
222 # [http @ 00000000003d2fa0] No trailing CRLF found in HTTP header.
223 headers = handle_youtubedl_headers(info_dict['http_headers'])
224 args += [
225 '-headers',
226 ''.join('%s: %s\r\n' % (key, val) for key, val in headers.items())]
227
228 env = None
229 proxy = self.params.get('proxy')
230 if proxy:
231 if not re.match(r'^[\da-zA-Z]+://', proxy):
232 proxy = 'http://%s' % proxy
233
234 if proxy.startswith('socks'):
235 self.report_warning(
236 '%s does not support SOCKS proxies. Downloading is likely to fail. '
237 'Consider adding --hls-prefer-native to your command.' % self.get_basename())
238
239 # Since December 2015 ffmpeg supports -http_proxy option (see
240 # http://git.videolan.org/?p=ffmpeg.git;a=commit;h=b4eb1f29ebddd60c41a2eb39f5af701e38e0d3fd)
241 # We could switch to the following code if we are able to detect version properly
242 # args += ['-http_proxy', proxy]
243 env = os.environ.copy()
244 compat_setenv('HTTP_PROXY', proxy, env=env)
245 compat_setenv('http_proxy', proxy, env=env)
246
247 protocol = info_dict.get('protocol')
248
249 if protocol == 'rtmp':
250 player_url = info_dict.get('player_url')
251 page_url = info_dict.get('page_url')
252 app = info_dict.get('app')
253 play_path = info_dict.get('play_path')
254 tc_url = info_dict.get('tc_url')
255 flash_version = info_dict.get('flash_version')
256 live = info_dict.get('rtmp_live', False)
257 if player_url is not None:
258 args += ['-rtmp_swfverify', player_url]
259 if page_url is not None:
260 args += ['-rtmp_pageurl', page_url]
261 if app is not None:
262 args += ['-rtmp_app', app]
263 if play_path is not None:
264 args += ['-rtmp_playpath', play_path]
265 if tc_url is not None:
266 args += ['-rtmp_tcurl', tc_url]
267 if flash_version is not None:
268 args += ['-rtmp_flashver', flash_version]
269 if live:
270 args += ['-rtmp_live', 'live']
271
272 args += ['-i', url, '-c', 'copy']
273 if protocol in ('m3u8', 'm3u8_native'):
274 if self.params.get('hls_use_mpegts', False) or tmpfilename == '-':
275 args += ['-f', 'mpegts']
276 else:
277 args += ['-f', 'mp4']
278 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')):
279 args += ['-bsf:a', 'aac_adtstoasc']
280 elif protocol == 'rtmp':
281 args += ['-f', 'flv']
282 else:
283 args += ['-f', EXT_TO_OUT_FORMATS.get(info_dict['ext'], info_dict['ext'])]
284
285 args = [encodeArgument(opt) for opt in args]
286 args.append(encodeFilename(ffpp._ffmpeg_filename_argument(tmpfilename), True))
287
288 self._debug_cmd(args)
289
290 proc = subprocess.Popen(args, stdin=subprocess.PIPE, env=env)
291 try:
292 retval = proc.wait()
293 except KeyboardInterrupt:
294 # subprocces.run would send the SIGKILL signal to ffmpeg and the
295 # mp4 file couldn't be played, but if we ask ffmpeg to quit it
296 # produces a file that is playable (this is mostly useful for live
297 # streams). Note that Windows is not affected and produces playable
298 # files (see https://github.com/rg3/youtube-dl/issues/8300).
299 if sys.platform != 'win32':
300 proc.communicate(b'q')
301 raise
302 return retval
303
304
305 class AVconvFD(FFmpegFD):
306 pass
307
308
309 _BY_NAME = dict(
310 (klass.get_basename(), klass)
311 for name, klass in globals().items()
312 if name.endswith('FD') and name != 'ExternalFD'
313 )
314
315
316 def list_external_downloaders():
317 return sorted(_BY_NAME.keys())
318
319
320 def get_external_downloader(external_downloader):
321 """ Given the name of the executable, see whether we support the given
322 downloader . """
323 # Drop .exe extension on Windows
324 bn = os.path.splitext(os.path.basename(external_downloader))[0]
325 return _BY_NAME[bn]