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.

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