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.

675 lines
23 KiB

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