embedthumbnail.py 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127
  1. # coding: utf-8
  2. from __future__ import unicode_literals
  3. import os
  4. import subprocess
  5. from .ffmpeg import FFmpegPostProcessor
  6. from ..utils import (
  7. check_executable,
  8. encodeArgument,
  9. encodeFilename,
  10. PostProcessingError,
  11. prepend_extension,
  12. replace_extension,
  13. shell_quote
  14. )
  15. class EmbedThumbnailPPError(PostProcessingError):
  16. pass
  17. class EmbedThumbnailPP(FFmpegPostProcessor):
  18. def __init__(self, downloader=None, already_have_thumbnail=False):
  19. super(EmbedThumbnailPP, self).__init__(downloader)
  20. self._already_have_thumbnail = already_have_thumbnail
  21. def run(self, info):
  22. filename = info['filepath']
  23. temp_filename = prepend_extension(filename, 'temp')
  24. if not info.get('thumbnails'):
  25. self._downloader.to_screen('[embedthumbnail] There aren\'t any thumbnails to embed')
  26. return [], info
  27. thumbnail_filename = info['thumbnails'][-1]['filename']
  28. if not os.path.exists(encodeFilename(thumbnail_filename)):
  29. self._downloader.report_warning(
  30. 'Skipping embedding the thumbnail because the file is missing.')
  31. return [], info
  32. def is_webp(path):
  33. with open(encodeFilename(path), 'rb') as f:
  34. b = f.read(12)
  35. return b[0:4] == b'RIFF' and b[8:] == b'WEBP'
  36. # Correct extension for WebP file with wrong extension (see #25687, #25717)
  37. _, thumbnail_ext = os.path.splitext(thumbnail_filename)
  38. if thumbnail_ext:
  39. thumbnail_ext = thumbnail_ext[1:].lower()
  40. if thumbnail_ext != 'webp' and is_webp(thumbnail_filename):
  41. self._downloader.to_screen(
  42. '[ffmpeg] Correcting extension to webp and escaping path for thumbnail "%s"' % thumbnail_filename)
  43. thumbnail_webp_filename = replace_extension(thumbnail_filename, 'webp')
  44. os.rename(encodeFilename(thumbnail_filename), encodeFilename(thumbnail_webp_filename))
  45. thumbnail_filename = thumbnail_webp_filename
  46. thumbnail_ext = 'webp'
  47. # Convert unsupported thumbnail formats to JPEG (see #25687, #25717)
  48. if thumbnail_ext not in ['jpg', 'png']:
  49. # NB: % is supposed to be escaped with %% but this does not work
  50. # for input files so working around with standard substitution
  51. escaped_thumbnail_filename = thumbnail_filename.replace('%', '#')
  52. os.rename(encodeFilename(thumbnail_filename), encodeFilename(escaped_thumbnail_filename))
  53. escaped_thumbnail_jpg_filename = replace_extension(escaped_thumbnail_filename, 'jpg')
  54. self._downloader.to_screen('[ffmpeg] Converting thumbnail "%s" to JPEG' % escaped_thumbnail_filename)
  55. self.run_ffmpeg(escaped_thumbnail_filename, escaped_thumbnail_jpg_filename, ['-bsf:v', 'mjpeg2jpeg'])
  56. os.remove(encodeFilename(escaped_thumbnail_filename))
  57. thumbnail_jpg_filename = replace_extension(thumbnail_filename, 'jpg')
  58. # Rename back to unescaped for further processing
  59. os.rename(encodeFilename(escaped_thumbnail_jpg_filename), encodeFilename(thumbnail_jpg_filename))
  60. thumbnail_filename = thumbnail_jpg_filename
  61. if info['ext'] == 'mp3':
  62. options = [
  63. '-c', 'copy', '-map', '0', '-map', '1',
  64. '-metadata:s:v', 'title="Album cover"', '-metadata:s:v', 'comment="Cover (Front)"']
  65. self._downloader.to_screen('[ffmpeg] Adding thumbnail to "%s"' % filename)
  66. self.run_ffmpeg_multiple_files([filename, thumbnail_filename], temp_filename, options)
  67. if not self._already_have_thumbnail:
  68. os.remove(encodeFilename(thumbnail_filename))
  69. os.remove(encodeFilename(filename))
  70. os.rename(encodeFilename(temp_filename), encodeFilename(filename))
  71. elif info['ext'] in ['m4a', 'mp4']:
  72. if not check_executable('AtomicParsley', ['-v']):
  73. raise EmbedThumbnailPPError('AtomicParsley was not found. Please install.')
  74. cmd = [encodeFilename('AtomicParsley', True),
  75. encodeFilename(filename, True),
  76. encodeArgument('--artwork'),
  77. encodeFilename(thumbnail_filename, True),
  78. encodeArgument('-o'),
  79. encodeFilename(temp_filename, True)]
  80. self._downloader.to_screen('[atomicparsley] Adding thumbnail to "%s"' % filename)
  81. if self._downloader.params.get('verbose', False):
  82. self._downloader.to_screen('[debug] AtomicParsley command line: %s' % shell_quote(cmd))
  83. p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  84. stdout, stderr = p.communicate()
  85. if p.returncode != 0:
  86. msg = stderr.decode('utf-8', 'replace').strip()
  87. raise EmbedThumbnailPPError(msg)
  88. if not self._already_have_thumbnail:
  89. os.remove(encodeFilename(thumbnail_filename))
  90. # for formats that don't support thumbnails (like 3gp) AtomicParsley
  91. # won't create to the temporary file
  92. if b'No changes' in stdout:
  93. self._downloader.report_warning('The file format doesn\'t support embedding a thumbnail')
  94. else:
  95. os.remove(encodeFilename(filename))
  96. os.rename(encodeFilename(temp_filename), encodeFilename(filename))
  97. else:
  98. raise EmbedThumbnailPPError('Only mp3 and m4a/mp4 are supported for thumbnail embedding for now.')
  99. return [], info