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.

508 lines
17 KiB

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