ffmpeg.py 25 KB

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