]>
Commit | Line | Data |
---|---|---|
1 | import enum | |
2 | import json | |
3 | import os.path | |
4 | import re | |
5 | import subprocess | |
6 | import sys | |
7 | import time | |
8 | import uuid | |
9 | ||
10 | from .fragment import FragmentFD | |
11 | from ..compat import functools | |
12 | from ..postprocessor.ffmpeg import EXT_TO_OUT_FORMATS, FFmpegPostProcessor | |
13 | from ..utils import ( | |
14 | Popen, | |
15 | RetryManager, | |
16 | _configuration_args, | |
17 | check_executable, | |
18 | classproperty, | |
19 | cli_bool_option, | |
20 | cli_option, | |
21 | cli_valueless_option, | |
22 | determine_ext, | |
23 | encodeArgument, | |
24 | encodeFilename, | |
25 | find_available_port, | |
26 | handle_youtubedl_headers, | |
27 | remove_end, | |
28 | sanitized_Request, | |
29 | traverse_obj, | |
30 | ) | |
31 | ||
32 | ||
33 | class Features(enum.Enum): | |
34 | TO_STDOUT = enum.auto() | |
35 | MULTIPLE_FORMATS = enum.auto() | |
36 | ||
37 | ||
38 | class ExternalFD(FragmentFD): | |
39 | SUPPORTED_PROTOCOLS = ('http', 'https', 'ftp', 'ftps') | |
40 | SUPPORTED_FEATURES = () | |
41 | _CAPTURE_STDERR = True | |
42 | ||
43 | def real_download(self, filename, info_dict): | |
44 | self.report_destination(filename) | |
45 | tmpfilename = self.temp_name(filename) | |
46 | ||
47 | try: | |
48 | started = time.time() | |
49 | retval = self._call_downloader(tmpfilename, info_dict) | |
50 | except KeyboardInterrupt: | |
51 | if not info_dict.get('is_live'): | |
52 | raise | |
53 | # Live stream downloading cancellation should be considered as | |
54 | # correct and expected termination thus all postprocessing | |
55 | # should take place | |
56 | retval = 0 | |
57 | self.to_screen('[%s] Interrupted by user' % self.get_basename()) | |
58 | ||
59 | if retval == 0: | |
60 | status = { | |
61 | 'filename': filename, | |
62 | 'status': 'finished', | |
63 | 'elapsed': time.time() - started, | |
64 | } | |
65 | if filename != '-': | |
66 | fsize = os.path.getsize(encodeFilename(tmpfilename)) | |
67 | self.try_rename(tmpfilename, filename) | |
68 | status.update({ | |
69 | 'downloaded_bytes': fsize, | |
70 | 'total_bytes': fsize, | |
71 | }) | |
72 | self._hook_progress(status, info_dict) | |
73 | return True | |
74 | else: | |
75 | self.to_stderr('\n') | |
76 | self.report_error('%s exited with code %d' % ( | |
77 | self.get_basename(), retval)) | |
78 | return False | |
79 | ||
80 | @classmethod | |
81 | def get_basename(cls): | |
82 | return cls.__name__[:-2].lower() | |
83 | ||
84 | @classproperty | |
85 | def EXE_NAME(cls): | |
86 | return cls.get_basename() | |
87 | ||
88 | @functools.cached_property | |
89 | def exe(self): | |
90 | return self.EXE_NAME | |
91 | ||
92 | @classmethod | |
93 | def available(cls, path=None): | |
94 | path = check_executable( | |
95 | cls.EXE_NAME if path in (None, cls.get_basename()) else path, | |
96 | [cls.AVAILABLE_OPT]) | |
97 | if not path: | |
98 | return False | |
99 | cls.exe = path | |
100 | return path | |
101 | ||
102 | @classmethod | |
103 | def supports(cls, info_dict): | |
104 | return all(( | |
105 | not info_dict.get('to_stdout') or Features.TO_STDOUT in cls.SUPPORTED_FEATURES, | |
106 | '+' not in info_dict['protocol'] or Features.MULTIPLE_FORMATS in cls.SUPPORTED_FEATURES, | |
107 | all(proto in cls.SUPPORTED_PROTOCOLS for proto in info_dict['protocol'].split('+')), | |
108 | )) | |
109 | ||
110 | @classmethod | |
111 | def can_download(cls, info_dict, path=None): | |
112 | return cls.available(path) and cls.supports(info_dict) | |
113 | ||
114 | def _option(self, command_option, param): | |
115 | return cli_option(self.params, command_option, param) | |
116 | ||
117 | def _bool_option(self, command_option, param, true_value='true', false_value='false', separator=None): | |
118 | return cli_bool_option(self.params, command_option, param, true_value, false_value, separator) | |
119 | ||
120 | def _valueless_option(self, command_option, param, expected_value=True): | |
121 | return cli_valueless_option(self.params, command_option, param, expected_value) | |
122 | ||
123 | def _configuration_args(self, keys=None, *args, **kwargs): | |
124 | return _configuration_args( | |
125 | self.get_basename(), self.params.get('external_downloader_args'), self.EXE_NAME, | |
126 | keys, *args, **kwargs) | |
127 | ||
128 | def _call_downloader(self, tmpfilename, info_dict): | |
129 | """ Either overwrite this or implement _make_cmd """ | |
130 | cmd = [encodeArgument(a) for a in self._make_cmd(tmpfilename, info_dict)] | |
131 | ||
132 | self._debug_cmd(cmd) | |
133 | ||
134 | if 'fragments' not in info_dict: | |
135 | _, stderr, returncode = self._call_process(cmd, info_dict) | |
136 | if returncode and stderr: | |
137 | self.to_stderr(stderr) | |
138 | return returncode | |
139 | ||
140 | skip_unavailable_fragments = self.params.get('skip_unavailable_fragments', True) | |
141 | ||
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: | |
145 | _, stderr, returncode = self._call_process(cmd, info_dict) | |
146 | if not returncode: | |
147 | break | |
148 | # TODO: Decide whether to retry based on error code | |
149 | # https://aria2.github.io/manual/en/html/aria2c.html#exit-status | |
150 | if stderr: | |
151 | self.to_stderr(stderr) | |
152 | retry.error = Exception() | |
153 | continue | |
154 | if not skip_unavailable_fragments and retry_manager.error: | |
155 | return -1 | |
156 | ||
157 | decrypt_fragment = self.decrypter(info_dict) | |
158 | dest, _ = self.sanitize_open(tmpfilename, 'wb') | |
159 | for frag_index, fragment in enumerate(info_dict['fragments']): | |
160 | fragment_filename = '%s-Frag%d' % (tmpfilename, frag_index) | |
161 | try: | |
162 | src, _ = self.sanitize_open(fragment_filename, 'rb') | |
163 | except OSError as err: | |
164 | if skip_unavailable_fragments and frag_index > 1: | |
165 | self.report_skip_fragment(frag_index, err) | |
166 | continue | |
167 | self.report_error(f'Unable to open fragment {frag_index}; {err}') | |
168 | return -1 | |
169 | dest.write(decrypt_fragment(fragment, src.read())) | |
170 | src.close() | |
171 | if not self.params.get('keep_fragments', False): | |
172 | self.try_remove(encodeFilename(fragment_filename)) | |
173 | dest.close() | |
174 | self.try_remove(encodeFilename('%s.frag.urls' % tmpfilename)) | |
175 | return 0 | |
176 | ||
177 | def _call_process(self, cmd, info_dict): | |
178 | return Popen.run(cmd, text=True, stderr=subprocess.PIPE) | |
179 | ||
180 | ||
181 | class CurlFD(ExternalFD): | |
182 | AVAILABLE_OPT = '-V' | |
183 | _CAPTURE_STDERR = False # curl writes the progress to stderr | |
184 | ||
185 | def _make_cmd(self, tmpfilename, info_dict): | |
186 | cmd = [self.exe, '--location', '-o', tmpfilename, '--compressed'] | |
187 | if info_dict.get('http_headers') is not None: | |
188 | for key, val in info_dict['http_headers'].items(): | |
189 | cmd += ['--header', f'{key}: {val}'] | |
190 | ||
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') | |
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 | |
200 | cmd += self._option('--max-filesize', 'max_filesize') | |
201 | cmd += self._option('--interface', 'source_address') | |
202 | cmd += self._option('--proxy', 'proxy') | |
203 | cmd += self._valueless_option('--insecure', 'nocheckcertificate') | |
204 | cmd += self._configuration_args() | |
205 | cmd += ['--', info_dict['url']] | |
206 | return cmd | |
207 | ||
208 | ||
209 | class AxelFD(ExternalFD): | |
210 | AVAILABLE_OPT = '-V' | |
211 | ||
212 | def _make_cmd(self, tmpfilename, info_dict): | |
213 | cmd = [self.exe, '-o', tmpfilename] | |
214 | if info_dict.get('http_headers') is not None: | |
215 | for key, val in info_dict['http_headers'].items(): | |
216 | cmd += ['-H', f'{key}: {val}'] | |
217 | cmd += self._configuration_args() | |
218 | cmd += ['--', info_dict['url']] | |
219 | return cmd | |
220 | ||
221 | ||
222 | class WgetFD(ExternalFD): | |
223 | AVAILABLE_OPT = '--version' | |
224 | ||
225 | def _make_cmd(self, tmpfilename, info_dict): | |
226 | cmd = [self.exe, '-O', tmpfilename, '-nv', '--no-cookies', '--compression=auto'] | |
227 | if info_dict.get('http_headers') is not None: | |
228 | for key, val in info_dict['http_headers'].items(): | |
229 | cmd += ['--header', f'{key}: {val}'] | |
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 | |
236 | cmd += self._option('--bind-address', 'source_address') | |
237 | proxy = self.params.get('proxy') | |
238 | if proxy: | |
239 | for var in ('http_proxy', 'https_proxy'): | |
240 | cmd += ['--execute', f'{var}={proxy}'] | |
241 | cmd += self._valueless_option('--no-check-certificate', 'nocheckcertificate') | |
242 | cmd += self._configuration_args() | |
243 | cmd += ['--', info_dict['url']] | |
244 | return cmd | |
245 | ||
246 | ||
247 | class Aria2cFD(ExternalFD): | |
248 | AVAILABLE_OPT = '-v' | |
249 | SUPPORTED_PROTOCOLS = ('http', 'https', 'ftp', 'ftps', 'dash_frag_urls', 'm3u8_frag_urls') | |
250 | ||
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 | ||
260 | @staticmethod | |
261 | def _aria2c_filename(fn): | |
262 | return fn if os.path.isabs(fn) else f'.{os.path.sep}{fn}' | |
263 | ||
264 | def _call_downloader(self, tmpfilename, info_dict): | |
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', []): | |
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 | ||
273 | def _make_cmd(self, tmpfilename, info_dict): | |
274 | cmd = [self.exe, '-c', | |
275 | '--console-log-level=warn', '--summary-interval=0', '--download-result=hide', | |
276 | '--http-accept-gzip=true', '--file-allocation=none', '-x16', '-j16', '-s16'] | |
277 | if 'fragments' in info_dict: | |
278 | cmd += ['--allow-overwrite=true', '--allow-piece-length-change=true'] | |
279 | else: | |
280 | cmd += ['--min-split-size', '1M'] | |
281 | ||
282 | if info_dict.get('http_headers') is not None: | |
283 | for key, val in info_dict['http_headers'].items(): | |
284 | cmd += ['--header', f'{key}: {val}'] | |
285 | cmd += self._option('--max-overall-download-limit', 'ratelimit') | |
286 | cmd += self._option('--interface', 'source_address') | |
287 | cmd += self._option('--all-proxy', 'proxy') | |
288 | cmd += self._bool_option('--check-certificate', 'nocheckcertificate', 'false', 'true', '=') | |
289 | cmd += self._bool_option('--remote-time', 'updatetime', 'true', 'false', '=') | |
290 | cmd += self._bool_option('--show-console-readout', 'noprogress', 'false', 'true', '=') | |
291 | cmd += self._configuration_args() | |
292 | ||
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 | ||
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 | |
305 | dn = os.path.dirname(tmpfilename) | |
306 | if dn: | |
307 | cmd += ['--dir', self._aria2c_filename(dn) + os.path.sep] | |
308 | if 'fragments' not in info_dict: | |
309 | cmd += ['--out', self._aria2c_filename(os.path.basename(tmpfilename))] | |
310 | cmd += ['--auto-file-renaming=false'] | |
311 | ||
312 | if 'fragments' in info_dict: | |
313 | cmd += ['--file-allocation=none', '--uri-selector=inorder'] | |
314 | url_list_file = '%s.frag.urls' % tmpfilename | |
315 | url_list = [] | |
316 | for frag_index, fragment in enumerate(info_dict['fragments']): | |
317 | fragment_filename = '%s-Frag%d' % (os.path.basename(tmpfilename), frag_index) | |
318 | url_list.append('%s\n\tout=%s' % (fragment['url'], self._aria2c_filename(fragment_filename))) | |
319 | stream, _ = self.sanitize_open(url_list_file, 'wb') | |
320 | stream.write('\n'.join(url_list).encode()) | |
321 | stream.close() | |
322 | cmd += ['-i', self._aria2c_filename(url_list_file)] | |
323 | else: | |
324 | cmd += ['--', info_dict['url']] | |
325 | return cmd | |
326 | ||
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 | ||
409 | ||
410 | class HttpieFD(ExternalFD): | |
411 | AVAILABLE_OPT = '--version' | |
412 | EXE_NAME = 'http' | |
413 | ||
414 | def _make_cmd(self, tmpfilename, info_dict): | |
415 | cmd = ['http', '--download', '--output', tmpfilename, info_dict['url']] | |
416 | ||
417 | if info_dict.get('http_headers') is not None: | |
418 | for key, val in info_dict['http_headers'].items(): | |
419 | cmd += [f'{key}:{val}'] | |
420 | return cmd | |
421 | ||
422 | ||
423 | class FFmpegFD(ExternalFD): | |
424 | SUPPORTED_PROTOCOLS = ('http', 'https', 'ftp', 'ftps', 'm3u8', 'm3u8_native', 'rtsp', 'rtmp', 'rtmp_ffmpeg', 'mms', 'http_dash_segments') | |
425 | SUPPORTED_FEATURES = (Features.TO_STDOUT, Features.MULTIPLE_FORMATS) | |
426 | ||
427 | @classmethod | |
428 | def available(cls, path=None): | |
429 | # TODO: Fix path for ffmpeg | |
430 | # Fixme: This may be wrong when --ffmpeg-location is used | |
431 | return FFmpegPostProcessor().available | |
432 | ||
433 | def on_process_started(self, proc, stdin): | |
434 | """ Override this in subclasses """ | |
435 | pass | |
436 | ||
437 | @classmethod | |
438 | def can_merge_formats(cls, info_dict, params): | |
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 | ||
446 | def _call_downloader(self, tmpfilename, info_dict): | |
447 | ffpp = FFmpegPostProcessor(downloader=self) | |
448 | if not ffpp.available: | |
449 | self.report_error('m3u8 download detected but ffmpeg could not be found. Please install') | |
450 | return False | |
451 | ffpp.check_version() | |
452 | ||
453 | args = [ffpp.executable, '-y'] | |
454 | ||
455 | for log_level in ('quiet', 'verbose'): | |
456 | if self.params.get(log_level, False): | |
457 | args += ['-loglevel', log_level] | |
458 | break | |
459 | if not self.params.get('verbose'): | |
460 | args += ['-hide_banner'] | |
461 | ||
462 | args += traverse_obj(info_dict, ('downloader_options', 'ffmpeg_args'), default=[]) | |
463 | ||
464 | # These exists only for compatibility. Extractors should use | |
465 | # info_dict['downloader_options']['ffmpeg_args'] instead | |
466 | args += info_dict.get('_ffmpeg_args') or [] | |
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 | |
472 | # https://github.com/ytdl-org/youtube-dl/issues/11800#issuecomment-275037127 | |
473 | # http://trac.ffmpeg.org/ticket/6125#comment:10 | |
474 | args += ['-seekable', '1' if seekable else '0'] | |
475 | ||
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 | |
481 | ||
482 | if proxy.startswith('socks'): | |
483 | self.report_warning( | |
484 | '%s does not support SOCKS proxies. Downloading is likely to fail. ' | |
485 | 'Consider adding --hls-prefer-native to your command.' % self.get_basename()) | |
486 | ||
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() | |
492 | env['HTTP_PROXY'] = proxy | |
493 | env['http_proxy'] = proxy | |
494 | ||
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) | |
505 | conn = info_dict.get('rtmp_conn') | |
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'] | |
520 | if isinstance(conn, list): | |
521 | for entry in conn: | |
522 | args += ['-rtmp_conn', entry] | |
523 | elif isinstance(conn, str): | |
524 | args += ['-rtmp_conn', conn] | |
525 | ||
526 | start_time, end_time = info_dict.get('section_start') or 0, info_dict.get('section_end') | |
527 | ||
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']): | |
531 | headers_dict = handle_youtubedl_headers(fmt['http_headers']) | |
532 | # Trailing \r\n after each HTTP header is important to prevent warning from ffmpeg/avconv: | |
533 | # [http @ 00000000003d2fa0] No trailing CRLF found in HTTP header. | |
534 | args.extend(['-headers', ''.join(f'{key}: {val}\r\n' for key, val in headers_dict.items())]) | |
535 | ||
536 | if start_time: | |
537 | args += ['-ss', str(start_time)] | |
538 | if end_time: | |
539 | args += ['-t', str(end_time - start_time)] | |
540 | ||
541 | args += self._configuration_args((f'_i{i + 1}', '_i')) + ['-i', fmt['url']] | |
542 | ||
543 | if not (start_time or end_time) or not self.params.get('force_keyframes_at_cuts'): | |
544 | args += ['-c', 'copy'] | |
545 | ||
546 | if info_dict.get('requested_formats') or protocol == 'http_dash_segments': | |
547 | for i, fmt in enumerate(selected_formats): | |
548 | stream_number = fmt.get('manifest_stream_number', 0) | |
549 | args.extend(['-map', f'{i}:{stream_number}']) | |
550 | ||
551 | if self.params.get('test', False): | |
552 | args += ['-fs', str(self._TEST_FILE_SIZE)] | |
553 | ||
554 | ext = info_dict['ext'] | |
555 | if protocol in ('m3u8', 'm3u8_native'): | |
556 | use_mpegts = (tmpfilename == '-') or self.params.get('hls_use_mpegts') | |
557 | if use_mpegts is None: | |
558 | use_mpegts = info_dict.get('is_live') | |
559 | if use_mpegts: | |
560 | args += ['-f', 'mpegts'] | |
561 | else: | |
562 | args += ['-f', 'mp4'] | |
563 | 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')): | |
564 | args += ['-bsf:a', 'aac_adtstoasc'] | |
565 | elif protocol == 'rtmp': | |
566 | args += ['-f', 'flv'] | |
567 | elif ext == 'mp4' and tmpfilename == '-': | |
568 | args += ['-f', 'mpegts'] | |
569 | elif ext == 'unknown_video': | |
570 | ext = determine_ext(remove_end(tmpfilename, '.part')) | |
571 | if ext == 'unknown_video': | |
572 | self.report_warning( | |
573 | 'The video format is unknown and cannot be downloaded by ffmpeg. ' | |
574 | 'Explicitly set the extension in the filename to attempt download in that format') | |
575 | else: | |
576 | self.report_warning(f'The video format is unknown. Trying to download as {ext} according to the filename') | |
577 | args += ['-f', EXT_TO_OUT_FORMATS.get(ext, ext)] | |
578 | else: | |
579 | args += ['-f', EXT_TO_OUT_FORMATS.get(ext, ext)] | |
580 | ||
581 | args += self._configuration_args(('_o1', '_o', '')) | |
582 | ||
583 | args = [encodeArgument(opt) for opt in args] | |
584 | args.append(encodeFilename(ffpp._ffmpeg_filename_argument(tmpfilename), True)) | |
585 | self._debug_cmd(args) | |
586 | ||
587 | piped = any(fmt['url'] in ('-', 'pipe:') for fmt in selected_formats) | |
588 | with Popen(args, stdin=subprocess.PIPE, env=env) as proc: | |
589 | if piped: | |
590 | self.on_process_started(proc, proc.stdin) | |
591 | try: | |
592 | retval = proc.wait() | |
593 | except BaseException as e: | |
594 | # subprocces.run would send the SIGKILL signal to ffmpeg and the | |
595 | # mp4 file couldn't be played, but if we ask ffmpeg to quit it | |
596 | # produces a file that is playable (this is mostly useful for live | |
597 | # streams). Note that Windows is not affected and produces playable | |
598 | # files (see https://github.com/ytdl-org/youtube-dl/issues/8300). | |
599 | if isinstance(e, KeyboardInterrupt) and sys.platform != 'win32' and not piped: | |
600 | proc.communicate_or_kill(b'q') | |
601 | else: | |
602 | proc.kill(timeout=None) | |
603 | raise | |
604 | return retval | |
605 | ||
606 | ||
607 | class AVconvFD(FFmpegFD): | |
608 | pass | |
609 | ||
610 | ||
611 | _BY_NAME = { | |
612 | klass.get_basename(): klass | |
613 | for name, klass in globals().items() | |
614 | if name.endswith('FD') and name not in ('ExternalFD', 'FragmentFD') | |
615 | } | |
616 | ||
617 | ||
618 | def list_external_downloaders(): | |
619 | return sorted(_BY_NAME.keys()) | |
620 | ||
621 | ||
622 | def get_external_downloader(external_downloader): | |
623 | """ Given the name of the executable, see whether we support the given downloader """ | |
624 | bn = os.path.splitext(os.path.basename(external_downloader))[0] | |
625 | return _BY_NAME.get(bn) or next(( | |
626 | klass for klass in _BY_NAME.values() if klass.EXE_NAME in bn | |
627 | ), None) |