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.

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