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