]> jfr.im git - yt-dlp.git/blame - youtube_dl/postprocessor/ffmpeg.py
[YoutubeDL] Fallback to `-f best` when merger is outdated
[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
PH
6import time
7
8
9from .common import AudioConversionError, PostProcessor
10
8c25f81b 11from ..compat import (
496c1923 12 compat_subprocess_get_DEVNULL,
8c25f81b
PH
13)
14from ..utils import (
f07b74fc 15 encodeArgument,
496c1923 16 encodeFilename,
95807118 17 get_exe_version,
48844745 18 is_outdated_version,
496c1923
PH
19 PostProcessingError,
20 prepend_extension,
21 shell_quote,
22 subtitles_filename,
bf6427d2 23 dfxp2srt,
496c1923
PH
24)
25
26
496c1923
PH
27class FFmpegPostProcessorError(PostProcessingError):
28 pass
29
d799b47b 30
496c1923 31class FFmpegPostProcessor(PostProcessor):
d47aeb22 32 def __init__(self, downloader=None):
496c1923 33 PostProcessor.__init__(self, downloader)
73fac4e9 34 self._determine_executables()
496c1923 35
48844745 36 def check_version(self):
f740fae2 37 if not self.available:
3aa578ca 38 raise FFmpegPostProcessorError('ffmpeg or avconv not found. Please install one.')
70484b9f 39 self.check_outdated()
48844745 40
70484b9f 41 def check_outdated(self):
65bf37ef 42 required_version = '10-0' if self.basename == 'avconv' else '1.0'
48844745 43 if is_outdated_version(
73fac4e9 44 self._versions[self.basename], required_version):
3aa578ca 45 warning = 'Your copy of %s is outdated, update %s to version %s or newer if you encounter any errors.' % (
73fac4e9 46 self.basename, self.basename, required_version)
6194bb14
PH
47 if self._downloader:
48 self._downloader.report_warning(warning)
70484b9f
S
49 return True
50 return False
48844745 51
496c1923 52 @staticmethod
73fac4e9
PH
53 def get_versions(downloader=None):
54 return FFmpegPostProcessor(downloader)._versions
6271f1ca 55
73fac4e9
PH
56 def _determine_executables(self):
57 programs = ['avprobe', 'avconv', 'ffmpeg', 'ffprobe']
58 prefer_ffmpeg = self._downloader.params.get('prefer_ffmpeg', False)
59
60 self.basename = None
61 self.probe_basename = None
62
63 self._paths = None
64 self._versions = None
65 if self._downloader:
66 location = self._downloader.params.get('ffmpeg_location')
67 if location is not None:
68 if not os.path.exists(location):
69 self._downloader.report_warning(
70 'ffmpeg-location %s does not exist! '
71 'Continuing without avconv/ffmpeg.' % (location))
72 self._versions = {}
73 return
74 elif not os.path.isdir(location):
75 basename = os.path.splitext(os.path.basename(location))[0]
76 if basename not in programs:
77 self._downloader.report_warning(
78 'Cannot identify executable %s, its basename should be one of %s. '
79 'Continuing without avconv/ffmpeg.' %
80 (location, ', '.join(programs)))
81 self._versions = {}
82 return None
83 location = os.path.dirname(os.path.abspath(location))
84 if basename in ('ffmpeg', 'ffprobe'):
85 prefer_ffmpeg = True
86
87 self._paths = dict(
88 (p, os.path.join(location, p)) for p in programs)
89 self._versions = dict(
90 (p, get_exe_version(self._paths[p], args=['-version']))
91 for p in programs)
92 if self._versions is None:
93 self._versions = dict(
94 (p, get_exe_version(p, args=['-version'])) for p in programs)
95 self._paths = dict((p, p) for p in programs)
96
97 if prefer_ffmpeg:
d28b5171 98 prefs = ('ffmpeg', 'avconv')
76b1bd67 99 else:
d28b5171
PH
100 prefs = ('avconv', 'ffmpeg')
101 for p in prefs:
102 if self._versions[p]:
73fac4e9
PH
103 self.basename = p
104 break
76b1bd67 105
73fac4e9 106 if prefer_ffmpeg:
50b51830 107 prefs = ('ffprobe', 'avprobe')
1a253e13
PH
108 else:
109 prefs = ('avprobe', 'ffprobe')
110 for p in prefs:
111 if self._versions[p]:
73fac4e9
PH
112 self.probe_basename = p
113 break
114
f740fae2 115 @property
73fac4e9
PH
116 def available(self):
117 return self.basename is not None
1a253e13 118
73fac4e9
PH
119 @property
120 def executable(self):
121 return self._paths[self.basename]
122
3da4b313
JMF
123 @property
124 def probe_available(self):
125 return self.probe_basename is not None
126
73fac4e9
PH
127 @property
128 def probe_executable(self):
129 return self._paths[self.probe_basename]
76b1bd67 130
496c1923 131 def run_ffmpeg_multiple_files(self, input_paths, out_path, opts):
48844745 132 self.check_version()
496c1923 133
52afb2ac
PH
134 oldest_mtime = min(
135 os.stat(encodeFilename(path)).st_mtime for path in input_paths)
43bc8890 136
496c1923
PH
137 files_cmd = []
138 for path in input_paths:
b0e87c31 139 files_cmd.extend([encodeArgument('-i'), encodeFilename(path, True)])
73fac4e9 140 cmd = ([encodeFilename(self.executable, True), encodeArgument('-y')] +
43bc8890
PH
141 files_cmd +
142 [encodeArgument(o) for o in opts] +
496c1923
PH
143 [encodeFilename(self._ffmpeg_filename_argument(out_path), True)])
144
145 if self._downloader.params.get('verbose', False):
3aa578ca 146 self._downloader.to_screen('[debug] ffmpeg command line: %s' % shell_quote(cmd))
cffcbc02 147 p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE)
62fec3b2 148 stdout, stderr = p.communicate()
496c1923
PH
149 if p.returncode != 0:
150 stderr = stderr.decode('utf-8', 'replace')
151 msg = stderr.strip().split('\n')[-1]
152 raise FFmpegPostProcessorError(msg)
dd29eb7f 153 self.try_utime(out_path, oldest_mtime, oldest_mtime)
cc55d088 154
496c1923
PH
155 def run_ffmpeg(self, path, out_path, opts):
156 self.run_ffmpeg_multiple_files([path], out_path, opts)
157
158 def _ffmpeg_filename_argument(self, fn):
159 # ffmpeg broke --, see https://ffmpeg.org/trac/ffmpeg/ticket/2127 for details
3aa578ca
PH
160 if fn.startswith('-'):
161 return './' + fn
496c1923
PH
162 return fn
163
164
165class FFmpegExtractAudioPP(FFmpegPostProcessor):
166 def __init__(self, downloader=None, preferredcodec=None, preferredquality=None, nopostoverwrites=False):
167 FFmpegPostProcessor.__init__(self, downloader)
168 if preferredcodec is None:
169 preferredcodec = 'best'
170 self._preferredcodec = preferredcodec
171 self._preferredquality = preferredquality
172 self._nopostoverwrites = nopostoverwrites
173
174 def get_audio_codec(self, path):
1a253e13 175
3da4b313 176 if not self.probe_available:
3aa578ca 177 raise PostProcessingError('ffprobe or avprobe not found. Please install one.')
496c1923
PH
178 try:
179 cmd = [
73fac4e9 180 encodeFilename(self.probe_executable, True),
b0e87c31 181 encodeArgument('-show_streams'),
496c1923 182 encodeFilename(self._ffmpeg_filename_argument(path), True)]
73fac4e9 183 if self._downloader.params.get('verbose', False):
5bfd430f 184 self._downloader.to_screen('[debug] %s command line: %s' % (self.basename, shell_quote(cmd)))
cffcbc02 185 handle = subprocess.Popen(cmd, stderr=compat_subprocess_get_DEVNULL(), stdout=subprocess.PIPE, stdin=subprocess.PIPE)
496c1923
PH
186 output = handle.communicate()[0]
187 if handle.wait() != 0:
188 return None
189 except (IOError, OSError):
190 return None
191 audio_codec = None
192 for line in output.decode('ascii', 'ignore').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 return None
198
199 def run_ffmpeg(self, path, out_path, codec, more_opts):
496c1923
PH
200 if codec is None:
201 acodec_opts = []
202 else:
203 acodec_opts = ['-acodec', codec]
204 opts = ['-vn'] + acodec_opts + more_opts
205 try:
206 FFmpegPostProcessor.run_ffmpeg(self, path, out_path, opts)
207 except FFmpegPostProcessorError as err:
208 raise AudioConversionError(err.msg)
209
210 def run(self, information):
211 path = information['filepath']
212
213 filecodec = self.get_audio_codec(path)
214 if filecodec is None:
3aa578ca 215 raise PostProcessingError('WARNING: unable to obtain file audio codec with ffprobe')
496c1923
PH
216
217 more_opts = []
218 if self._preferredcodec == 'best' or self._preferredcodec == filecodec or (self._preferredcodec == 'm4a' and filecodec == 'aac'):
219 if filecodec == 'aac' and self._preferredcodec in ['m4a', 'best']:
220 # Lossless, but in another container
221 acodec = 'copy'
222 extension = 'm4a'
467d3c9a 223 more_opts = ['-bsf:a', 'aac_adtstoasc']
496c1923
PH
224 elif filecodec in ['aac', 'mp3', 'vorbis', 'opus']:
225 # Lossless if possible
226 acodec = 'copy'
227 extension = filecodec
228 if filecodec == 'aac':
229 more_opts = ['-f', 'adts']
230 if filecodec == 'vorbis':
231 extension = 'ogg'
232 else:
233 # MP3 otherwise.
234 acodec = 'libmp3lame'
235 extension = 'mp3'
236 more_opts = []
237 if self._preferredquality is not None:
238 if int(self._preferredquality) < 10:
467d3c9a 239 more_opts += ['-q:a', self._preferredquality]
496c1923 240 else:
467d3c9a 241 more_opts += ['-b:a', self._preferredquality + 'k']
496c1923
PH
242 else:
243 # We convert the audio (lossy)
244 acodec = {'mp3': 'libmp3lame', 'aac': 'aac', 'm4a': 'aac', 'opus': 'opus', 'vorbis': 'libvorbis', 'wav': None}[self._preferredcodec]
245 extension = self._preferredcodec
246 more_opts = []
247 if self._preferredquality is not None:
248 # The opus codec doesn't support the -aq option
249 if int(self._preferredquality) < 10 and extension != 'opus':
467d3c9a 250 more_opts += ['-q:a', self._preferredquality]
496c1923 251 else:
467d3c9a 252 more_opts += ['-b:a', self._preferredquality + 'k']
496c1923
PH
253 if self._preferredcodec == 'aac':
254 more_opts += ['-f', 'adts']
255 if self._preferredcodec == 'm4a':
467d3c9a 256 more_opts += ['-bsf:a', 'aac_adtstoasc']
496c1923
PH
257 if self._preferredcodec == 'vorbis':
258 extension = 'ogg'
259 if self._preferredcodec == 'wav':
260 extension = 'wav'
261 more_opts += ['-f', 'wav']
262
3aa578ca 263 prefix, sep, ext = path.rpartition('.') # not os.path.splitext, since the latter does not work on unicode in all setups
496c1923
PH
264 new_path = prefix + sep + extension
265
266 # If we download foo.mp3 and convert it to... foo.mp3, then don't delete foo.mp3, silly.
ce81b141
JMF
267 if (new_path == path or
268 (self._nopostoverwrites and os.path.exists(encodeFilename(new_path)))):
269 self._downloader.to_screen('[youtube] Post-process file %s exists, skipping' % new_path)
592e97e8 270 return [], information
496c1923
PH
271
272 try:
ce81b141
JMF
273 self._downloader.to_screen('[' + self.basename + '] Destination: ' + new_path)
274 self.run_ffmpeg(path, new_path, acodec, more_opts)
70a1165b
JMF
275 except AudioConversionError as e:
276 raise PostProcessingError(
277 'audio conversion failed: ' + e.msg)
278 except Exception:
279 raise PostProcessingError('error running ' + self.basename)
496c1923
PH
280
281 # Try to update the date time for extracted audio file.
282 if information.get('filetime') is not None:
dd29eb7f
S
283 self.try_utime(
284 new_path, time.time(), information['filetime'],
285 errnote='Cannot update utime of audio file')
496c1923
PH
286
287 information['filepath'] = new_path
ddbed364 288 information['ext'] = extension
289
592e97e8 290 return [path], information
496c1923
PH
291
292
4f026faf 293class FFmpegVideoConvertorPP(FFmpegPostProcessor):
5f6a1245 294 def __init__(self, downloader=None, preferedformat=None):
4f026faf 295 super(FFmpegVideoConvertorPP, self).__init__(downloader)
5f6a1245 296 self._preferedformat = preferedformat
496c1923
PH
297
298 def run(self, information):
299 path = information['filepath']
3aa578ca 300 prefix, sep, ext = path.rpartition('.')
496c1923
PH
301 outpath = prefix + sep + self._preferedformat
302 if information['ext'] == self._preferedformat:
3aa578ca 303 self._downloader.to_screen('[ffmpeg] Not converting video file %s - already is in target format %s' % (path, self._preferedformat))
592e97e8 304 return [], information
3aa578ca 305 self._downloader.to_screen('[' + 'ffmpeg' + '] Converting video from %s to %s, Destination: ' % (information['ext'], self._preferedformat) + outpath)
496c1923
PH
306 self.run_ffmpeg(path, outpath, [])
307 information['filepath'] = outpath
308 information['format'] = self._preferedformat
309 information['ext'] = self._preferedformat
592e97e8 310 return [path], information
496c1923
PH
311
312
313class FFmpegEmbedSubtitlePP(FFmpegPostProcessor):
314 # See http://www.loc.gov/standards/iso639-2/ISO-639-2_utf-8.txt
315 _lang_map = {
316 'aa': 'aar',
317 'ab': 'abk',
318 'ae': 'ave',
319 'af': 'afr',
320 'ak': 'aka',
321 'am': 'amh',
322 'an': 'arg',
323 'ar': 'ara',
324 'as': 'asm',
325 'av': 'ava',
326 'ay': 'aym',
327 'az': 'aze',
328 'ba': 'bak',
329 'be': 'bel',
330 'bg': 'bul',
331 'bh': 'bih',
332 'bi': 'bis',
333 'bm': 'bam',
334 'bn': 'ben',
335 'bo': 'bod',
336 'br': 'bre',
337 'bs': 'bos',
338 'ca': 'cat',
339 'ce': 'che',
340 'ch': 'cha',
341 'co': 'cos',
342 'cr': 'cre',
343 'cs': 'ces',
344 'cu': 'chu',
345 'cv': 'chv',
346 'cy': 'cym',
347 'da': 'dan',
348 'de': 'deu',
349 'dv': 'div',
350 'dz': 'dzo',
351 'ee': 'ewe',
352 'el': 'ell',
353 'en': 'eng',
354 'eo': 'epo',
355 'es': 'spa',
356 'et': 'est',
357 'eu': 'eus',
358 'fa': 'fas',
359 'ff': 'ful',
360 'fi': 'fin',
361 'fj': 'fij',
362 'fo': 'fao',
363 'fr': 'fra',
364 'fy': 'fry',
365 'ga': 'gle',
366 'gd': 'gla',
367 'gl': 'glg',
368 'gn': 'grn',
369 'gu': 'guj',
370 'gv': 'glv',
371 'ha': 'hau',
372 'he': 'heb',
373 'hi': 'hin',
374 'ho': 'hmo',
375 'hr': 'hrv',
376 'ht': 'hat',
377 'hu': 'hun',
378 'hy': 'hye',
379 'hz': 'her',
380 'ia': 'ina',
381 'id': 'ind',
382 'ie': 'ile',
383 'ig': 'ibo',
384 'ii': 'iii',
385 'ik': 'ipk',
386 'io': 'ido',
387 'is': 'isl',
388 'it': 'ita',
389 'iu': 'iku',
390 'ja': 'jpn',
391 'jv': 'jav',
392 'ka': 'kat',
393 'kg': 'kon',
394 'ki': 'kik',
395 'kj': 'kua',
396 'kk': 'kaz',
397 'kl': 'kal',
398 'km': 'khm',
399 'kn': 'kan',
400 'ko': 'kor',
401 'kr': 'kau',
402 'ks': 'kas',
403 'ku': 'kur',
404 'kv': 'kom',
405 'kw': 'cor',
406 'ky': 'kir',
407 'la': 'lat',
408 'lb': 'ltz',
409 'lg': 'lug',
410 'li': 'lim',
411 'ln': 'lin',
412 'lo': 'lao',
413 'lt': 'lit',
414 'lu': 'lub',
415 'lv': 'lav',
416 'mg': 'mlg',
417 'mh': 'mah',
418 'mi': 'mri',
419 'mk': 'mkd',
420 'ml': 'mal',
421 'mn': 'mon',
422 'mr': 'mar',
423 'ms': 'msa',
424 'mt': 'mlt',
425 'my': 'mya',
426 'na': 'nau',
427 'nb': 'nob',
428 'nd': 'nde',
429 'ne': 'nep',
430 'ng': 'ndo',
431 'nl': 'nld',
432 'nn': 'nno',
433 'no': 'nor',
434 'nr': 'nbl',
435 'nv': 'nav',
436 'ny': 'nya',
437 'oc': 'oci',
438 'oj': 'oji',
439 'om': 'orm',
440 'or': 'ori',
441 'os': 'oss',
442 'pa': 'pan',
443 'pi': 'pli',
444 'pl': 'pol',
445 'ps': 'pus',
446 'pt': 'por',
447 'qu': 'que',
448 'rm': 'roh',
449 'rn': 'run',
450 'ro': 'ron',
451 'ru': 'rus',
452 'rw': 'kin',
453 'sa': 'san',
454 'sc': 'srd',
455 'sd': 'snd',
456 'se': 'sme',
457 'sg': 'sag',
458 'si': 'sin',
459 'sk': 'slk',
460 'sl': 'slv',
461 'sm': 'smo',
462 'sn': 'sna',
463 'so': 'som',
464 'sq': 'sqi',
465 'sr': 'srp',
466 'ss': 'ssw',
467 'st': 'sot',
468 'su': 'sun',
469 'sv': 'swe',
470 'sw': 'swa',
471 'ta': 'tam',
472 'te': 'tel',
473 'tg': 'tgk',
474 'th': 'tha',
475 'ti': 'tir',
476 'tk': 'tuk',
477 'tl': 'tgl',
478 'tn': 'tsn',
479 'to': 'ton',
480 'tr': 'tur',
481 'ts': 'tso',
482 'tt': 'tat',
483 'tw': 'twi',
484 'ty': 'tah',
485 'ug': 'uig',
486 'uk': 'ukr',
487 'ur': 'urd',
488 'uz': 'uzb',
489 've': 'ven',
490 'vi': 'vie',
491 'vo': 'vol',
492 'wa': 'wln',
493 'wo': 'wol',
494 'xh': 'xho',
495 'yi': 'yid',
496 'yo': 'yor',
497 'za': 'zha',
498 'zh': 'zho',
499 'zu': 'zul',
500 }
501
496c1923
PH
502 @classmethod
503 def _conver_lang_code(cls, code):
504 """Convert language code from ISO 639-1 to ISO 639-2/T"""
505 return cls._lang_map.get(code[:2])
506
507 def run(self, information):
083c1bb9
N
508 if information['ext'] not in ['mp4', 'mkv']:
509 self._downloader.to_screen('[ffmpeg] Subtitles can only be embedded in mp4 or mkv files')
592e97e8 510 return [], information
c84dd8a9
JMF
511 subtitles = information.get('requested_subtitles')
512 if not subtitles:
3aa578ca 513 self._downloader.to_screen('[ffmpeg] There aren\'t any subtitles to embed')
592e97e8 514 return [], information
496c1923 515
c84dd8a9 516 sub_langs = list(subtitles.keys())
496c1923 517 filename = information['filepath']
14523ed9
JMF
518 sub_filenames = [subtitles_filename(filename, lang, sub_info['ext']) for lang, sub_info in subtitles.items()]
519 input_files = [filename] + sub_filenames
496c1923 520
e205db3b
JMF
521 opts = [
522 '-map', '0',
523 '-c', 'copy',
524 # Don't copy the existing subtitles, we may be running the
525 # postprocessor a second time
526 '-map', '-0:s',
527 ]
083c1bb9
N
528 if information['ext'] == 'mp4':
529 opts += ['-c:s', 'mov_text']
496c1923 530 for (i, lang) in enumerate(sub_langs):
2875cf01 531 opts.extend(['-map', '%d:0' % (i + 1)])
496c1923
PH
532 lang_code = self._conver_lang_code(lang)
533 if lang_code is not None:
534 opts.extend(['-metadata:s:s:%d' % i, 'language=%s' % lang_code])
496c1923 535
2875cf01 536 temp_filename = prepend_extension(filename, 'temp')
3aa578ca 537 self._downloader.to_screen('[ffmpeg] Embedding subtitles in \'%s\'' % filename)
496c1923
PH
538 self.run_ffmpeg_multiple_files(input_files, temp_filename, opts)
539 os.remove(encodeFilename(filename))
540 os.rename(encodeFilename(temp_filename), encodeFilename(filename))
541
14523ed9 542 return sub_filenames, information
496c1923
PH
543
544
545class FFmpegMetadataPP(FFmpegPostProcessor):
546 def run(self, info):
547 metadata = {}
88cf6fb3 548 if info.get('title') is not None:
496c1923
PH
549 metadata['title'] = info['title']
550 if info.get('upload_date') is not None:
551 metadata['date'] = info['upload_date']
e7db87f7 552 if info.get('artist') is not None:
553 metadata['artist'] = info['artist']
554 elif info.get('uploader') is not None:
496c1923
PH
555 metadata['artist'] = info['uploader']
556 elif info.get('uploader_id') is not None:
557 metadata['artist'] = info['uploader_id']
bd3cbe07
DP
558 if info.get('description') is not None:
559 metadata['description'] = info['description']
2cf0ecac 560 metadata['comment'] = info['description']
bd3cbe07 561 if info.get('webpage_url') is not None:
2cf0ecac 562 metadata['purl'] = info['webpage_url']
e7db87f7 563 if info.get('album') is not None:
564 metadata['album'] = info['album']
496c1923
PH
565
566 if not metadata:
3aa578ca 567 self._downloader.to_screen('[ffmpeg] There isn\'t any metadata to add')
592e97e8 568 return [], info
496c1923
PH
569
570 filename = info['filepath']
571 temp_filename = prepend_extension(filename, 'temp')
572
3aa578ca 573 if info['ext'] == 'm4a':
39c68260 574 options = ['-vn', '-acodec', 'copy']
575 else:
576 options = ['-c', 'copy']
577
496c1923
PH
578 for (name, value) in metadata.items():
579 options.extend(['-metadata', '%s=%s' % (name, value)])
580
3aa578ca 581 self._downloader.to_screen('[ffmpeg] Adding metadata to \'%s\'' % filename)
496c1923
PH
582 self.run_ffmpeg(filename, temp_filename, options)
583 os.remove(encodeFilename(filename))
584 os.rename(encodeFilename(temp_filename), encodeFilename(filename))
592e97e8 585 return [], info
496c1923
PH
586
587
588class FFmpegMergerPP(FFmpegPostProcessor):
589 def run(self, info):
590 filename = info['filepath']
5b5fbc08 591 temp_filename = prepend_extension(filename, 'temp')
bc3e582f 592 args = ['-c', 'copy', '-map', '0:v:0', '-map', '1:a:0']
3aa578ca 593 self._downloader.to_screen('[ffmpeg] Merging formats into "%s"' % filename)
5b5fbc08
JMF
594 self.run_ffmpeg_multiple_files(info['__files_to_merge'], temp_filename, args)
595 os.rename(encodeFilename(temp_filename), encodeFilename(filename))
d47aeb22 596 return info['__files_to_merge'], info
496c1923 597
0c14e2fb 598
6271f1ca
PH
599class FFmpegFixupStretchedPP(FFmpegPostProcessor):
600 def run(self, info):
601 stretched_ratio = info.get('stretched_ratio')
602 if stretched_ratio is None or stretched_ratio == 1:
592e97e8 603 return [], info
6271f1ca
PH
604
605 filename = info['filepath']
606 temp_filename = prepend_extension(filename, 'temp')
607
608 options = ['-c', 'copy', '-aspect', '%f' % stretched_ratio]
609 self._downloader.to_screen('[ffmpeg] Fixing aspect ratio in "%s"' % filename)
610 self.run_ffmpeg(filename, temp_filename, options)
611
612 os.remove(encodeFilename(filename))
613 os.rename(encodeFilename(temp_filename), encodeFilename(filename))
614
592e97e8 615 return [], info
62cd676c
PH
616
617
618class FFmpegFixupM4aPP(FFmpegPostProcessor):
619 def run(self, info):
620 if info.get('container') != 'm4a_dash':
592e97e8 621 return [], info
62cd676c
PH
622
623 filename = info['filepath']
624 temp_filename = prepend_extension(filename, 'temp')
625
626 options = ['-c', 'copy', '-f', 'mp4']
627 self._downloader.to_screen('[ffmpeg] Correcting container in "%s"' % filename)
628 self.run_ffmpeg(filename, temp_filename, options)
629
630 os.remove(encodeFilename(filename))
631 os.rename(encodeFilename(temp_filename), encodeFilename(filename))
632
592e97e8 633 return [], info
e9fade72
JMF
634
635
636class FFmpegSubtitlesConvertorPP(FFmpegPostProcessor):
637 def __init__(self, downloader=None, format=None):
638 super(FFmpegSubtitlesConvertorPP, self).__init__(downloader)
639 self.format = format
640
641 def run(self, info):
642 subs = info.get('requested_subtitles')
643 filename = info['filepath']
644 new_ext = self.format
645 new_format = new_ext
646 if new_format == 'vtt':
647 new_format = 'webvtt'
648 if subs is None:
649 self._downloader.to_screen('[ffmpeg] There aren\'t any subtitles to convert')
592e97e8 650 return [], info
e9fade72
JMF
651 self._downloader.to_screen('[ffmpeg] Converting subtitles')
652 for lang, sub in subs.items():
653 ext = sub['ext']
654 if ext == new_ext:
655 self._downloader.to_screen(
656 '[ffmpeg] Subtitle file for %s is already in the requested'
657 'format' % new_ext)
658 continue
659 new_file = subtitles_filename(filename, lang, new_ext)
bf6427d2
YCH
660
661 if ext == 'dfxp' or ext == 'ttml':
662 self._downloader.report_warning(
663 'You have requested to convert dfxp (TTML) subtitles into another format, '
664 'which results in style information loss')
665
666 dfxp_file = subtitles_filename(filename, lang, ext)
667 srt_file = subtitles_filename(filename, lang, 'srt')
668
669 with io.open(dfxp_file, 'rt', encoding='utf-8') as f:
670 srt_data = dfxp2srt(f.read())
671
672 with io.open(srt_file, 'wt', encoding='utf-8') as f:
673 f.write(srt_data)
674
675 ext = 'srt'
676 subs[lang] = {
677 'ext': 'srt',
678 'data': srt_data
679 }
680
681 if new_ext == 'srt':
682 continue
683
e9fade72
JMF
684 self.run_ffmpeg(
685 subtitles_filename(filename, lang, ext),
686 new_file, ['-f', new_format])
687
688 with io.open(new_file, 'rt', encoding='utf-8') as f:
689 subs[lang] = {
690 'ext': ext,
691 'data': f.read(),
692 }
693
592e97e8 694 return [], info