logo

youtube-dl

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

ffmpeg.py (26220B)


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