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.

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