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.

646 lines
25 KiB

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. import re
  7. from .common import AudioConversionError, PostProcessor
  8. from ..utils import (
  9. encodeArgument,
  10. encodeFilename,
  11. get_exe_version,
  12. is_outdated_version,
  13. PostProcessingError,
  14. prepend_extension,
  15. shell_quote,
  16. subtitles_filename,
  17. dfxp2srt,
  18. ISO639Utils,
  19. replace_extension,
  20. )
  21. EXT_TO_OUT_FORMATS = {
  22. 'aac': 'adts',
  23. 'flac': 'flac',
  24. 'm4a': 'ipod',
  25. 'mka': 'matroska',
  26. 'mkv': 'matroska',
  27. 'mpg': 'mpeg',
  28. 'ogv': 'ogg',
  29. 'ts': 'mpegts',
  30. 'wma': 'asf',
  31. 'wmv': 'asf',
  32. }
  33. ACODECS = {
  34. 'mp3': 'libmp3lame',
  35. 'aac': 'aac',
  36. 'flac': 'flac',
  37. 'm4a': 'aac',
  38. 'opus': 'libopus',
  39. 'vorbis': 'libvorbis',
  40. 'wav': None,
  41. }
  42. class FFmpegPostProcessorError(PostProcessingError):
  43. pass
  44. class FFmpegPostProcessor(PostProcessor):
  45. def __init__(self, downloader=None):
  46. PostProcessor.__init__(self, downloader)
  47. self._determine_executables()
  48. def check_version(self):
  49. if not self.available:
  50. raise FFmpegPostProcessorError('ffmpeg or avconv not found. Please install one.')
  51. required_version = '10-0' if self.basename == 'avconv' else '1.0'
  52. if is_outdated_version(
  53. self._versions[self.basename], required_version):
  54. warning = 'Your copy of %s is outdated, update %s to version %s or newer if you encounter any errors.' % (
  55. self.basename, self.basename, required_version)
  56. if self._downloader:
  57. self._downloader.report_warning(warning)
  58. @staticmethod
  59. def get_versions(downloader=None):
  60. return FFmpegPostProcessor(downloader)._versions
  61. def _determine_executables(self):
  62. programs = ['avprobe', 'avconv', 'ffmpeg', 'ffprobe']
  63. prefer_ffmpeg = True
  64. def get_ffmpeg_version(path):
  65. ver = get_exe_version(path, args=['-version'])
  66. if ver:
  67. regexs = [
  68. r'(?:\d+:)?([0-9.]+)-[0-9]+ubuntu[0-9.]+$', # Ubuntu, see [1]
  69. r'n([0-9.]+)$', # Arch Linux
  70. # 1. http://www.ducea.com/2006/06/17/ubuntu-package-version-naming-explanation/
  71. ]
  72. for regex in regexs:
  73. mobj = re.match(regex, ver)
  74. if mobj:
  75. ver = mobj.group(1)
  76. return ver
  77. self.basename = None
  78. self.probe_basename = None
  79. self._paths = None
  80. self._versions = None
  81. if self._downloader:
  82. prefer_ffmpeg = self._downloader.params.get('prefer_ffmpeg', True)
  83. location = self._downloader.params.get('ffmpeg_location')
  84. if location is not None:
  85. if not os.path.exists(location):
  86. self._downloader.report_warning(
  87. 'ffmpeg-location %s does not exist! '
  88. 'Continuing without avconv/ffmpeg.' % (location))
  89. self._versions = {}
  90. return
  91. elif not os.path.isdir(location):
  92. basename = os.path.splitext(os.path.basename(location))[0]
  93. if basename not in programs:
  94. self._downloader.report_warning(
  95. 'Cannot identify executable %s, its basename should be one of %s. '
  96. 'Continuing without avconv/ffmpeg.' %
  97. (location, ', '.join(programs)))
  98. self._versions = {}
  99. return None
  100. location = os.path.dirname(os.path.abspath(location))
  101. if basename in ('ffmpeg', 'ffprobe'):
  102. prefer_ffmpeg = True
  103. self._paths = dict(
  104. (p, os.path.join(location, p)) for p in programs)
  105. self._versions = dict(
  106. (p, get_ffmpeg_version(self._paths[p])) for p in programs)
  107. if self._versions is None:
  108. self._versions = dict(
  109. (p, get_ffmpeg_version(p)) for p in programs)
  110. self._paths = dict((p, p) for p in programs)
  111. if prefer_ffmpeg is False:
  112. prefs = ('avconv', 'ffmpeg')
  113. else:
  114. prefs = ('ffmpeg', 'avconv')
  115. for p in prefs:
  116. if self._versions[p]:
  117. self.basename = p
  118. break
  119. if prefer_ffmpeg is False:
  120. prefs = ('avprobe', 'ffprobe')
  121. else:
  122. prefs = ('ffprobe', 'avprobe')
  123. for p in prefs:
  124. if self._versions[p]:
  125. self.probe_basename = p
  126. break
  127. @property
  128. def available(self):
  129. return self.basename is not None
  130. @property
  131. def executable(self):
  132. return self._paths[self.basename]
  133. @property
  134. def probe_available(self):
  135. return self.probe_basename is not None
  136. @property
  137. def probe_executable(self):
  138. return self._paths[self.probe_basename]
  139. def get_audio_codec(self, path):
  140. if not self.probe_available and not self.available:
  141. raise PostProcessingError('ffprobe/avprobe and ffmpeg/avconv not found. Please install one.')
  142. try:
  143. if self.probe_available:
  144. cmd = [
  145. encodeFilename(self.probe_executable, True),
  146. encodeArgument('-show_streams')]
  147. else:
  148. cmd = [
  149. encodeFilename(self.executable, True),
  150. encodeArgument('-i')]
  151. cmd.append(encodeFilename(self._ffmpeg_filename_argument(path), True))
  152. if self._downloader.params.get('verbose', False):
  153. self._downloader.to_screen(
  154. '[debug] %s command line: %s' % (self.basename, shell_quote(cmd)))
  155. handle = subprocess.Popen(
  156. cmd, stderr=subprocess.PIPE,
  157. stdout=subprocess.PIPE, stdin=subprocess.PIPE)
  158. stdout_data, stderr_data = handle.communicate()
  159. expected_ret = 0 if self.probe_available else 1
  160. if handle.wait() != expected_ret:
  161. return None
  162. except (IOError, OSError):
  163. return None
  164. output = (stdout_data if self.probe_available else stderr_data).decode('ascii', 'ignore')
  165. if self.probe_available:
  166. audio_codec = None
  167. for line in output.split('\n'):
  168. if line.startswith('codec_name='):
  169. audio_codec = line.split('=')[1].strip()
  170. elif line.strip() == 'codec_type=audio' and audio_codec is not None:
  171. return audio_codec
  172. else:
  173. # Stream #FILE_INDEX:STREAM_INDEX[STREAM_ID](LANGUAGE): CODEC_TYPE: CODEC_NAME
  174. mobj = re.search(
  175. r'Stream\s*#\d+:\d+(?:\[0x[0-9a-f]+\])?(?:\([a-z]{3}\))?:\s*Audio:\s*([0-9a-z]+)',
  176. output)
  177. if mobj:
  178. return mobj.group(1)
  179. return None
  180. def run_ffmpeg_multiple_files(self, input_paths, out_path, opts):
  181. self.check_version()
  182. oldest_mtime = min(
  183. os.stat(encodeFilename(path)).st_mtime for path in input_paths)
  184. opts += self._configuration_args()
  185. files_cmd = []
  186. for path in input_paths:
  187. files_cmd.extend([
  188. encodeArgument('-i'),
  189. encodeFilename(self._ffmpeg_filename_argument(path), True)
  190. ])
  191. cmd = [encodeFilename(self.executable, True), encodeArgument('-y')]
  192. # avconv does not have repeat option
  193. if self.basename == 'ffmpeg':
  194. cmd += [encodeArgument('-loglevel'), encodeArgument('repeat+info')]
  195. cmd += (files_cmd
  196. + [encodeArgument(o) for o in opts]
  197. + [encodeFilename(self._ffmpeg_filename_argument(out_path), True)])
  198. if self._downloader.params.get('verbose', False):
  199. self._downloader.to_screen('[debug] ffmpeg command line: %s' % shell_quote(cmd))
  200. p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE)
  201. stdout, stderr = p.communicate()
  202. if p.returncode != 0:
  203. stderr = stderr.decode('utf-8', 'replace')
  204. msg = stderr.strip().split('\n')[-1]
  205. raise FFmpegPostProcessorError(msg)
  206. self.try_utime(out_path, oldest_mtime, oldest_mtime)
  207. def run_ffmpeg(self, path, out_path, opts):
  208. self.run_ffmpeg_multiple_files([path], out_path, opts)
  209. def _ffmpeg_filename_argument(self, fn):
  210. # Always use 'file:' because the filename may contain ':' (ffmpeg
  211. # interprets that as a protocol) or can start with '-' (-- is broken in
  212. # ffmpeg, see https://ffmpeg.org/trac/ffmpeg/ticket/2127 for details)
  213. # Also leave '-' intact in order not to break streaming to stdout.
  214. return 'file:' + fn if fn != '-' else fn
  215. class FFmpegExtractAudioPP(FFmpegPostProcessor):
  216. def __init__(self, downloader=None, preferredcodec=None, preferredquality=None, nopostoverwrites=False):
  217. FFmpegPostProcessor.__init__(self, downloader)
  218. if preferredcodec is None:
  219. preferredcodec = 'best'
  220. self._preferredcodec = preferredcodec
  221. self._preferredquality = preferredquality
  222. self._nopostoverwrites = nopostoverwrites
  223. def run_ffmpeg(self, path, out_path, codec, more_opts):
  224. if codec is None:
  225. acodec_opts = []
  226. else:
  227. acodec_opts = ['-acodec', codec]
  228. opts = ['-vn'] + acodec_opts + more_opts
  229. try:
  230. FFmpegPostProcessor.run_ffmpeg(self, path, out_path, opts)
  231. except FFmpegPostProcessorError as err:
  232. raise AudioConversionError(err.msg)
  233. def run(self, information):
  234. path = information['filepath']
  235. filecodec = self.get_audio_codec(path)
  236. if filecodec is None:
  237. raise PostProcessingError('WARNING: unable to obtain file audio codec with ffprobe')
  238. more_opts = []
  239. if self._preferredcodec == 'best' or self._preferredcodec == filecodec or (self._preferredcodec == 'm4a' and filecodec == 'aac'):
  240. if filecodec == 'aac' and self._preferredcodec in ['m4a', 'best']:
  241. # Lossless, but in another container
  242. acodec = 'copy'
  243. extension = 'm4a'
  244. more_opts = ['-bsf:a', 'aac_adtstoasc']
  245. elif filecodec in ['aac', 'flac', 'mp3', 'vorbis', 'opus']:
  246. # Lossless if possible
  247. acodec = 'copy'
  248. extension = filecodec
  249. if filecodec == 'aac':
  250. more_opts = ['-f', 'adts']
  251. if filecodec == 'vorbis':
  252. extension = 'ogg'
  253. else:
  254. # MP3 otherwise.
  255. acodec = 'libmp3lame'
  256. extension = 'mp3'
  257. more_opts = []
  258. if self._preferredquality is not None:
  259. if int(self._preferredquality) < 10:
  260. more_opts += ['-q:a', self._preferredquality]
  261. else:
  262. more_opts += ['-b:a', self._preferredquality + 'k']
  263. else:
  264. # We convert the audio (lossy if codec is lossy)
  265. acodec = ACODECS[self._preferredcodec]
  266. extension = self._preferredcodec
  267. more_opts = []
  268. if self._preferredquality is not None:
  269. # The opus codec doesn't support the -aq option
  270. if int(self._preferredquality) < 10 and extension != 'opus':
  271. more_opts += ['-q:a', self._preferredquality]
  272. else:
  273. more_opts += ['-b:a', self._preferredquality + 'k']
  274. if self._preferredcodec == 'aac':
  275. more_opts += ['-f', 'adts']
  276. if self._preferredcodec == 'm4a':
  277. more_opts += ['-bsf:a', 'aac_adtstoasc']
  278. if self._preferredcodec == 'vorbis':
  279. extension = 'ogg'
  280. if self._preferredcodec == 'wav':
  281. extension = 'wav'
  282. more_opts += ['-f', 'wav']
  283. prefix, sep, ext = path.rpartition('.') # not os.path.splitext, since the latter does not work on unicode in all setups
  284. new_path = prefix + sep + extension
  285. information['filepath'] = new_path
  286. information['ext'] = extension
  287. # If we download foo.mp3 and convert it to... foo.mp3, then don't delete foo.mp3, silly.
  288. if (new_path == path
  289. or (self._nopostoverwrites and os.path.exists(encodeFilename(new_path)))):
  290. self._downloader.to_screen('[ffmpeg] Post-process file %s exists, skipping' % new_path)
  291. return [], information
  292. try:
  293. self._downloader.to_screen('[ffmpeg] Destination: ' + new_path)
  294. self.run_ffmpeg(path, new_path, acodec, more_opts)
  295. except AudioConversionError as e:
  296. raise PostProcessingError(
  297. 'audio conversion failed: ' + e.msg)
  298. except Exception:
  299. raise PostProcessingError('error running ' + self.basename)
  300. # Try to update the date time for extracted audio file.
  301. if information.get('filetime') is not None:
  302. self.try_utime(
  303. new_path, time.time(), information['filetime'],
  304. errnote='Cannot update utime of audio file')
  305. return [path], information
  306. class FFmpegVideoConvertorPP(FFmpegPostProcessor):
  307. def __init__(self, downloader=None, preferedformat=None):
  308. super(FFmpegVideoConvertorPP, self).__init__(downloader)
  309. self._preferedformat = preferedformat
  310. def run(self, information):
  311. path = information['filepath']
  312. if information['ext'] == self._preferedformat:
  313. self._downloader.to_screen('[ffmpeg] Not converting video file %s - already is in target format %s' % (path, self._preferedformat))
  314. return [], information
  315. options = []
  316. if self._preferedformat == 'avi':
  317. options.extend(['-c:v', 'libxvid', '-vtag', 'XVID'])
  318. prefix, sep, ext = path.rpartition('.')
  319. outpath = prefix + sep + self._preferedformat
  320. self._downloader.to_screen('[' + 'ffmpeg' + '] Converting video from %s to %s, Destination: ' % (information['ext'], self._preferedformat) + outpath)
  321. self.run_ffmpeg(path, outpath, options)
  322. information['filepath'] = outpath
  323. information['format'] = self._preferedformat
  324. information['ext'] = self._preferedformat
  325. return [path], information
  326. class FFmpegEmbedSubtitlePP(FFmpegPostProcessor):
  327. def run(self, information):
  328. if information['ext'] not in ('mp4', 'webm', 'mkv'):
  329. self._downloader.to_screen('[ffmpeg] Subtitles can only be embedded in mp4, webm or mkv files')
  330. return [], information
  331. subtitles = information.get('requested_subtitles')
  332. if not subtitles:
  333. self._downloader.to_screen('[ffmpeg] There aren\'t any subtitles to embed')
  334. return [], information
  335. filename = information['filepath']
  336. ext = information['ext']
  337. sub_langs = []
  338. sub_filenames = []
  339. webm_vtt_warn = False
  340. for lang, sub_info in subtitles.items():
  341. sub_ext = sub_info['ext']
  342. if ext != 'webm' or ext == 'webm' and sub_ext == 'vtt':
  343. sub_langs.append(lang)
  344. sub_filenames.append(subtitles_filename(filename, lang, sub_ext, ext))
  345. else:
  346. if not webm_vtt_warn and ext == 'webm' and sub_ext != 'vtt':
  347. webm_vtt_warn = True
  348. self._downloader.to_screen('[ffmpeg] Only WebVTT subtitles can be embedded in webm files')
  349. if not sub_langs:
  350. return [], information
  351. input_files = [filename] + sub_filenames
  352. opts = [
  353. '-map', '0',
  354. '-c', 'copy',
  355. # Don't copy the existing subtitles, we may be running the
  356. # postprocessor a second time
  357. '-map', '-0:s',
  358. # Don't copy Apple TV chapters track, bin_data (see #19042, #19024,
  359. # https://trac.ffmpeg.org/ticket/6016)
  360. '-map', '-0:d',
  361. ]
  362. if information['ext'] == 'mp4':
  363. opts += ['-c:s', 'mov_text']
  364. for (i, lang) in enumerate(sub_langs):
  365. opts.extend(['-map', '%d:0' % (i + 1)])
  366. lang_code = ISO639Utils.short2long(lang) or lang
  367. opts.extend(['-metadata:s:s:%d' % i, 'language=%s' % lang_code])
  368. temp_filename = prepend_extension(filename, 'temp')
  369. self._downloader.to_screen('[ffmpeg] Embedding subtitles in \'%s\'' % filename)
  370. self.run_ffmpeg_multiple_files(input_files, temp_filename, opts)
  371. os.remove(encodeFilename(filename))
  372. os.rename(encodeFilename(temp_filename), encodeFilename(filename))
  373. return sub_filenames, information
  374. class FFmpegMetadataPP(FFmpegPostProcessor):
  375. def run(self, info):
  376. metadata = {}
  377. def add(meta_list, info_list=None):
  378. if not info_list:
  379. info_list = meta_list
  380. if not isinstance(meta_list, (list, tuple)):
  381. meta_list = (meta_list,)
  382. if not isinstance(info_list, (list, tuple)):
  383. info_list = (info_list,)
  384. for info_f in info_list:
  385. if info.get(info_f) is not None:
  386. for meta_f in meta_list:
  387. metadata[meta_f] = info[info_f]
  388. break
  389. add('title', ('track', 'title'))
  390. add('date', 'upload_date')
  391. add(('description', 'comment'), 'description')
  392. add('purl', 'webpage_url')
  393. add('track', 'track_number')
  394. add('artist', ('artist', 'creator', 'uploader', 'uploader_id'))
  395. add('genre')
  396. add('album')
  397. add('album_artist')
  398. add('disc', 'disc_number')
  399. if not metadata:
  400. self._downloader.to_screen('[ffmpeg] There isn\'t any metadata to add')
  401. return [], info
  402. filename = info['filepath']
  403. temp_filename = prepend_extension(filename, 'temp')
  404. in_filenames = [filename]
  405. options = []
  406. if info['ext'] == 'm4a':
  407. options.extend(['-vn', '-acodec', 'copy'])
  408. else:
  409. options.extend(['-c', 'copy'])
  410. for (name, value) in metadata.items():
  411. options.extend(['-metadata', '%s=%s' % (name, value)])
  412. chapters = info.get('chapters', [])
  413. if chapters:
  414. metadata_filename = replace_extension(filename, 'meta')
  415. with io.open(metadata_filename, 'wt', encoding='utf-8') as f:
  416. def ffmpeg_escape(text):
  417. return re.sub(r'(=|;|#|\\|\n)', r'\\\1', text)
  418. metadata_file_content = ';FFMETADATA1\n'
  419. for chapter in chapters:
  420. metadata_file_content += '[CHAPTER]\nTIMEBASE=1/1000\n'
  421. metadata_file_content += 'START=%d\n' % (chapter['start_time'] * 1000)
  422. metadata_file_content += 'END=%d\n' % (chapter['end_time'] * 1000)
  423. chapter_title = chapter.get('title')
  424. if chapter_title:
  425. metadata_file_content += 'title=%s\n' % ffmpeg_escape(chapter_title)
  426. f.write(metadata_file_content)
  427. in_filenames.append(metadata_filename)
  428. options.extend(['-map_metadata', '1'])
  429. self._downloader.to_screen('[ffmpeg] Adding metadata to \'%s\'' % filename)
  430. self.run_ffmpeg_multiple_files(in_filenames, temp_filename, options)
  431. if chapters:
  432. os.remove(metadata_filename)
  433. os.remove(encodeFilename(filename))
  434. os.rename(encodeFilename(temp_filename), encodeFilename(filename))
  435. return [], info
  436. class FFmpegMergerPP(FFmpegPostProcessor):
  437. def run(self, info):
  438. filename = info['filepath']
  439. temp_filename = prepend_extension(filename, 'temp')
  440. args = ['-c', 'copy', '-map', '0:v:0', '-map', '1:a:0']
  441. self._downloader.to_screen('[ffmpeg] Merging formats into "%s"' % filename)
  442. self.run_ffmpeg_multiple_files(info['__files_to_merge'], temp_filename, args)
  443. os.rename(encodeFilename(temp_filename), encodeFilename(filename))
  444. return info['__files_to_merge'], info
  445. def can_merge(self):
  446. # TODO: figure out merge-capable ffmpeg version
  447. if self.basename != 'avconv':
  448. return True
  449. required_version = '10-0'
  450. if is_outdated_version(
  451. self._versions[self.basename], required_version):
  452. warning = ('Your copy of %s is outdated and unable to properly mux separate video and audio files, '
  453. 'youtube-dl will download single file media. '
  454. 'Update %s to version %s or newer to fix this.') % (
  455. self.basename, self.basename, required_version)
  456. if self._downloader:
  457. self._downloader.report_warning(warning)
  458. return False
  459. return True
  460. class FFmpegFixupStretchedPP(FFmpegPostProcessor):
  461. def run(self, info):
  462. stretched_ratio = info.get('stretched_ratio')
  463. if stretched_ratio is None or stretched_ratio == 1:
  464. return [], info
  465. filename = info['filepath']
  466. temp_filename = prepend_extension(filename, 'temp')
  467. options = ['-c', 'copy', '-aspect', '%f' % stretched_ratio]
  468. self._downloader.to_screen('[ffmpeg] Fixing aspect ratio in "%s"' % filename)
  469. self.run_ffmpeg(filename, temp_filename, options)
  470. os.remove(encodeFilename(filename))
  471. os.rename(encodeFilename(temp_filename), encodeFilename(filename))
  472. return [], info
  473. class FFmpegFixupM4aPP(FFmpegPostProcessor):
  474. def run(self, info):
  475. if info.get('container') != 'm4a_dash':
  476. return [], info
  477. filename = info['filepath']
  478. temp_filename = prepend_extension(filename, 'temp')
  479. options = ['-c', 'copy', '-f', 'mp4']
  480. self._downloader.to_screen('[ffmpeg] Correcting container in "%s"' % filename)
  481. self.run_ffmpeg(filename, temp_filename, options)
  482. os.remove(encodeFilename(filename))
  483. os.rename(encodeFilename(temp_filename), encodeFilename(filename))
  484. return [], info
  485. class FFmpegFixupM3u8PP(FFmpegPostProcessor):
  486. def run(self, info):
  487. filename = info['filepath']
  488. if self.get_audio_codec(filename) == 'aac':
  489. temp_filename = prepend_extension(filename, 'temp')
  490. options = ['-c', 'copy', '-f', 'mp4', '-bsf:a', 'aac_adtstoasc']
  491. self._downloader.to_screen('[ffmpeg] Fixing malformed AAC bitstream in "%s"' % filename)
  492. self.run_ffmpeg(filename, temp_filename, options)
  493. os.remove(encodeFilename(filename))
  494. os.rename(encodeFilename(temp_filename), encodeFilename(filename))
  495. return [], info
  496. class FFmpegSubtitlesConvertorPP(FFmpegPostProcessor):
  497. def __init__(self, downloader=None, format=None):
  498. super(FFmpegSubtitlesConvertorPP, self).__init__(downloader)
  499. self.format = format
  500. def run(self, info):
  501. subs = info.get('requested_subtitles')
  502. filename = info['filepath']
  503. new_ext = self.format
  504. new_format = new_ext
  505. if new_format == 'vtt':
  506. new_format = 'webvtt'
  507. if subs is None:
  508. self._downloader.to_screen('[ffmpeg] There aren\'t any subtitles to convert')
  509. return [], info
  510. self._downloader.to_screen('[ffmpeg] Converting subtitles')
  511. sub_filenames = []
  512. for lang, sub in subs.items():
  513. ext = sub['ext']
  514. if ext == new_ext:
  515. self._downloader.to_screen(
  516. '[ffmpeg] Subtitle file for %s is already in the requested format' % new_ext)
  517. continue
  518. old_file = subtitles_filename(filename, lang, ext, info.get('ext'))
  519. sub_filenames.append(old_file)
  520. new_file = subtitles_filename(filename, lang, new_ext, info.get('ext'))
  521. if ext in ('dfxp', 'ttml', 'tt'):
  522. self._downloader.report_warning(
  523. 'You have requested to convert dfxp (TTML) subtitles into another format, '
  524. 'which results in style information loss')
  525. dfxp_file = old_file
  526. srt_file = subtitles_filename(filename, lang, 'srt', info.get('ext'))
  527. with open(dfxp_file, 'rb') as f:
  528. srt_data = dfxp2srt(f.read())
  529. with io.open(srt_file, 'wt', encoding='utf-8') as f:
  530. f.write(srt_data)
  531. old_file = srt_file
  532. subs[lang] = {
  533. 'ext': 'srt',
  534. 'data': srt_data
  535. }
  536. if new_ext == 'srt':
  537. continue
  538. else:
  539. sub_filenames.append(srt_file)
  540. self.run_ffmpeg(old_file, new_file, ['-f', new_format])
  541. with io.open(new_file, 'rt', encoding='utf-8') as f:
  542. subs[lang] = {
  543. 'ext': new_ext,
  544. 'data': f.read(),
  545. }
  546. return sub_filenames, info