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.

543 lines
18 KiB

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