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.

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