]>
Raphaƫl G. Git Repositories - youtubedl/blob - youtube_dl/downloader/external.py
1 from __future__
import unicode_literals
8 from .common
import FileDownloader
13 from ..postprocessor
.ffmpeg
import FFmpegPostProcessor
, EXT_TO_OUT_FORMATS
18 cli_configuration_args
,
21 handle_youtubedl_headers
,
27 class ExternalFD(FileDownloader
):
28 def real_download(self
, filename
, info_dict
):
29 self
.report_destination(filename
)
30 tmpfilename
= self
.temp_name(filename
)
33 retval
= self
._call
_downloader
(tmpfilename
, info_dict
)
34 except KeyboardInterrupt:
35 if not info_dict
.get('is_live'):
37 # Live stream downloading cancellation should be considered as
38 # correct and expected termination thus all postprocessing
41 self
.to_screen('[%s] Interrupted by user' % self
.get_basename())
44 fsize
= os
.path
.getsize(encodeFilename(tmpfilename
))
45 self
.to_screen('\r[%s] Downloaded %s bytes' % (self
.get_basename(), fsize
))
46 self
.try_rename(tmpfilename
, filename
)
48 'downloaded_bytes': fsize
,
56 self
.report_error('%s exited with code %d' % (
57 self
.get_basename(), retval
))
61 def get_basename(cls
):
62 return cls
.__name
__[:-2].lower()
66 return self
.params
.get('external_downloader')
70 return check_executable(cls
.get_basename(), [cls
.AVAILABLE_OPT
])
73 def supports(cls
, info_dict
):
74 return info_dict
['protocol'] in ('http', 'https', 'ftp', 'ftps')
77 def can_download(cls
, info_dict
):
78 return cls
.available() and cls
.supports(info_dict
)
80 def _option(self
, command_option
, param
):
81 return cli_option(self
.params
, command_option
, param
)
83 def _bool_option(self
, command_option
, param
, true_value
='true', false_value
='false', separator
=None):
84 return cli_bool_option(self
.params
, command_option
, param
, true_value
, false_value
, separator
)
86 def _valueless_option(self
, command_option
, param
, expected_value
=True):
87 return cli_valueless_option(self
.params
, command_option
, param
, expected_value
)
89 def _configuration_args(self
, default
=[]):
90 return cli_configuration_args(self
.params
, 'external_downloader_args', default
)
92 def _call_downloader(self
, tmpfilename
, info_dict
):
93 """ Either overwrite this or implement _make_cmd """
94 cmd
= [encodeArgument(a
) for a
in self
._make
_cmd
(tmpfilename
, info_dict
)]
99 cmd
, stderr
=subprocess
.PIPE
)
100 _
, stderr
= p
.communicate()
101 if p
.returncode
!= 0:
102 self
.to_stderr(stderr
.decode('utf-8', 'replace'))
106 class CurlFD(ExternalFD
):
109 def _make_cmd(self
, tmpfilename
, info_dict
):
110 cmd
= [self
.exe
, '--location', '-o', tmpfilename
]
111 for key
, val
in info_dict
['http_headers'].items():
112 cmd
+= ['--header', '%s: %s' % (key
, val
)]
113 cmd
+= self
._bool
_option
('--continue-at', 'continuedl', '-', '0')
114 cmd
+= self
._valueless
_option
('--silent', 'noprogress')
115 cmd
+= self
._valueless
_option
('--verbose', 'verbose')
116 cmd
+= self
._option
('--limit-rate', 'ratelimit')
117 cmd
+= self
._option
('--retry', 'retries')
118 cmd
+= self
._option
('--max-filesize', 'max_filesize')
119 cmd
+= self
._option
('--interface', 'source_address')
120 cmd
+= self
._option
('--proxy', 'proxy')
121 cmd
+= self
._valueless
_option
('--insecure', 'nocheckcertificate')
122 cmd
+= self
._configuration
_args
()
123 cmd
+= ['--', info_dict
['url']]
126 def _call_downloader(self
, tmpfilename
, info_dict
):
127 cmd
= [encodeArgument(a
) for a
in self
._make
_cmd
(tmpfilename
, info_dict
)]
131 # curl writes the progress to stderr so don't capture it.
132 p
= subprocess
.Popen(cmd
)
137 class AxelFD(ExternalFD
):
140 def _make_cmd(self
, tmpfilename
, info_dict
):
141 cmd
= [self
.exe
, '-o', tmpfilename
]
142 for key
, val
in info_dict
['http_headers'].items():
143 cmd
+= ['-H', '%s: %s' % (key
, val
)]
144 cmd
+= self
._configuration
_args
()
145 cmd
+= ['--', info_dict
['url']]
149 class WgetFD(ExternalFD
):
150 AVAILABLE_OPT
= '--version'
152 def _make_cmd(self
, tmpfilename
, info_dict
):
153 cmd
= [self
.exe
, '-O', tmpfilename
, '-nv', '--no-cookies']
154 for key
, val
in info_dict
['http_headers'].items():
155 cmd
+= ['--header', '%s: %s' % (key
, val
)]
156 cmd
+= self
._option
('--bind-address', 'source_address')
157 cmd
+= self
._option
('--proxy', 'proxy')
158 cmd
+= self
._valueless
_option
('--no-check-certificate', 'nocheckcertificate')
159 cmd
+= self
._configuration
_args
()
160 cmd
+= ['--', info_dict
['url']]
164 class Aria2cFD(ExternalFD
):
167 def _make_cmd(self
, tmpfilename
, info_dict
):
168 cmd
= [self
.exe
, '-c']
169 cmd
+= self
._configuration
_args
([
170 '--min-split-size', '1M', '--max-connection-per-server', '4'])
171 dn
= os
.path
.dirname(tmpfilename
)
174 cmd
+= ['--out', os
.path
.basename(tmpfilename
)]
175 for key
, val
in info_dict
['http_headers'].items():
176 cmd
+= ['--header', '%s: %s' % (key
, val
)]
177 cmd
+= self
._option
('--interface', 'source_address')
178 cmd
+= self
._option
('--all-proxy', 'proxy')
179 cmd
+= self
._bool
_option
('--check-certificate', 'nocheckcertificate', 'false', 'true', '=')
180 cmd
+= ['--', info_dict
['url']]
184 class HttpieFD(ExternalFD
):
187 return check_executable('http', ['--version'])
189 def _make_cmd(self
, tmpfilename
, info_dict
):
190 cmd
= ['http', '--download', '--output', tmpfilename
, info_dict
['url']]
191 for key
, val
in info_dict
['http_headers'].items():
192 cmd
+= ['%s:%s' % (key
, val
)]
196 class FFmpegFD(ExternalFD
):
198 def supports(cls
, info_dict
):
199 return info_dict
['protocol'] in ('http', 'https', 'ftp', 'ftps', 'm3u8', 'rtsp', 'rtmp', 'mms')
203 return FFmpegPostProcessor().available
205 def _call_downloader(self
, tmpfilename
, info_dict
):
206 url
= info_dict
['url']
207 ffpp
= FFmpegPostProcessor(downloader
=self
)
208 if not ffpp
.available
:
209 self
.report_error('m3u8 download detected but ffmpeg or avconv could not be found. Please install one.')
213 args
= [ffpp
.executable
, '-y']
215 seekable
= info_dict
.get('_seekable')
216 if seekable
is not None:
217 # setting -seekable prevents ffmpeg from guessing if the server
218 # supports seeking(by adding the header `Range: bytes=0-`), which
219 # can cause problems in some cases
220 # https://github.com/rg3/youtube-dl/issues/11800#issuecomment-275037127
221 # http://trac.ffmpeg.org/ticket/6125#comment:10
222 args
+= ['-seekable', '1' if seekable
else '0']
224 args
+= self
._configuration
_args
()
226 # start_time = info_dict.get('start_time') or 0
228 # args += ['-ss', compat_str(start_time)]
229 # end_time = info_dict.get('end_time')
231 # args += ['-t', compat_str(end_time - start_time)]
233 if info_dict
['http_headers'] and re
.match(r
'^https?://', url
):
234 # Trailing \r\n after each HTTP header is important to prevent warning from ffmpeg/avconv:
235 # [http @ 00000000003d2fa0] No trailing CRLF found in HTTP header.
236 headers
= handle_youtubedl_headers(info_dict
['http_headers'])
239 ''.join('%s: %s\r\n' % (key
, val
) for key
, val
in headers
.items())]
242 proxy
= self
.params
.get('proxy')
244 if not re
.match(r
'^[\da-zA-Z]+://', proxy
):
245 proxy
= 'http://%s' % proxy
247 if proxy
.startswith('socks'):
249 '%s does not support SOCKS proxies. Downloading is likely to fail. '
250 'Consider adding --hls-prefer-native to your command.' % self
.get_basename())
252 # Since December 2015 ffmpeg supports -http_proxy option (see
253 # http://git.videolan.org/?p=ffmpeg.git;a=commit;h=b4eb1f29ebddd60c41a2eb39f5af701e38e0d3fd)
254 # We could switch to the following code if we are able to detect version properly
255 # args += ['-http_proxy', proxy]
256 env
= os
.environ
.copy()
257 compat_setenv('HTTP_PROXY', proxy
, env
=env
)
258 compat_setenv('http_proxy', proxy
, env
=env
)
260 protocol
= info_dict
.get('protocol')
262 if protocol
== 'rtmp':
263 player_url
= info_dict
.get('player_url')
264 page_url
= info_dict
.get('page_url')
265 app
= info_dict
.get('app')
266 play_path
= info_dict
.get('play_path')
267 tc_url
= info_dict
.get('tc_url')
268 flash_version
= info_dict
.get('flash_version')
269 live
= info_dict
.get('rtmp_live', False)
270 if player_url
is not None:
271 args
+= ['-rtmp_swfverify', player_url
]
272 if page_url
is not None:
273 args
+= ['-rtmp_pageurl', page_url
]
275 args
+= ['-rtmp_app', app
]
276 if play_path
is not None:
277 args
+= ['-rtmp_playpath', play_path
]
278 if tc_url
is not None:
279 args
+= ['-rtmp_tcurl', tc_url
]
280 if flash_version
is not None:
281 args
+= ['-rtmp_flashver', flash_version
]
283 args
+= ['-rtmp_live', 'live']
285 args
+= ['-i', url
, '-c', 'copy']
287 if self
.params
.get('test', False):
288 args
+= ['-fs', compat_str(self
._TEST
_FILE
_SIZE
)]
290 if protocol
in ('m3u8', 'm3u8_native'):
291 if self
.params
.get('hls_use_mpegts', False) or tmpfilename
== '-':
292 args
+= ['-f', 'mpegts']
294 args
+= ['-f', 'mp4']
295 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')):
296 args
+= ['-bsf:a', 'aac_adtstoasc']
297 elif protocol
== 'rtmp':
298 args
+= ['-f', 'flv']
300 args
+= ['-f', EXT_TO_OUT_FORMATS
.get(info_dict
['ext'], info_dict
['ext'])]
302 args
= [encodeArgument(opt
) for opt
in args
]
303 args
.append(encodeFilename(ffpp
._ffmpeg
_filename
_argument
(tmpfilename
), True))
305 self
._debug
_cmd
(args
)
307 proc
= subprocess
.Popen(args
, stdin
=subprocess
.PIPE
, env
=env
)
310 except KeyboardInterrupt:
311 # subprocces.run would send the SIGKILL signal to ffmpeg and the
312 # mp4 file couldn't be played, but if we ask ffmpeg to quit it
313 # produces a file that is playable (this is mostly useful for live
314 # streams). Note that Windows is not affected and produces playable
315 # files (see https://github.com/rg3/youtube-dl/issues/8300).
316 if sys
.platform
!= 'win32':
317 proc
.communicate(b
'q')
322 class AVconvFD(FFmpegFD
):
327 (klass
.get_basename(), klass
)
328 for name
, klass
in globals().items()
329 if name
.endswith('FD') and name
!= 'ExternalFD'
333 def list_external_downloaders():
334 return sorted(_BY_NAME
.keys())
337 def get_external_downloader(external_downloader
):
338 """ Given the name of the executable, see whether we support the given
340 # Drop .exe extension on Windows
341 bn
= os
.path
.splitext(os
.path
.basename(external_downloader
))[0]