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.

579 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 get_audio_codec(self, path):
  119. if not self.probe_available:
  120. raise PostProcessingError('ffprobe or avprobe not found. Please install one.')
  121. try:
  122. cmd = [
  123. encodeFilename(self.probe_executable, True),
  124. encodeArgument('-show_streams'),
  125. encodeFilename(self._ffmpeg_filename_argument(path), True)]
  126. if self._downloader.params.get('verbose', False):
  127. self._downloader.to_screen('[debug] %s command line: %s' % (self.basename, shell_quote(cmd)))
  128. handle = subprocess.Popen(cmd, stderr=compat_subprocess_get_DEVNULL(), stdout=subprocess.PIPE, stdin=subprocess.PIPE)
  129. output = handle.communicate()[0]
  130. if handle.wait() != 0:
  131. return None
  132. except (IOError, OSError):
  133. return None
  134. audio_codec = None
  135. for line in output.decode('ascii', 'ignore').split('\n'):
  136. if line.startswith('codec_name='):
  137. audio_codec = line.split('=')[1].strip()
  138. elif line.strip() == 'codec_type=audio' and audio_codec is not None:
  139. return audio_codec
  140. return None
  141. def run_ffmpeg_multiple_files(self, input_paths, out_path, opts):
  142. self.check_version()
  143. oldest_mtime = min(
  144. os.stat(encodeFilename(path)).st_mtime for path in input_paths)
  145. opts += self._configuration_args()
  146. files_cmd = []
  147. for path in input_paths:
  148. files_cmd.extend([
  149. encodeArgument('-i'),
  150. encodeFilename(self._ffmpeg_filename_argument(path), True)
  151. ])
  152. cmd = ([encodeFilename(self.executable, True), encodeArgument('-y')] +
  153. files_cmd +
  154. [encodeArgument(o) for o in opts] +
  155. [encodeFilename(self._ffmpeg_filename_argument(out_path), True)])
  156. if self._downloader.params.get('verbose', False):
  157. self._downloader.to_screen('[debug] ffmpeg command line: %s' % shell_quote(cmd))
  158. p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE)
  159. stdout, stderr = p.communicate()
  160. if p.returncode != 0:
  161. stderr = stderr.decode('utf-8', 'replace')
  162. msg = stderr.strip().split('\n')[-1]
  163. raise FFmpegPostProcessorError(msg)
  164. self.try_utime(out_path, oldest_mtime, oldest_mtime)
  165. def run_ffmpeg(self, path, out_path, opts):
  166. self.run_ffmpeg_multiple_files([path], out_path, opts)
  167. def _ffmpeg_filename_argument(self, fn):
  168. # Always use 'file:' because the filename may contain ':' (ffmpeg
  169. # interprets that as a protocol) or can start with '-' (-- is broken in
  170. # ffmpeg, see https://ffmpeg.org/trac/ffmpeg/ticket/2127 for details)
  171. # Also leave '-' intact in order not to break streaming to stdout.
  172. return 'file:' + fn if fn != '-' else fn
  173. class FFmpegExtractAudioPP(FFmpegPostProcessor):
  174. def __init__(self, downloader=None, preferredcodec=None, preferredquality=None, nopostoverwrites=False):
  175. FFmpegPostProcessor.__init__(self, downloader)
  176. if preferredcodec is None:
  177. preferredcodec = 'best'
  178. self._preferredcodec = preferredcodec
  179. self._preferredquality = preferredquality
  180. self._nopostoverwrites = nopostoverwrites
  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. information['filepath'] = new_path
  244. information['ext'] = extension
  245. # If we download foo.mp3 and convert it to... foo.mp3, then don't delete foo.mp3, silly.
  246. if (new_path == path or
  247. (self._nopostoverwrites and os.path.exists(encodeFilename(new_path)))):
  248. self._downloader.to_screen('[ffmpeg] Post-process file %s exists, skipping' % new_path)
  249. return [], information
  250. try:
  251. self._downloader.to_screen('[ffmpeg] Destination: ' + new_path)
  252. self.run_ffmpeg(path, new_path, acodec, more_opts)
  253. except AudioConversionError as e:
  254. raise PostProcessingError(
  255. 'audio conversion failed: ' + e.msg)
  256. except Exception:
  257. raise PostProcessingError('error running ' + self.basename)
  258. # Try to update the date time for extracted audio file.
  259. if information.get('filetime') is not None:
  260. self.try_utime(
  261. new_path, time.time(), information['filetime'],
  262. errnote='Cannot update utime of audio file')
  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. def add(meta_list, info_list=None):
  334. if not info_list:
  335. info_list = meta_list
  336. if not isinstance(meta_list, (list, tuple)):
  337. meta_list = (meta_list,)
  338. if not isinstance(info_list, (list, tuple)):
  339. info_list = (info_list,)
  340. for info_f in info_list:
  341. if info.get(info_f) is not None:
  342. for meta_f in meta_list:
  343. metadata[meta_f] = info[info_f]
  344. break
  345. add('title', ('track', 'title'))
  346. add('date', 'upload_date')
  347. add(('description', 'comment'), 'description')
  348. add('purl', 'webpage_url')
  349. add('track', 'track_number')
  350. add('artist', ('artist', 'creator', 'uploader', 'uploader_id'))
  351. add('genre')
  352. add('album')
  353. add('album_artist')
  354. add('disc', 'disc_number')
  355. if not metadata:
  356. self._downloader.to_screen('[ffmpeg] There isn\'t any metadata to add')
  357. return [], info
  358. filename = info['filepath']
  359. temp_filename = prepend_extension(filename, 'temp')
  360. if info['ext'] == 'm4a':
  361. options = ['-vn', '-acodec', 'copy']
  362. else:
  363. options = ['-c', 'copy']
  364. for (name, value) in metadata.items():
  365. options.extend(['-metadata', '%s=%s' % (name, value)])
  366. self._downloader.to_screen('[ffmpeg] Adding metadata to \'%s\'' % filename)
  367. self.run_ffmpeg(filename, temp_filename, options)
  368. os.remove(encodeFilename(filename))
  369. os.rename(encodeFilename(temp_filename), encodeFilename(filename))
  370. return [], info
  371. class FFmpegMergerPP(FFmpegPostProcessor):
  372. def run(self, info):
  373. filename = info['filepath']
  374. temp_filename = prepend_extension(filename, 'temp')
  375. args = ['-c', 'copy', '-map', '0:v:0', '-map', '1:a:0']
  376. self._downloader.to_screen('[ffmpeg] Merging formats into "%s"' % filename)
  377. self.run_ffmpeg_multiple_files(info['__files_to_merge'], temp_filename, args)
  378. os.rename(encodeFilename(temp_filename), encodeFilename(filename))
  379. return info['__files_to_merge'], info
  380. def can_merge(self):
  381. # TODO: figure out merge-capable ffmpeg version
  382. if self.basename != 'avconv':
  383. return True
  384. required_version = '10-0'
  385. if is_outdated_version(
  386. self._versions[self.basename], required_version):
  387. warning = ('Your copy of %s is outdated and unable to properly mux separate video and audio files, '
  388. 'youtube-dl will download single file media. '
  389. 'Update %s to version %s or newer to fix this.') % (
  390. self.basename, self.basename, required_version)
  391. if self._downloader:
  392. self._downloader.report_warning(warning)
  393. return False
  394. return True
  395. class FFmpegFixupStretchedPP(FFmpegPostProcessor):
  396. def run(self, info):
  397. stretched_ratio = info.get('stretched_ratio')
  398. if stretched_ratio is None or stretched_ratio == 1:
  399. return [], info
  400. filename = info['filepath']
  401. temp_filename = prepend_extension(filename, 'temp')
  402. options = ['-c', 'copy', '-aspect', '%f' % stretched_ratio]
  403. self._downloader.to_screen('[ffmpeg] Fixing aspect ratio in "%s"' % filename)
  404. self.run_ffmpeg(filename, temp_filename, options)
  405. os.remove(encodeFilename(filename))
  406. os.rename(encodeFilename(temp_filename), encodeFilename(filename))
  407. return [], info
  408. class FFmpegFixupM4aPP(FFmpegPostProcessor):
  409. def run(self, info):
  410. if info.get('container') != 'm4a_dash':
  411. return [], info
  412. filename = info['filepath']
  413. temp_filename = prepend_extension(filename, 'temp')
  414. options = ['-c', 'copy', '-f', 'mp4']
  415. self._downloader.to_screen('[ffmpeg] Correcting container in "%s"' % filename)
  416. self.run_ffmpeg(filename, temp_filename, options)
  417. os.remove(encodeFilename(filename))
  418. os.rename(encodeFilename(temp_filename), encodeFilename(filename))
  419. return [], info
  420. class FFmpegFixupM3u8PP(FFmpegPostProcessor):
  421. def run(self, info):
  422. filename = info['filepath']
  423. if self.get_audio_codec(filename) == 'aac':
  424. temp_filename = prepend_extension(filename, 'temp')
  425. options = ['-c', 'copy', '-f', 'mp4', '-bsf:a', 'aac_adtstoasc']
  426. self._downloader.to_screen('[ffmpeg] Fixing malformated aac bitstream in "%s"' % filename)
  427. self.run_ffmpeg(filename, temp_filename, options)
  428. os.remove(encodeFilename(filename))
  429. os.rename(encodeFilename(temp_filename), encodeFilename(filename))
  430. return [], info
  431. class FFmpegSubtitlesConvertorPP(FFmpegPostProcessor):
  432. def __init__(self, downloader=None, format=None):
  433. super(FFmpegSubtitlesConvertorPP, self).__init__(downloader)
  434. self.format = format
  435. def run(self, info):
  436. subs = info.get('requested_subtitles')
  437. filename = info['filepath']
  438. new_ext = self.format
  439. new_format = new_ext
  440. if new_format == 'vtt':
  441. new_format = 'webvtt'
  442. if subs is None:
  443. self._downloader.to_screen('[ffmpeg] There aren\'t any subtitles to convert')
  444. return [], info
  445. self._downloader.to_screen('[ffmpeg] Converting subtitles')
  446. sub_filenames = []
  447. for lang, sub in subs.items():
  448. ext = sub['ext']
  449. if ext == new_ext:
  450. self._downloader.to_screen(
  451. '[ffmpeg] Subtitle file for %s is already in the requested'
  452. 'format' % new_ext)
  453. continue
  454. old_file = subtitles_filename(filename, lang, ext)
  455. sub_filenames.append(old_file)
  456. new_file = subtitles_filename(filename, lang, new_ext)
  457. if ext == 'dfxp' or ext == 'ttml' or ext == 'tt':
  458. self._downloader.report_warning(
  459. 'You have requested to convert dfxp (TTML) subtitles into another format, '
  460. 'which results in style information loss')
  461. dfxp_file = old_file
  462. srt_file = subtitles_filename(filename, lang, 'srt')
  463. with io.open(dfxp_file, 'rt', encoding='utf-8') as f:
  464. srt_data = dfxp2srt(f.read())
  465. with io.open(srt_file, 'wt', encoding='utf-8') as f:
  466. f.write(srt_data)
  467. old_file = srt_file
  468. subs[lang] = {
  469. 'ext': 'srt',
  470. 'data': srt_data
  471. }
  472. if new_ext == 'srt':
  473. continue
  474. else:
  475. sub_filenames.append(srt_file)
  476. self.run_ffmpeg(old_file, new_file, ['-f', new_format])
  477. with io.open(new_file, 'rt', encoding='utf-8') as f:
  478. subs[lang] = {
  479. 'ext': new_ext,
  480. 'data': f.read(),
  481. }
  482. return sub_filenames, info