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
19 KiB

10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
  1. from __future__ import unicode_literals
  2. import os
  3. import subprocess
  4. import sys
  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. )
  20. class FFmpegPostProcessorError(PostProcessingError):
  21. pass
  22. class FFmpegPostProcessor(PostProcessor):
  23. def __init__(self, downloader=None, deletetempfiles=False):
  24. PostProcessor.__init__(self, downloader)
  25. self._versions = self.get_versions()
  26. self._deletetempfiles = deletetempfiles
  27. def check_version(self):
  28. if not self._executable:
  29. raise FFmpegPostProcessorError('ffmpeg or avconv not found. Please install one.')
  30. required_version = '10-0' if self._uses_avconv() else '1.0'
  31. if is_outdated_version(
  32. self._versions[self._executable], required_version):
  33. warning = 'Your copy of %s is outdated, update %s to version %s or newer if you encounter any errors.' % (
  34. self._executable, self._executable, required_version)
  35. if self._downloader:
  36. self._downloader.report_warning(warning)
  37. @staticmethod
  38. def get_versions():
  39. programs = ['avprobe', 'avconv', 'ffmpeg', 'ffprobe']
  40. return dict((p, get_exe_version(p, args=['-version'])) for p in programs)
  41. @property
  42. def available(self):
  43. return self._executable is not None
  44. @property
  45. def _executable(self):
  46. if self._downloader.params.get('prefer_ffmpeg', False):
  47. prefs = ('ffmpeg', 'avconv')
  48. else:
  49. prefs = ('avconv', 'ffmpeg')
  50. for p in prefs:
  51. if self._versions[p]:
  52. return p
  53. return None
  54. @property
  55. def _probe_executable(self):
  56. if self._downloader.params.get('prefer_ffmpeg', False):
  57. prefs = ('ffprobe', 'avprobe')
  58. else:
  59. prefs = ('avprobe', 'ffprobe')
  60. for p in prefs:
  61. if self._versions[p]:
  62. return p
  63. return None
  64. def _uses_avconv(self):
  65. return self._executable == 'avconv'
  66. def run_ffmpeg_multiple_files(self, input_paths, out_path, opts):
  67. self.check_version()
  68. oldest_mtime = min(
  69. os.stat(encodeFilename(path)).st_mtime for path in input_paths)
  70. files_cmd = []
  71. for path in input_paths:
  72. files_cmd.extend([encodeArgument('-i'), encodeFilename(path, True)])
  73. cmd = ([encodeFilename(self._executable, True), encodeArgument('-y')] +
  74. files_cmd +
  75. [encodeArgument(o) for o in opts] +
  76. [encodeFilename(self._ffmpeg_filename_argument(out_path), True)])
  77. if self._downloader.params.get('verbose', False):
  78. self._downloader.to_screen('[debug] ffmpeg command line: %s' % shell_quote(cmd))
  79. p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  80. stdout, stderr = p.communicate()
  81. if p.returncode != 0:
  82. stderr = stderr.decode('utf-8', 'replace')
  83. msg = stderr.strip().split('\n')[-1]
  84. raise FFmpegPostProcessorError(msg)
  85. os.utime(encodeFilename(out_path), (oldest_mtime, oldest_mtime))
  86. if self._deletetempfiles:
  87. for ipath in input_paths:
  88. os.remove(ipath)
  89. def run_ffmpeg(self, path, out_path, opts):
  90. self.run_ffmpeg_multiple_files([path], out_path, opts)
  91. def _ffmpeg_filename_argument(self, fn):
  92. # ffmpeg broke --, see https://ffmpeg.org/trac/ffmpeg/ticket/2127 for details
  93. if fn.startswith('-'):
  94. return './' + fn
  95. return fn
  96. class FFmpegExtractAudioPP(FFmpegPostProcessor):
  97. def __init__(self, downloader=None, preferredcodec=None, preferredquality=None, nopostoverwrites=False):
  98. FFmpegPostProcessor.__init__(self, downloader)
  99. if preferredcodec is None:
  100. preferredcodec = 'best'
  101. self._preferredcodec = preferredcodec
  102. self._preferredquality = preferredquality
  103. self._nopostoverwrites = nopostoverwrites
  104. def get_audio_codec(self, path):
  105. if not self._probe_executable:
  106. raise PostProcessingError('ffprobe or avprobe not found. Please install one.')
  107. try:
  108. cmd = [
  109. encodeFilename(self._probe_executable, True),
  110. encodeArgument('-show_streams'),
  111. encodeFilename(self._ffmpeg_filename_argument(path), True)]
  112. handle = subprocess.Popen(cmd, stderr=compat_subprocess_get_DEVNULL(), stdout=subprocess.PIPE)
  113. output = handle.communicate()[0]
  114. if handle.wait() != 0:
  115. return None
  116. except (IOError, OSError):
  117. return None
  118. audio_codec = None
  119. for line in output.decode('ascii', 'ignore').split('\n'):
  120. if line.startswith('codec_name='):
  121. audio_codec = line.split('=')[1].strip()
  122. elif line.strip() == 'codec_type=audio' and audio_codec is not None:
  123. return audio_codec
  124. return None
  125. def run_ffmpeg(self, path, out_path, codec, more_opts):
  126. if codec is None:
  127. acodec_opts = []
  128. else:
  129. acodec_opts = ['-acodec', codec]
  130. opts = ['-vn'] + acodec_opts + more_opts
  131. try:
  132. FFmpegPostProcessor.run_ffmpeg(self, path, out_path, opts)
  133. except FFmpegPostProcessorError as err:
  134. raise AudioConversionError(err.msg)
  135. def run(self, information):
  136. path = information['filepath']
  137. filecodec = self.get_audio_codec(path)
  138. if filecodec is None:
  139. raise PostProcessingError('WARNING: unable to obtain file audio codec with ffprobe')
  140. uses_avconv = self._uses_avconv()
  141. more_opts = []
  142. if self._preferredcodec == 'best' or self._preferredcodec == filecodec or (self._preferredcodec == 'm4a' and filecodec == 'aac'):
  143. if filecodec == 'aac' and self._preferredcodec in ['m4a', 'best']:
  144. # Lossless, but in another container
  145. acodec = 'copy'
  146. extension = 'm4a'
  147. more_opts = ['-bsf:a' if uses_avconv else '-absf', 'aac_adtstoasc']
  148. elif filecodec in ['aac', 'mp3', 'vorbis', 'opus']:
  149. # Lossless if possible
  150. acodec = 'copy'
  151. extension = filecodec
  152. if filecodec == 'aac':
  153. more_opts = ['-f', 'adts']
  154. if filecodec == 'vorbis':
  155. extension = 'ogg'
  156. else:
  157. # MP3 otherwise.
  158. acodec = 'libmp3lame'
  159. extension = 'mp3'
  160. more_opts = []
  161. if self._preferredquality is not None:
  162. if int(self._preferredquality) < 10:
  163. more_opts += ['-q:a' if uses_avconv else '-aq', self._preferredquality]
  164. else:
  165. more_opts += ['-b:a' if uses_avconv else '-ab', self._preferredquality + 'k']
  166. else:
  167. # We convert the audio (lossy)
  168. acodec = {'mp3': 'libmp3lame', 'aac': 'aac', 'm4a': 'aac', 'opus': 'opus', 'vorbis': 'libvorbis', 'wav': None}[self._preferredcodec]
  169. extension = self._preferredcodec
  170. more_opts = []
  171. if self._preferredquality is not None:
  172. # The opus codec doesn't support the -aq option
  173. if int(self._preferredquality) < 10 and extension != 'opus':
  174. more_opts += ['-q:a' if uses_avconv else '-aq', self._preferredquality]
  175. else:
  176. more_opts += ['-b:a' if uses_avconv else '-ab', self._preferredquality + 'k']
  177. if self._preferredcodec == 'aac':
  178. more_opts += ['-f', 'adts']
  179. if self._preferredcodec == 'm4a':
  180. more_opts += ['-bsf:a' if uses_avconv else '-absf', 'aac_adtstoasc']
  181. if self._preferredcodec == 'vorbis':
  182. extension = 'ogg'
  183. if self._preferredcodec == 'wav':
  184. extension = 'wav'
  185. more_opts += ['-f', 'wav']
  186. prefix, sep, ext = path.rpartition('.') # not os.path.splitext, since the latter does not work on unicode in all setups
  187. new_path = prefix + sep + extension
  188. # If we download foo.mp3 and convert it to... foo.mp3, then don't delete foo.mp3, silly.
  189. if new_path == path:
  190. self._nopostoverwrites = True
  191. try:
  192. if self._nopostoverwrites and os.path.exists(encodeFilename(new_path)):
  193. self._downloader.to_screen('[youtube] Post-process file %s exists, skipping' % new_path)
  194. else:
  195. self._downloader.to_screen('[' + self._executable + '] Destination: ' + new_path)
  196. self.run_ffmpeg(path, new_path, acodec, more_opts)
  197. except:
  198. etype, e, tb = sys.exc_info()
  199. if isinstance(e, AudioConversionError):
  200. msg = 'audio conversion failed: ' + e.msg
  201. else:
  202. msg = 'error running ' + self._executable
  203. raise PostProcessingError(msg)
  204. # Try to update the date time for extracted audio file.
  205. if information.get('filetime') is not None:
  206. try:
  207. os.utime(encodeFilename(new_path), (time.time(), information['filetime']))
  208. except:
  209. self._downloader.report_warning('Cannot update utime of audio file')
  210. information['filepath'] = new_path
  211. return self._nopostoverwrites, information
  212. class FFmpegVideoConvertorPP(FFmpegPostProcessor):
  213. def __init__(self, downloader=None, preferedformat=None):
  214. super(FFmpegVideoConvertorPP, self).__init__(downloader)
  215. self._preferedformat = preferedformat
  216. def run(self, information):
  217. path = information['filepath']
  218. prefix, sep, ext = path.rpartition('.')
  219. outpath = prefix + sep + self._preferedformat
  220. if information['ext'] == self._preferedformat:
  221. self._downloader.to_screen('[ffmpeg] Not converting video file %s - already is in target format %s' % (path, self._preferedformat))
  222. return True, information
  223. self._downloader.to_screen('[' + 'ffmpeg' + '] Converting video from %s to %s, Destination: ' % (information['ext'], self._preferedformat) + outpath)
  224. self.run_ffmpeg(path, outpath, [])
  225. information['filepath'] = outpath
  226. information['format'] = self._preferedformat
  227. information['ext'] = self._preferedformat
  228. return False, information
  229. class FFmpegEmbedSubtitlePP(FFmpegPostProcessor):
  230. # See http://www.loc.gov/standards/iso639-2/ISO-639-2_utf-8.txt
  231. _lang_map = {
  232. 'aa': 'aar',
  233. 'ab': 'abk',
  234. 'ae': 'ave',
  235. 'af': 'afr',
  236. 'ak': 'aka',
  237. 'am': 'amh',
  238. 'an': 'arg',
  239. 'ar': 'ara',
  240. 'as': 'asm',
  241. 'av': 'ava',
  242. 'ay': 'aym',
  243. 'az': 'aze',
  244. 'ba': 'bak',
  245. 'be': 'bel',
  246. 'bg': 'bul',
  247. 'bh': 'bih',
  248. 'bi': 'bis',
  249. 'bm': 'bam',
  250. 'bn': 'ben',
  251. 'bo': 'bod',
  252. 'br': 'bre',
  253. 'bs': 'bos',
  254. 'ca': 'cat',
  255. 'ce': 'che',
  256. 'ch': 'cha',
  257. 'co': 'cos',
  258. 'cr': 'cre',
  259. 'cs': 'ces',
  260. 'cu': 'chu',
  261. 'cv': 'chv',
  262. 'cy': 'cym',
  263. 'da': 'dan',
  264. 'de': 'deu',
  265. 'dv': 'div',
  266. 'dz': 'dzo',
  267. 'ee': 'ewe',
  268. 'el': 'ell',
  269. 'en': 'eng',
  270. 'eo': 'epo',
  271. 'es': 'spa',
  272. 'et': 'est',
  273. 'eu': 'eus',
  274. 'fa': 'fas',
  275. 'ff': 'ful',
  276. 'fi': 'fin',
  277. 'fj': 'fij',
  278. 'fo': 'fao',
  279. 'fr': 'fra',
  280. 'fy': 'fry',
  281. 'ga': 'gle',
  282. 'gd': 'gla',
  283. 'gl': 'glg',
  284. 'gn': 'grn',
  285. 'gu': 'guj',
  286. 'gv': 'glv',
  287. 'ha': 'hau',
  288. 'he': 'heb',
  289. 'hi': 'hin',
  290. 'ho': 'hmo',
  291. 'hr': 'hrv',
  292. 'ht': 'hat',
  293. 'hu': 'hun',
  294. 'hy': 'hye',
  295. 'hz': 'her',
  296. 'ia': 'ina',
  297. 'id': 'ind',
  298. 'ie': 'ile',
  299. 'ig': 'ibo',
  300. 'ii': 'iii',
  301. 'ik': 'ipk',
  302. 'io': 'ido',
  303. 'is': 'isl',
  304. 'it': 'ita',
  305. 'iu': 'iku',
  306. 'ja': 'jpn',
  307. 'jv': 'jav',
  308. 'ka': 'kat',
  309. 'kg': 'kon',
  310. 'ki': 'kik',
  311. 'kj': 'kua',
  312. 'kk': 'kaz',
  313. 'kl': 'kal',
  314. 'km': 'khm',
  315. 'kn': 'kan',
  316. 'ko': 'kor',
  317. 'kr': 'kau',
  318. 'ks': 'kas',
  319. 'ku': 'kur',
  320. 'kv': 'kom',
  321. 'kw': 'cor',
  322. 'ky': 'kir',
  323. 'la': 'lat',
  324. 'lb': 'ltz',
  325. 'lg': 'lug',
  326. 'li': 'lim',
  327. 'ln': 'lin',
  328. 'lo': 'lao',
  329. 'lt': 'lit',
  330. 'lu': 'lub',
  331. 'lv': 'lav',
  332. 'mg': 'mlg',
  333. 'mh': 'mah',
  334. 'mi': 'mri',
  335. 'mk': 'mkd',
  336. 'ml': 'mal',
  337. 'mn': 'mon',
  338. 'mr': 'mar',
  339. 'ms': 'msa',
  340. 'mt': 'mlt',
  341. 'my': 'mya',
  342. 'na': 'nau',
  343. 'nb': 'nob',
  344. 'nd': 'nde',
  345. 'ne': 'nep',
  346. 'ng': 'ndo',
  347. 'nl': 'nld',
  348. 'nn': 'nno',
  349. 'no': 'nor',
  350. 'nr': 'nbl',
  351. 'nv': 'nav',
  352. 'ny': 'nya',
  353. 'oc': 'oci',
  354. 'oj': 'oji',
  355. 'om': 'orm',
  356. 'or': 'ori',
  357. 'os': 'oss',
  358. 'pa': 'pan',
  359. 'pi': 'pli',
  360. 'pl': 'pol',
  361. 'ps': 'pus',
  362. 'pt': 'por',
  363. 'qu': 'que',
  364. 'rm': 'roh',
  365. 'rn': 'run',
  366. 'ro': 'ron',
  367. 'ru': 'rus',
  368. 'rw': 'kin',
  369. 'sa': 'san',
  370. 'sc': 'srd',
  371. 'sd': 'snd',
  372. 'se': 'sme',
  373. 'sg': 'sag',
  374. 'si': 'sin',
  375. 'sk': 'slk',
  376. 'sl': 'slv',
  377. 'sm': 'smo',
  378. 'sn': 'sna',
  379. 'so': 'som',
  380. 'sq': 'sqi',
  381. 'sr': 'srp',
  382. 'ss': 'ssw',
  383. 'st': 'sot',
  384. 'su': 'sun',
  385. 'sv': 'swe',
  386. 'sw': 'swa',
  387. 'ta': 'tam',
  388. 'te': 'tel',
  389. 'tg': 'tgk',
  390. 'th': 'tha',
  391. 'ti': 'tir',
  392. 'tk': 'tuk',
  393. 'tl': 'tgl',
  394. 'tn': 'tsn',
  395. 'to': 'ton',
  396. 'tr': 'tur',
  397. 'ts': 'tso',
  398. 'tt': 'tat',
  399. 'tw': 'twi',
  400. 'ty': 'tah',
  401. 'ug': 'uig',
  402. 'uk': 'ukr',
  403. 'ur': 'urd',
  404. 'uz': 'uzb',
  405. 've': 'ven',
  406. 'vi': 'vie',
  407. 'vo': 'vol',
  408. 'wa': 'wln',
  409. 'wo': 'wol',
  410. 'xh': 'xho',
  411. 'yi': 'yid',
  412. 'yo': 'yor',
  413. 'za': 'zha',
  414. 'zh': 'zho',
  415. 'zu': 'zul',
  416. }
  417. def __init__(self, downloader=None, subtitlesformat='srt'):
  418. super(FFmpegEmbedSubtitlePP, self).__init__(downloader)
  419. self._subformat = subtitlesformat
  420. @classmethod
  421. def _conver_lang_code(cls, code):
  422. """Convert language code from ISO 639-1 to ISO 639-2/T"""
  423. return cls._lang_map.get(code[:2])
  424. def run(self, information):
  425. if information['ext'] != 'mp4':
  426. self._downloader.to_screen('[ffmpeg] Subtitles can only be embedded in mp4 files')
  427. return True, information
  428. if not information.get('subtitles'):
  429. self._downloader.to_screen('[ffmpeg] There aren\'t any subtitles to embed')
  430. return True, information
  431. sub_langs = [key for key in information['subtitles']]
  432. filename = information['filepath']
  433. input_files = [filename] + [subtitles_filename(filename, lang, self._subformat) for lang in sub_langs]
  434. opts = [
  435. '-map', '0',
  436. '-c', 'copy',
  437. # Don't copy the existing subtitles, we may be running the
  438. # postprocessor a second time
  439. '-map', '-0:s',
  440. '-c:s', 'mov_text',
  441. ]
  442. for (i, lang) in enumerate(sub_langs):
  443. opts.extend(['-map', '%d:0' % (i + 1)])
  444. lang_code = self._conver_lang_code(lang)
  445. if lang_code is not None:
  446. opts.extend(['-metadata:s:s:%d' % i, 'language=%s' % lang_code])
  447. temp_filename = prepend_extension(filename, 'temp')
  448. self._downloader.to_screen('[ffmpeg] Embedding subtitles in \'%s\'' % filename)
  449. self.run_ffmpeg_multiple_files(input_files, temp_filename, opts)
  450. os.remove(encodeFilename(filename))
  451. os.rename(encodeFilename(temp_filename), encodeFilename(filename))
  452. return True, information
  453. class FFmpegMetadataPP(FFmpegPostProcessor):
  454. def run(self, info):
  455. metadata = {}
  456. if info.get('title') is not None:
  457. metadata['title'] = info['title']
  458. if info.get('upload_date') is not None:
  459. metadata['date'] = info['upload_date']
  460. if info.get('uploader') is not None:
  461. metadata['artist'] = info['uploader']
  462. elif info.get('uploader_id') is not None:
  463. metadata['artist'] = info['uploader_id']
  464. if info.get('description') is not None:
  465. metadata['description'] = info['description']
  466. if info.get('webpage_url') is not None:
  467. metadata['comment'] = info['webpage_url']
  468. if not metadata:
  469. self._downloader.to_screen('[ffmpeg] There isn\'t any metadata to add')
  470. return True, info
  471. filename = info['filepath']
  472. temp_filename = prepend_extension(filename, 'temp')
  473. if info['ext'] == 'm4a':
  474. options = ['-vn', '-acodec', 'copy']
  475. else:
  476. options = ['-c', 'copy']
  477. for (name, value) in metadata.items():
  478. options.extend(['-metadata', '%s=%s' % (name, value)])
  479. self._downloader.to_screen('[ffmpeg] Adding metadata to \'%s\'' % filename)
  480. self.run_ffmpeg(filename, temp_filename, options)
  481. os.remove(encodeFilename(filename))
  482. os.rename(encodeFilename(temp_filename), encodeFilename(filename))
  483. return True, info
  484. class FFmpegMergerPP(FFmpegPostProcessor):
  485. def run(self, info):
  486. filename = info['filepath']
  487. args = ['-c', 'copy', '-map', '0:v:0', '-map', '1:a:0']
  488. self._downloader.to_screen('[ffmpeg] Merging formats into "%s"' % filename)
  489. self.run_ffmpeg_multiple_files(info['__files_to_merge'], filename, args)
  490. return True, info
  491. class FFmpegAudioFixPP(FFmpegPostProcessor):
  492. def run(self, info):
  493. filename = info['filepath']
  494. temp_filename = prepend_extension(filename, 'temp')
  495. options = ['-vn', '-acodec', 'copy']
  496. self._downloader.to_screen('[ffmpeg] Fixing audio file "%s"' % filename)
  497. self.run_ffmpeg(filename, temp_filename, options)
  498. os.remove(encodeFilename(filename))
  499. os.rename(encodeFilename(temp_filename), encodeFilename(filename))
  500. return True, info
  501. class FFmpegFixupStretchedPP(FFmpegPostProcessor):
  502. def run(self, info):
  503. stretched_ratio = info.get('stretched_ratio')
  504. if stretched_ratio is None or stretched_ratio == 1:
  505. return
  506. filename = info['filepath']
  507. temp_filename = prepend_extension(filename, 'temp')
  508. options = ['-c', 'copy', '-aspect', '%f' % stretched_ratio]
  509. self._downloader.to_screen('[ffmpeg] Fixing aspect ratio in "%s"' % filename)
  510. self.run_ffmpeg(filename, temp_filename, options)
  511. os.remove(encodeFilename(filename))
  512. os.rename(encodeFilename(temp_filename), encodeFilename(filename))
  513. return True, info