logo

youtube-dl

[mirror] Download/Watch videos from video hostersgit clone https://hacktivis.me/git/mirror/youtube-dl.git

ffmpeg.py (26025B)


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