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.

573 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. # Also leave '-' intact in order not to break streaming to stdout.
  149. return 'file:' + fn if fn != '-' else fn
  150. class FFmpegExtractAudioPP(FFmpegPostProcessor):
  151. def __init__(self, downloader=None, preferredcodec=None, preferredquality=None, nopostoverwrites=False):
  152. FFmpegPostProcessor.__init__(self, downloader)
  153. if preferredcodec is None:
  154. preferredcodec = 'best'
  155. self._preferredcodec = preferredcodec
  156. self._preferredquality = preferredquality
  157. self._nopostoverwrites = nopostoverwrites
  158. def get_audio_codec(self, path):
  159. if not self.probe_available:
  160. raise PostProcessingError('ffprobe or avprobe not found. Please install one.')
  161. try:
  162. cmd = [
  163. encodeFilename(self.probe_executable, True),
  164. encodeArgument('-show_streams'),
  165. encodeFilename(self._ffmpeg_filename_argument(path), True)]
  166. if self._downloader.params.get('verbose', False):
  167. self._downloader.to_screen('[debug] %s command line: %s' % (self.basename, shell_quote(cmd)))
  168. handle = subprocess.Popen(cmd, stderr=compat_subprocess_get_DEVNULL(), stdout=subprocess.PIPE, stdin=subprocess.PIPE)
  169. output = handle.communicate()[0]
  170. if handle.wait() != 0:
  171. return None
  172. except (IOError, OSError):
  173. return None
  174. audio_codec = None
  175. for line in output.decode('ascii', 'ignore').split('\n'):
  176. if line.startswith('codec_name='):
  177. audio_codec = line.split('=')[1].strip()
  178. elif line.strip() == 'codec_type=audio' and audio_codec is not None:
  179. return audio_codec
  180. return None
  181. def run_ffmpeg(self, path, out_path, codec, more_opts):
  182. if codec is None:
  183. acodec_opts = []
  184. else:
  185. acodec_opts = ['-acodec', codec]
  186. opts = ['-vn'] + acodec_opts + more_opts
  187. try:
  188. FFmpegPostProcessor.run_ffmpeg(self, path, out_path, opts)
  189. except FFmpegPostProcessorError as err:
  190. raise AudioConversionError(err.msg)
  191. def run(self, information):
  192. path = information['filepath']
  193. filecodec = self.get_audio_codec(path)
  194. if filecodec is None:
  195. raise PostProcessingError('WARNING: unable to obtain file audio codec with ffprobe')
  196. more_opts = []
  197. if self._preferredcodec == 'best' or self._preferredcodec == filecodec or (self._preferredcodec == 'm4a' and filecodec == 'aac'):
  198. if filecodec == 'aac' and self._preferredcodec in ['m4a', 'best']:
  199. # Lossless, but in another container
  200. acodec = 'copy'
  201. extension = 'm4a'
  202. more_opts = ['-bsf:a', 'aac_adtstoasc']
  203. elif filecodec in ['aac', 'mp3', 'vorbis', 'opus']:
  204. # Lossless if possible
  205. acodec = 'copy'
  206. extension = filecodec
  207. if filecodec == 'aac':
  208. more_opts = ['-f', 'adts']
  209. if filecodec == 'vorbis':
  210. extension = 'ogg'
  211. else:
  212. # MP3 otherwise.
  213. acodec = 'libmp3lame'
  214. extension = 'mp3'
  215. more_opts = []
  216. if self._preferredquality is not None:
  217. if int(self._preferredquality) < 10:
  218. more_opts += ['-q:a', self._preferredquality]
  219. else:
  220. more_opts += ['-b:a', self._preferredquality + 'k']
  221. else:
  222. # We convert the audio (lossy)
  223. acodec = {'mp3': 'libmp3lame', 'aac': 'aac', 'm4a': 'aac', 'opus': 'opus', 'vorbis': 'libvorbis', 'wav': None}[self._preferredcodec]
  224. extension = self._preferredcodec
  225. more_opts = []
  226. if self._preferredquality is not None:
  227. # The opus codec doesn't support the -aq option
  228. if int(self._preferredquality) < 10 and extension != 'opus':
  229. more_opts += ['-q:a', self._preferredquality]
  230. else:
  231. more_opts += ['-b:a', self._preferredquality + 'k']
  232. if self._preferredcodec == 'aac':
  233. more_opts += ['-f', 'adts']
  234. if self._preferredcodec == 'm4a':
  235. more_opts += ['-bsf:a', 'aac_adtstoasc']
  236. if self._preferredcodec == 'vorbis':
  237. extension = 'ogg'
  238. if self._preferredcodec == 'wav':
  239. extension = 'wav'
  240. more_opts += ['-f', 'wav']
  241. prefix, sep, ext = path.rpartition('.') # not os.path.splitext, since the latter does not work on unicode in all setups
  242. new_path = prefix + sep + extension
  243. # If we download foo.mp3 and convert it to... foo.mp3, then don't delete foo.mp3, silly.
  244. if (new_path == path or
  245. (self._nopostoverwrites and os.path.exists(encodeFilename(new_path)))):
  246. self._downloader.to_screen('[ffmpeg] Post-process file %s exists, skipping' % new_path)
  247. return [], information
  248. try:
  249. self._downloader.to_screen('[ffmpeg] Destination: ' + new_path)
  250. self.run_ffmpeg(path, new_path, acodec, more_opts)
  251. except AudioConversionError as e:
  252. raise PostProcessingError(
  253. 'audio conversion failed: ' + e.msg)
  254. except Exception:
  255. raise PostProcessingError('error running ' + self.basename)
  256. # Try to update the date time for extracted audio file.
  257. if information.get('filetime') is not None:
  258. self.try_utime(
  259. new_path, time.time(), information['filetime'],
  260. errnote='Cannot update utime of audio file')
  261. information['filepath'] = new_path
  262. information['ext'] = extension
  263. return [path], information
  264. class FFmpegVideoConvertorPP(FFmpegPostProcessor):
  265. def __init__(self, downloader=None, preferedformat=None):
  266. super(FFmpegVideoConvertorPP, self).__init__(downloader)
  267. self._preferedformat = preferedformat
  268. def run(self, information):
  269. path = information['filepath']
  270. if information['ext'] == self._preferedformat:
  271. self._downloader.to_screen('[ffmpeg] Not converting video file %s - already is in target format %s' % (path, self._preferedformat))
  272. return [], information
  273. options = []
  274. if self._preferedformat == 'avi':
  275. options.extend(['-c:v', 'libxvid', '-vtag', 'XVID'])
  276. prefix, sep, ext = path.rpartition('.')
  277. outpath = prefix + sep + self._preferedformat
  278. self._downloader.to_screen('[' + 'ffmpeg' + '] Converting video from %s to %s, Destination: ' % (information['ext'], self._preferedformat) + outpath)
  279. self.run_ffmpeg(path, outpath, options)
  280. information['filepath'] = outpath
  281. information['format'] = self._preferedformat
  282. information['ext'] = self._preferedformat
  283. return [path], information
  284. class FFmpegEmbedSubtitlePP(FFmpegPostProcessor):
  285. def run(self, information):
  286. if information['ext'] not in ('mp4', 'webm', 'mkv'):
  287. self._downloader.to_screen('[ffmpeg] Subtitles can only be embedded in mp4, webm or mkv files')
  288. return [], information
  289. subtitles = information.get('requested_subtitles')
  290. if not subtitles:
  291. self._downloader.to_screen('[ffmpeg] There aren\'t any subtitles to embed')
  292. return [], information
  293. filename = information['filepath']
  294. ext = information['ext']
  295. sub_langs = []
  296. sub_filenames = []
  297. webm_vtt_warn = False
  298. for lang, sub_info in subtitles.items():
  299. sub_ext = sub_info['ext']
  300. if ext != 'webm' or ext == 'webm' and sub_ext == 'vtt':
  301. sub_langs.append(lang)
  302. sub_filenames.append(subtitles_filename(filename, lang, sub_ext))
  303. else:
  304. if not webm_vtt_warn and ext == 'webm' and sub_ext != 'vtt':
  305. webm_vtt_warn = True
  306. self._downloader.to_screen('[ffmpeg] Only WebVTT subtitles can be embedded in webm files')
  307. if not sub_langs:
  308. return [], information
  309. input_files = [filename] + sub_filenames
  310. opts = [
  311. '-map', '0',
  312. '-c', 'copy',
  313. # Don't copy the existing subtitles, we may be running the
  314. # postprocessor a second time
  315. '-map', '-0:s',
  316. ]
  317. if information['ext'] == 'mp4':
  318. opts += ['-c:s', 'mov_text']
  319. for (i, lang) in enumerate(sub_langs):
  320. opts.extend(['-map', '%d:0' % (i + 1)])
  321. lang_code = ISO639Utils.short2long(lang)
  322. if lang_code is not None:
  323. opts.extend(['-metadata:s:s:%d' % i, 'language=%s' % lang_code])
  324. temp_filename = prepend_extension(filename, 'temp')
  325. self._downloader.to_screen('[ffmpeg] Embedding subtitles in \'%s\'' % filename)
  326. self.run_ffmpeg_multiple_files(input_files, temp_filename, opts)
  327. os.remove(encodeFilename(filename))
  328. os.rename(encodeFilename(temp_filename), encodeFilename(filename))
  329. return sub_filenames, information
  330. class FFmpegMetadataPP(FFmpegPostProcessor):
  331. def run(self, info):
  332. metadata = {}
  333. if info.get('title') is not None:
  334. metadata['title'] = info['title']
  335. if info.get('upload_date') is not None:
  336. metadata['date'] = info['upload_date']
  337. if info.get('artist') is not None:
  338. metadata['artist'] = info['artist']
  339. elif info.get('uploader') is not None:
  340. metadata['artist'] = info['uploader']
  341. elif info.get('uploader_id') is not None:
  342. metadata['artist'] = info['uploader_id']
  343. if info.get('description') is not None:
  344. metadata['description'] = info['description']
  345. metadata['comment'] = info['description']
  346. if info.get('webpage_url') is not None:
  347. metadata['purl'] = info['webpage_url']
  348. if info.get('album') is not None:
  349. metadata['album'] = info['album']
  350. if not metadata:
  351. self._downloader.to_screen('[ffmpeg] There isn\'t any metadata to add')
  352. return [], info
  353. filename = info['filepath']
  354. temp_filename = prepend_extension(filename, 'temp')
  355. if info['ext'] == 'm4a':
  356. options = ['-vn', '-acodec', 'copy']
  357. else:
  358. options = ['-c', 'copy']
  359. for (name, value) in metadata.items():
  360. options.extend(['-metadata', '%s=%s' % (name, value)])
  361. self._downloader.to_screen('[ffmpeg] Adding metadata to \'%s\'' % filename)
  362. self.run_ffmpeg(filename, temp_filename, options)
  363. os.remove(encodeFilename(filename))
  364. os.rename(encodeFilename(temp_filename), encodeFilename(filename))
  365. return [], info
  366. class FFmpegMergerPP(FFmpegPostProcessor):
  367. def run(self, info):
  368. filename = info['filepath']
  369. temp_filename = prepend_extension(filename, 'temp')
  370. args = ['-c', 'copy', '-map', '0:v:0', '-map', '1:a:0']
  371. self._downloader.to_screen('[ffmpeg] Merging formats into "%s"' % filename)
  372. self.run_ffmpeg_multiple_files(info['__files_to_merge'], temp_filename, args)
  373. os.rename(encodeFilename(temp_filename), encodeFilename(filename))
  374. return info['__files_to_merge'], info
  375. def can_merge(self):
  376. # TODO: figure out merge-capable ffmpeg version
  377. if self.basename != 'avconv':
  378. return True
  379. required_version = '10-0'
  380. if is_outdated_version(
  381. self._versions[self.basename], required_version):
  382. warning = ('Your copy of %s is outdated and unable to properly mux separate video and audio files, '
  383. 'youtube-dl will download single file media. '
  384. 'Update %s to version %s or newer to fix this.') % (
  385. self.basename, self.basename, required_version)
  386. if self._downloader:
  387. self._downloader.report_warning(warning)
  388. return False
  389. return True
  390. class FFmpegFixupStretchedPP(FFmpegPostProcessor):
  391. def run(self, info):
  392. stretched_ratio = info.get('stretched_ratio')
  393. if stretched_ratio is None or stretched_ratio == 1:
  394. return [], info
  395. filename = info['filepath']
  396. temp_filename = prepend_extension(filename, 'temp')
  397. options = ['-c', 'copy', '-aspect', '%f' % stretched_ratio]
  398. self._downloader.to_screen('[ffmpeg] Fixing aspect ratio in "%s"' % filename)
  399. self.run_ffmpeg(filename, temp_filename, options)
  400. os.remove(encodeFilename(filename))
  401. os.rename(encodeFilename(temp_filename), encodeFilename(filename))
  402. return [], info
  403. class FFmpegFixupM4aPP(FFmpegPostProcessor):
  404. def run(self, info):
  405. if info.get('container') != 'm4a_dash':
  406. return [], info
  407. filename = info['filepath']
  408. temp_filename = prepend_extension(filename, 'temp')
  409. options = ['-c', 'copy', '-f', 'mp4']
  410. self._downloader.to_screen('[ffmpeg] Correcting container in "%s"' % filename)
  411. self.run_ffmpeg(filename, temp_filename, options)
  412. os.remove(encodeFilename(filename))
  413. os.rename(encodeFilename(temp_filename), encodeFilename(filename))
  414. return [], info
  415. class FFmpegFixupM3u8PP(FFmpegPostProcessor):
  416. def run(self, info):
  417. filename = info['filepath']
  418. temp_filename = prepend_extension(filename, 'temp')
  419. options = ['-c', 'copy', '-f', 'mp4', '-bsf:a', 'aac_adtstoasc']
  420. self._downloader.to_screen('[ffmpeg] Fixing malformated aac bitstream in "%s"' % filename)
  421. self.run_ffmpeg(filename, temp_filename, options)
  422. os.remove(encodeFilename(filename))
  423. os.rename(encodeFilename(temp_filename), encodeFilename(filename))
  424. return [], info
  425. class FFmpegSubtitlesConvertorPP(FFmpegPostProcessor):
  426. def __init__(self, downloader=None, format=None):
  427. super(FFmpegSubtitlesConvertorPP, self).__init__(downloader)
  428. self.format = format
  429. def run(self, info):
  430. subs = info.get('requested_subtitles')
  431. filename = info['filepath']
  432. new_ext = self.format
  433. new_format = new_ext
  434. if new_format == 'vtt':
  435. new_format = 'webvtt'
  436. if subs is None:
  437. self._downloader.to_screen('[ffmpeg] There aren\'t any subtitles to convert')
  438. return [], info
  439. self._downloader.to_screen('[ffmpeg] Converting subtitles')
  440. sub_filenames = []
  441. for lang, sub in subs.items():
  442. ext = sub['ext']
  443. if ext == new_ext:
  444. self._downloader.to_screen(
  445. '[ffmpeg] Subtitle file for %s is already in the requested'
  446. 'format' % new_ext)
  447. continue
  448. old_file = subtitles_filename(filename, lang, ext)
  449. sub_filenames.append(old_file)
  450. new_file = subtitles_filename(filename, lang, new_ext)
  451. if ext == 'dfxp' or ext == 'ttml' or ext == 'tt':
  452. self._downloader.report_warning(
  453. 'You have requested to convert dfxp (TTML) subtitles into another format, '
  454. 'which results in style information loss')
  455. dfxp_file = old_file
  456. srt_file = subtitles_filename(filename, lang, 'srt')
  457. with io.open(dfxp_file, 'rt', encoding='utf-8') as f:
  458. srt_data = dfxp2srt(f.read())
  459. with io.open(srt_file, 'wt', encoding='utf-8') as f:
  460. f.write(srt_data)
  461. old_file = srt_file
  462. subs[lang] = {
  463. 'ext': 'srt',
  464. 'data': srt_data
  465. }
  466. if new_ext == 'srt':
  467. continue
  468. else:
  469. sub_filenames.append(srt_file)
  470. self.run_ffmpeg(old_file, new_file, ['-f', new_format])
  471. with io.open(new_file, 'rt', encoding='utf-8') as f:
  472. subs[lang] = {
  473. 'ext': new_ext,
  474. 'data': f.read(),
  475. }
  476. return sub_filenames, info