embedthumbnail.py 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115
  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. shell_quote
  13. )
  14. class EmbedThumbnailPPError(PostProcessingError):
  15. pass
  16. class EmbedThumbnailPP(FFmpegPostProcessor):
  17. def __init__(self, downloader=None, already_have_thumbnail=False):
  18. super(EmbedThumbnailPP, self).__init__(downloader)
  19. self._already_have_thumbnail = already_have_thumbnail
  20. def run(self, info):
  21. filename = info['filepath']
  22. temp_filename = prepend_extension(filename, 'temp')
  23. if not info.get('thumbnails'):
  24. self._downloader.to_screen('[embedthumbnail] There aren\'t any thumbnails to embed')
  25. return [], info
  26. thumbnail_filename = info['thumbnails'][-1]['filename']
  27. if not os.path.exists(encodeFilename(thumbnail_filename)):
  28. self._downloader.report_warning(
  29. 'Skipping embedding the thumbnail because the file is missing.')
  30. return [], info
  31. # Check for mislabeled webp file
  32. with open(encodeFilename(thumbnail_filename), "rb") as f:
  33. b = f.read(16)
  34. if b'\x57\x45\x42\x50' in b: # Binary for WEBP
  35. [thumbnail_filename_path, thumbnail_filename_extension] = os.path.splitext(thumbnail_filename)
  36. if not thumbnail_filename_extension == ".webp":
  37. webp_thumbnail_filename = thumbnail_filename_path + ".webp"
  38. os.rename(encodeFilename(thumbnail_filename), encodeFilename(webp_thumbnail_filename))
  39. thumbnail_filename = webp_thumbnail_filename
  40. # If not a jpg or png thumbnail, convert it to jpg using ffmpeg
  41. if not os.path.splitext(thumbnail_filename)[1].lower() in ['.jpg', '.png']:
  42. jpg_thumbnail_filename = os.path.splitext(thumbnail_filename)[0] + ".jpg"
  43. jpg_thumbnail_filename = os.path.join(os.path.dirname(jpg_thumbnail_filename), os.path.basename(jpg_thumbnail_filename).replace('%', '_')) # ffmpeg interprets % as image sequence
  44. self._downloader.to_screen('[ffmpeg] Converting thumbnail "%s" to JPEG' % thumbnail_filename)
  45. self.run_ffmpeg(thumbnail_filename, jpg_thumbnail_filename, ['-bsf:v', 'mjpeg2jpeg'])
  46. os.remove(encodeFilename(thumbnail_filename))
  47. thumbnail_filename = jpg_thumbnail_filename
  48. if info['ext'] == 'mp3':
  49. options = [
  50. '-c', 'copy', '-map', '0', '-map', '1',
  51. '-metadata:s:v', 'title="Album cover"', '-metadata:s:v', 'comment="Cover (Front)"']
  52. self._downloader.to_screen('[ffmpeg] Adding thumbnail to "%s"' % filename)
  53. self.run_ffmpeg_multiple_files([filename, thumbnail_filename], temp_filename, options)
  54. if not self._already_have_thumbnail:
  55. os.remove(encodeFilename(thumbnail_filename))
  56. os.remove(encodeFilename(filename))
  57. os.rename(encodeFilename(temp_filename), encodeFilename(filename))
  58. elif info['ext'] in ['m4a', 'mp4']:
  59. if not check_executable('AtomicParsley', ['-v']):
  60. raise EmbedThumbnailPPError('AtomicParsley was not found. Please install.')
  61. cmd = [encodeFilename('AtomicParsley', True),
  62. encodeFilename(filename, True),
  63. encodeArgument('--artwork'),
  64. encodeFilename(thumbnail_filename, True),
  65. encodeArgument('-o'),
  66. encodeFilename(temp_filename, True)]
  67. self._downloader.to_screen('[atomicparsley] Adding thumbnail to "%s"' % filename)
  68. if self._downloader.params.get('verbose', False):
  69. self._downloader.to_screen('[debug] AtomicParsley command line: %s' % shell_quote(cmd))
  70. p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  71. stdout, stderr = p.communicate()
  72. if p.returncode != 0:
  73. msg = stderr.decode('utf-8', 'replace').strip()
  74. raise EmbedThumbnailPPError(msg)
  75. if not self._already_have_thumbnail:
  76. os.remove(encodeFilename(thumbnail_filename))
  77. # for formats that don't support thumbnails (like 3gp) AtomicParsley
  78. # won't create to the temporary file
  79. if b'No changes' in stdout:
  80. self._downloader.report_warning('The file format doesn\'t support embedding a thumbnail')
  81. else:
  82. os.remove(encodeFilename(filename))
  83. os.rename(encodeFilename(temp_filename), encodeFilename(filename))
  84. else:
  85. raise EmbedThumbnailPPError('Only mp3 and m4a/mp4 are supported for thumbnail embedding for now.')
  86. return [], info