2
0

ffmpeg.py 23 KB

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