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.

594 lines
20 KiB

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