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.

502 lines
17 KiB

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