]> jfr.im git - yt-dlp.git/blame - youtube_dl/postprocessor/ffmpeg.py
Fix W504 and disable W503 (closes #20863)
[yt-dlp.git] / youtube_dl / postprocessor / ffmpeg.py
CommitLineData
3aa578ca
PH
1from __future__ import unicode_literals
2
e9fade72 3import io
496c1923
PH
4import os
5import subprocess
496c1923 6import time
fa2a36d9 7import re
496c1923
PH
8
9
10from .common import AudioConversionError, PostProcessor
11
8c25f81b 12from ..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,
496c1923
PH
24)
25
26
a755f825 27EXT_TO_OUT_FORMATS = {
21bfcd3d
PH
28 'aac': 'adts',
29 'flac': 'flac',
30 'm4a': 'ipod',
31 'mka': 'matroska',
32 'mkv': 'matroska',
33 'mpg': 'mpeg',
34 'ogv': 'ogg',
35 'ts': 'mpegts',
36 'wma': 'asf',
37 'wmv': 'asf',
38}
39ACODECS = {
40 'mp3': 'libmp3lame',
41 'aac': 'aac',
42 'flac': 'flac',
43 'm4a': 'aac',
d2ae7e24 44 'opus': 'libopus',
21bfcd3d
PH
45 'vorbis': 'libvorbis',
46 'wav': None,
a755f825 47}
48
49
496c1923
PH
50class FFmpegPostProcessorError(PostProcessingError):
51 pass
52
d799b47b 53
496c1923 54class FFmpegPostProcessor(PostProcessor):
d47aeb22 55 def __init__(self, downloader=None):
496c1923 56 PostProcessor.__init__(self, downloader)
73fac4e9 57 self._determine_executables()
496c1923 58
48844745 59 def check_version(self):
f740fae2 60 if not self.available:
3aa578ca 61 raise FFmpegPostProcessorError('ffmpeg or avconv not found. Please install one.')
48844745 62
65bf37ef 63 required_version = '10-0' if self.basename == 'avconv' else '1.0'
48844745 64 if is_outdated_version(
73fac4e9 65 self._versions[self.basename], required_version):
3aa578ca 66 warning = 'Your copy of %s is outdated, update %s to version %s or newer if you encounter any errors.' % (
73fac4e9 67 self.basename, self.basename, required_version)
6194bb14
PH
68 if self._downloader:
69 self._downloader.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:
d4a24f40 99 prefer_ffmpeg = self._downloader.params.get('prefer_ffmpeg', True)
73fac4e9
PH
100 location = self._downloader.params.get('ffmpeg_location')
101 if location is not None:
102 if not os.path.exists(location):
103 self._downloader.report_warning(
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:
111 self._downloader.report_warning(
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))
30d9e209 177 if self._downloader.params.get('verbose', False):
eb35b163
RA
178 self._downloader.to_screen(
179 '[debug] %s command line: %s' % (self.basename, shell_quote(cmd)))
180 handle = subprocess.Popen(
181 cmd, stderr=subprocess.PIPE,
182 stdout=subprocess.PIPE, stdin=subprocess.PIPE)
183 stdout_data, stderr_data = handle.communicate()
184 expected_ret = 0 if self.probe_available else 1
185 if handle.wait() != expected_ret:
30d9e209
RA
186 return None
187 except (IOError, OSError):
188 return None
eb35b163
RA
189 output = (stdout_data if self.probe_available else stderr_data).decode('ascii', 'ignore')
190 if self.probe_available:
191 audio_codec = None
192 for line in output.split('\n'):
193 if line.startswith('codec_name='):
194 audio_codec = line.split('=')[1].strip()
195 elif line.strip() == 'codec_type=audio' and audio_codec is not None:
196 return audio_codec
197 else:
198 # Stream #FILE_INDEX:STREAM_INDEX[STREAM_ID](LANGUAGE): CODEC_TYPE: CODEC_NAME
199 mobj = re.search(
200 r'Stream\s*#\d+:\d+(?:\[0x[0-9a-f]+\])?(?:\([a-z]{3}\))?:\s*Audio:\s*([0-9a-z]+)',
201 output)
202 if mobj:
203 return mobj.group(1)
30d9e209
RA
204 return None
205
496c1923 206 def run_ffmpeg_multiple_files(self, input_paths, out_path, opts):
48844745 207 self.check_version()
496c1923 208
52afb2ac
PH
209 oldest_mtime = min(
210 os.stat(encodeFilename(path)).st_mtime for path in input_paths)
43bc8890 211
15006fed
S
212 opts += self._configuration_args()
213
496c1923
PH
214 files_cmd = []
215 for path in input_paths:
8a7bbd16
JMF
216 files_cmd.extend([
217 encodeArgument('-i'),
218 encodeFilename(self._ffmpeg_filename_argument(path), True)
219 ])
ce52c7c1
S
220 cmd = [encodeFilename(self.executable, True), encodeArgument('-y')]
221 # avconv does not have repeat option
222 if self.basename == 'ffmpeg':
223 cmd += [encodeArgument('-loglevel'), encodeArgument('repeat+info')]
3089bc74
S
224 cmd += (files_cmd
225 + [encodeArgument(o) for o in opts]
226 + [encodeFilename(self._ffmpeg_filename_argument(out_path), True)])
496c1923
PH
227
228 if self._downloader.params.get('verbose', False):
3aa578ca 229 self._downloader.to_screen('[debug] ffmpeg command line: %s' % shell_quote(cmd))
cffcbc02 230 p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE)
62fec3b2 231 stdout, stderr = p.communicate()
496c1923
PH
232 if p.returncode != 0:
233 stderr = stderr.decode('utf-8', 'replace')
234 msg = stderr.strip().split('\n')[-1]
235 raise FFmpegPostProcessorError(msg)
dd29eb7f 236 self.try_utime(out_path, oldest_mtime, oldest_mtime)
cc55d088 237
496c1923
PH
238 def run_ffmpeg(self, path, out_path, opts):
239 self.run_ffmpeg_multiple_files([path], out_path, opts)
240
241 def _ffmpeg_filename_argument(self, fn):
8a7bbd16
JMF
242 # Always use 'file:' because the filename may contain ':' (ffmpeg
243 # interprets that as a protocol) or can start with '-' (-- is broken in
244 # ffmpeg, see https://ffmpeg.org/trac/ffmpeg/ticket/2127 for details)
b9f2fdd3 245 # Also leave '-' intact in order not to break streaming to stdout.
d868f43c 246 return 'file:' + fn if fn != '-' else fn
496c1923
PH
247
248
249class FFmpegExtractAudioPP(FFmpegPostProcessor):
250 def __init__(self, downloader=None, preferredcodec=None, preferredquality=None, nopostoverwrites=False):
251 FFmpegPostProcessor.__init__(self, downloader)
252 if preferredcodec is None:
253 preferredcodec = 'best'
254 self._preferredcodec = preferredcodec
255 self._preferredquality = preferredquality
256 self._nopostoverwrites = nopostoverwrites
257
496c1923 258 def run_ffmpeg(self, path, out_path, codec, more_opts):
496c1923
PH
259 if codec is None:
260 acodec_opts = []
261 else:
262 acodec_opts = ['-acodec', codec]
263 opts = ['-vn'] + acodec_opts + more_opts
264 try:
265 FFmpegPostProcessor.run_ffmpeg(self, path, out_path, opts)
266 except FFmpegPostProcessorError as err:
267 raise AudioConversionError(err.msg)
268
269 def run(self, information):
270 path = information['filepath']
271
272 filecodec = self.get_audio_codec(path)
273 if filecodec is None:
3aa578ca 274 raise PostProcessingError('WARNING: unable to obtain file audio codec with ffprobe')
496c1923
PH
275
276 more_opts = []
277 if self._preferredcodec == 'best' or self._preferredcodec == filecodec or (self._preferredcodec == 'm4a' and filecodec == 'aac'):
278 if filecodec == 'aac' and self._preferredcodec in ['m4a', 'best']:
279 # Lossless, but in another container
280 acodec = 'copy'
281 extension = 'm4a'
467d3c9a 282 more_opts = ['-bsf:a', 'aac_adtstoasc']
21bfcd3d 283 elif filecodec in ['aac', 'flac', 'mp3', 'vorbis', 'opus']:
496c1923
PH
284 # Lossless if possible
285 acodec = 'copy'
286 extension = filecodec
287 if filecodec == 'aac':
288 more_opts = ['-f', 'adts']
289 if filecodec == 'vorbis':
290 extension = 'ogg'
291 else:
292 # MP3 otherwise.
293 acodec = 'libmp3lame'
294 extension = 'mp3'
295 more_opts = []
296 if self._preferredquality is not None:
297 if int(self._preferredquality) < 10:
467d3c9a 298 more_opts += ['-q:a', self._preferredquality]
496c1923 299 else:
467d3c9a 300 more_opts += ['-b:a', self._preferredquality + 'k']
496c1923 301 else:
21bfcd3d
PH
302 # We convert the audio (lossy if codec is lossy)
303 acodec = ACODECS[self._preferredcodec]
496c1923
PH
304 extension = self._preferredcodec
305 more_opts = []
306 if self._preferredquality is not None:
307 # The opus codec doesn't support the -aq option
308 if int(self._preferredquality) < 10 and extension != 'opus':
467d3c9a 309 more_opts += ['-q:a', self._preferredquality]
496c1923 310 else:
467d3c9a 311 more_opts += ['-b:a', self._preferredquality + 'k']
496c1923
PH
312 if self._preferredcodec == 'aac':
313 more_opts += ['-f', 'adts']
314 if self._preferredcodec == 'm4a':
467d3c9a 315 more_opts += ['-bsf:a', 'aac_adtstoasc']
496c1923
PH
316 if self._preferredcodec == 'vorbis':
317 extension = 'ogg'
318 if self._preferredcodec == 'wav':
319 extension = 'wav'
320 more_opts += ['-f', 'wav']
321
3aa578ca 322 prefix, sep, ext = path.rpartition('.') # not os.path.splitext, since the latter does not work on unicode in all setups
496c1923 323 new_path = prefix + sep + extension
0b94dbb1 324
2273e2c5
PM
325 information['filepath'] = new_path
326 information['ext'] = extension
496c1923
PH
327
328 # If we download foo.mp3 and convert it to... foo.mp3, then don't delete foo.mp3, silly.
3089bc74
S
329 if (new_path == path
330 or (self._nopostoverwrites and os.path.exists(encodeFilename(new_path)))):
9750e7d7 331 self._downloader.to_screen('[ffmpeg] Post-process file %s exists, skipping' % new_path)
592e97e8 332 return [], information
496c1923
PH
333
334 try:
deb85c32 335 self._downloader.to_screen('[ffmpeg] Destination: ' + new_path)
ce81b141 336 self.run_ffmpeg(path, new_path, acodec, more_opts)
70a1165b
JMF
337 except AudioConversionError as e:
338 raise PostProcessingError(
339 'audio conversion failed: ' + e.msg)
340 except Exception:
341 raise PostProcessingError('error running ' + self.basename)
496c1923
PH
342
343 # Try to update the date time for extracted audio file.
344 if information.get('filetime') is not None:
dd29eb7f
S
345 self.try_utime(
346 new_path, time.time(), information['filetime'],
347 errnote='Cannot update utime of audio file')
496c1923 348
592e97e8 349 return [path], information
496c1923
PH
350
351
4f026faf 352class FFmpegVideoConvertorPP(FFmpegPostProcessor):
5f6a1245 353 def __init__(self, downloader=None, preferedformat=None):
4f026faf 354 super(FFmpegVideoConvertorPP, self).__init__(downloader)
5f6a1245 355 self._preferedformat = preferedformat
496c1923
PH
356
357 def run(self, information):
358 path = information['filepath']
496c1923 359 if information['ext'] == self._preferedformat:
3aa578ca 360 self._downloader.to_screen('[ffmpeg] Not converting video file %s - already is in target format %s' % (path, self._preferedformat))
592e97e8 361 return [], information
15006fed
S
362 options = []
363 if self._preferedformat == 'avi':
364 options.extend(['-c:v', 'libxvid', '-vtag', 'XVID'])
365 prefix, sep, ext = path.rpartition('.')
366 outpath = prefix + sep + self._preferedformat
3aa578ca 367 self._downloader.to_screen('[' + 'ffmpeg' + '] Converting video from %s to %s, Destination: ' % (information['ext'], self._preferedformat) + outpath)
d84f1d14 368 self.run_ffmpeg(path, outpath, options)
496c1923
PH
369 information['filepath'] = outpath
370 information['format'] = self._preferedformat
f72b0a60 371 information['ext'] = self._preferedformat
592e97e8 372 return [path], information
496c1923
PH
373
374
375class FFmpegEmbedSubtitlePP(FFmpegPostProcessor):
496c1923 376 def run(self, information):
40025ee2
S
377 if information['ext'] not in ('mp4', 'webm', 'mkv'):
378 self._downloader.to_screen('[ffmpeg] Subtitles can only be embedded in mp4, webm or mkv files')
592e97e8 379 return [], information
c84dd8a9
JMF
380 subtitles = information.get('requested_subtitles')
381 if not subtitles:
3aa578ca 382 self._downloader.to_screen('[ffmpeg] There aren\'t any subtitles to embed')
592e97e8 383 return [], information
496c1923 384
496c1923 385 filename = information['filepath']
40025ee2
S
386
387 ext = information['ext']
388 sub_langs = []
389 sub_filenames = []
390 webm_vtt_warn = False
391
392 for lang, sub_info in subtitles.items():
393 sub_ext = sub_info['ext']
394 if ext != 'webm' or ext == 'webm' and sub_ext == 'vtt':
395 sub_langs.append(lang)
396 sub_filenames.append(subtitles_filename(filename, lang, sub_ext))
397 else:
398 if not webm_vtt_warn and ext == 'webm' and sub_ext != 'vtt':
399 webm_vtt_warn = True
400 self._downloader.to_screen('[ffmpeg] Only WebVTT subtitles can be embedded in webm files')
401
402 if not sub_langs:
403 return [], information
404
14523ed9 405 input_files = [filename] + sub_filenames
496c1923 406
e205db3b 407 opts = [
23495d6a
YCH
408 '-map', '0',
409 '-c', 'copy',
e205db3b
JMF
410 # Don't copy the existing subtitles, we may be running the
411 # postprocessor a second time
412 '-map', '-0:s',
7f903dd8
T
413 # Don't copy Apple TV chapters track, bin_data (see #19042, #19024,
414 # https://trac.ffmpeg.org/ticket/6016)
415 '-map', '-0:d',
e205db3b 416 ]
083c1bb9
N
417 if information['ext'] == 'mp4':
418 opts += ['-c:s', 'mov_text']
496c1923 419 for (i, lang) in enumerate(sub_langs):
2875cf01 420 opts.extend(['-map', '%d:0' % (i + 1)])
04fb6928
S
421 lang_code = ISO639Utils.short2long(lang) or lang
422 opts.extend(['-metadata:s:s:%d' % i, 'language=%s' % lang_code])
496c1923 423
2875cf01 424 temp_filename = prepend_extension(filename, 'temp')
3aa578ca 425 self._downloader.to_screen('[ffmpeg] Embedding subtitles in \'%s\'' % filename)
496c1923
PH
426 self.run_ffmpeg_multiple_files(input_files, temp_filename, opts)
427 os.remove(encodeFilename(filename))
428 os.rename(encodeFilename(temp_filename), encodeFilename(filename))
429
14523ed9 430 return sub_filenames, information
496c1923
PH
431
432
433class FFmpegMetadataPP(FFmpegPostProcessor):
434 def run(self, info):
435 metadata = {}
4bd143a3
S
436
437 def add(meta_list, info_list=None):
438 if not info_list:
439 info_list = meta_list
440 if not isinstance(meta_list, (list, tuple)):
441 meta_list = (meta_list,)
442 if not isinstance(info_list, (list, tuple)):
443 info_list = (info_list,)
444 for info_f in info_list:
445 if info.get(info_f) is not None:
446 for meta_f in meta_list:
447 metadata[meta_f] = info[info_f]
448 break
449
450 add('title', ('track', 'title'))
451 add('date', 'upload_date')
452 add(('description', 'comment'), 'description')
453 add('purl', 'webpage_url')
454 add('track', 'track_number')
455 add('artist', ('artist', 'creator', 'uploader', 'uploader_id'))
456 add('genre')
457 add('album')
458 add('album_artist')
459 add('disc', 'disc_number')
496c1923
PH
460
461 if not metadata:
3aa578ca 462 self._downloader.to_screen('[ffmpeg] There isn\'t any metadata to add')
592e97e8 463 return [], info
496c1923
PH
464
465 filename = info['filepath']
466 temp_filename = prepend_extension(filename, 'temp')
fa2a36d9 467 in_filenames = [filename]
468 options = []
496c1923 469
3aa578ca 470 if info['ext'] == 'm4a':
fa2a36d9 471 options.extend(['-vn', '-acodec', 'copy'])
39c68260 472 else:
fa2a36d9 473 options.extend(['-c', 'copy'])
39c68260 474
496c1923
PH
475 for (name, value) in metadata.items():
476 options.extend(['-metadata', '%s=%s' % (name, value)])
477
fa2a36d9 478 chapters = info.get('chapters', [])
479 if chapters:
5192ee17 480 metadata_filename = replace_extension(filename, 'meta')
fa2a36d9 481 with io.open(metadata_filename, 'wt', encoding='utf-8') as f:
482 def ffmpeg_escape(text):
483 return re.sub(r'(=|;|#|\\|\n)', r'\\\1', text)
484
485 metadata_file_content = ';FFMETADATA1\n'
486 for chapter in chapters:
487 metadata_file_content += '[CHAPTER]\nTIMEBASE=1/1000\n'
488 metadata_file_content += 'START=%d\n' % (chapter['start_time'] * 1000)
489 metadata_file_content += 'END=%d\n' % (chapter['end_time'] * 1000)
490 chapter_title = chapter.get('title')
491 if chapter_title:
492 metadata_file_content += 'title=%s\n' % ffmpeg_escape(chapter_title)
493 f.write(metadata_file_content)
494 in_filenames.append(metadata_filename)
495 options.extend(['-map_metadata', '1'])
496
3aa578ca 497 self._downloader.to_screen('[ffmpeg] Adding metadata to \'%s\'' % filename)
fa2a36d9 498 self.run_ffmpeg_multiple_files(in_filenames, temp_filename, options)
499 if chapters:
500 os.remove(metadata_filename)
496c1923
PH
501 os.remove(encodeFilename(filename))
502 os.rename(encodeFilename(temp_filename), encodeFilename(filename))
592e97e8 503 return [], info
496c1923
PH
504
505
506class FFmpegMergerPP(FFmpegPostProcessor):
507 def run(self, info):
508 filename = info['filepath']
5b5fbc08 509 temp_filename = prepend_extension(filename, 'temp')
bc3e582f 510 args = ['-c', 'copy', '-map', '0:v:0', '-map', '1:a:0']
3aa578ca 511 self._downloader.to_screen('[ffmpeg] Merging formats into "%s"' % filename)
5b5fbc08
JMF
512 self.run_ffmpeg_multiple_files(info['__files_to_merge'], temp_filename, args)
513 os.rename(encodeFilename(temp_filename), encodeFilename(filename))
d47aeb22 514 return info['__files_to_merge'], info
496c1923 515
13763ce5
S
516 def can_merge(self):
517 # TODO: figure out merge-capable ffmpeg version
518 if self.basename != 'avconv':
519 return True
520
521 required_version = '10-0'
522 if is_outdated_version(
523 self._versions[self.basename], required_version):
524 warning = ('Your copy of %s is outdated and unable to properly mux separate video and audio files, '
525 'youtube-dl will download single file media. '
526 'Update %s to version %s or newer to fix this.') % (
527 self.basename, self.basename, required_version)
528 if self._downloader:
529 self._downloader.report_warning(warning)
530 return False
531 return True
532
0c14e2fb 533
6271f1ca
PH
534class FFmpegFixupStretchedPP(FFmpegPostProcessor):
535 def run(self, info):
536 stretched_ratio = info.get('stretched_ratio')
537 if stretched_ratio is None or stretched_ratio == 1:
592e97e8 538 return [], info
6271f1ca
PH
539
540 filename = info['filepath']
541 temp_filename = prepend_extension(filename, 'temp')
542
543 options = ['-c', 'copy', '-aspect', '%f' % stretched_ratio]
544 self._downloader.to_screen('[ffmpeg] Fixing aspect ratio in "%s"' % filename)
545 self.run_ffmpeg(filename, temp_filename, options)
546
547 os.remove(encodeFilename(filename))
548 os.rename(encodeFilename(temp_filename), encodeFilename(filename))
549
592e97e8 550 return [], info
62cd676c
PH
551
552
553class FFmpegFixupM4aPP(FFmpegPostProcessor):
554 def run(self, info):
555 if info.get('container') != 'm4a_dash':
592e97e8 556 return [], info
62cd676c
PH
557
558 filename = info['filepath']
559 temp_filename = prepend_extension(filename, 'temp')
560
561 options = ['-c', 'copy', '-f', 'mp4']
562 self._downloader.to_screen('[ffmpeg] Correcting container in "%s"' % filename)
563 self.run_ffmpeg(filename, temp_filename, options)
564
565 os.remove(encodeFilename(filename))
566 os.rename(encodeFilename(temp_filename), encodeFilename(filename))
567
592e97e8 568 return [], info
e9fade72
JMF
569
570
f17f8651 571class FFmpegFixupM3u8PP(FFmpegPostProcessor):
572 def run(self, info):
573 filename = info['filepath']
30d9e209
RA
574 if self.get_audio_codec(filename) == 'aac':
575 temp_filename = prepend_extension(filename, 'temp')
f17f8651 576
30d9e209 577 options = ['-c', 'copy', '-f', 'mp4', '-bsf:a', 'aac_adtstoasc']
a02682fd 578 self._downloader.to_screen('[ffmpeg] Fixing malformed AAC bitstream in "%s"' % filename)
30d9e209 579 self.run_ffmpeg(filename, temp_filename, options)
f17f8651 580
30d9e209
RA
581 os.remove(encodeFilename(filename))
582 os.rename(encodeFilename(temp_filename), encodeFilename(filename))
f17f8651 583 return [], info
584
585
e9fade72
JMF
586class FFmpegSubtitlesConvertorPP(FFmpegPostProcessor):
587 def __init__(self, downloader=None, format=None):
588 super(FFmpegSubtitlesConvertorPP, self).__init__(downloader)
589 self.format = format
590
591 def run(self, info):
592 subs = info.get('requested_subtitles')
593 filename = info['filepath']
594 new_ext = self.format
595 new_format = new_ext
596 if new_format == 'vtt':
597 new_format = 'webvtt'
598 if subs is None:
599 self._downloader.to_screen('[ffmpeg] There aren\'t any subtitles to convert')
592e97e8 600 return [], info
e9fade72 601 self._downloader.to_screen('[ffmpeg] Converting subtitles')
e04398e3 602 sub_filenames = []
e9fade72
JMF
603 for lang, sub in subs.items():
604 ext = sub['ext']
605 if ext == new_ext:
606 self._downloader.to_screen(
0f57447d 607 '[ffmpeg] Subtitle file for %s is already in the requested format' % new_ext)
e9fade72 608 continue
e04398e3
JMF
609 old_file = subtitles_filename(filename, lang, ext)
610 sub_filenames.append(old_file)
e9fade72 611 new_file = subtitles_filename(filename, lang, new_ext)
bf6427d2 612
40fcba5e 613 if ext in ('dfxp', 'ttml', 'tt'):
bf6427d2
YCH
614 self._downloader.report_warning(
615 'You have requested to convert dfxp (TTML) subtitles into another format, '
616 'which results in style information loss')
617
e04398e3 618 dfxp_file = old_file
bf6427d2
YCH
619 srt_file = subtitles_filename(filename, lang, 'srt')
620
3869028f 621 with open(dfxp_file, 'rb') as f:
bf6427d2
YCH
622 srt_data = dfxp2srt(f.read())
623
624 with io.open(srt_file, 'wt', encoding='utf-8') as f:
625 f.write(srt_data)
7e62c2eb 626 old_file = srt_file
bf6427d2 627
bf6427d2
YCH
628 subs[lang] = {
629 'ext': 'srt',
630 'data': srt_data
631 }
632
633 if new_ext == 'srt':
634 continue
7b8b007c
JMF
635 else:
636 sub_filenames.append(srt_file)
bf6427d2 637
e04398e3 638 self.run_ffmpeg(old_file, new_file, ['-f', new_format])
e9fade72
JMF
639
640 with io.open(new_file, 'rt', encoding='utf-8') as f:
641 subs[lang] = {
3547d265 642 'ext': new_ext,
e9fade72
JMF
643 'data': f.read(),
644 }
645
e04398e3 646 return sub_filenames, info