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