]>
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
)
32 retval
= self
._call
_downloader
(tmpfilename
, info_dict
)
34 fsize
= os
.path
.getsize(encodeFilename(tmpfilename
))
35 self
.to_screen('\r[%s] Downloaded %s bytes' % (self
.get_basename(), fsize
))
36 self
.try_rename(tmpfilename
, filename
)
38 'downloaded_bytes': fsize
,
46 self
.report_error('%s exited with code %d' % (
47 self
.get_basename(), retval
))
51 def get_basename(cls
):
52 return cls
.__name
__[:-2].lower()
56 return self
.params
.get('external_downloader')
60 return check_executable(cls
.get_basename(), [cls
.AVAILABLE_OPT
])
63 def supports(cls
, info_dict
):
64 return info_dict
['protocol'] in ('http', 'https', 'ftp', 'ftps')
67 def can_download(cls
, info_dict
):
68 return cls
.available() and cls
.supports(info_dict
)
70 def _option(self
, command_option
, param
):
71 return cli_option(self
.params
, command_option
, param
)
73 def _bool_option(self
, command_option
, param
, true_value
='true', false_value
='false', separator
=None):
74 return cli_bool_option(self
.params
, command_option
, param
, true_value
, false_value
, separator
)
76 def _valueless_option(self
, command_option
, param
, expected_value
=True):
77 return cli_valueless_option(self
.params
, command_option
, param
, expected_value
)
79 def _configuration_args(self
, default
=[]):
80 return cli_configuration_args(self
.params
, 'external_downloader_args', default
)
82 def _call_downloader(self
, tmpfilename
, info_dict
):
83 """ Either overwrite this or implement _make_cmd """
84 cmd
= [encodeArgument(a
) for a
in self
._make
_cmd
(tmpfilename
, info_dict
)]
89 cmd
, stderr
=subprocess
.PIPE
)
90 _
, stderr
= p
.communicate()
92 self
.to_stderr(stderr
.decode('utf-8', 'replace'))
96 class CurlFD(ExternalFD
):
99 def _make_cmd(self
, tmpfilename
, info_dict
):
100 cmd
= [self
.exe
, '--location', '-o', tmpfilename
]
101 for key
, val
in info_dict
['http_headers'].items():
102 cmd
+= ['--header', '%s: %s' % (key
, val
)]
103 cmd
+= self
._bool
_option
('--continue-at', 'continuedl', '-', '0')
104 cmd
+= self
._valueless
_option
('--silent', 'noprogress')
105 cmd
+= self
._valueless
_option
('--verbose', 'verbose')
106 cmd
+= self
._option
('--limit-rate', 'ratelimit')
107 cmd
+= self
._option
('--retry', 'retries')
108 cmd
+= self
._option
('--max-filesize', 'max_filesize')
109 cmd
+= self
._option
('--interface', 'source_address')
110 cmd
+= self
._option
('--proxy', 'proxy')
111 cmd
+= self
._valueless
_option
('--insecure', 'nocheckcertificate')
112 cmd
+= self
._configuration
_args
()
113 cmd
+= ['--', info_dict
['url']]
116 def _call_downloader(self
, tmpfilename
, info_dict
):
117 cmd
= [encodeArgument(a
) for a
in self
._make
_cmd
(tmpfilename
, info_dict
)]
121 # curl writes the progress to stderr so don't capture it.
122 p
= subprocess
.Popen(cmd
)
127 class AxelFD(ExternalFD
):
130 def _make_cmd(self
, tmpfilename
, info_dict
):
131 cmd
= [self
.exe
, '-o', tmpfilename
]
132 for key
, val
in info_dict
['http_headers'].items():
133 cmd
+= ['-H', '%s: %s' % (key
, val
)]
134 cmd
+= self
._configuration
_args
()
135 cmd
+= ['--', info_dict
['url']]
139 class WgetFD(ExternalFD
):
140 AVAILABLE_OPT
= '--version'
142 def _make_cmd(self
, tmpfilename
, info_dict
):
143 cmd
= [self
.exe
, '-O', tmpfilename
, '-nv', '--no-cookies']
144 for key
, val
in info_dict
['http_headers'].items():
145 cmd
+= ['--header', '%s: %s' % (key
, val
)]
146 cmd
+= self
._option
('--bind-address', 'source_address')
147 cmd
+= self
._option
('--proxy', 'proxy')
148 cmd
+= self
._valueless
_option
('--no-check-certificate', 'nocheckcertificate')
149 cmd
+= self
._configuration
_args
()
150 cmd
+= ['--', info_dict
['url']]
154 class Aria2cFD(ExternalFD
):
157 def _make_cmd(self
, tmpfilename
, info_dict
):
158 cmd
= [self
.exe
, '-c']
159 cmd
+= self
._configuration
_args
([
160 '--min-split-size', '1M', '--max-connection-per-server', '4'])
161 dn
= os
.path
.dirname(tmpfilename
)
164 cmd
+= ['--out', os
.path
.basename(tmpfilename
)]
165 for key
, val
in info_dict
['http_headers'].items():
166 cmd
+= ['--header', '%s: %s' % (key
, val
)]
167 cmd
+= self
._option
('--interface', 'source_address')
168 cmd
+= self
._option
('--all-proxy', 'proxy')
169 cmd
+= self
._bool
_option
('--check-certificate', 'nocheckcertificate', 'false', 'true', '=')
170 cmd
+= ['--', info_dict
['url']]
174 class HttpieFD(ExternalFD
):
177 return check_executable('http', ['--version'])
179 def _make_cmd(self
, tmpfilename
, info_dict
):
180 cmd
= ['http', '--download', '--output', tmpfilename
, info_dict
['url']]
181 for key
, val
in info_dict
['http_headers'].items():
182 cmd
+= ['%s:%s' % (key
, val
)]
186 class FFmpegFD(ExternalFD
):
188 def supports(cls
, info_dict
):
189 return info_dict
['protocol'] in ('http', 'https', 'ftp', 'ftps', 'm3u8', 'rtsp', 'rtmp', 'mms')
193 return FFmpegPostProcessor().available
195 def _call_downloader(self
, tmpfilename
, info_dict
):
196 url
= info_dict
['url']
197 ffpp
= FFmpegPostProcessor(downloader
=self
)
198 if not ffpp
.available
:
199 self
.report_error('m3u8 download detected but ffmpeg or avconv could not be found. Please install one.')
203 args
= [ffpp
.executable
, '-y']
205 seekable
= info_dict
.get('_seekable')
206 if seekable
is not None:
207 # setting -seekable prevents ffmpeg from guessing if the server
208 # supports seeking(by adding the header `Range: bytes=0-`), which
209 # can cause problems in some cases
210 # https://github.com/rg3/youtube-dl/issues/11800#issuecomment-275037127
211 # http://trac.ffmpeg.org/ticket/6125#comment:10
212 args
+= ['-seekable', '1' if seekable
else '0']
214 args
+= self
._configuration
_args
()
216 # start_time = info_dict.get('start_time') or 0
218 # args += ['-ss', compat_str(start_time)]
219 # end_time = info_dict.get('end_time')
221 # args += ['-t', compat_str(end_time - start_time)]
223 if info_dict
['http_headers'] and re
.match(r
'^https?://', url
):
224 # Trailing \r\n after each HTTP header is important to prevent warning from ffmpeg/avconv:
225 # [http @ 00000000003d2fa0] No trailing CRLF found in HTTP header.
226 headers
= handle_youtubedl_headers(info_dict
['http_headers'])
229 ''.join('%s: %s\r\n' % (key
, val
) for key
, val
in headers
.items())]
232 proxy
= self
.params
.get('proxy')
234 if not re
.match(r
'^[\da-zA-Z]+://', proxy
):
235 proxy
= 'http://%s' % proxy
237 if proxy
.startswith('socks'):
239 '%s does not support SOCKS proxies. Downloading is likely to fail. '
240 'Consider adding --hls-prefer-native to your command.' % self
.get_basename())
242 # Since December 2015 ffmpeg supports -http_proxy option (see
243 # http://git.videolan.org/?p=ffmpeg.git;a=commit;h=b4eb1f29ebddd60c41a2eb39f5af701e38e0d3fd)
244 # We could switch to the following code if we are able to detect version properly
245 # args += ['-http_proxy', proxy]
246 env
= os
.environ
.copy()
247 compat_setenv('HTTP_PROXY', proxy
, env
=env
)
248 compat_setenv('http_proxy', proxy
, env
=env
)
250 protocol
= info_dict
.get('protocol')
252 if protocol
== 'rtmp':
253 player_url
= info_dict
.get('player_url')
254 page_url
= info_dict
.get('page_url')
255 app
= info_dict
.get('app')
256 play_path
= info_dict
.get('play_path')
257 tc_url
= info_dict
.get('tc_url')
258 flash_version
= info_dict
.get('flash_version')
259 live
= info_dict
.get('rtmp_live', False)
260 if player_url
is not None:
261 args
+= ['-rtmp_swfverify', player_url
]
262 if page_url
is not None:
263 args
+= ['-rtmp_pageurl', page_url
]
265 args
+= ['-rtmp_app', app
]
266 if play_path
is not None:
267 args
+= ['-rtmp_playpath', play_path
]
268 if tc_url
is not None:
269 args
+= ['-rtmp_tcurl', tc_url
]
270 if flash_version
is not None:
271 args
+= ['-rtmp_flashver', flash_version
]
273 args
+= ['-rtmp_live', 'live']
275 args
+= ['-i', url
, '-c', 'copy']
277 if self
.params
.get('test', False):
278 args
+= ['-fs', compat_str(self
._TEST
_FILE
_SIZE
)]
280 if protocol
in ('m3u8', 'm3u8_native'):
281 if self
.params
.get('hls_use_mpegts', False) or tmpfilename
== '-':
282 args
+= ['-f', 'mpegts']
284 args
+= ['-f', 'mp4']
285 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')):
286 args
+= ['-bsf:a', 'aac_adtstoasc']
287 elif protocol
== 'rtmp':
288 args
+= ['-f', 'flv']
290 args
+= ['-f', EXT_TO_OUT_FORMATS
.get(info_dict
['ext'], info_dict
['ext'])]
292 args
= [encodeArgument(opt
) for opt
in args
]
293 args
.append(encodeFilename(ffpp
._ffmpeg
_filename
_argument
(tmpfilename
), True))
295 self
._debug
_cmd
(args
)
297 proc
= subprocess
.Popen(args
, stdin
=subprocess
.PIPE
, env
=env
)
300 except KeyboardInterrupt:
301 # subprocces.run would send the SIGKILL signal to ffmpeg and the
302 # mp4 file couldn't be played, but if we ask ffmpeg to quit it
303 # produces a file that is playable (this is mostly useful for live
304 # streams). Note that Windows is not affected and produces playable
305 # files (see https://github.com/rg3/youtube-dl/issues/8300).
306 if sys
.platform
!= 'win32':
307 proc
.communicate(b
'q')
312 class AVconvFD(FFmpegFD
):
317 (klass
.get_basename(), klass
)
318 for name
, klass
in globals().items()
319 if name
.endswith('FD') and name
!= 'ExternalFD'
323 def list_external_downloaders():
324 return sorted(_BY_NAME
.keys())
327 def get_external_downloader(external_downloader
):
328 """ Given the name of the executable, see whether we support the given
330 # Drop .exe extension on Windows
331 bn
= os
.path
.splitext(os
.path
.basename(external_downloader
))[0]