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.

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