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.

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