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