logo

youtube-dl

[mirror] Download/Watch videos from video hostersgit clone https://hacktivis.me/git/mirror/youtube-dl.git

embedthumbnail.py (5905B)


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