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.

625 lines
24 KiB

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