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.

580 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. 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. temp_filename = prepend_extension(filename, 'temp')
  424. options = ['-c', 'copy', '-f', 'mp4', '-bsf:a', 'aac_adtstoasc']
  425. self._downloader.to_screen('[ffmpeg] Fixing malformated aac bitstream in "%s"' % filename)
  426. self.run_ffmpeg(filename, temp_filename, options)
  427. os.remove(encodeFilename(filename))
  428. os.rename(encodeFilename(temp_filename), encodeFilename(filename))
  429. return [], info
  430. class FFmpegSubtitlesConvertorPP(FFmpegPostProcessor):
  431. def __init__(self, downloader=None, format=None):
  432. super(FFmpegSubtitlesConvertorPP, self).__init__(downloader)
  433. self.format = format
  434. def run(self, info):
  435. subs = info.get('requested_subtitles')
  436. filename = info['filepath']
  437. new_ext = self.format
  438. new_format = new_ext
  439. if new_format == 'vtt':
  440. new_format = 'webvtt'
  441. if subs is None:
  442. self._downloader.to_screen('[ffmpeg] There aren\'t any subtitles to convert')
  443. return [], info
  444. self._downloader.to_screen('[ffmpeg] Converting subtitles')
  445. sub_filenames = []
  446. for lang, sub in subs.items():
  447. ext = sub['ext']
  448. if ext == new_ext:
  449. self._downloader.to_screen(
  450. '[ffmpeg] Subtitle file for %s is already in the requested'
  451. 'format' % new_ext)
  452. continue
  453. old_file = subtitles_filename(filename, lang, ext)
  454. sub_filenames.append(old_file)
  455. new_file = subtitles_filename(filename, lang, new_ext)
  456. if ext == 'dfxp' or ext == 'ttml' or ext == 'tt':
  457. self._downloader.report_warning(
  458. 'You have requested to convert dfxp (TTML) subtitles into another format, '
  459. 'which results in style information loss')
  460. dfxp_file = old_file
  461. srt_file = subtitles_filename(filename, lang, 'srt')
  462. with io.open(dfxp_file, 'rt', encoding='utf-8') as f:
  463. srt_data = dfxp2srt(f.read())
  464. with io.open(srt_file, 'wt', encoding='utf-8') as f:
  465. f.write(srt_data)
  466. old_file = srt_file
  467. subs[lang] = {
  468. 'ext': 'srt',
  469. 'data': srt_data
  470. }
  471. if new_ext == 'srt':
  472. continue
  473. else:
  474. sub_filenames.append(srt_file)
  475. self.run_ffmpeg(old_file, new_file, ['-f', new_format])
  476. with io.open(new_file, 'rt', encoding='utf-8') as f:
  477. subs[lang] = {
  478. 'ext': new_ext,
  479. 'data': f.read(),
  480. }
  481. return sub_filenames, info