ffmpeg.py 16 KB

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