embedthumbnail.py 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. # -*- coding: utf-8 -*-
  2. from __future__ import unicode_literals
  3. import os
  4. import subprocess
  5. from .ffmpeg import FFmpegPostProcessor
  6. from ..compat import (
  7. compat_urlretrieve,
  8. )
  9. from ..utils import (
  10. check_executable,
  11. encodeFilename,
  12. PostProcessingError,
  13. prepend_extension,
  14. shell_quote
  15. )
  16. class EmbedThumbnailPPError(PostProcessingError):
  17. pass
  18. class EmbedThumbnailPP(FFmpegPostProcessor):
  19. def run(self, info):
  20. filename = info['filepath']
  21. temp_filename = prepend_extension(filename, 'temp')
  22. temp_thumbnail = prepend_extension(filename, 'thumb')
  23. if not info.get('thumbnail'):
  24. raise EmbedThumbnailPPError('Thumbnail was not found. Nothing to do.')
  25. compat_urlretrieve(info['thumbnail'], temp_thumbnail)
  26. if info['ext'] == 'mp3':
  27. options = ['-i', temp_thumbnail, '-c', 'copy', '-map', '0', '-map', '1',
  28. '-metadata:s:v', 'title="Album cover"', '-metadata:s:v', 'comment="Cover (Front)"']
  29. self._downloader.to_screen('[ffmpeg] Adding thumbnail to "%s"' % filename)
  30. self.run_ffmpeg(filename, temp_filename, options)
  31. os.remove(encodeFilename(temp_thumbnail))
  32. os.remove(encodeFilename(filename))
  33. os.rename(encodeFilename(temp_filename), encodeFilename(filename))
  34. elif info['ext'] == 'm4a':
  35. if not check_executable('AtomicParsley', ['-v']):
  36. raise EmbedThumbnailPPError('AtomicParsley was not found. Please install.')
  37. cmd = ['AtomicParsley', filename, '--artwork', temp_thumbnail, '-o', temp_filename]
  38. self._downloader.to_screen('[atomicparsley] Adding thumbnail to "%s"' % filename)
  39. if self._downloader.params.get('verbose', False):
  40. self._downloader.to_screen('[debug] AtomicParsley command line: %s' % shell_quote(cmd))
  41. p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  42. stdout, stderr = p.communicate()
  43. if p.returncode != 0:
  44. msg = stderr.decode('utf-8', 'replace').strip()
  45. raise EmbedThumbnailPPError(msg)
  46. os.remove(encodeFilename(temp_thumbnail))
  47. # for formats that don't support thumbnails (like 3gp) AtomicParsley
  48. # won't create to the temporary file
  49. if b'No changes' in stdout:
  50. self._downloader.report_warning('The file format doesn\'t support embedding a thumbnail')
  51. else:
  52. os.remove(encodeFilename(filename))
  53. os.rename(encodeFilename(temp_filename), encodeFilename(filename))
  54. else:
  55. raise EmbedThumbnailPPError('Only mp3 and m4a are supported for thumbnail embedding for now.')
  56. return [], info