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.

554 lines
18 KiB

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