]>
Commit | Line | Data |
---|---|---|
3aa578ca PH |
1 | from __future__ import unicode_literals |
2 | ||
e9fade72 | 3 | import io |
496c1923 PH |
4 | import os |
5 | import subprocess | |
496c1923 | 6 | import time |
fa2a36d9 | 7 | import re |
496c1923 PH |
8 | |
9 | ||
10 | from .common import AudioConversionError, PostProcessor | |
11 | ||
8c25f81b | 12 | from ..utils import ( |
f07b74fc | 13 | encodeArgument, |
496c1923 | 14 | encodeFilename, |
95807118 | 15 | get_exe_version, |
48844745 | 16 | is_outdated_version, |
496c1923 PH |
17 | PostProcessingError, |
18 | prepend_extension, | |
19 | shell_quote, | |
20 | subtitles_filename, | |
bf6427d2 | 21 | dfxp2srt, |
39672624 | 22 | ISO639Utils, |
fa2a36d9 | 23 | replace_extension, |
f5b1bca9 | 24 | process_communicate_or_kill, |
496c1923 PH |
25 | ) |
26 | ||
27 | ||
a755f825 | 28 | EXT_TO_OUT_FORMATS = { |
21bfcd3d PH |
29 | 'aac': 'adts', |
30 | 'flac': 'flac', | |
31 | 'm4a': 'ipod', | |
32 | 'mka': 'matroska', | |
33 | 'mkv': 'matroska', | |
34 | 'mpg': 'mpeg', | |
35 | 'ogv': 'ogg', | |
36 | 'ts': 'mpegts', | |
37 | 'wma': 'asf', | |
38 | 'wmv': 'asf', | |
39 | } | |
40 | ACODECS = { | |
41 | 'mp3': 'libmp3lame', | |
42 | 'aac': 'aac', | |
43 | 'flac': 'flac', | |
44 | 'm4a': 'aac', | |
d2ae7e24 | 45 | 'opus': 'libopus', |
21bfcd3d PH |
46 | 'vorbis': 'libvorbis', |
47 | 'wav': None, | |
a755f825 | 48 | } |
49 | ||
50 | ||
496c1923 PH |
51 | class FFmpegPostProcessorError(PostProcessingError): |
52 | pass | |
53 | ||
d799b47b | 54 | |
496c1923 | 55 | class FFmpegPostProcessor(PostProcessor): |
d47aeb22 | 56 | def __init__(self, downloader=None): |
496c1923 | 57 | PostProcessor.__init__(self, downloader) |
73fac4e9 | 58 | self._determine_executables() |
496c1923 | 59 | |
48844745 | 60 | def check_version(self): |
f740fae2 | 61 | if not self.available: |
3aa578ca | 62 | raise FFmpegPostProcessorError('ffmpeg or avconv not found. Please install one.') |
48844745 | 63 | |
65bf37ef | 64 | required_version = '10-0' if self.basename == 'avconv' else '1.0' |
48844745 | 65 | if is_outdated_version( |
73fac4e9 | 66 | self._versions[self.basename], required_version): |
3aa578ca | 67 | warning = 'Your copy of %s is outdated, update %s to version %s or newer if you encounter any errors.' % ( |
73fac4e9 | 68 | self.basename, self.basename, required_version) |
f446cc66 | 69 | self.report_warning(warning) |
48844745 | 70 | |
496c1923 | 71 | @staticmethod |
73fac4e9 PH |
72 | def get_versions(downloader=None): |
73 | return FFmpegPostProcessor(downloader)._versions | |
6271f1ca | 74 | |
73fac4e9 PH |
75 | def _determine_executables(self): |
76 | programs = ['avprobe', 'avconv', 'ffmpeg', 'ffprobe'] | |
d4a24f40 | 77 | prefer_ffmpeg = True |
73fac4e9 | 78 | |
a64646e4 RA |
79 | def get_ffmpeg_version(path): |
80 | ver = get_exe_version(path, args=['-version']) | |
81 | if ver: | |
82 | regexs = [ | |
cbdc688c | 83 | r'(?:\d+:)?([0-9.]+)-[0-9]+ubuntu[0-9.]+$', # Ubuntu, see [1] |
5caa531a | 84 | r'n([0-9.]+)$', # Arch Linux |
cbdc688c | 85 | # 1. http://www.ducea.com/2006/06/17/ubuntu-package-version-naming-explanation/ |
a64646e4 RA |
86 | ] |
87 | for regex in regexs: | |
88 | mobj = re.match(regex, ver) | |
89 | if mobj: | |
90 | ver = mobj.group(1) | |
91 | return ver | |
92 | ||
73fac4e9 PH |
93 | self.basename = None |
94 | self.probe_basename = None | |
95 | ||
96 | self._paths = None | |
97 | self._versions = None | |
98 | if self._downloader: | |
f446cc66 | 99 | prefer_ffmpeg = self.get_param('prefer_ffmpeg', True) |
100 | location = self.get_param('ffmpeg_location') | |
73fac4e9 PH |
101 | if location is not None: |
102 | if not os.path.exists(location): | |
f446cc66 | 103 | self.report_warning( |
73fac4e9 PH |
104 | 'ffmpeg-location %s does not exist! ' |
105 | 'Continuing without avconv/ffmpeg.' % (location)) | |
106 | self._versions = {} | |
107 | return | |
108 | elif not os.path.isdir(location): | |
109 | basename = os.path.splitext(os.path.basename(location))[0] | |
110 | if basename not in programs: | |
f446cc66 | 111 | self.report_warning( |
73fac4e9 PH |
112 | 'Cannot identify executable %s, its basename should be one of %s. ' |
113 | 'Continuing without avconv/ffmpeg.' % | |
114 | (location, ', '.join(programs))) | |
115 | self._versions = {} | |
116 | return None | |
117 | location = os.path.dirname(os.path.abspath(location)) | |
118 | if basename in ('ffmpeg', 'ffprobe'): | |
119 | prefer_ffmpeg = True | |
120 | ||
121 | self._paths = dict( | |
122 | (p, os.path.join(location, p)) for p in programs) | |
123 | self._versions = dict( | |
a64646e4 | 124 | (p, get_ffmpeg_version(self._paths[p])) for p in programs) |
73fac4e9 PH |
125 | if self._versions is None: |
126 | self._versions = dict( | |
a64646e4 | 127 | (p, get_ffmpeg_version(p)) for p in programs) |
73fac4e9 PH |
128 | self._paths = dict((p, p) for p in programs) |
129 | ||
d4a24f40 | 130 | if prefer_ffmpeg is False: |
d28b5171 | 131 | prefs = ('avconv', 'ffmpeg') |
d4a24f40 S |
132 | else: |
133 | prefs = ('ffmpeg', 'avconv') | |
d28b5171 PH |
134 | for p in prefs: |
135 | if self._versions[p]: | |
73fac4e9 PH |
136 | self.basename = p |
137 | break | |
76b1bd67 | 138 | |
d4a24f40 | 139 | if prefer_ffmpeg is False: |
1a253e13 | 140 | prefs = ('avprobe', 'ffprobe') |
d4a24f40 S |
141 | else: |
142 | prefs = ('ffprobe', 'avprobe') | |
1a253e13 PH |
143 | for p in prefs: |
144 | if self._versions[p]: | |
73fac4e9 PH |
145 | self.probe_basename = p |
146 | break | |
147 | ||
f740fae2 | 148 | @property |
73fac4e9 PH |
149 | def available(self): |
150 | return self.basename is not None | |
1a253e13 | 151 | |
73fac4e9 PH |
152 | @property |
153 | def executable(self): | |
154 | return self._paths[self.basename] | |
155 | ||
3da4b313 JMF |
156 | @property |
157 | def probe_available(self): | |
158 | return self.probe_basename is not None | |
159 | ||
73fac4e9 PH |
160 | @property |
161 | def probe_executable(self): | |
162 | return self._paths[self.probe_basename] | |
76b1bd67 | 163 | |
30d9e209 | 164 | def get_audio_codec(self, path): |
eb35b163 RA |
165 | if not self.probe_available and not self.available: |
166 | raise PostProcessingError('ffprobe/avprobe and ffmpeg/avconv not found. Please install one.') | |
30d9e209 | 167 | try: |
eb35b163 RA |
168 | if self.probe_available: |
169 | cmd = [ | |
170 | encodeFilename(self.probe_executable, True), | |
171 | encodeArgument('-show_streams')] | |
172 | else: | |
173 | cmd = [ | |
174 | encodeFilename(self.executable, True), | |
175 | encodeArgument('-i')] | |
176 | cmd.append(encodeFilename(self._ffmpeg_filename_argument(path), True)) | |
f446cc66 | 177 | self.write_debug('%s command line: %s' % (self.basename, shell_quote(cmd))) |
eb35b163 RA |
178 | handle = subprocess.Popen( |
179 | cmd, stderr=subprocess.PIPE, | |
180 | stdout=subprocess.PIPE, stdin=subprocess.PIPE) | |
f5b1bca9 | 181 | stdout_data, stderr_data = process_communicate_or_kill(handle) |
eb35b163 RA |
182 | expected_ret = 0 if self.probe_available else 1 |
183 | if handle.wait() != expected_ret: | |
30d9e209 RA |
184 | return None |
185 | except (IOError, OSError): | |
186 | return None | |
eb35b163 RA |
187 | output = (stdout_data if self.probe_available else stderr_data).decode('ascii', 'ignore') |
188 | if self.probe_available: | |
189 | audio_codec = None | |
190 | for line in output.split('\n'): | |
191 | if line.startswith('codec_name='): | |
192 | audio_codec = line.split('=')[1].strip() | |
193 | elif line.strip() == 'codec_type=audio' and audio_codec is not None: | |
194 | return audio_codec | |
195 | else: | |
196 | # Stream #FILE_INDEX:STREAM_INDEX[STREAM_ID](LANGUAGE): CODEC_TYPE: CODEC_NAME | |
197 | mobj = re.search( | |
198 | r'Stream\s*#\d+:\d+(?:\[0x[0-9a-f]+\])?(?:\([a-z]{3}\))?:\s*Audio:\s*([0-9a-z]+)', | |
199 | output) | |
200 | if mobj: | |
201 | return mobj.group(1) | |
30d9e209 RA |
202 | return None |
203 | ||
496c1923 | 204 | def run_ffmpeg_multiple_files(self, input_paths, out_path, opts): |
48844745 | 205 | self.check_version() |
496c1923 | 206 | |
52afb2ac PH |
207 | oldest_mtime = min( |
208 | os.stat(encodeFilename(path)).st_mtime for path in input_paths) | |
43bc8890 | 209 | |
43820c03 | 210 | opts += self._configuration_args(exe=self.basename) |
15006fed | 211 | |
496c1923 PH |
212 | files_cmd = [] |
213 | for path in input_paths: | |
8a7bbd16 JMF |
214 | files_cmd.extend([ |
215 | encodeArgument('-i'), | |
216 | encodeFilename(self._ffmpeg_filename_argument(path), True) | |
217 | ]) | |
ce52c7c1 S |
218 | cmd = [encodeFilename(self.executable, True), encodeArgument('-y')] |
219 | # avconv does not have repeat option | |
220 | if self.basename == 'ffmpeg': | |
221 | cmd += [encodeArgument('-loglevel'), encodeArgument('repeat+info')] | |
3089bc74 S |
222 | cmd += (files_cmd |
223 | + [encodeArgument(o) for o in opts] | |
224 | + [encodeFilename(self._ffmpeg_filename_argument(out_path), True)]) | |
496c1923 | 225 | |
f446cc66 | 226 | self.write_debug('ffmpeg command line: %s' % shell_quote(cmd)) |
cffcbc02 | 227 | p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE) |
f5b1bca9 | 228 | stdout, stderr = process_communicate_or_kill(p) |
496c1923 PH |
229 | if p.returncode != 0: |
230 | stderr = stderr.decode('utf-8', 'replace') | |
231 | msg = stderr.strip().split('\n')[-1] | |
232 | raise FFmpegPostProcessorError(msg) | |
dd29eb7f | 233 | self.try_utime(out_path, oldest_mtime, oldest_mtime) |
cc55d088 | 234 | |
496c1923 PH |
235 | def run_ffmpeg(self, path, out_path, opts): |
236 | self.run_ffmpeg_multiple_files([path], out_path, opts) | |
237 | ||
238 | def _ffmpeg_filename_argument(self, fn): | |
8a7bbd16 JMF |
239 | # Always use 'file:' because the filename may contain ':' (ffmpeg |
240 | # interprets that as a protocol) or can start with '-' (-- is broken in | |
241 | # ffmpeg, see https://ffmpeg.org/trac/ffmpeg/ticket/2127 for details) | |
b9f2fdd3 | 242 | # Also leave '-' intact in order not to break streaming to stdout. |
d868f43c | 243 | return 'file:' + fn if fn != '-' else fn |
496c1923 PH |
244 | |
245 | ||
246 | class FFmpegExtractAudioPP(FFmpegPostProcessor): | |
247 | def __init__(self, downloader=None, preferredcodec=None, preferredquality=None, nopostoverwrites=False): | |
248 | FFmpegPostProcessor.__init__(self, downloader) | |
249 | if preferredcodec is None: | |
250 | preferredcodec = 'best' | |
251 | self._preferredcodec = preferredcodec | |
252 | self._preferredquality = preferredquality | |
253 | self._nopostoverwrites = nopostoverwrites | |
254 | ||
496c1923 | 255 | def run_ffmpeg(self, path, out_path, codec, more_opts): |
496c1923 PH |
256 | if codec is None: |
257 | acodec_opts = [] | |
258 | else: | |
259 | acodec_opts = ['-acodec', codec] | |
260 | opts = ['-vn'] + acodec_opts + more_opts | |
261 | try: | |
262 | FFmpegPostProcessor.run_ffmpeg(self, path, out_path, opts) | |
263 | except FFmpegPostProcessorError as err: | |
264 | raise AudioConversionError(err.msg) | |
265 | ||
266 | def run(self, information): | |
267 | path = information['filepath'] | |
268 | ||
269 | filecodec = self.get_audio_codec(path) | |
270 | if filecodec is None: | |
3aa578ca | 271 | raise PostProcessingError('WARNING: unable to obtain file audio codec with ffprobe') |
496c1923 PH |
272 | |
273 | more_opts = [] | |
274 | if self._preferredcodec == 'best' or self._preferredcodec == filecodec or (self._preferredcodec == 'm4a' and filecodec == 'aac'): | |
275 | if filecodec == 'aac' and self._preferredcodec in ['m4a', 'best']: | |
276 | # Lossless, but in another container | |
277 | acodec = 'copy' | |
278 | extension = 'm4a' | |
467d3c9a | 279 | more_opts = ['-bsf:a', 'aac_adtstoasc'] |
21bfcd3d | 280 | elif filecodec in ['aac', 'flac', 'mp3', 'vorbis', 'opus']: |
496c1923 PH |
281 | # Lossless if possible |
282 | acodec = 'copy' | |
283 | extension = filecodec | |
284 | if filecodec == 'aac': | |
285 | more_opts = ['-f', 'adts'] | |
286 | if filecodec == 'vorbis': | |
287 | extension = 'ogg' | |
288 | else: | |
289 | # MP3 otherwise. | |
290 | acodec = 'libmp3lame' | |
291 | extension = 'mp3' | |
292 | more_opts = [] | |
293 | if self._preferredquality is not None: | |
294 | if int(self._preferredquality) < 10: | |
467d3c9a | 295 | more_opts += ['-q:a', self._preferredquality] |
496c1923 | 296 | else: |
467d3c9a | 297 | more_opts += ['-b:a', self._preferredquality + 'k'] |
496c1923 | 298 | else: |
21bfcd3d PH |
299 | # We convert the audio (lossy if codec is lossy) |
300 | acodec = ACODECS[self._preferredcodec] | |
496c1923 PH |
301 | extension = self._preferredcodec |
302 | more_opts = [] | |
303 | if self._preferredquality is not None: | |
304 | # The opus codec doesn't support the -aq option | |
305 | if int(self._preferredquality) < 10 and extension != 'opus': | |
467d3c9a | 306 | more_opts += ['-q:a', self._preferredquality] |
496c1923 | 307 | else: |
467d3c9a | 308 | more_opts += ['-b:a', self._preferredquality + 'k'] |
496c1923 PH |
309 | if self._preferredcodec == 'aac': |
310 | more_opts += ['-f', 'adts'] | |
311 | if self._preferredcodec == 'm4a': | |
467d3c9a | 312 | more_opts += ['-bsf:a', 'aac_adtstoasc'] |
496c1923 PH |
313 | if self._preferredcodec == 'vorbis': |
314 | extension = 'ogg' | |
315 | if self._preferredcodec == 'wav': | |
316 | extension = 'wav' | |
317 | more_opts += ['-f', 'wav'] | |
318 | ||
3aa578ca | 319 | prefix, sep, ext = path.rpartition('.') # not os.path.splitext, since the latter does not work on unicode in all setups |
496c1923 | 320 | new_path = prefix + sep + extension |
0b94dbb1 | 321 | |
2273e2c5 PM |
322 | information['filepath'] = new_path |
323 | information['ext'] = extension | |
496c1923 PH |
324 | |
325 | # If we download foo.mp3 and convert it to... foo.mp3, then don't delete foo.mp3, silly. | |
3089bc74 S |
326 | if (new_path == path |
327 | or (self._nopostoverwrites and os.path.exists(encodeFilename(new_path)))): | |
1b77b347 | 328 | self.to_screen('Post-process file %s exists, skipping' % new_path) |
592e97e8 | 329 | return [], information |
496c1923 PH |
330 | |
331 | try: | |
1b77b347 | 332 | self.to_screen('Destination: ' + new_path) |
ce81b141 | 333 | self.run_ffmpeg(path, new_path, acodec, more_opts) |
70a1165b JMF |
334 | except AudioConversionError as e: |
335 | raise PostProcessingError( | |
336 | 'audio conversion failed: ' + e.msg) | |
337 | except Exception: | |
338 | raise PostProcessingError('error running ' + self.basename) | |
496c1923 PH |
339 | |
340 | # Try to update the date time for extracted audio file. | |
341 | if information.get('filetime') is not None: | |
dd29eb7f S |
342 | self.try_utime( |
343 | new_path, time.time(), information['filetime'], | |
344 | errnote='Cannot update utime of audio file') | |
496c1923 | 345 | |
592e97e8 | 346 | return [path], information |
496c1923 PH |
347 | |
348 | ||
efe87a10 FS |
349 | class FFmpegVideoRemuxerPP(FFmpegPostProcessor): |
350 | def __init__(self, downloader=None, preferedformat=None): | |
351 | super(FFmpegVideoRemuxerPP, self).__init__(downloader) | |
352 | self._preferedformat = preferedformat | |
353 | ||
354 | def run(self, information): | |
355 | path = information['filepath'] | |
356 | if information['ext'] == self._preferedformat: | |
1b77b347 | 357 | self.to_screen('Not remuxing video file %s - already is in target format %s' % (path, self._preferedformat)) |
efe87a10 | 358 | return [], information |
e0da59fe | 359 | options = ['-c', 'copy', '-map', '0', '-dn'] |
efe87a10 FS |
360 | prefix, sep, ext = path.rpartition('.') |
361 | outpath = prefix + sep + self._preferedformat | |
1b77b347 | 362 | self.to_screen('Remuxing video from %s to %s, Destination: ' % (information['ext'], self._preferedformat) + outpath) |
efe87a10 FS |
363 | self.run_ffmpeg(path, outpath, options) |
364 | information['filepath'] = outpath | |
365 | information['format'] = self._preferedformat | |
366 | information['ext'] = self._preferedformat | |
367 | return [path], information | |
368 | ||
369 | ||
4f026faf | 370 | class FFmpegVideoConvertorPP(FFmpegPostProcessor): |
5f6a1245 | 371 | def __init__(self, downloader=None, preferedformat=None): |
4f026faf | 372 | super(FFmpegVideoConvertorPP, self).__init__(downloader) |
5f6a1245 | 373 | self._preferedformat = preferedformat |
496c1923 PH |
374 | |
375 | def run(self, information): | |
376 | path = information['filepath'] | |
496c1923 | 377 | if information['ext'] == self._preferedformat: |
1b77b347 | 378 | self.to_screen('Not converting video file %s - already is in target format %s' % (path, self._preferedformat)) |
592e97e8 | 379 | return [], information |
15006fed S |
380 | options = [] |
381 | if self._preferedformat == 'avi': | |
382 | options.extend(['-c:v', 'libxvid', '-vtag', 'XVID']) | |
383 | prefix, sep, ext = path.rpartition('.') | |
384 | outpath = prefix + sep + self._preferedformat | |
1b77b347 | 385 | self.to_screen('Converting video from %s to %s, Destination: ' % (information['ext'], self._preferedformat) + outpath) |
d84f1d14 | 386 | self.run_ffmpeg(path, outpath, options) |
496c1923 PH |
387 | information['filepath'] = outpath |
388 | information['format'] = self._preferedformat | |
f72b0a60 | 389 | information['ext'] = self._preferedformat |
592e97e8 | 390 | return [path], information |
496c1923 PH |
391 | |
392 | ||
393 | class FFmpegEmbedSubtitlePP(FFmpegPostProcessor): | |
496c1923 | 394 | def run(self, information): |
40025ee2 | 395 | if information['ext'] not in ('mp4', 'webm', 'mkv'): |
1b77b347 | 396 | self.to_screen('Subtitles can only be embedded in mp4, webm or mkv files') |
592e97e8 | 397 | return [], information |
c84dd8a9 JMF |
398 | subtitles = information.get('requested_subtitles') |
399 | if not subtitles: | |
1b77b347 | 400 | self.to_screen('There aren\'t any subtitles to embed') |
592e97e8 | 401 | return [], information |
496c1923 | 402 | |
496c1923 | 403 | filename = information['filepath'] |
40025ee2 S |
404 | |
405 | ext = information['ext'] | |
406 | sub_langs = [] | |
407 | sub_filenames = [] | |
408 | webm_vtt_warn = False | |
409 | ||
410 | for lang, sub_info in subtitles.items(): | |
411 | sub_ext = sub_info['ext'] | |
503d4a44 | 412 | if sub_ext == 'json': |
1b77b347 | 413 | self.to_screen('JSON subtitles cannot be embedded') |
503d4a44 | 414 | elif ext != 'webm' or ext == 'webm' and sub_ext == 'vtt': |
40025ee2 | 415 | sub_langs.append(lang) |
824fa511 | 416 | sub_filenames.append(subtitles_filename(filename, lang, sub_ext, ext)) |
40025ee2 S |
417 | else: |
418 | if not webm_vtt_warn and ext == 'webm' and sub_ext != 'vtt': | |
419 | webm_vtt_warn = True | |
1b77b347 | 420 | self.to_screen('Only WebVTT subtitles can be embedded in webm files') |
40025ee2 S |
421 | |
422 | if not sub_langs: | |
423 | return [], information | |
424 | ||
14523ed9 | 425 | input_files = [filename] + sub_filenames |
496c1923 | 426 | |
e205db3b | 427 | opts = [ |
e0da59fe | 428 | '-c', 'copy', '-map', '0', '-dn', |
e205db3b JMF |
429 | # Don't copy the existing subtitles, we may be running the |
430 | # postprocessor a second time | |
431 | '-map', '-0:s', | |
7f903dd8 T |
432 | # Don't copy Apple TV chapters track, bin_data (see #19042, #19024, |
433 | # https://trac.ffmpeg.org/ticket/6016) | |
434 | '-map', '-0:d', | |
e205db3b | 435 | ] |
083c1bb9 N |
436 | if information['ext'] == 'mp4': |
437 | opts += ['-c:s', 'mov_text'] | |
496c1923 | 438 | for (i, lang) in enumerate(sub_langs): |
2875cf01 | 439 | opts.extend(['-map', '%d:0' % (i + 1)]) |
04fb6928 S |
440 | lang_code = ISO639Utils.short2long(lang) or lang |
441 | opts.extend(['-metadata:s:s:%d' % i, 'language=%s' % lang_code]) | |
496c1923 | 442 | |
2875cf01 | 443 | temp_filename = prepend_extension(filename, 'temp') |
1b77b347 | 444 | self.to_screen('Embedding subtitles in \'%s\'' % filename) |
496c1923 PH |
445 | self.run_ffmpeg_multiple_files(input_files, temp_filename, opts) |
446 | os.remove(encodeFilename(filename)) | |
447 | os.rename(encodeFilename(temp_filename), encodeFilename(filename)) | |
448 | ||
14523ed9 | 449 | return sub_filenames, information |
496c1923 PH |
450 | |
451 | ||
452 | class FFmpegMetadataPP(FFmpegPostProcessor): | |
453 | def run(self, info): | |
454 | metadata = {} | |
4bd143a3 S |
455 | |
456 | def add(meta_list, info_list=None): | |
457 | if not info_list: | |
458 | info_list = meta_list | |
459 | if not isinstance(meta_list, (list, tuple)): | |
460 | meta_list = (meta_list,) | |
461 | if not isinstance(info_list, (list, tuple)): | |
462 | info_list = (info_list,) | |
463 | for info_f in info_list: | |
464 | if info.get(info_f) is not None: | |
465 | for meta_f in meta_list: | |
466 | metadata[meta_f] = info[info_f] | |
467 | break | |
468 | ||
2791e80b S |
469 | # See [1-4] for some info on media metadata/metadata supported |
470 | # by ffmpeg. | |
471 | # 1. https://kdenlive.org/en/project/adding-meta-data-to-mp4-video/ | |
472 | # 2. https://wiki.multimedia.cx/index.php/FFmpeg_Metadata | |
473 | # 3. https://kodi.wiki/view/Video_file_tagging | |
474 | # 4. http://atomicparsley.sourceforge.net/mpeg-4files.html | |
475 | ||
4bd143a3 S |
476 | add('title', ('track', 'title')) |
477 | add('date', 'upload_date') | |
478 | add(('description', 'comment'), 'description') | |
479 | add('purl', 'webpage_url') | |
480 | add('track', 'track_number') | |
481 | add('artist', ('artist', 'creator', 'uploader', 'uploader_id')) | |
482 | add('genre') | |
483 | add('album') | |
484 | add('album_artist') | |
485 | add('disc', 'disc_number') | |
2791e80b S |
486 | add('show', 'series') |
487 | add('season_number') | |
488 | add('episode_id', ('episode', 'episode_id')) | |
489 | add('episode_sort', 'episode_number') | |
496c1923 PH |
490 | |
491 | if not metadata: | |
1b77b347 | 492 | self.to_screen('There isn\'t any metadata to add') |
592e97e8 | 493 | return [], info |
496c1923 PH |
494 | |
495 | filename = info['filepath'] | |
496 | temp_filename = prepend_extension(filename, 'temp') | |
fa2a36d9 | 497 | in_filenames = [filename] |
e0da59fe | 498 | options = ['-map', '0', '-dn'] |
496c1923 | 499 | |
3aa578ca | 500 | if info['ext'] == 'm4a': |
fa2a36d9 | 501 | options.extend(['-vn', '-acodec', 'copy']) |
39c68260 | 502 | else: |
fa2a36d9 | 503 | options.extend(['-c', 'copy']) |
39c68260 | 504 | |
496c1923 PH |
505 | for (name, value) in metadata.items(): |
506 | options.extend(['-metadata', '%s=%s' % (name, value)]) | |
507 | ||
fa2a36d9 | 508 | chapters = info.get('chapters', []) |
509 | if chapters: | |
5192ee17 | 510 | metadata_filename = replace_extension(filename, 'meta') |
fa2a36d9 | 511 | with io.open(metadata_filename, 'wt', encoding='utf-8') as f: |
512 | def ffmpeg_escape(text): | |
513 | return re.sub(r'(=|;|#|\\|\n)', r'\\\1', text) | |
514 | ||
515 | metadata_file_content = ';FFMETADATA1\n' | |
516 | for chapter in chapters: | |
517 | metadata_file_content += '[CHAPTER]\nTIMEBASE=1/1000\n' | |
518 | metadata_file_content += 'START=%d\n' % (chapter['start_time'] * 1000) | |
519 | metadata_file_content += 'END=%d\n' % (chapter['end_time'] * 1000) | |
520 | chapter_title = chapter.get('title') | |
521 | if chapter_title: | |
522 | metadata_file_content += 'title=%s\n' % ffmpeg_escape(chapter_title) | |
523 | f.write(metadata_file_content) | |
524 | in_filenames.append(metadata_filename) | |
525 | options.extend(['-map_metadata', '1']) | |
526 | ||
1b77b347 | 527 | self.to_screen('Adding metadata to \'%s\'' % filename) |
fa2a36d9 | 528 | self.run_ffmpeg_multiple_files(in_filenames, temp_filename, options) |
529 | if chapters: | |
530 | os.remove(metadata_filename) | |
496c1923 PH |
531 | os.remove(encodeFilename(filename)) |
532 | os.rename(encodeFilename(temp_filename), encodeFilename(filename)) | |
592e97e8 | 533 | return [], info |
496c1923 PH |
534 | |
535 | ||
536 | class FFmpegMergerPP(FFmpegPostProcessor): | |
537 | def run(self, info): | |
538 | filename = info['filepath'] | |
5b5fbc08 | 539 | temp_filename = prepend_extension(filename, 'temp') |
d03cfdce | 540 | args = ['-c', 'copy'] |
541 | for (i, fmt) in enumerate(info['requested_formats']): | |
542 | if fmt.get('acodec') != 'none': | |
543 | args.extend(['-map', '%u:a:0' % (i)]) | |
544 | if fmt.get('vcodec') != 'none': | |
545 | args.extend(['-map', '%u:v:0' % (i)]) | |
1b77b347 | 546 | self.to_screen('Merging formats into "%s"' % filename) |
5b5fbc08 JMF |
547 | self.run_ffmpeg_multiple_files(info['__files_to_merge'], temp_filename, args) |
548 | os.rename(encodeFilename(temp_filename), encodeFilename(filename)) | |
d47aeb22 | 549 | return info['__files_to_merge'], info |
496c1923 | 550 | |
13763ce5 S |
551 | def can_merge(self): |
552 | # TODO: figure out merge-capable ffmpeg version | |
553 | if self.basename != 'avconv': | |
554 | return True | |
555 | ||
556 | required_version = '10-0' | |
557 | if is_outdated_version( | |
558 | self._versions[self.basename], required_version): | |
559 | warning = ('Your copy of %s is outdated and unable to properly mux separate video and audio files, ' | |
cefecac1 | 560 | 'youtube-dlc will download single file media. ' |
13763ce5 S |
561 | 'Update %s to version %s or newer to fix this.') % ( |
562 | self.basename, self.basename, required_version) | |
f446cc66 | 563 | self.report_warning(warning) |
13763ce5 S |
564 | return False |
565 | return True | |
566 | ||
0c14e2fb | 567 | |
6271f1ca PH |
568 | class FFmpegFixupStretchedPP(FFmpegPostProcessor): |
569 | def run(self, info): | |
570 | stretched_ratio = info.get('stretched_ratio') | |
571 | if stretched_ratio is None or stretched_ratio == 1: | |
592e97e8 | 572 | return [], info |
6271f1ca PH |
573 | |
574 | filename = info['filepath'] | |
575 | temp_filename = prepend_extension(filename, 'temp') | |
576 | ||
e0da59fe | 577 | options = ['-c', 'copy', '-map', '0', '-dn', '-aspect', '%f' % stretched_ratio] |
1b77b347 | 578 | self.to_screen('Fixing aspect ratio in "%s"' % filename) |
6271f1ca PH |
579 | self.run_ffmpeg(filename, temp_filename, options) |
580 | ||
581 | os.remove(encodeFilename(filename)) | |
582 | os.rename(encodeFilename(temp_filename), encodeFilename(filename)) | |
583 | ||
592e97e8 | 584 | return [], info |
62cd676c PH |
585 | |
586 | ||
587 | class FFmpegFixupM4aPP(FFmpegPostProcessor): | |
588 | def run(self, info): | |
589 | if info.get('container') != 'm4a_dash': | |
592e97e8 | 590 | return [], info |
62cd676c PH |
591 | |
592 | filename = info['filepath'] | |
593 | temp_filename = prepend_extension(filename, 'temp') | |
594 | ||
e0da59fe | 595 | options = ['-c', 'copy', '-map', '0', '-dn', '-f', 'mp4'] |
1b77b347 | 596 | self.to_screen('Correcting container in "%s"' % filename) |
62cd676c PH |
597 | self.run_ffmpeg(filename, temp_filename, options) |
598 | ||
599 | os.remove(encodeFilename(filename)) | |
600 | os.rename(encodeFilename(temp_filename), encodeFilename(filename)) | |
601 | ||
592e97e8 | 602 | return [], info |
e9fade72 JMF |
603 | |
604 | ||
f17f8651 | 605 | class FFmpegFixupM3u8PP(FFmpegPostProcessor): |
606 | def run(self, info): | |
607 | filename = info['filepath'] | |
30d9e209 RA |
608 | if self.get_audio_codec(filename) == 'aac': |
609 | temp_filename = prepend_extension(filename, 'temp') | |
f17f8651 | 610 | |
e0da59fe | 611 | options = ['-c', 'copy', '-map', '0', '-dn', '-f', 'mp4', '-bsf:a', 'aac_adtstoasc'] |
1b77b347 | 612 | self.to_screen('Fixing malformed AAC bitstream in "%s"' % filename) |
30d9e209 | 613 | self.run_ffmpeg(filename, temp_filename, options) |
f17f8651 | 614 | |
30d9e209 RA |
615 | os.remove(encodeFilename(filename)) |
616 | os.rename(encodeFilename(temp_filename), encodeFilename(filename)) | |
f17f8651 | 617 | return [], info |
618 | ||
619 | ||
e9fade72 JMF |
620 | class FFmpegSubtitlesConvertorPP(FFmpegPostProcessor): |
621 | def __init__(self, downloader=None, format=None): | |
622 | super(FFmpegSubtitlesConvertorPP, self).__init__(downloader) | |
623 | self.format = format | |
624 | ||
625 | def run(self, info): | |
626 | subs = info.get('requested_subtitles') | |
627 | filename = info['filepath'] | |
628 | new_ext = self.format | |
629 | new_format = new_ext | |
630 | if new_format == 'vtt': | |
631 | new_format = 'webvtt' | |
632 | if subs is None: | |
1b77b347 | 633 | self.to_screen('There aren\'t any subtitles to convert') |
592e97e8 | 634 | return [], info |
1b77b347 | 635 | self.to_screen('Converting subtitles') |
e04398e3 | 636 | sub_filenames = [] |
e9fade72 JMF |
637 | for lang, sub in subs.items(): |
638 | ext = sub['ext'] | |
639 | if ext == new_ext: | |
1b77b347 | 640 | self.to_screen('Subtitle file for %s is already in the requested format' % new_ext) |
e9fade72 | 641 | continue |
503d4a44 | 642 | elif ext == 'json': |
1b77b347 | 643 | self.to_screen( |
644 | 'You have requested to convert json subtitles into another format, ' | |
503d4a44 | 645 | 'which is currently not possible') |
646 | continue | |
824fa511 | 647 | old_file = subtitles_filename(filename, lang, ext, info.get('ext')) |
e04398e3 | 648 | sub_filenames.append(old_file) |
824fa511 | 649 | new_file = subtitles_filename(filename, lang, new_ext, info.get('ext')) |
bf6427d2 | 650 | |
40fcba5e | 651 | if ext in ('dfxp', 'ttml', 'tt'): |
f446cc66 | 652 | self.report_warning( |
1b77b347 | 653 | 'You have requested to convert dfxp (TTML) subtitles into another format, ' |
bf6427d2 YCH |
654 | 'which results in style information loss') |
655 | ||
e04398e3 | 656 | dfxp_file = old_file |
824fa511 | 657 | srt_file = subtitles_filename(filename, lang, 'srt', info.get('ext')) |
bf6427d2 | 658 | |
3869028f | 659 | with open(dfxp_file, 'rb') as f: |
bf6427d2 YCH |
660 | srt_data = dfxp2srt(f.read()) |
661 | ||
662 | with io.open(srt_file, 'wt', encoding='utf-8') as f: | |
663 | f.write(srt_data) | |
7e62c2eb | 664 | old_file = srt_file |
bf6427d2 | 665 | |
bf6427d2 YCH |
666 | subs[lang] = { |
667 | 'ext': 'srt', | |
668 | 'data': srt_data | |
669 | } | |
670 | ||
671 | if new_ext == 'srt': | |
672 | continue | |
7b8b007c JMF |
673 | else: |
674 | sub_filenames.append(srt_file) | |
bf6427d2 | 675 | |
e04398e3 | 676 | self.run_ffmpeg(old_file, new_file, ['-f', new_format]) |
e9fade72 JMF |
677 | |
678 | with io.open(new_file, 'rt', encoding='utf-8') as f: | |
679 | subs[lang] = { | |
3547d265 | 680 | 'ext': new_ext, |
e9fade72 JMF |
681 | 'data': f.read(), |
682 | } | |
683 | ||
e04398e3 | 684 | return sub_filenames, info |