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.

524 lines
20 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. ISO639Utils,
  21. )
  22. class FFmpegPostProcessorError(PostProcessingError):
  23. pass
  24. class FFmpegPostProcessor(PostProcessor):
  25. def __init__(self, downloader=None):
  26. PostProcessor.__init__(self, downloader)
  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 = False
  44. self.basename = None
  45. self.probe_basename = None
  46. self._paths = None
  47. self._versions = None
  48. if self._downloader:
  49. prefer_ffmpeg = self._downloader.params.get('prefer_ffmpeg', False)
  50. location = self._downloader.params.get('ffmpeg_location')
  51. if location is not None:
  52. if not os.path.exists(location):
  53. self._downloader.report_warning(
  54. 'ffmpeg-location %s does not exist! '
  55. 'Continuing without avconv/ffmpeg.' % (location))
  56. self._versions = {}
  57. return
  58. elif not os.path.isdir(location):
  59. basename = os.path.splitext(os.path.basename(location))[0]
  60. if basename not in programs:
  61. self._downloader.report_warning(
  62. 'Cannot identify executable %s, its basename should be one of %s. '
  63. 'Continuing without avconv/ffmpeg.' %
  64. (location, ', '.join(programs)))
  65. self._versions = {}
  66. return None
  67. location = os.path.dirname(os.path.abspath(location))
  68. if basename in ('ffmpeg', 'ffprobe'):
  69. prefer_ffmpeg = True
  70. self._paths = dict(
  71. (p, os.path.join(location, p)) for p in programs)
  72. self._versions = dict(
  73. (p, get_exe_version(self._paths[p], args=['-version']))
  74. for p in programs)
  75. if self._versions is None:
  76. self._versions = dict(
  77. (p, get_exe_version(p, args=['-version'])) for p in programs)
  78. self._paths = dict((p, p) for p in programs)
  79. if prefer_ffmpeg:
  80. prefs = ('ffmpeg', 'avconv')
  81. else:
  82. prefs = ('avconv', 'ffmpeg')
  83. for p in prefs:
  84. if self._versions[p]:
  85. self.basename = p
  86. break
  87. if prefer_ffmpeg:
  88. prefs = ('ffprobe', 'avprobe')
  89. else:
  90. prefs = ('avprobe', 'ffprobe')
  91. for p in prefs:
  92. if self._versions[p]:
  93. self.probe_basename = p
  94. break
  95. @property
  96. def available(self):
  97. return self.basename is not None
  98. @property
  99. def executable(self):
  100. return self._paths[self.basename]
  101. @property
  102. def probe_available(self):
  103. return self.probe_basename is not None
  104. @property
  105. def probe_executable(self):
  106. return self._paths[self.probe_basename]
  107. def run_ffmpeg_multiple_files(self, input_paths, out_path, opts):
  108. self.check_version()
  109. oldest_mtime = min(
  110. os.stat(encodeFilename(path)).st_mtime for path in input_paths)
  111. opts += self._configuration_args()
  112. files_cmd = []
  113. for path in input_paths:
  114. files_cmd.extend([
  115. encodeArgument('-i'),
  116. encodeFilename(self._ffmpeg_filename_argument(path), True)
  117. ])
  118. cmd = ([encodeFilename(self.executable, True), encodeArgument('-y')] +
  119. files_cmd +
  120. [encodeArgument(o) for o in opts] +
  121. [encodeFilename(self._ffmpeg_filename_argument(out_path), True)])
  122. if self._downloader.params.get('verbose', False):
  123. self._downloader.to_screen('[debug] ffmpeg command line: %s' % shell_quote(cmd))
  124. p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE)
  125. stdout, stderr = p.communicate()
  126. if p.returncode != 0:
  127. stderr = stderr.decode('utf-8', 'replace')
  128. msg = stderr.strip().split('\n')[-1]
  129. raise FFmpegPostProcessorError(msg)
  130. self.try_utime(out_path, oldest_mtime, oldest_mtime)
  131. def run_ffmpeg(self, path, out_path, opts):
  132. self.run_ffmpeg_multiple_files([path], out_path, opts)
  133. def _ffmpeg_filename_argument(self, fn):
  134. # Always use 'file:' because the filename may contain ':' (ffmpeg
  135. # interprets that as a protocol) or can start with '-' (-- is broken in
  136. # ffmpeg, see https://ffmpeg.org/trac/ffmpeg/ticket/2127 for details)
  137. return 'file:' + fn
  138. class FFmpegExtractAudioPP(FFmpegPostProcessor):
  139. def __init__(self, downloader=None, preferredcodec=None, preferredquality=None, nopostoverwrites=False):
  140. FFmpegPostProcessor.__init__(self, downloader)
  141. if preferredcodec is None:
  142. preferredcodec = 'best'
  143. self._preferredcodec = preferredcodec
  144. self._preferredquality = preferredquality
  145. self._nopostoverwrites = nopostoverwrites
  146. def get_audio_codec(self, path):
  147. if not self.probe_available:
  148. raise PostProcessingError('ffprobe or avprobe not found. Please install one.')
  149. try:
  150. cmd = [
  151. encodeFilename(self.probe_executable, True),
  152. encodeArgument('-show_streams'),
  153. encodeFilename(self._ffmpeg_filename_argument(path), True)]
  154. if self._downloader.params.get('verbose', False):
  155. self._downloader.to_screen('[debug] %s command line: %s' % (self.basename, shell_quote(cmd)))
  156. handle = subprocess.Popen(cmd, stderr=compat_subprocess_get_DEVNULL(), stdout=subprocess.PIPE, stdin=subprocess.PIPE)
  157. output = handle.communicate()[0]
  158. if handle.wait() != 0:
  159. return None
  160. except (IOError, OSError):
  161. return None
  162. audio_codec = None
  163. for line in output.decode('ascii', 'ignore').split('\n'):
  164. if line.startswith('codec_name='):
  165. audio_codec = line.split('=')[1].strip()
  166. elif line.strip() == 'codec_type=audio' and audio_codec is not None:
  167. return audio_codec
  168. return None
  169. def run_ffmpeg(self, path, out_path, codec, more_opts):
  170. if codec is None:
  171. acodec_opts = []
  172. else:
  173. acodec_opts = ['-acodec', codec]
  174. opts = ['-vn'] + acodec_opts + more_opts
  175. try:
  176. FFmpegPostProcessor.run_ffmpeg(self, path, out_path, opts)
  177. except FFmpegPostProcessorError as err:
  178. raise AudioConversionError(err.msg)
  179. def run(self, information):
  180. path = information['filepath']
  181. filecodec = self.get_audio_codec(path)
  182. if filecodec is None:
  183. raise PostProcessingError('WARNING: unable to obtain file audio codec with ffprobe')
  184. more_opts = []
  185. if self._preferredcodec == 'best' or self._preferredcodec == filecodec or (self._preferredcodec == 'm4a' and filecodec == 'aac'):
  186. if filecodec == 'aac' and self._preferredcodec in ['m4a', 'best']:
  187. # Lossless, but in another container
  188. acodec = 'copy'
  189. extension = 'm4a'
  190. more_opts = ['-bsf:a', 'aac_adtstoasc']
  191. elif filecodec in ['aac', 'mp3', 'vorbis', 'opus']:
  192. # Lossless if possible
  193. acodec = 'copy'
  194. extension = filecodec
  195. if filecodec == 'aac':
  196. more_opts = ['-f', 'adts']
  197. if filecodec == 'vorbis':
  198. extension = 'ogg'
  199. else:
  200. # MP3 otherwise.
  201. acodec = 'libmp3lame'
  202. extension = 'mp3'
  203. more_opts = []
  204. if self._preferredquality is not None:
  205. if int(self._preferredquality) < 10:
  206. more_opts += ['-q:a', self._preferredquality]
  207. else:
  208. more_opts += ['-b:a', self._preferredquality + 'k']
  209. else:
  210. # We convert the audio (lossy)
  211. acodec = {'mp3': 'libmp3lame', 'aac': 'aac', 'm4a': 'aac', 'opus': 'opus', 'vorbis': 'libvorbis', 'wav': None}[self._preferredcodec]
  212. extension = self._preferredcodec
  213. more_opts = []
  214. if self._preferredquality is not None:
  215. # The opus codec doesn't support the -aq option
  216. if int(self._preferredquality) < 10 and extension != 'opus':
  217. more_opts += ['-q:a', self._preferredquality]
  218. else:
  219. more_opts += ['-b:a', self._preferredquality + 'k']
  220. if self._preferredcodec == 'aac':
  221. more_opts += ['-f', 'adts']
  222. if self._preferredcodec == 'm4a':
  223. more_opts += ['-bsf:a', 'aac_adtstoasc']
  224. if self._preferredcodec == 'vorbis':
  225. extension = 'ogg'
  226. if self._preferredcodec == 'wav':
  227. extension = 'wav'
  228. more_opts += ['-f', 'wav']
  229. prefix, sep, ext = path.rpartition('.') # not os.path.splitext, since the latter does not work on unicode in all setups
  230. new_path = prefix + sep + extension
  231. # If we download foo.mp3 and convert it to... foo.mp3, then don't delete foo.mp3, silly.
  232. if (new_path == path or
  233. (self._nopostoverwrites and os.path.exists(encodeFilename(new_path)))):
  234. self._downloader.to_screen('[ffmpeg] Post-process file %s exists, skipping' % new_path)
  235. return [], information
  236. try:
  237. self._downloader.to_screen('[ffmpeg] Destination: ' + new_path)
  238. self.run_ffmpeg(path, new_path, acodec, more_opts)
  239. except AudioConversionError as e:
  240. raise PostProcessingError(
  241. 'audio conversion failed: ' + e.msg)
  242. except Exception:
  243. raise PostProcessingError('error running ' + self.basename)
  244. # Try to update the date time for extracted audio file.
  245. if information.get('filetime') is not None:
  246. self.try_utime(
  247. new_path, time.time(), information['filetime'],
  248. errnote='Cannot update utime of audio file')
  249. information['filepath'] = new_path
  250. information['ext'] = extension
  251. return [path], information
  252. class FFmpegVideoConvertorPP(FFmpegPostProcessor):
  253. def __init__(self, downloader=None, preferedformat=None):
  254. super(FFmpegVideoConvertorPP, self).__init__(downloader)
  255. self._preferedformat = preferedformat
  256. def run(self, information):
  257. path = information['filepath']
  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 [], information
  261. options = []
  262. if self._preferedformat == 'avi':
  263. options.extend(['-c:v', 'libxvid', '-vtag', 'XVID'])
  264. prefix, sep, ext = path.rpartition('.')
  265. outpath = prefix + sep + self._preferedformat
  266. self._downloader.to_screen('[' + 'ffmpeg' + '] Converting video from %s to %s, Destination: ' % (information['ext'], self._preferedformat) + outpath)
  267. self.run_ffmpeg(path, outpath, options)
  268. information['filepath'] = outpath
  269. information['format'] = self._preferedformat
  270. information['ext'] = self._preferedformat
  271. return [path], information
  272. class FFmpegEmbedSubtitlePP(FFmpegPostProcessor):
  273. def run(self, information):
  274. if information['ext'] not in ['mp4', 'mkv']:
  275. self._downloader.to_screen('[ffmpeg] Subtitles can only be embedded in mp4 or mkv files')
  276. return [], information
  277. subtitles = information.get('requested_subtitles')
  278. if not subtitles:
  279. self._downloader.to_screen('[ffmpeg] There aren\'t any subtitles to embed')
  280. return [], information
  281. sub_langs = list(subtitles.keys())
  282. filename = information['filepath']
  283. sub_filenames = [subtitles_filename(filename, lang, sub_info['ext']) for lang, sub_info in subtitles.items()]
  284. input_files = [filename] + sub_filenames
  285. opts = [
  286. '-map', '0',
  287. '-c', 'copy',
  288. # Don't copy the existing subtitles, we may be running the
  289. # postprocessor a second time
  290. '-map', '-0:s',
  291. ]
  292. if information['ext'] == 'mp4':
  293. opts += ['-c:s', 'mov_text']
  294. for (i, lang) in enumerate(sub_langs):
  295. opts.extend(['-map', '%d:0' % (i + 1)])
  296. lang_code = ISO639Utils.short2long(lang)
  297. if lang_code is not None:
  298. opts.extend(['-metadata:s:s:%d' % i, 'language=%s' % lang_code])
  299. temp_filename = prepend_extension(filename, 'temp')
  300. self._downloader.to_screen('[ffmpeg] Embedding subtitles in \'%s\'' % filename)
  301. self.run_ffmpeg_multiple_files(input_files, temp_filename, opts)
  302. os.remove(encodeFilename(filename))
  303. os.rename(encodeFilename(temp_filename), encodeFilename(filename))
  304. return sub_filenames, information
  305. class FFmpegMetadataPP(FFmpegPostProcessor):
  306. def run(self, info):
  307. metadata = {}
  308. if info.get('title') is not None:
  309. metadata['title'] = info['title']
  310. if info.get('upload_date') is not None:
  311. metadata['date'] = info['upload_date']
  312. if info.get('artist') is not None:
  313. metadata['artist'] = info['artist']
  314. elif info.get('uploader') is not None:
  315. metadata['artist'] = info['uploader']
  316. elif info.get('uploader_id') is not None:
  317. metadata['artist'] = info['uploader_id']
  318. if info.get('description') is not None:
  319. metadata['description'] = info['description']
  320. metadata['comment'] = info['description']
  321. if info.get('webpage_url') is not None:
  322. metadata['purl'] = info['webpage_url']
  323. if info.get('album') is not None:
  324. metadata['album'] = info['album']
  325. if not metadata:
  326. self._downloader.to_screen('[ffmpeg] There isn\'t any metadata to add')
  327. return [], info
  328. filename = info['filepath']
  329. temp_filename = prepend_extension(filename, 'temp')
  330. if info['ext'] == 'm4a':
  331. options = ['-vn', '-acodec', 'copy']
  332. else:
  333. options = ['-c', 'copy']
  334. for (name, value) in metadata.items():
  335. options.extend(['-metadata', '%s=%s' % (name, value)])
  336. self._downloader.to_screen('[ffmpeg] Adding metadata to \'%s\'' % filename)
  337. self.run_ffmpeg(filename, temp_filename, options)
  338. os.remove(encodeFilename(filename))
  339. os.rename(encodeFilename(temp_filename), encodeFilename(filename))
  340. return [], info
  341. class FFmpegMergerPP(FFmpegPostProcessor):
  342. def run(self, info):
  343. filename = info['filepath']
  344. temp_filename = prepend_extension(filename, 'temp')
  345. args = ['-c', 'copy', '-map', '0:v:0', '-map', '1:a:0']
  346. self._downloader.to_screen('[ffmpeg] Merging formats into "%s"' % filename)
  347. self.run_ffmpeg_multiple_files(info['__files_to_merge'], temp_filename, args)
  348. os.rename(encodeFilename(temp_filename), encodeFilename(filename))
  349. return info['__files_to_merge'], info
  350. def can_merge(self):
  351. # TODO: figure out merge-capable ffmpeg version
  352. if self.basename != 'avconv':
  353. return True
  354. required_version = '10-0'
  355. if is_outdated_version(
  356. self._versions[self.basename], required_version):
  357. warning = ('Your copy of %s is outdated and unable to properly mux separate video and audio files, '
  358. 'youtube-dl will download single file media. '
  359. 'Update %s to version %s or newer to fix this.') % (
  360. self.basename, self.basename, required_version)
  361. if self._downloader:
  362. self._downloader.report_warning(warning)
  363. return False
  364. return True
  365. class FFmpegFixupStretchedPP(FFmpegPostProcessor):
  366. def run(self, info):
  367. stretched_ratio = info.get('stretched_ratio')
  368. if stretched_ratio is None or stretched_ratio == 1:
  369. return [], info
  370. filename = info['filepath']
  371. temp_filename = prepend_extension(filename, 'temp')
  372. options = ['-c', 'copy', '-aspect', '%f' % stretched_ratio]
  373. self._downloader.to_screen('[ffmpeg] Fixing aspect ratio in "%s"' % filename)
  374. self.run_ffmpeg(filename, temp_filename, options)
  375. os.remove(encodeFilename(filename))
  376. os.rename(encodeFilename(temp_filename), encodeFilename(filename))
  377. return [], info
  378. class FFmpegFixupM4aPP(FFmpegPostProcessor):
  379. def run(self, info):
  380. if info.get('container') != 'm4a_dash':
  381. return [], info
  382. filename = info['filepath']
  383. temp_filename = prepend_extension(filename, 'temp')
  384. options = ['-c', 'copy', '-f', 'mp4']
  385. self._downloader.to_screen('[ffmpeg] Correcting container in "%s"' % filename)
  386. self.run_ffmpeg(filename, temp_filename, options)
  387. os.remove(encodeFilename(filename))
  388. os.rename(encodeFilename(temp_filename), encodeFilename(filename))
  389. return [], info
  390. class FFmpegSubtitlesConvertorPP(FFmpegPostProcessor):
  391. def __init__(self, downloader=None, format=None):
  392. super(FFmpegSubtitlesConvertorPP, self).__init__(downloader)
  393. self.format = format
  394. def run(self, info):
  395. subs = info.get('requested_subtitles')
  396. filename = info['filepath']
  397. new_ext = self.format
  398. new_format = new_ext
  399. if new_format == 'vtt':
  400. new_format = 'webvtt'
  401. if subs is None:
  402. self._downloader.to_screen('[ffmpeg] There aren\'t any subtitles to convert')
  403. return [], info
  404. self._downloader.to_screen('[ffmpeg] Converting subtitles')
  405. for lang, sub in subs.items():
  406. ext = sub['ext']
  407. if ext == new_ext:
  408. self._downloader.to_screen(
  409. '[ffmpeg] Subtitle file for %s is already in the requested'
  410. 'format' % new_ext)
  411. continue
  412. new_file = subtitles_filename(filename, lang, new_ext)
  413. if ext == 'dfxp' or ext == 'ttml':
  414. self._downloader.report_warning(
  415. 'You have requested to convert dfxp (TTML) subtitles into another format, '
  416. 'which results in style information loss')
  417. dfxp_file = subtitles_filename(filename, lang, ext)
  418. srt_file = subtitles_filename(filename, lang, 'srt')
  419. with io.open(dfxp_file, 'rt', encoding='utf-8') as f:
  420. srt_data = dfxp2srt(f.read())
  421. with io.open(srt_file, 'wt', encoding='utf-8') as f:
  422. f.write(srt_data)
  423. ext = 'srt'
  424. subs[lang] = {
  425. 'ext': 'srt',
  426. 'data': srt_data
  427. }
  428. if new_ext == 'srt':
  429. continue
  430. self.run_ffmpeg(
  431. subtitles_filename(filename, lang, ext),
  432. new_file, ['-f', new_format])
  433. with io.open(new_file, 'rt', encoding='utf-8') as f:
  434. subs[lang] = {
  435. 'ext': ext,
  436. 'data': f.read(),
  437. }
  438. return [], info