You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

657 lines
25 KiB

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