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.

707 lines
24 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'] not in ['mp4', 'mkv']:
  457. self._downloader.to_screen('[ffmpeg] Subtitles can only be embedded in mp4 or mkv 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. ]
  474. if information['ext'] == 'mp4':
  475. opts += ['-c:s', 'mov_text']
  476. for (i, lang) in enumerate(sub_langs):
  477. opts.extend(['-map', '%d:0' % (i + 1)])
  478. lang_code = self._conver_lang_code(lang)
  479. if lang_code is not None:
  480. opts.extend(['-metadata:s:s:%d' % i, 'language=%s' % lang_code])
  481. temp_filename = prepend_extension(filename, 'temp')
  482. self._downloader.to_screen('[ffmpeg] Embedding subtitles in \'%s\'' % filename)
  483. self.run_ffmpeg_multiple_files(input_files, temp_filename, opts)
  484. os.remove(encodeFilename(filename))
  485. os.rename(encodeFilename(temp_filename), encodeFilename(filename))
  486. return sub_filenames, information
  487. class FFmpegMetadataPP(FFmpegPostProcessor):
  488. def run(self, info):
  489. metadata = {}
  490. if info.get('title') is not None:
  491. metadata['title'] = info['title']
  492. if info.get('upload_date') is not None:
  493. metadata['date'] = info['upload_date']
  494. if info.get('artist') is not None:
  495. metadata['artist'] = info['artist']
  496. elif 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 info.get('album') is not None:
  506. metadata['album'] = info['album']
  507. if not metadata:
  508. self._downloader.to_screen('[ffmpeg] There isn\'t any metadata to add')
  509. return [], info
  510. filename = info['filepath']
  511. temp_filename = prepend_extension(filename, 'temp')
  512. if info['ext'] == 'm4a':
  513. options = ['-vn', '-acodec', 'copy']
  514. else:
  515. options = ['-c', 'copy']
  516. for (name, value) in metadata.items():
  517. options.extend(['-metadata', '%s=%s' % (name, value)])
  518. self._downloader.to_screen('[ffmpeg] Adding metadata to \'%s\'' % filename)
  519. self.run_ffmpeg(filename, temp_filename, options)
  520. os.remove(encodeFilename(filename))
  521. os.rename(encodeFilename(temp_filename), encodeFilename(filename))
  522. return [], info
  523. class FFmpegMergerPP(FFmpegPostProcessor):
  524. def run(self, info):
  525. filename = info['filepath']
  526. temp_filename = prepend_extension(filename, 'temp')
  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'], temp_filename, args)
  530. os.rename(encodeFilename(temp_filename), encodeFilename(filename))
  531. return info['__files_to_merge'], info
  532. def can_merge(self):
  533. # TODO: figure out merge-capable ffmpeg version
  534. if self.basename != 'avconv':
  535. return True
  536. required_version = '10-0'
  537. if is_outdated_version(
  538. self._versions[self.basename], required_version):
  539. warning = ('Your copy of %s is outdated and unable to properly mux separate video and audio files, '
  540. 'youtube-dl will download single file media. '
  541. 'Update %s to version %s or newer to fix this.') % (
  542. self.basename, self.basename, required_version)
  543. if self._downloader:
  544. self._downloader.report_warning(warning)
  545. return False
  546. return True
  547. class FFmpegFixupStretchedPP(FFmpegPostProcessor):
  548. def run(self, info):
  549. stretched_ratio = info.get('stretched_ratio')
  550. if stretched_ratio is None or stretched_ratio == 1:
  551. return [], info
  552. filename = info['filepath']
  553. temp_filename = prepend_extension(filename, 'temp')
  554. options = ['-c', 'copy', '-aspect', '%f' % stretched_ratio]
  555. self._downloader.to_screen('[ffmpeg] Fixing aspect ratio in "%s"' % filename)
  556. self.run_ffmpeg(filename, temp_filename, options)
  557. os.remove(encodeFilename(filename))
  558. os.rename(encodeFilename(temp_filename), encodeFilename(filename))
  559. return [], info
  560. class FFmpegFixupM4aPP(FFmpegPostProcessor):
  561. def run(self, info):
  562. if info.get('container') != 'm4a_dash':
  563. return [], info
  564. filename = info['filepath']
  565. temp_filename = prepend_extension(filename, 'temp')
  566. options = ['-c', 'copy', '-f', 'mp4']
  567. self._downloader.to_screen('[ffmpeg] Correcting container in "%s"' % filename)
  568. self.run_ffmpeg(filename, temp_filename, options)
  569. os.remove(encodeFilename(filename))
  570. os.rename(encodeFilename(temp_filename), encodeFilename(filename))
  571. return [], info
  572. class FFmpegSubtitlesConvertorPP(FFmpegPostProcessor):
  573. def __init__(self, downloader=None, format=None):
  574. super(FFmpegSubtitlesConvertorPP, self).__init__(downloader)
  575. self.format = format
  576. def run(self, info):
  577. subs = info.get('requested_subtitles')
  578. filename = info['filepath']
  579. new_ext = self.format
  580. new_format = new_ext
  581. if new_format == 'vtt':
  582. new_format = 'webvtt'
  583. if subs is None:
  584. self._downloader.to_screen('[ffmpeg] There aren\'t any subtitles to convert')
  585. return [], info
  586. self._downloader.to_screen('[ffmpeg] Converting subtitles')
  587. for lang, sub in subs.items():
  588. ext = sub['ext']
  589. if ext == new_ext:
  590. self._downloader.to_screen(
  591. '[ffmpeg] Subtitle file for %s is already in the requested'
  592. 'format' % new_ext)
  593. continue
  594. new_file = subtitles_filename(filename, lang, new_ext)
  595. if ext == 'dfxp' or ext == 'ttml':
  596. self._downloader.report_warning(
  597. 'You have requested to convert dfxp (TTML) subtitles into another format, '
  598. 'which results in style information loss')
  599. dfxp_file = subtitles_filename(filename, lang, ext)
  600. srt_file = subtitles_filename(filename, lang, 'srt')
  601. with io.open(dfxp_file, 'rt', encoding='utf-8') as f:
  602. srt_data = dfxp2srt(f.read())
  603. with io.open(srt_file, 'wt', encoding='utf-8') as f:
  604. f.write(srt_data)
  605. ext = 'srt'
  606. subs[lang] = {
  607. 'ext': 'srt',
  608. 'data': srt_data
  609. }
  610. if new_ext == 'srt':
  611. continue
  612. self.run_ffmpeg(
  613. subtitles_filename(filename, lang, ext),
  614. new_file, ['-f', new_format])
  615. with io.open(new_file, 'rt', encoding='utf-8') as f:
  616. subs[lang] = {
  617. 'ext': ext,
  618. 'data': f.read(),
  619. }
  620. return [], info