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.

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