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.

689 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. dfxp2srt,
  20. )
  21. class FFmpegPostProcessorError(PostProcessingError):
  22. pass
  23. class FFmpegPostProcessor(PostProcessor):
  24. def __init__(self, downloader=None):
  25. PostProcessor.__init__(self, downloader)
  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. 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_available:
  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 or
  227. (self._nopostoverwrites and os.path.exists(encodeFilename(new_path)))):
  228. self._downloader.to_screen('[youtube] Post-process file %s exists, skipping' % new_path)
  229. return [], information
  230. try:
  231. self._downloader.to_screen('[' + self.basename + '] Destination: ' + new_path)
  232. self.run_ffmpeg(path, new_path, acodec, more_opts)
  233. except AudioConversionError as e:
  234. raise PostProcessingError(
  235. 'audio conversion failed: ' + e.msg)
  236. except Exception:
  237. raise PostProcessingError('error running ' + self.basename)
  238. # Try to update the date time for extracted audio file.
  239. if information.get('filetime') is not None:
  240. self.try_utime(
  241. new_path, time.time(), information['filetime'],
  242. errnote='Cannot update utime of audio file')
  243. information['filepath'] = new_path
  244. information['ext'] = extension
  245. return [path], information
  246. class FFmpegVideoConvertorPP(FFmpegPostProcessor):
  247. def __init__(self, downloader=None, preferedformat=None):
  248. super(FFmpegVideoConvertorPP, self).__init__(downloader)
  249. self._preferedformat = preferedformat
  250. def run(self, information):
  251. path = information['filepath']
  252. prefix, sep, ext = path.rpartition('.')
  253. outpath = prefix + sep + self._preferedformat
  254. if information['ext'] == self._preferedformat:
  255. self._downloader.to_screen('[ffmpeg] Not converting video file %s - already is in target format %s' % (path, self._preferedformat))
  256. return [], information
  257. self._downloader.to_screen('[' + 'ffmpeg' + '] Converting video from %s to %s, Destination: ' % (information['ext'], self._preferedformat) + outpath)
  258. self.run_ffmpeg(path, outpath, [])
  259. information['filepath'] = outpath
  260. information['format'] = self._preferedformat
  261. information['ext'] = self._preferedformat
  262. return [path], information
  263. class FFmpegEmbedSubtitlePP(FFmpegPostProcessor):
  264. # See http://www.loc.gov/standards/iso639-2/ISO-639-2_utf-8.txt
  265. _lang_map = {
  266. 'aa': 'aar',
  267. 'ab': 'abk',
  268. 'ae': 'ave',
  269. 'af': 'afr',
  270. 'ak': 'aka',
  271. 'am': 'amh',
  272. 'an': 'arg',
  273. 'ar': 'ara',
  274. 'as': 'asm',
  275. 'av': 'ava',
  276. 'ay': 'aym',
  277. 'az': 'aze',
  278. 'ba': 'bak',
  279. 'be': 'bel',
  280. 'bg': 'bul',
  281. 'bh': 'bih',
  282. 'bi': 'bis',
  283. 'bm': 'bam',
  284. 'bn': 'ben',
  285. 'bo': 'bod',
  286. 'br': 'bre',
  287. 'bs': 'bos',
  288. 'ca': 'cat',
  289. 'ce': 'che',
  290. 'ch': 'cha',
  291. 'co': 'cos',
  292. 'cr': 'cre',
  293. 'cs': 'ces',
  294. 'cu': 'chu',
  295. 'cv': 'chv',
  296. 'cy': 'cym',
  297. 'da': 'dan',
  298. 'de': 'deu',
  299. 'dv': 'div',
  300. 'dz': 'dzo',
  301. 'ee': 'ewe',
  302. 'el': 'ell',
  303. 'en': 'eng',
  304. 'eo': 'epo',
  305. 'es': 'spa',
  306. 'et': 'est',
  307. 'eu': 'eus',
  308. 'fa': 'fas',
  309. 'ff': 'ful',
  310. 'fi': 'fin',
  311. 'fj': 'fij',
  312. 'fo': 'fao',
  313. 'fr': 'fra',
  314. 'fy': 'fry',
  315. 'ga': 'gle',
  316. 'gd': 'gla',
  317. 'gl': 'glg',
  318. 'gn': 'grn',
  319. 'gu': 'guj',
  320. 'gv': 'glv',
  321. 'ha': 'hau',
  322. 'he': 'heb',
  323. 'hi': 'hin',
  324. 'ho': 'hmo',
  325. 'hr': 'hrv',
  326. 'ht': 'hat',
  327. 'hu': 'hun',
  328. 'hy': 'hye',
  329. 'hz': 'her',
  330. 'ia': 'ina',
  331. 'id': 'ind',
  332. 'ie': 'ile',
  333. 'ig': 'ibo',
  334. 'ii': 'iii',
  335. 'ik': 'ipk',
  336. 'io': 'ido',
  337. 'is': 'isl',
  338. 'it': 'ita',
  339. 'iu': 'iku',
  340. 'ja': 'jpn',
  341. 'jv': 'jav',
  342. 'ka': 'kat',
  343. 'kg': 'kon',
  344. 'ki': 'kik',
  345. 'kj': 'kua',
  346. 'kk': 'kaz',
  347. 'kl': 'kal',
  348. 'km': 'khm',
  349. 'kn': 'kan',
  350. 'ko': 'kor',
  351. 'kr': 'kau',
  352. 'ks': 'kas',
  353. 'ku': 'kur',
  354. 'kv': 'kom',
  355. 'kw': 'cor',
  356. 'ky': 'kir',
  357. 'la': 'lat',
  358. 'lb': 'ltz',
  359. 'lg': 'lug',
  360. 'li': 'lim',
  361. 'ln': 'lin',
  362. 'lo': 'lao',
  363. 'lt': 'lit',
  364. 'lu': 'lub',
  365. 'lv': 'lav',
  366. 'mg': 'mlg',
  367. 'mh': 'mah',
  368. 'mi': 'mri',
  369. 'mk': 'mkd',
  370. 'ml': 'mal',
  371. 'mn': 'mon',
  372. 'mr': 'mar',
  373. 'ms': 'msa',
  374. 'mt': 'mlt',
  375. 'my': 'mya',
  376. 'na': 'nau',
  377. 'nb': 'nob',
  378. 'nd': 'nde',
  379. 'ne': 'nep',
  380. 'ng': 'ndo',
  381. 'nl': 'nld',
  382. 'nn': 'nno',
  383. 'no': 'nor',
  384. 'nr': 'nbl',
  385. 'nv': 'nav',
  386. 'ny': 'nya',
  387. 'oc': 'oci',
  388. 'oj': 'oji',
  389. 'om': 'orm',
  390. 'or': 'ori',
  391. 'os': 'oss',
  392. 'pa': 'pan',
  393. 'pi': 'pli',
  394. 'pl': 'pol',
  395. 'ps': 'pus',
  396. 'pt': 'por',
  397. 'qu': 'que',
  398. 'rm': 'roh',
  399. 'rn': 'run',
  400. 'ro': 'ron',
  401. 'ru': 'rus',
  402. 'rw': 'kin',
  403. 'sa': 'san',
  404. 'sc': 'srd',
  405. 'sd': 'snd',
  406. 'se': 'sme',
  407. 'sg': 'sag',
  408. 'si': 'sin',
  409. 'sk': 'slk',
  410. 'sl': 'slv',
  411. 'sm': 'smo',
  412. 'sn': 'sna',
  413. 'so': 'som',
  414. 'sq': 'sqi',
  415. 'sr': 'srp',
  416. 'ss': 'ssw',
  417. 'st': 'sot',
  418. 'su': 'sun',
  419. 'sv': 'swe',
  420. 'sw': 'swa',
  421. 'ta': 'tam',
  422. 'te': 'tel',
  423. 'tg': 'tgk',
  424. 'th': 'tha',
  425. 'ti': 'tir',
  426. 'tk': 'tuk',
  427. 'tl': 'tgl',
  428. 'tn': 'tsn',
  429. 'to': 'ton',
  430. 'tr': 'tur',
  431. 'ts': 'tso',
  432. 'tt': 'tat',
  433. 'tw': 'twi',
  434. 'ty': 'tah',
  435. 'ug': 'uig',
  436. 'uk': 'ukr',
  437. 'ur': 'urd',
  438. 'uz': 'uzb',
  439. 've': 'ven',
  440. 'vi': 'vie',
  441. 'vo': 'vol',
  442. 'wa': 'wln',
  443. 'wo': 'wol',
  444. 'xh': 'xho',
  445. 'yi': 'yid',
  446. 'yo': 'yor',
  447. 'za': 'zha',
  448. 'zh': 'zho',
  449. 'zu': 'zul',
  450. }
  451. @classmethod
  452. def _conver_lang_code(cls, code):
  453. """Convert language code from ISO 639-1 to ISO 639-2/T"""
  454. return cls._lang_map.get(code[:2])
  455. def run(self, information):
  456. if information['ext'] != 'mp4':
  457. self._downloader.to_screen('[ffmpeg] Subtitles can only be embedded in mp4 files')
  458. return [], information
  459. subtitles = information.get('requested_subtitles')
  460. if not subtitles:
  461. self._downloader.to_screen('[ffmpeg] There aren\'t any subtitles to embed')
  462. return [], information
  463. sub_langs = list(subtitles.keys())
  464. filename = information['filepath']
  465. sub_filenames = [subtitles_filename(filename, lang, sub_info['ext']) for lang, sub_info in subtitles.items()]
  466. input_files = [filename] + sub_filenames
  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 sub_filenames, 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 [], 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 [], info
  522. class FFmpegMergerPP(FFmpegPostProcessor):
  523. def run(self, info):
  524. filename = info['filepath']
  525. temp_filename = prepend_extension(filename, 'temp')
  526. args = ['-c', 'copy', '-map', '0:v:0', '-map', '1:a:0']
  527. self._downloader.to_screen('[ffmpeg] Merging formats into "%s"' % filename)
  528. self.run_ffmpeg_multiple_files(info['__files_to_merge'], temp_filename, args)
  529. os.rename(encodeFilename(temp_filename), encodeFilename(filename))
  530. return info['__files_to_merge'], info
  531. class FFmpegFixupStretchedPP(FFmpegPostProcessor):
  532. def run(self, info):
  533. stretched_ratio = info.get('stretched_ratio')
  534. if stretched_ratio is None or stretched_ratio == 1:
  535. return [], info
  536. filename = info['filepath']
  537. temp_filename = prepend_extension(filename, 'temp')
  538. options = ['-c', 'copy', '-aspect', '%f' % stretched_ratio]
  539. self._downloader.to_screen('[ffmpeg] Fixing aspect ratio in "%s"' % filename)
  540. self.run_ffmpeg(filename, temp_filename, options)
  541. os.remove(encodeFilename(filename))
  542. os.rename(encodeFilename(temp_filename), encodeFilename(filename))
  543. return [], info
  544. class FFmpegFixupM4aPP(FFmpegPostProcessor):
  545. def run(self, info):
  546. if info.get('container') != 'm4a_dash':
  547. return [], info
  548. filename = info['filepath']
  549. temp_filename = prepend_extension(filename, 'temp')
  550. options = ['-c', 'copy', '-f', 'mp4']
  551. self._downloader.to_screen('[ffmpeg] Correcting container in "%s"' % filename)
  552. self.run_ffmpeg(filename, temp_filename, options)
  553. os.remove(encodeFilename(filename))
  554. os.rename(encodeFilename(temp_filename), encodeFilename(filename))
  555. return [], info
  556. class FFmpegSubtitlesConvertorPP(FFmpegPostProcessor):
  557. def __init__(self, downloader=None, format=None):
  558. super(FFmpegSubtitlesConvertorPP, self).__init__(downloader)
  559. self.format = format
  560. def run(self, info):
  561. subs = info.get('requested_subtitles')
  562. filename = info['filepath']
  563. new_ext = self.format
  564. new_format = new_ext
  565. if new_format == 'vtt':
  566. new_format = 'webvtt'
  567. if subs is None:
  568. self._downloader.to_screen('[ffmpeg] There aren\'t any subtitles to convert')
  569. return [], info
  570. self._downloader.to_screen('[ffmpeg] Converting subtitles')
  571. for lang, sub in subs.items():
  572. ext = sub['ext']
  573. if ext == new_ext:
  574. self._downloader.to_screen(
  575. '[ffmpeg] Subtitle file for %s is already in the requested'
  576. 'format' % new_ext)
  577. continue
  578. new_file = subtitles_filename(filename, lang, new_ext)
  579. if ext == 'dfxp' or ext == 'ttml':
  580. self._downloader.report_warning(
  581. 'You have requested to convert dfxp (TTML) subtitles into another format, '
  582. 'which results in style information loss')
  583. dfxp_file = subtitles_filename(filename, lang, ext)
  584. srt_file = subtitles_filename(filename, lang, 'srt')
  585. with io.open(dfxp_file, 'rt', encoding='utf-8') as f:
  586. srt_data = dfxp2srt(f.read())
  587. with io.open(srt_file, 'wt', encoding='utf-8') as f:
  588. f.write(srt_data)
  589. ext = 'srt'
  590. subs[lang] = {
  591. 'ext': 'srt',
  592. 'data': srt_data
  593. }
  594. if new_ext == 'srt':
  595. continue
  596. self.run_ffmpeg(
  597. subtitles_filename(filename, lang, ext),
  598. new_file, ['-f', new_format])
  599. with io.open(new_file, 'rt', encoding='utf-8') as f:
  600. subs[lang] = {
  601. 'ext': ext,
  602. 'data': f.read(),
  603. }
  604. return [], info