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.

568 lines
19 KiB

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