2 from __future__
import unicode_literals
11 from mutagen
.flac
import Picture
, FLAC
12 from mutagen
.mp4
import MP4
, MP4Cover
13 from mutagen
.oggopus
import OggOpus
14 from mutagen
.oggvorbis
import OggVorbis
19 from .common
import PostProcessor
22 FFmpegThumbnailsConvertorPP
,
36 class EmbedThumbnailPPError(PostProcessingError
):
40 class EmbedThumbnailPP(FFmpegPostProcessor
):
42 def __init__(self
, downloader
=None, already_have_thumbnail
=False):
43 FFmpegPostProcessor
.__init
__(self
, downloader
)
44 self
._already
_have
_thumbnail
= already_have_thumbnail
46 def _get_thumbnail_resolution(self
, filename
, thumbnail_dict
):
48 width
, height
= thumbnail_dict
.get('width'), thumbnail_dict
.get('height')
53 size_regex
= r
',\s*(?P<w>\d+)x(?P<h>\d+)\s*[,\[]'
54 size_result
= self
.run_ffmpeg(filename
, None, ['-hide_banner'], expected_retcodes
=(1,))
55 mobj
= re
.search(size_regex
, size_result
)
58 except PostProcessingError
as err
:
59 self
.report_warning('unable to find the thumbnail resolution; %s' % error_to_compat_str(err
))
61 return int(mobj
.group('w')), int(mobj
.group('h'))
63 def _report_run(self
, exe
, filename
):
64 self
.to_screen('%s: Adding thumbnail to "%s"' % (exe
, filename
))
66 @PostProcessor._restrict_to(images
=False)
68 filename
= info
['filepath']
69 temp_filename
= prepend_extension(filename
, 'temp')
71 if not info
.get('thumbnails'):
72 self
.to_screen('There aren\'t any thumbnails to embed')
75 idx
= next((-i
for i
, t
in enumerate(info
['thumbnails'][::-1], 1) if t
.get('filepath')), None)
77 self
.to_screen('There are no thumbnails on disk')
79 thumbnail_filename
= info
['thumbnails'][idx
]['filepath']
80 if not os
.path
.exists(encodeFilename(thumbnail_filename
)):
81 self
.report_warning('Skipping embedding the thumbnail because the file is missing.')
84 # Correct extension for WebP file with wrong extension (see #25687, #25717)
85 convertor
= FFmpegThumbnailsConvertorPP(self
._downloader
)
86 convertor
.fixup_webp(info
, idx
)
88 original_thumbnail
= thumbnail_filename
= info
['thumbnails'][idx
]['filepath']
90 # Convert unsupported thumbnail formats to PNG (see #25687, #25717)
91 # Original behavior was to convert to JPG, but since JPG is a lossy
92 # format, there will be some additional data loss.
93 # PNG, on the other hand, is lossless.
94 thumbnail_ext
= os
.path
.splitext(thumbnail_filename
)[1][1:]
95 if thumbnail_ext
not in ('jpg', 'jpeg', 'png'):
96 thumbnail_filename
= convertor
.convert_thumbnail(thumbnail_filename
, 'png')
99 mtime
= os
.stat(encodeFilename(filename
)).st_mtime
102 if info
['ext'] == 'mp3':
104 '-c', 'copy', '-map', '0:0', '-map', '1:0', '-id3v2_version', '3',
105 '-metadata:s:v', 'title="Album cover"', '-metadata:s:v', 'comment="Cover (front)"']
107 self
._report
_run
('ffmpeg', filename
)
108 self
.run_ffmpeg_multiple_files([filename
, thumbnail_filename
], temp_filename
, options
)
110 elif info
['ext'] in ['mkv', 'mka']:
111 options
= ['-c', 'copy', '-map', '0', '-dn']
113 mimetype
= 'image/%s' % ('png' if thumbnail_ext
== 'png' else 'jpeg')
114 old_stream
, new_stream
= self
.get_stream_number(
115 filename
, ('tags', 'mimetype'), mimetype
)
116 if old_stream
is not None:
117 options
.extend(['-map', '-0:%d' % old_stream
])
120 '-attach', thumbnail_filename
,
121 '-metadata:s:%d' % new_stream
, 'mimetype=%s' % mimetype
,
122 '-metadata:s:%d' % new_stream
, 'filename=cover.%s' % thumbnail_ext
])
124 self
._report
_run
('ffmpeg', filename
)
125 self
.run_ffmpeg(filename
, temp_filename
, options
)
127 elif info
['ext'] in ['m4a', 'mp4', 'mov']:
128 prefer_atomicparsley
= 'embed-thumbnail-atomicparsley' in self
.get_param('compat_opts', [])
129 # Method 1: Use mutagen
130 if not has_mutagen
or prefer_atomicparsley
:
134 self
._report
_run
('mutagen', filename
)
136 # NOTE: the 'covr' atom is a non-standard MPEG-4 atom,
137 # Apple iTunes 'M4A' files include the 'moov.udta.meta.ilst' atom.
138 f
= {'jpeg': MP4Cover.FORMAT_JPEG, 'png': MP4Cover.FORMAT_PNG}
[imghdr
.what(thumbnail_filename
)]
139 with open(thumbnail_filename
, 'rb') as thumbfile
:
140 thumb_data
= thumbfile
.read()
141 meta
.tags
['covr'] = [MP4Cover(data
=thumb_data
, imageformat
=f
)]
143 temp_filename
= filename
144 except Exception as err
:
145 self
.report_warning('unable to embed using mutagen; %s' % error_to_compat_str(err
))
148 # Method 2: Use ffmpeg+ffprobe
149 if not success
and not prefer_atomicparsley
:
152 options
= ['-c', 'copy', '-map', '0', '-dn', '-map', '1']
154 old_stream
, new_stream
= self
.get_stream_number(
155 filename
, ('disposition', 'attached_pic'), 1)
156 if old_stream
is not None:
157 options
.extend(['-map', '-0:%d' % old_stream
])
159 options
.extend(['-disposition:%s' % new_stream
, 'attached_pic'])
161 self
._report
_run
('ffmpeg', filename
)
162 self
.run_ffmpeg_multiple_files([filename
, thumbnail_filename
], temp_filename
, options
)
163 except PostProcessingError
as err
:
164 self
.report_warning('unable to embed using ffprobe & ffmpeg; %s' % error_to_compat_str(err
))
167 # Method 3: Use AtomicParsley
170 atomicparsley
= next((
171 x
for x
in ['AtomicParsley', 'atomicparsley']
172 if check_executable(x
, ['-v'])), None)
173 if atomicparsley
is None:
174 raise EmbedThumbnailPPError('AtomicParsley was not found. Please install')
176 cmd
= [encodeFilename(atomicparsley
, True),
177 encodeFilename(filename
, True),
178 encodeArgument('--artwork'),
179 encodeFilename(thumbnail_filename
, True),
180 encodeArgument('-o'),
181 encodeFilename(temp_filename
, True)]
182 cmd
+= [encodeArgument(o
) for o
in self
._configuration
_args
('AtomicParsley')]
184 self
._report
_run
('atomicparsley', filename
)
185 self
.write_debug('AtomicParsley command line: %s' % shell_quote(cmd
))
186 p
= Popen(cmd
, stdout
=subprocess
.PIPE
, stderr
=subprocess
.PIPE
)
187 stdout
, stderr
= p
.communicate_or_kill()
188 if p
.returncode
!= 0:
189 msg
= stderr
.decode('utf-8', 'replace').strip()
190 raise EmbedThumbnailPPError(msg
)
191 # for formats that don't support thumbnails (like 3gp) AtomicParsley
192 # won't create to the temporary file
193 if b
'No changes' in stdout
:
194 self
.report_warning('The file format doesn\'t support embedding a thumbnail')
197 elif info
['ext'] in ['ogg', 'opus', 'flac']:
199 raise EmbedThumbnailPPError('module mutagen was not found. Please install using `python -m pip install mutagen`')
201 self
._report
_run
('mutagen', filename
)
202 f
= {'opus': OggOpus, 'flac': FLAC, 'ogg': OggVorbis}
[info
['ext']](filename
)
205 pic
.mime
= 'image/%s' % imghdr
.what(thumbnail_filename
)
206 with open(thumbnail_filename
, 'rb') as thumbfile
:
207 pic
.data
= thumbfile
.read()
208 pic
.type = 3 # front cover
209 res
= self
._get
_thumbnail
_resolution
(thumbnail_filename
, info
['thumbnails'][idx
])
211 pic
.width
, pic
.height
= res
213 if info
['ext'] == 'flac':
216 # https://wiki.xiph.org/VorbisComment#METADATA_BLOCK_PICTURE
217 f
['METADATA_BLOCK_PICTURE'] = base64
.b64encode(pic
.write()).decode('ascii')
219 temp_filename
= filename
222 raise EmbedThumbnailPPError('Supported filetypes for thumbnail embedding are: mp3, mkv/mka, ogg/opus/flac, m4a/mp4/mov')
224 if success
and temp_filename
!= filename
:
225 os
.replace(temp_filename
, filename
)
227 self
.try_utime(filename
, mtime
, mtime
)
229 files_to_delete
= [thumbnail_filename
]
230 if self
._already
_have
_thumbnail
:
231 if original_thumbnail
== thumbnail_filename
:
233 elif original_thumbnail
!= thumbnail_filename
:
234 files_to_delete
.append(original_thumbnail
)
235 return files_to_delete
, info