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