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.

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