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