embedthumbnail.py 5.7 KB

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