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.

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