6 from .common
import PostProcessor
7 from .ffmpeg
import FFmpegPostProcessor
, FFmpegThumbnailsConvertorPP
8 from ..compat
import imghdr
9 from ..dependencies
import mutagen
21 from mutagen
.flac
import FLAC
, Picture
22 from mutagen
.mp4
import MP4
, MP4Cover
23 from mutagen
.oggopus
import OggOpus
24 from mutagen
.oggvorbis
import OggVorbis
27 class EmbedThumbnailPPError(PostProcessingError
):
31 class EmbedThumbnailPP(FFmpegPostProcessor
):
33 def __init__(self
, downloader
=None, already_have_thumbnail
=False):
34 FFmpegPostProcessor
.__init
__(self
, downloader
)
35 self
._already
_have
_thumbnail
= already_have_thumbnail
37 def _get_thumbnail_resolution(self
, filename
, thumbnail_dict
):
39 width
, height
= thumbnail_dict
.get('width'), thumbnail_dict
.get('height')
44 size_regex
= r
',\s*(?P<w>\d+)x(?P<h>\d+)\s*[,\[]'
45 size_result
= self
.run_ffmpeg(filename
, None, ['-hide_banner'], expected_retcodes
=(1,))
46 mobj
= re
.search(size_regex
, size_result
)
49 except PostProcessingError
as err
:
50 self
.report_warning(f
'unable to find the thumbnail resolution; {err}')
52 return int(mobj
.group('w')), int(mobj
.group('h'))
54 def _report_run(self
, exe
, filename
):
55 self
.to_screen(f
'{exe}: Adding thumbnail to "{filename}"')
57 @PostProcessor._restrict
_to
(images
=False)
59 filename
= info
['filepath']
60 temp_filename
= prepend_extension(filename
, 'temp')
62 if not info
.get('thumbnails'):
63 self
.to_screen('There aren\'t any thumbnails to embed')
66 idx
= next((-i
for i
, t
in enumerate(info
['thumbnails'][::-1], 1) if t
.get('filepath')), None)
68 self
.to_screen('There are no thumbnails on disk')
70 thumbnail_filename
= info
['thumbnails'][idx
]['filepath']
71 if not os
.path
.exists(encodeFilename(thumbnail_filename
)):
72 self
.report_warning('Skipping embedding the thumbnail because the file is missing.')
75 # Correct extension for WebP file with wrong extension (see #25687, #25717)
76 convertor
= FFmpegThumbnailsConvertorPP(self
._downloader
)
77 convertor
.fixup_webp(info
, idx
)
79 original_thumbnail
= thumbnail_filename
= info
['thumbnails'][idx
]['filepath']
81 # Convert unsupported thumbnail formats (see #25687, #25717)
82 # PNG is preferred since JPEG is lossy
83 thumbnail_ext
= os
.path
.splitext(thumbnail_filename
)[1][1:]
84 if info
['ext'] not in ('mkv', 'mka') and thumbnail_ext
not in ('jpg', 'jpeg', 'png'):
85 thumbnail_filename
= convertor
.convert_thumbnail(thumbnail_filename
, 'png')
88 mtime
= os
.stat(encodeFilename(filename
)).st_mtime
91 if info
['ext'] == 'mp3':
93 '-c', 'copy', '-map', '0:0', '-map', '1:0', '-write_id3v1', '1', '-id3v2_version', '3',
94 '-metadata:s:v', 'title="Album cover"', '-metadata:s:v', 'comment=Cover (front)']
96 self
._report
_run
('ffmpeg', filename
)
97 self
.run_ffmpeg_multiple_files([filename
, thumbnail_filename
], temp_filename
, options
)
99 elif info
['ext'] in ['mkv', 'mka']:
100 options
= list(self
.stream_copy_opts())
102 mimetype
= f
'image/{thumbnail_ext.replace("jpg", "jpeg")}'
103 old_stream
, new_stream
= self
.get_stream_number(
104 filename
, ('tags', 'mimetype'), mimetype
)
105 if old_stream
is not None:
106 options
.extend(['-map', f
'-0:{old_stream}'])
109 '-attach', self
._ffmpeg
_filename
_argument
(thumbnail_filename
),
110 f
'-metadata:s:{new_stream}', f
'mimetype={mimetype}',
111 f
'-metadata:s:{new_stream}', f
'filename=cover.{thumbnail_ext}'])
113 self
._report
_run
('ffmpeg', filename
)
114 self
.run_ffmpeg(filename
, temp_filename
, options
)
116 elif info
['ext'] in ['m4a', 'mp4', 'm4v', 'mov']:
117 prefer_atomicparsley
= 'embed-thumbnail-atomicparsley' in self
.get_param('compat_opts', [])
118 # Method 1: Use mutagen
119 if not mutagen
or prefer_atomicparsley
:
122 self
._report
_run
('mutagen', filename
)
123 f
= {'jpeg': MP4Cover
.FORMAT_JPEG
, 'png': MP4Cover
.FORMAT_PNG
}
125 with
open(thumbnail_filename
, 'rb') as thumbfile
:
126 thumb_data
= thumbfile
.read()
128 type_
= imghdr
.what(h
=thumb_data
)
130 raise ValueError('could not determine image type')
132 raise ValueError(f
'incompatible image type: {type_}')
135 # NOTE: the 'covr' atom is a non-standard MPEG-4 atom,
136 # Apple iTunes 'M4A' files include the 'moov.udta.meta.ilst' atom.
137 meta
.tags
['covr'] = [MP4Cover(data
=thumb_data
, imageformat
=f
[type_
])]
139 temp_filename
= filename
140 except Exception as err
:
141 self
.report_warning(f
'unable to embed using mutagen; {err}')
144 # Method 2: Use AtomicParsley
147 atomicparsley
= next((
148 # libatomicparsley.so : See https://github.com/xibr/ytdlp-lazy/issues/1
149 x
for x
in ['AtomicParsley', 'atomicparsley', 'libatomicparsley.so']
150 if check_executable(x
, ['-v'])), None)
151 if atomicparsley
is None:
152 self
.to_screen('Neither mutagen nor AtomicParsley was found. Falling back to ffmpeg')
155 if not prefer_atomicparsley
:
156 self
.to_screen('mutagen was not found. Falling back to AtomicParsley')
157 cmd
= [encodeFilename(atomicparsley
, True),
158 encodeFilename(filename
, True),
159 encodeArgument('--artwork'),
160 encodeFilename(thumbnail_filename
, True),
161 encodeArgument('-o'),
162 encodeFilename(temp_filename
, True)]
163 cmd
+= [encodeArgument(o
) for o
in self
._configuration
_args
('AtomicParsley')]
165 self
._report
_run
('atomicparsley', filename
)
166 self
.write_debug(f
'AtomicParsley command line: {shell_quote(cmd)}')
167 stdout
, stderr
, returncode
= Popen
.run(cmd
, text
=True, stdout
=subprocess
.PIPE
, stderr
=subprocess
.PIPE
)
169 self
.report_warning(f
'Unable to embed thumbnails using AtomicParsley; {stderr.strip()}')
171 # for formats that don't support thumbnails (like 3gp) AtomicParsley
172 # won't create to the temporary file
173 elif 'No changes' in stdout
:
174 self
.report_warning('The file format doesn\'t support embedding a thumbnail')
177 # Method 3: Use ffmpeg+ffprobe
178 # Thumbnails attached using this method doesn't show up as cover in some cases
179 # See https://github.com/yt-dlp/yt-dlp/issues/2125, https://github.com/yt-dlp/yt-dlp/issues/411
183 options
= [*self
.stream_copy_opts(), '-map', '1']
185 old_stream
, new_stream
= self
.get_stream_number(
186 filename
, ('disposition', 'attached_pic'), 1)
187 if old_stream
is not None:
188 options
.extend(['-map', f
'-0:{old_stream}'])
190 options
.extend([f
'-disposition:{new_stream}', 'attached_pic'])
192 self
._report
_run
('ffmpeg', filename
)
193 self
.run_ffmpeg_multiple_files([filename
, thumbnail_filename
], temp_filename
, options
)
194 except PostProcessingError
as err
:
196 raise EmbedThumbnailPPError(f
'Unable to embed using ffprobe & ffmpeg; {err}')
198 elif info
['ext'] in ['ogg', 'opus', 'flac']:
200 raise EmbedThumbnailPPError('module mutagen was not found. Please install using `python3 -m pip install mutagen`')
202 self
._report
_run
('mutagen', filename
)
203 f
= {'opus': OggOpus
, 'flac': FLAC
, 'ogg': OggVorbis
}[info
['ext']](filename
)
206 pic
.mime
= f
'image/{imghdr.what(thumbnail_filename)}'
207 with
open(thumbnail_filename
, 'rb') as thumbfile
:
208 pic
.data
= thumbfile
.read()
209 pic
.type = 3 # front cover
210 res
= self
._get
_thumbnail
_resolution
(thumbnail_filename
, info
['thumbnails'][idx
])
212 pic
.width
, pic
.height
= res
214 if info
['ext'] == 'flac':
217 # https://wiki.xiph.org/VorbisComment#METADATA_BLOCK_PICTURE
218 f
['METADATA_BLOCK_PICTURE'] = base64
.b64encode(pic
.write()).decode('ascii')
220 temp_filename
= filename
223 raise EmbedThumbnailPPError('Supported filetypes for thumbnail embedding are: mp3, mkv/mka, ogg/opus/flac, m4a/mp4/m4v/mov')
225 if success
and temp_filename
!= filename
:
226 os
.replace(temp_filename
, filename
)
228 self
.try_utime(filename
, mtime
, mtime
)
229 converted
= original_thumbnail
!= thumbnail_filename
230 self
._delete
_downloaded
_files
(
231 thumbnail_filename
if converted
or not self
._already
_have
_thumbnail
else None,
232 original_thumbnail
if converted
and not self
._already
_have
_thumbnail
else None,