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.

676 lines
23 KiB

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