[ffmpeg] convert format ext to ffmpeg output formats codes
[youtube-dl] / youtube_dl / downloader / external.py
1 from __future__ import unicode_literals
2
3 import os.path
4 import subprocess
5 import sys
6 import re
7
8 from .common import FileDownloader
9 from ..postprocessor.ffmpeg import FFmpegPostProcessor, EXT_TO_OUT_FORMATS
10 from ..compat import compat_str
11 from ..utils import (
12     cli_option,
13     cli_valueless_option,
14     cli_bool_option,
15     cli_configuration_args,
16     encodeFilename,
17     encodeArgument,
18     handle_youtubedl_headers,
19     check_executable,
20 )
21
22
23 class ExternalFD(FileDownloader):
24     def real_download(self, filename, info_dict):
25         self.report_destination(filename)
26         tmpfilename = self.temp_name(filename)
27
28         retval = self._call_downloader(tmpfilename, info_dict)
29         if retval == 0:
30             fsize = os.path.getsize(encodeFilename(tmpfilename))
31             self.to_screen('\r[%s] Downloaded %s bytes' % (self.get_basename(), fsize))
32             self.try_rename(tmpfilename, filename)
33             self._hook_progress({
34                 'downloaded_bytes': fsize,
35                 'total_bytes': fsize,
36                 'filename': filename,
37                 'status': 'finished',
38             })
39             return True
40         else:
41             self.to_stderr('\n')
42             self.report_error('%s exited with code %d' % (
43                 self.get_basename(), retval))
44             return False
45
46     @classmethod
47     def get_basename(cls):
48         return cls.__name__[:-2].lower()
49
50     @property
51     def exe(self):
52         return self.params.get('external_downloader')
53
54     @classmethod
55     def available(cls):
56         return check_executable(cls.get_basename(), cls.available_opt)
57
58     @classmethod
59     def supports(cls, info_dict):
60         return info_dict['protocol'] in ('http', 'https', 'ftp', 'ftps')
61
62     def _option(self, command_option, param):
63         return cli_option(self.params, command_option, param)
64
65     def _bool_option(self, command_option, param, true_value='true', false_value='false', separator=None):
66         return cli_bool_option(self.params, command_option, param, true_value, false_value, separator)
67
68     def _valueless_option(self, command_option, param, expected_value=True):
69         return cli_valueless_option(self.params, command_option, param, expected_value)
70
71     def _configuration_args(self, default=[]):
72         return cli_configuration_args(self.params, 'external_downloader_args', default)
73
74     def _call_downloader(self, tmpfilename, info_dict):
75         """ Either overwrite this or implement _make_cmd """
76         cmd = [encodeArgument(a) for a in self._make_cmd(tmpfilename, info_dict)]
77
78         self._debug_cmd(cmd)
79
80         p = subprocess.Popen(
81             cmd, stderr=subprocess.PIPE)
82         _, stderr = p.communicate()
83         if p.returncode != 0:
84             self.to_stderr(stderr)
85         return p.returncode
86
87
88 class CurlFD(ExternalFD):
89     available_opt = ['-V']
90
91     def _make_cmd(self, tmpfilename, info_dict):
92         cmd = [self.exe, '--location', '-o', tmpfilename]
93         for key, val in info_dict['http_headers'].items():
94             cmd += ['--header', '%s: %s' % (key, val)]
95         cmd += self._option('--interface', 'source_address')
96         cmd += self._option('--proxy', 'proxy')
97         cmd += self._valueless_option('--insecure', 'nocheckcertificate')
98         cmd += self._configuration_args()
99         cmd += ['--', info_dict['url']]
100         return cmd
101
102
103 class AxelFD(ExternalFD):
104     available_opt = ['-V']
105
106     def _make_cmd(self, tmpfilename, info_dict):
107         cmd = [self.exe, '-o', tmpfilename]
108         for key, val in info_dict['http_headers'].items():
109             cmd += ['-H', '%s: %s' % (key, val)]
110         cmd += self._configuration_args()
111         cmd += ['--', info_dict['url']]
112         return cmd
113
114
115 class WgetFD(ExternalFD):
116     available_opt = ['--version']
117
118     def _make_cmd(self, tmpfilename, info_dict):
119         cmd = [self.exe, '-O', tmpfilename, '-nv', '--no-cookies']
120         for key, val in info_dict['http_headers'].items():
121             cmd += ['--header', '%s: %s' % (key, val)]
122         cmd += self._option('--bind-address', 'source_address')
123         cmd += self._option('--proxy', 'proxy')
124         cmd += self._valueless_option('--no-check-certificate', 'nocheckcertificate')
125         cmd += self._configuration_args()
126         cmd += ['--', info_dict['url']]
127         return cmd
128
129
130 class Aria2cFD(ExternalFD):
131     available_opt = ['-v']
132
133     def _make_cmd(self, tmpfilename, info_dict):
134         cmd = [self.exe, '-c']
135         cmd += self._configuration_args([
136             '--min-split-size', '1M', '--max-connection-per-server', '4'])
137         dn = os.path.dirname(tmpfilename)
138         if dn:
139             cmd += ['--dir', dn]
140         cmd += ['--out', os.path.basename(tmpfilename)]
141         for key, val in info_dict['http_headers'].items():
142             cmd += ['--header', '%s: %s' % (key, val)]
143         cmd += self._option('--interface', 'source_address')
144         cmd += self._option('--all-proxy', 'proxy')
145         cmd += self._bool_option('--check-certificate', 'nocheckcertificate', 'false', 'true', '=')
146         cmd += ['--', info_dict['url']]
147         return cmd
148
149
150 class HttpieFD(ExternalFD):
151     @classmethod
152     def available(cls):
153         return check_executable('http', ['--version'])
154
155     def _make_cmd(self, tmpfilename, info_dict):
156         cmd = ['http', '--download', '--output', tmpfilename, info_dict['url']]
157         for key, val in info_dict['http_headers'].items():
158             cmd += ['%s:%s' % (key, val)]
159         return cmd
160
161
162 class FFmpegFD(ExternalFD):
163     @classmethod
164     def supports(cls, info_dict):
165         return info_dict['protocol'] in ('http', 'https', 'ftp', 'ftps', 'm3u8', 'rtsp', 'rtmp', 'mms')
166
167     @classmethod
168     def available(cls):
169         return FFmpegPostProcessor().available
170
171     def _call_downloader(self, tmpfilename, info_dict):
172         url = info_dict['url']
173         ffpp = FFmpegPostProcessor(downloader=self)
174         ffpp.check_version()
175
176         args = [ffpp.executable, '-y']
177
178         start_time = info_dict.get('start_time') or 0
179         if start_time:
180             args += ['-ss', compat_str(start_time)]
181         end_time = info_dict.get('end_time')
182         if end_time:
183             args += ['-t', compat_str(end_time - start_time)]
184
185         if info_dict['http_headers'] and re.match(r'^https?://', url):
186             # Trailing \r\n after each HTTP header is important to prevent warning from ffmpeg/avconv:
187             # [http @ 00000000003d2fa0] No trailing CRLF found in HTTP header.
188             headers = handle_youtubedl_headers(info_dict['http_headers'])
189             args += [
190                 '-headers',
191                 ''.join('%s: %s\r\n' % (key, val) for key, val in headers.items())]
192
193         args += ['-i', url, '-c', 'copy']
194         if info_dict.get('protocol') == 'm3u8':
195             if self.params.get('hls_use_mpegts', False):
196                 args += ['-f', 'mpegts']
197             else:
198                 args += ['-f', 'mp4', '-bsf:a', 'aac_adtstoasc']
199         else:
200             args += ['-f', EXT_TO_OUT_FORMATS.get(info_dict['ext'], info_dict['ext'])]
201
202         args = [encodeArgument(opt) for opt in args]
203         args.append(encodeFilename(ffpp._ffmpeg_filename_argument(tmpfilename), True))
204
205         self._debug_cmd(args)
206
207         proc = subprocess.Popen(args, stdin=subprocess.PIPE)
208         try:
209             retval = proc.wait()
210         except KeyboardInterrupt:
211             # subprocces.run would send the SIGKILL signal to ffmpeg and the
212             # mp4 file couldn't be played, but if we ask ffmpeg to quit it
213             # produces a file that is playable (this is mostly useful for live
214             # streams). Note that Windows is not affected and produces playable
215             # files (see https://github.com/rg3/youtube-dl/issues/8300).
216             if sys.platform != 'win32':
217                 proc.communicate(b'q')
218             raise
219         return retval
220
221
222 class AVconvFD(FFmpegFD):
223     pass
224
225 _BY_NAME = dict(
226     (klass.get_basename(), klass)
227     for name, klass in globals().items()
228     if name.endswith('FD') and name != 'ExternalFD'
229 )
230
231
232 def list_external_downloaders():
233     return sorted(_BY_NAME.keys())
234
235
236 def get_external_downloader(external_downloader):
237     """ Given the name of the executable, see whether we support the given
238         downloader . """
239     # Drop .exe extension on Windows
240     bn = os.path.splitext(os.path.basename(external_downloader))[0]
241     return _BY_NAME[bn]