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.

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