]>
Commit | Line | Data |
---|---|---|
c487cf00 | 1 | import enum |
8c53322c | 2 | import json |
222516d9 | 3 | import os.path |
f0298f65 | 4 | import re |
222516d9 | 5 | import subprocess |
12b84ac8 | 6 | import sys |
f0298f65 | 7 | import time |
8c53322c | 8 | import uuid |
5219cb3e | 9 | |
1009f67c | 10 | from .fragment import FragmentFD |
14f25df2 | 11 | from ..compat import functools |
f8271158 | 12 | from ..postprocessor.ffmpeg import EXT_TO_OUT_FORMATS, FFmpegPostProcessor |
222516d9 | 13 | from ..utils import ( |
f8271158 | 14 | Popen, |
be5c1ae8 | 15 | RetryManager, |
f8271158 | 16 | _configuration_args, |
17 | check_executable, | |
28787f16 | 18 | classproperty, |
f8271158 | 19 | cli_bool_option, |
1195a38f S |
20 | cli_option, |
21 | cli_valueless_option, | |
af6793f8 | 22 | determine_ext, |
74f8654a | 23 | encodeArgument, |
f8271158 | 24 | encodeFilename, |
8c53322c | 25 | find_available_port, |
af6793f8 | 26 | remove_end, |
8c53322c | 27 | sanitized_Request, |
0a5a191a | 28 | traverse_obj, |
222516d9 PH |
29 | ) |
30 | ||
31 | ||
c487cf00 | 32 | class Features(enum.Enum): |
33 | TO_STDOUT = enum.auto() | |
34 | MULTIPLE_FORMATS = enum.auto() | |
35 | ||
36 | ||
1009f67c | 37 | class ExternalFD(FragmentFD): |
5219cb3e | 38 | SUPPORTED_PROTOCOLS = ('http', 'https', 'ftp', 'ftps') |
c487cf00 | 39 | SUPPORTED_FEATURES = () |
f0c9fb96 | 40 | _CAPTURE_STDERR = True |
5219cb3e | 41 | |
222516d9 PH |
42 | def real_download(self, filename, info_dict): |
43 | self.report_destination(filename) | |
44 | tmpfilename = self.temp_name(filename) | |
45 | ||
e7db6759 | 46 | try: |
f0298f65 | 47 | started = time.time() |
e7db6759 S |
48 | retval = self._call_downloader(tmpfilename, info_dict) |
49 | except KeyboardInterrupt: | |
50 | if not info_dict.get('is_live'): | |
51 | raise | |
52 | # Live stream downloading cancellation should be considered as | |
53 | # correct and expected termination thus all postprocessing | |
54 | # should take place | |
55 | retval = 0 | |
56 | self.to_screen('[%s] Interrupted by user' % self.get_basename()) | |
57 | ||
222516d9 | 58 | if retval == 0: |
f0298f65 S |
59 | status = { |
60 | 'filename': filename, | |
61 | 'status': 'finished', | |
62 | 'elapsed': time.time() - started, | |
63 | } | |
64 | if filename != '-': | |
80aa2460 | 65 | fsize = os.path.getsize(encodeFilename(tmpfilename)) |
80aa2460 | 66 | self.try_rename(tmpfilename, filename) |
f0298f65 | 67 | status.update({ |
80aa2460 JH |
68 | 'downloaded_bytes': fsize, |
69 | 'total_bytes': fsize, | |
80aa2460 | 70 | }) |
3ba7740d | 71 | self._hook_progress(status, info_dict) |
222516d9 PH |
72 | return True |
73 | else: | |
74 | self.to_stderr('\n') | |
75 | self.report_error('%s exited with code %d' % ( | |
76 | self.get_basename(), retval)) | |
77 | return False | |
78 | ||
79 | @classmethod | |
80 | def get_basename(cls): | |
81 | return cls.__name__[:-2].lower() | |
82 | ||
28787f16 | 83 | @classproperty |
84 | def EXE_NAME(cls): | |
85 | return cls.get_basename() | |
86 | ||
2762dbb1 | 87 | @functools.cached_property |
222516d9 | 88 | def exe(self): |
28787f16 | 89 | return self.EXE_NAME |
222516d9 | 90 | |
99cbe98c | 91 | @classmethod |
7f7de7f9 | 92 | def available(cls, path=None): |
28787f16 | 93 | path = check_executable( |
94 | cls.EXE_NAME if path in (None, cls.get_basename()) else path, | |
95 | [cls.AVAILABLE_OPT]) | |
96 | if not path: | |
97 | return False | |
98 | cls.exe = path | |
99 | return path | |
99cbe98c | 100 | |
222516d9 PH |
101 | @classmethod |
102 | def supports(cls, info_dict): | |
c487cf00 | 103 | return all(( |
104 | not info_dict.get('to_stdout') or Features.TO_STDOUT in cls.SUPPORTED_FEATURES, | |
105 | '+' not in info_dict['protocol'] or Features.MULTIPLE_FORMATS in cls.SUPPORTED_FEATURES, | |
7e68567e | 106 | not traverse_obj(info_dict, ('hls_aes', ...), 'extra_param_to_segment_url'), |
c487cf00 | 107 | all(proto in cls.SUPPORTED_PROTOCOLS for proto in info_dict['protocol'].split('+')), |
108 | )) | |
222516d9 | 109 | |
2cb99ebb | 110 | @classmethod |
7f7de7f9 | 111 | def can_download(cls, info_dict, path=None): |
112 | return cls.available(path) and cls.supports(info_dict) | |
2cb99ebb | 113 | |
bf812ef7 | 114 | def _option(self, command_option, param): |
1195a38f | 115 | return cli_option(self.params, command_option, param) |
bf812ef7 | 116 | |
266b0ad6 | 117 | def _bool_option(self, command_option, param, true_value='true', false_value='false', separator=None): |
1195a38f | 118 | return cli_bool_option(self.params, command_option, param, true_value, false_value, separator) |
266b0ad6 | 119 | |
dc534b67 | 120 | def _valueless_option(self, command_option, param, expected_value=True): |
1195a38f | 121 | return cli_valueless_option(self.params, command_option, param, expected_value) |
f30c2e8e | 122 | |
330690a2 | 123 | def _configuration_args(self, keys=None, *args, **kwargs): |
124 | return _configuration_args( | |
28787f16 | 125 | self.get_basename(), self.params.get('external_downloader_args'), self.EXE_NAME, |
330690a2 | 126 | keys, *args, **kwargs) |
c75f0b36 | 127 | |
222516d9 PH |
128 | def _call_downloader(self, tmpfilename, info_dict): |
129 | """ Either overwrite this or implement _make_cmd """ | |
74f8654a | 130 | cmd = [encodeArgument(a) for a in self._make_cmd(tmpfilename, info_dict)] |
222516d9 | 131 | |
74f8654a | 132 | self._debug_cmd(cmd) |
222516d9 | 133 | |
fc5c8b64 | 134 | if 'fragments' not in info_dict: |
8c53322c | 135 | _, stderr, returncode = self._call_process(cmd, info_dict) |
f0c9fb96 | 136 | if returncode and stderr: |
137 | self.to_stderr(stderr) | |
138 | return returncode | |
fc5c8b64 | 139 | |
fc5c8b64 | 140 | skip_unavailable_fragments = self.params.get('skip_unavailable_fragments', True) |
141 | ||
be5c1ae8 | 142 | retry_manager = RetryManager(self.params.get('fragment_retries'), self.report_retry, |
143 | frag_index=None, fatal=not skip_unavailable_fragments) | |
144 | for retry in retry_manager: | |
8c53322c | 145 | _, stderr, returncode = self._call_process(cmd, info_dict) |
f0c9fb96 | 146 | if not returncode: |
fc5c8b64 | 147 | break |
148 | # TODO: Decide whether to retry based on error code | |
149 | # https://aria2.github.io/manual/en/html/aria2c.html#exit-status | |
f0c9fb96 | 150 | if stderr: |
151 | self.to_stderr(stderr) | |
be5c1ae8 | 152 | retry.error = Exception() |
153 | continue | |
154 | if not skip_unavailable_fragments and retry_manager.error: | |
155 | return -1 | |
fc5c8b64 | 156 | |
157 | decrypt_fragment = self.decrypter(info_dict) | |
205a0654 | 158 | dest, _ = self.sanitize_open(tmpfilename, 'wb') |
fc5c8b64 | 159 | for frag_index, fragment in enumerate(info_dict['fragments']): |
160 | fragment_filename = '%s-Frag%d' % (tmpfilename, frag_index) | |
161 | try: | |
205a0654 | 162 | src, _ = self.sanitize_open(fragment_filename, 'rb') |
86e5f3ed | 163 | except OSError as err: |
fc5c8b64 | 164 | if skip_unavailable_fragments and frag_index > 1: |
b4b855eb | 165 | self.report_skip_fragment(frag_index, err) |
fc5c8b64 | 166 | continue |
b4b855eb | 167 | self.report_error(f'Unable to open fragment {frag_index}; {err}') |
fc5c8b64 | 168 | return -1 |
169 | dest.write(decrypt_fragment(fragment, src.read())) | |
170 | src.close() | |
171 | if not self.params.get('keep_fragments', False): | |
45806d44 | 172 | self.try_remove(encodeFilename(fragment_filename)) |
fc5c8b64 | 173 | dest.close() |
45806d44 | 174 | self.try_remove(encodeFilename('%s.frag.urls' % tmpfilename)) |
fc5c8b64 | 175 | return 0 |
222516d9 | 176 | |
8c53322c | 177 | def _call_process(self, cmd, info_dict): |
66aeaac9 | 178 | return Popen.run(cmd, text=True, stderr=subprocess.PIPE if self._CAPTURE_STDERR else None) |
8c53322c | 179 | |
222516d9 | 180 | |
384b6202 | 181 | class CurlFD(ExternalFD): |
91ee320b | 182 | AVAILABLE_OPT = '-V' |
f0c9fb96 | 183 | _CAPTURE_STDERR = False # curl writes the progress to stderr |
99cbe98c | 184 | |
384b6202 | 185 | def _make_cmd(self, tmpfilename, info_dict): |
af14914b | 186 | cmd = [self.exe, '--location', '-o', tmpfilename, '--compressed'] |
002ea8fe | 187 | if info_dict.get('http_headers') is not None: |
188 | for key, val in info_dict['http_headers'].items(): | |
86e5f3ed | 189 | cmd += ['--header', f'{key}: {val}'] |
002ea8fe | 190 | |
98e698f1 RA |
191 | cmd += self._bool_option('--continue-at', 'continuedl', '-', '0') |
192 | cmd += self._valueless_option('--silent', 'noprogress') | |
193 | cmd += self._valueless_option('--verbose', 'verbose') | |
194 | cmd += self._option('--limit-rate', 'ratelimit') | |
37b239b3 S |
195 | retry = self._option('--retry', 'retries') |
196 | if len(retry) == 2: | |
197 | if retry[1] in ('inf', 'infinite'): | |
198 | retry[1] = '2147483647' | |
199 | cmd += retry | |
98e698f1 | 200 | cmd += self._option('--max-filesize', 'max_filesize') |
9f3da138 | 201 | cmd += self._option('--interface', 'source_address') |
e7a8c303 | 202 | cmd += self._option('--proxy', 'proxy') |
dc534b67 | 203 | cmd += self._valueless_option('--insecure', 'nocheckcertificate') |
c75f0b36 | 204 | cmd += self._configuration_args() |
384b6202 PH |
205 | cmd += ['--', info_dict['url']] |
206 | return cmd | |
207 | ||
208 | ||
e0ac5214 | 209 | class AxelFD(ExternalFD): |
91ee320b | 210 | AVAILABLE_OPT = '-V' |
99cbe98c | 211 | |
e0ac5214 | 212 | def _make_cmd(self, tmpfilename, info_dict): |
213 | cmd = [self.exe, '-o', tmpfilename] | |
002ea8fe | 214 | if info_dict.get('http_headers') is not None: |
215 | for key, val in info_dict['http_headers'].items(): | |
86e5f3ed | 216 | cmd += ['-H', f'{key}: {val}'] |
e0ac5214 | 217 | cmd += self._configuration_args() |
218 | cmd += ['--', info_dict['url']] | |
219 | return cmd | |
220 | ||
221 | ||
222516d9 | 222 | class WgetFD(ExternalFD): |
91ee320b | 223 | AVAILABLE_OPT = '--version' |
99cbe98c | 224 | |
222516d9 | 225 | def _make_cmd(self, tmpfilename, info_dict): |
af14914b | 226 | cmd = [self.exe, '-O', tmpfilename, '-nv', '--no-cookies', '--compression=auto'] |
002ea8fe | 227 | if info_dict.get('http_headers') is not None: |
228 | for key, val in info_dict['http_headers'].items(): | |
86e5f3ed | 229 | cmd += ['--header', f'{key}: {val}'] |
8c80603f S |
230 | cmd += self._option('--limit-rate', 'ratelimit') |
231 | retry = self._option('--tries', 'retries') | |
232 | if len(retry) == 2: | |
233 | if retry[1] in ('inf', 'infinite'): | |
234 | retry[1] = '0' | |
235 | cmd += retry | |
9f3da138 | 236 | cmd += self._option('--bind-address', 'source_address') |
8a23db95 | 237 | proxy = self.params.get('proxy') |
238 | if proxy: | |
239 | for var in ('http_proxy', 'https_proxy'): | |
86e5f3ed | 240 | cmd += ['--execute', f'{var}={proxy}'] |
dc534b67 | 241 | cmd += self._valueless_option('--no-check-certificate', 'nocheckcertificate') |
c75f0b36 | 242 | cmd += self._configuration_args() |
222516d9 PH |
243 | cmd += ['--', info_dict['url']] |
244 | return cmd | |
245 | ||
246 | ||
384b6202 | 247 | class Aria2cFD(ExternalFD): |
91ee320b | 248 | AVAILABLE_OPT = '-v' |
52a8a1e1 | 249 | SUPPORTED_PROTOCOLS = ('http', 'https', 'ftp', 'ftps', 'dash_frag_urls', 'm3u8_frag_urls') |
99cbe98c | 250 | |
0a473f2f | 251 | @staticmethod |
252 | def supports_manifest(manifest): | |
253 | UNSUPPORTED_FEATURES = [ | |
254 | r'#EXT-X-BYTERANGE', # playlists composed of byte ranges of media files [1] | |
255 | # 1. https://tools.ietf.org/html/draft-pantos-http-live-streaming-17#section-4.3.2.2 | |
256 | ] | |
257 | check_results = (not re.search(feature, manifest) for feature in UNSUPPORTED_FEATURES) | |
258 | return all(check_results) | |
259 | ||
af7a5eef | 260 | @staticmethod |
261 | def _aria2c_filename(fn): | |
262 | return fn if os.path.isabs(fn) else f'.{os.path.sep}{fn}' | |
263 | ||
8c53322c | 264 | def _call_downloader(self, tmpfilename, info_dict): |
ad68b16a | 265 | # FIXME: Disabled due to https://github.com/yt-dlp/yt-dlp/issues/5931 |
266 | if False and 'no-external-downloader-progress' not in self.params.get('compat_opts', []): | |
8c53322c L |
267 | info_dict['__rpc'] = { |
268 | 'port': find_available_port() or 19190, | |
269 | 'secret': str(uuid.uuid4()), | |
270 | } | |
271 | return super()._call_downloader(tmpfilename, info_dict) | |
272 | ||
384b6202 | 273 | def _make_cmd(self, tmpfilename, info_dict): |
2b3bf01c | 274 | cmd = [self.exe, '-c', |
275 | '--console-log-level=warn', '--summary-interval=0', '--download-result=hide', | |
dcd55f76 | 276 | '--http-accept-gzip=true', '--file-allocation=none', '-x16', '-j16', '-s16'] |
2b3bf01c | 277 | if 'fragments' in info_dict: |
278 | cmd += ['--allow-overwrite=true', '--allow-piece-length-change=true'] | |
ff0f78e1 | 279 | else: |
280 | cmd += ['--min-split-size', '1M'] | |
2b3bf01c | 281 | |
002ea8fe | 282 | if info_dict.get('http_headers') is not None: |
283 | for key, val in info_dict['http_headers'].items(): | |
86e5f3ed | 284 | cmd += ['--header', f'{key}: {val}'] |
691d5823 | 285 | cmd += self._option('--max-overall-download-limit', 'ratelimit') |
9f3da138 | 286 | cmd += self._option('--interface', 'source_address') |
bf812ef7 | 287 | cmd += self._option('--all-proxy', 'proxy') |
266b0ad6 | 288 | cmd += self._bool_option('--check-certificate', 'nocheckcertificate', 'false', 'true', '=') |
71f47617 | 289 | cmd += self._bool_option('--remote-time', 'updatetime', 'true', 'false', '=') |
f44afb54 | 290 | cmd += self._bool_option('--show-console-readout', 'noprogress', 'false', 'true', '=') |
2b3bf01c | 291 | cmd += self._configuration_args() |
292 | ||
8c53322c L |
293 | if '__rpc' in info_dict: |
294 | cmd += [ | |
295 | '--enable-rpc', | |
296 | f'--rpc-listen-port={info_dict["__rpc"]["port"]}', | |
297 | f'--rpc-secret={info_dict["__rpc"]["secret"]}'] | |
298 | ||
eb55bad5 | 299 | # aria2c strips out spaces from the beginning/end of filenames and paths. |
300 | # We work around this issue by adding a "./" to the beginning of the | |
301 | # filename and relative path, and adding a "/" at the end of the path. | |
302 | # See: https://github.com/yt-dlp/yt-dlp/issues/276 | |
303 | # https://github.com/ytdl-org/youtube-dl/issues/20312 | |
304 | # https://github.com/aria2/aria2/issues/1373 | |
2b3bf01c | 305 | dn = os.path.dirname(tmpfilename) |
306 | if dn: | |
af7a5eef | 307 | cmd += ['--dir', self._aria2c_filename(dn) + os.path.sep] |
2b3bf01c | 308 | if 'fragments' not in info_dict: |
af7a5eef | 309 | cmd += ['--out', self._aria2c_filename(os.path.basename(tmpfilename))] |
5219cb3e | 310 | cmd += ['--auto-file-renaming=false'] |
2b3bf01c | 311 | |
d7009caa | 312 | if 'fragments' in info_dict: |
fe845284 | 313 | cmd += ['--file-allocation=none', '--uri-selector=inorder'] |
5219cb3e | 314 | url_list_file = '%s.frag.urls' % tmpfilename |
315 | url_list = [] | |
fe845284 | 316 | for frag_index, fragment in enumerate(info_dict['fragments']): |
317 | fragment_filename = '%s-Frag%d' % (os.path.basename(tmpfilename), frag_index) | |
af7a5eef | 318 | url_list.append('%s\n\tout=%s' % (fragment['url'], self._aria2c_filename(fragment_filename))) |
205a0654 | 319 | stream, _ = self.sanitize_open(url_list_file, 'wb') |
0f06bcd7 | 320 | stream.write('\n'.join(url_list).encode()) |
539d158c | 321 | stream.close() |
af7a5eef | 322 | cmd += ['-i', self._aria2c_filename(url_list_file)] |
5219cb3e | 323 | else: |
324 | cmd += ['--', info_dict['url']] | |
384b6202 PH |
325 | return cmd |
326 | ||
8c53322c L |
327 | def aria2c_rpc(self, rpc_port, rpc_secret, method, params=()): |
328 | # Does not actually need to be UUID, just unique | |
329 | sanitycheck = str(uuid.uuid4()) | |
330 | d = json.dumps({ | |
331 | 'jsonrpc': '2.0', | |
332 | 'id': sanitycheck, | |
333 | 'method': method, | |
334 | 'params': [f'token:{rpc_secret}', *params], | |
335 | }).encode('utf-8') | |
336 | request = sanitized_Request( | |
337 | f'http://localhost:{rpc_port}/jsonrpc', | |
338 | data=d, headers={ | |
339 | 'Content-Type': 'application/json', | |
340 | 'Content-Length': f'{len(d)}', | |
341 | 'Ytdl-request-proxy': '__noproxy__', | |
342 | }) | |
343 | with self.ydl.urlopen(request) as r: | |
344 | resp = json.load(r) | |
345 | assert resp.get('id') == sanitycheck, 'Something went wrong with RPC server' | |
346 | return resp['result'] | |
347 | ||
348 | def _call_process(self, cmd, info_dict): | |
349 | if '__rpc' not in info_dict: | |
350 | return super()._call_process(cmd, info_dict) | |
351 | ||
352 | send_rpc = functools.partial(self.aria2c_rpc, info_dict['__rpc']['port'], info_dict['__rpc']['secret']) | |
353 | started = time.time() | |
354 | ||
355 | fragmented = 'fragments' in info_dict | |
356 | frag_count = len(info_dict['fragments']) if fragmented else 1 | |
357 | status = { | |
358 | 'filename': info_dict.get('_filename'), | |
359 | 'status': 'downloading', | |
360 | 'elapsed': 0, | |
361 | 'downloaded_bytes': 0, | |
362 | 'fragment_count': frag_count if fragmented else None, | |
363 | 'fragment_index': 0 if fragmented else None, | |
364 | } | |
365 | self._hook_progress(status, info_dict) | |
366 | ||
367 | def get_stat(key, *obj, average=False): | |
368 | val = tuple(filter(None, map(float, traverse_obj(obj, (..., ..., key))))) or [0] | |
369 | return sum(val) / (len(val) if average else 1) | |
370 | ||
371 | with Popen(cmd, text=True, stdout=subprocess.DEVNULL, stderr=subprocess.PIPE) as p: | |
372 | # Add a small sleep so that RPC client can receive response, | |
373 | # or the connection stalls infinitely | |
374 | time.sleep(0.2) | |
375 | retval = p.poll() | |
376 | while retval is None: | |
377 | # We don't use tellStatus as we won't know the GID without reading stdout | |
378 | # Ref: https://aria2.github.io/manual/en/html/aria2c.html#aria2.tellActive | |
379 | active = send_rpc('aria2.tellActive') | |
380 | completed = send_rpc('aria2.tellStopped', [0, frag_count]) | |
381 | ||
382 | downloaded = get_stat('totalLength', completed) + get_stat('completedLength', active) | |
383 | speed = get_stat('downloadSpeed', active) | |
384 | total = frag_count * get_stat('totalLength', active, completed, average=True) | |
385 | if total < downloaded: | |
386 | total = None | |
387 | ||
388 | status.update({ | |
389 | 'downloaded_bytes': int(downloaded), | |
390 | 'speed': speed, | |
391 | 'total_bytes': None if fragmented else total, | |
392 | 'total_bytes_estimate': total, | |
393 | 'eta': (total - downloaded) / (speed or 1), | |
394 | 'fragment_index': min(frag_count, len(completed) + 1) if fragmented else None, | |
395 | 'elapsed': time.time() - started | |
396 | }) | |
397 | self._hook_progress(status, info_dict) | |
398 | ||
399 | if not active and len(completed) >= frag_count: | |
400 | send_rpc('aria2.shutdown') | |
401 | retval = p.wait() | |
402 | break | |
403 | ||
404 | time.sleep(0.1) | |
405 | retval = p.poll() | |
406 | ||
407 | return '', p.stderr.read(), retval | |
408 | ||
906e2f0e JMF |
409 | |
410 | class HttpieFD(ExternalFD): | |
52a8a1e1 | 411 | AVAILABLE_OPT = '--version' |
28787f16 | 412 | EXE_NAME = 'http' |
99cbe98c | 413 | |
906e2f0e JMF |
414 | def _make_cmd(self, tmpfilename, info_dict): |
415 | cmd = ['http', '--download', '--output', tmpfilename, info_dict['url']] | |
002ea8fe | 416 | |
417 | if info_dict.get('http_headers') is not None: | |
418 | for key, val in info_dict['http_headers'].items(): | |
86e5f3ed | 419 | cmd += [f'{key}:{val}'] |
906e2f0e JMF |
420 | return cmd |
421 | ||
12b84ac8 | 422 | |
423 | class FFmpegFD(ExternalFD): | |
6251555f | 424 | SUPPORTED_PROTOCOLS = ('http', 'https', 'ftp', 'ftps', 'm3u8', 'm3u8_native', 'rtsp', 'rtmp', 'rtmp_ffmpeg', 'mms', 'http_dash_segments') |
c487cf00 | 425 | SUPPORTED_FEATURES = (Features.TO_STDOUT, Features.MULTIPLE_FORMATS) |
12b84ac8 | 426 | |
99cbe98c | 427 | @classmethod |
52a8a1e1 | 428 | def available(cls, path=None): |
429 | # TODO: Fix path for ffmpeg | |
dbf5416a | 430 | # Fixme: This may be wrong when --ffmpeg-location is used |
99cbe98c | 431 | return FFmpegPostProcessor().available |
432 | ||
e36d50c5 | 433 | def on_process_started(self, proc, stdin): |
434 | """ Override this in subclasses """ | |
435 | pass | |
436 | ||
dbf5416a | 437 | @classmethod |
d5fe04f5 | 438 | def can_merge_formats(cls, info_dict, params): |
dbf5416a | 439 | return ( |
440 | info_dict.get('requested_formats') | |
441 | and info_dict.get('protocol') | |
442 | and not params.get('allow_unplayable_formats') | |
443 | and 'no-direct-merge' not in params.get('compat_opts', []) | |
444 | and cls.can_download(info_dict)) | |
445 | ||
12b84ac8 | 446 | def _call_downloader(self, tmpfilename, info_dict): |
12b84ac8 | 447 | ffpp = FFmpegPostProcessor(downloader=self) |
77dea16a | 448 | if not ffpp.available: |
e3b771a8 | 449 | self.report_error('m3u8 download detected but ffmpeg could not be found. Please install') |
77dea16a | 450 | return False |
12b84ac8 | 451 | ffpp.check_version() |
452 | ||
453 | args = [ffpp.executable, '-y'] | |
454 | ||
a609e61a S |
455 | for log_level in ('quiet', 'verbose'): |
456 | if self.params.get(log_level, False): | |
457 | args += ['-loglevel', log_level] | |
458 | break | |
2ec1759f | 459 | if not self.params.get('verbose'): |
460 | args += ['-hide_banner'] | |
a609e61a | 461 | |
0a5a191a | 462 | args += traverse_obj(info_dict, ('downloader_options', 'ffmpeg_args'), default=[]) |
bb36a55c | 463 | |
0a5a191a | 464 | # These exists only for compatibility. Extractors should use |
465 | # info_dict['downloader_options']['ffmpeg_args'] instead | |
1d485a1a | 466 | args += info_dict.get('_ffmpeg_args') or [] |
36fce548 RA |
467 | seekable = info_dict.get('_seekable') |
468 | if seekable is not None: | |
469 | # setting -seekable prevents ffmpeg from guessing if the server | |
470 | # supports seeking(by adding the header `Range: bytes=0-`), which | |
471 | # can cause problems in some cases | |
067aa17e | 472 | # https://github.com/ytdl-org/youtube-dl/issues/11800#issuecomment-275037127 |
36fce548 RA |
473 | # http://trac.ffmpeg.org/ticket/6125#comment:10 |
474 | args += ['-seekable', '1' if seekable else '0'] | |
475 | ||
e62d9c5c S |
476 | env = None |
477 | proxy = self.params.get('proxy') | |
478 | if proxy: | |
479 | if not re.match(r'^[\da-zA-Z]+://', proxy): | |
480 | proxy = 'http://%s' % proxy | |
20bad91d YCH |
481 | |
482 | if proxy.startswith('socks'): | |
483 | self.report_warning( | |
6c9b71bc YCH |
484 | '%s does not support SOCKS proxies. Downloading is likely to fail. ' |
485 | 'Consider adding --hls-prefer-native to your command.' % self.get_basename()) | |
20bad91d | 486 | |
e62d9c5c S |
487 | # Since December 2015 ffmpeg supports -http_proxy option (see |
488 | # http://git.videolan.org/?p=ffmpeg.git;a=commit;h=b4eb1f29ebddd60c41a2eb39f5af701e38e0d3fd) | |
489 | # We could switch to the following code if we are able to detect version properly | |
490 | # args += ['-http_proxy', proxy] | |
491 | env = os.environ.copy() | |
ac668111 | 492 | env['HTTP_PROXY'] = proxy |
493 | env['http_proxy'] = proxy | |
e62d9c5c | 494 | |
4230c489 | 495 | protocol = info_dict.get('protocol') |
496 | ||
497 | if protocol == 'rtmp': | |
498 | player_url = info_dict.get('player_url') | |
499 | page_url = info_dict.get('page_url') | |
500 | app = info_dict.get('app') | |
501 | play_path = info_dict.get('play_path') | |
502 | tc_url = info_dict.get('tc_url') | |
503 | flash_version = info_dict.get('flash_version') | |
504 | live = info_dict.get('rtmp_live', False) | |
d7d86fdd | 505 | conn = info_dict.get('rtmp_conn') |
4230c489 | 506 | if player_url is not None: |
507 | args += ['-rtmp_swfverify', player_url] | |
508 | if page_url is not None: | |
509 | args += ['-rtmp_pageurl', page_url] | |
510 | if app is not None: | |
511 | args += ['-rtmp_app', app] | |
512 | if play_path is not None: | |
513 | args += ['-rtmp_playpath', play_path] | |
514 | if tc_url is not None: | |
515 | args += ['-rtmp_tcurl', tc_url] | |
516 | if flash_version is not None: | |
517 | args += ['-rtmp_flashver', flash_version] | |
518 | if live: | |
519 | args += ['-rtmp_live', 'live'] | |
d7d86fdd RA |
520 | if isinstance(conn, list): |
521 | for entry in conn: | |
522 | args += ['-rtmp_conn', entry] | |
c487cf00 | 523 | elif isinstance(conn, str): |
d7d86fdd | 524 | args += ['-rtmp_conn', conn] |
4230c489 | 525 | |
5ec1b6b7 | 526 | start_time, end_time = info_dict.get('section_start') or 0, info_dict.get('section_end') |
527 | ||
3cf50fa8 | 528 | selected_formats = info_dict.get('requested_formats') or [info_dict] |
529 | for i, fmt in enumerate(selected_formats): | |
530 | if fmt.get('http_headers') and re.match(r'^https?://', fmt['url']): | |
3cf50fa8 | 531 | # Trailing \r\n after each HTTP header is important to prevent warning from ffmpeg/avconv: |
532 | # [http @ 00000000003d2fa0] No trailing CRLF found in HTTP header. | |
955c8958 | 533 | args.extend(['-headers', ''.join(f'{key}: {val}\r\n' for key, val in fmt['http_headers'].items())]) |
3cf50fa8 | 534 | |
5ec1b6b7 | 535 | if start_time: |
536 | args += ['-ss', str(start_time)] | |
537 | if end_time: | |
538 | args += ['-t', str(end_time - start_time)] | |
539 | ||
3cf50fa8 | 540 | args += self._configuration_args((f'_i{i + 1}', '_i')) + ['-i', fmt['url']] |
6b6c16ca | 541 | |
5ec1b6b7 | 542 | if not (start_time or end_time) or not self.params.get('force_keyframes_at_cuts'): |
543 | args += ['-c', 'copy'] | |
544 | ||
6251555f | 545 | if info_dict.get('requested_formats') or protocol == 'http_dash_segments': |
3cf50fa8 | 546 | for i, fmt in enumerate(selected_formats): |
6251555f | 547 | stream_number = fmt.get('manifest_stream_number', 0) |
234416e4 | 548 | args.extend(['-map', f'{i}:{stream_number}']) |
6d0fe752 JH |
549 | |
550 | if self.params.get('test', False): | |
c487cf00 | 551 | args += ['-fs', str(self._TEST_FILE_SIZE)] |
6d0fe752 | 552 | |
e5611e8e | 553 | ext = info_dict['ext'] |
f5436c5d | 554 | if protocol in ('m3u8', 'm3u8_native'): |
9bd20204 | 555 | use_mpegts = (tmpfilename == '-') or self.params.get('hls_use_mpegts') |
556 | if use_mpegts is None: | |
557 | use_mpegts = info_dict.get('is_live') | |
558 | if use_mpegts: | |
12b84ac8 | 559 | args += ['-f', 'mpegts'] |
560 | else: | |
8bdc1494 | 561 | args += ['-f', 'mp4'] |
8913ef74 | 562 | if (ffpp.basename == 'ffmpeg' and ffpp._features.get('needs_adtstoasc')) and (not info_dict.get('acodec') or info_dict['acodec'].split('.')[0] in ('aac', 'mp4a')): |
8bdc1494 | 563 | args += ['-bsf:a', 'aac_adtstoasc'] |
4230c489 | 564 | elif protocol == 'rtmp': |
565 | args += ['-f', 'flv'] | |
e5611e8e | 566 | elif ext == 'mp4' and tmpfilename == '-': |
567 | args += ['-f', 'mpegts'] | |
af6793f8 | 568 | elif ext == 'unknown_video': |
569 | ext = determine_ext(remove_end(tmpfilename, '.part')) | |
570 | if ext == 'unknown_video': | |
571 | self.report_warning( | |
572 | 'The video format is unknown and cannot be downloaded by ffmpeg. ' | |
573 | 'Explicitly set the extension in the filename to attempt download in that format') | |
574 | else: | |
575 | self.report_warning(f'The video format is unknown. Trying to download as {ext} according to the filename') | |
576 | args += ['-f', EXT_TO_OUT_FORMATS.get(ext, ext)] | |
12b84ac8 | 577 | else: |
e5611e8e | 578 | args += ['-f', EXT_TO_OUT_FORMATS.get(ext, ext)] |
12b84ac8 | 579 | |
6251555f | 580 | args += self._configuration_args(('_o1', '_o', '')) |
330690a2 | 581 | |
12b84ac8 | 582 | args = [encodeArgument(opt) for opt in args] |
d868f43c | 583 | args.append(encodeFilename(ffpp._ffmpeg_filename_argument(tmpfilename), True)) |
12b84ac8 | 584 | self._debug_cmd(args) |
585 | ||
3cf50fa8 | 586 | piped = any(fmt['url'] in ('-', 'pipe:') for fmt in selected_formats) |
f0c9fb96 | 587 | with Popen(args, stdin=subprocess.PIPE, env=env) as proc: |
3cf50fa8 | 588 | if piped: |
f0c9fb96 | 589 | self.on_process_started(proc, proc.stdin) |
590 | try: | |
591 | retval = proc.wait() | |
592 | except BaseException as e: | |
593 | # subprocces.run would send the SIGKILL signal to ffmpeg and the | |
594 | # mp4 file couldn't be played, but if we ask ffmpeg to quit it | |
595 | # produces a file that is playable (this is mostly useful for live | |
596 | # streams). Note that Windows is not affected and produces playable | |
597 | # files (see https://github.com/ytdl-org/youtube-dl/issues/8300). | |
3cf50fa8 | 598 | if isinstance(e, KeyboardInterrupt) and sys.platform != 'win32' and not piped: |
f0c9fb96 | 599 | proc.communicate_or_kill(b'q') |
600 | else: | |
601 | proc.kill(timeout=None) | |
602 | raise | |
603 | return retval | |
12b84ac8 | 604 | |
605 | ||
606 | class AVconvFD(FFmpegFD): | |
607 | pass | |
608 | ||
582be358 | 609 | |
28787f16 | 610 | _BY_NAME = { |
611 | klass.get_basename(): klass | |
222516d9 | 612 | for name, klass in globals().items() |
1009f67c | 613 | if name.endswith('FD') and name not in ('ExternalFD', 'FragmentFD') |
28787f16 | 614 | } |
615 | ||
222516d9 PH |
616 | |
617 | def list_external_downloaders(): | |
618 | return sorted(_BY_NAME.keys()) | |
619 | ||
620 | ||
621 | def get_external_downloader(external_downloader): | |
e1eabd7b | 622 | """ Given the name of the executable, see whether we support the given downloader """ |
6c4d20cd | 623 | bn = os.path.splitext(os.path.basename(external_downloader))[0] |
e1eabd7b | 624 | return _BY_NAME.get(bn) or next(( |
625 | klass for klass in _BY_NAME.values() if klass.EXE_NAME in bn | |
626 | ), None) |