We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
Disable thumbnails conversion
### Checklist

- [X] I'm reporting a feature request
- [X] I've looked through the [README](https://github.com/yt-dlp/yt-dlp#readme)
- [X] I've verified that I'm running yt-dlp version **2022.03.08.1**. ([update instructions](https://github.com/yt-dlp/yt-dlp#update))
- [X] I've searched the [bugtracker](https://github.com/yt-dlp/yt-dlp/issues?q=) for similar issues including closed ones. DO NOT post duplicates
- [X] I've read the [guidelines for opening an issue](https://github.com/yt-dlp/yt-dlp/blob/master/CONTRIBUTING.md#opening-an-issue)

### Description

When embedding thumbnails using `--embed-thumbnail`, they get automatically converted to `.png`
People like me would like to keep them in the original format. (i.e. `webp`), which is compatible with the `.mkv` container when inserted as attachment.

actual output
```
[ThumbnailsConvertor] Converting thumbnail "/path/to/thumbnail.webp" to png
[EmbedThumbnail] ffmpeg: Adding thumbnail to "/path/to/video.mkv"
```

expected output
```
[EmbedThumbnail] ffmpeg: Adding thumbnail to "/path/to/thumbnail.mkv"
```

--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `yt_dlp/postprocessor/embedthumbnail.py`
Content:
```
1 import base64
2 import imghdr
3 import os
4 import re
5 import subprocess
6 
7 from .common import PostProcessor
8 from .ffmpeg import FFmpegPostProcessor, FFmpegThumbnailsConvertorPP
9 from ..dependencies import mutagen
10 from ..utils import (
11     Popen,
12     PostProcessingError,
13     check_executable,
14     encodeArgument,
15     encodeFilename,
16     error_to_compat_str,
17     prepend_extension,
18     shell_quote,
19 )
20 
21 if mutagen:
22     from mutagen.flac import FLAC, Picture
23     from mutagen.mp4 import MP4, MP4Cover
24     from mutagen.oggopus import OggOpus
25     from mutagen.oggvorbis import OggVorbis
26 
27 
28 class EmbedThumbnailPPError(PostProcessingError):
29     pass
30 
31 
32 class EmbedThumbnailPP(FFmpegPostProcessor):
33 
34     def __init__(self, downloader=None, already_have_thumbnail=False):
35         FFmpegPostProcessor.__init__(self, downloader)
36         self._already_have_thumbnail = already_have_thumbnail
37 
38     def _get_thumbnail_resolution(self, filename, thumbnail_dict):
39         def guess():
40             width, height = thumbnail_dict.get('width'), thumbnail_dict.get('height')
41             if width and height:
42                 return width, height
43 
44         try:
45             size_regex = r',\s*(?P<w>\d+)x(?P<h>\d+)\s*[,\[]'
46             size_result = self.run_ffmpeg(filename, None, ['-hide_banner'], expected_retcodes=(1,))
47             mobj = re.search(size_regex, size_result)
48             if mobj is None:
49                 return guess()
50         except PostProcessingError as err:
51             self.report_warning('unable to find the thumbnail resolution; %s' % error_to_compat_str(err))
52             return guess()
53         return int(mobj.group('w')), int(mobj.group('h'))
54 
55     def _report_run(self, exe, filename):
56         self.to_screen(f'{exe}: Adding thumbnail to "{filename}"')
57 
58     @PostProcessor._restrict_to(images=False)
59     def run(self, info):
60         filename = info['filepath']
61         temp_filename = prepend_extension(filename, 'temp')
62 
63         if not info.get('thumbnails'):
64             self.to_screen('There aren\'t any thumbnails to embed')
65             return [], info
66 
67         idx = next((-i for i, t in enumerate(info['thumbnails'][::-1], 1) if t.get('filepath')), None)
68         if idx is None:
69             self.to_screen('There are no thumbnails on disk')
70             return [], info
71         thumbnail_filename = info['thumbnails'][idx]['filepath']
72         if not os.path.exists(encodeFilename(thumbnail_filename)):
73             self.report_warning('Skipping embedding the thumbnail because the file is missing.')
74             return [], info
75 
76         # Correct extension for WebP file with wrong extension (see #25687, #25717)
77         convertor = FFmpegThumbnailsConvertorPP(self._downloader)
78         convertor.fixup_webp(info, idx)
79 
80         original_thumbnail = thumbnail_filename = info['thumbnails'][idx]['filepath']
81 
82         # Convert unsupported thumbnail formats to PNG (see #25687, #25717)
83         # Original behavior was to convert to JPG, but since JPG is a lossy
84         # format, there will be some additional data loss.
85         # PNG, on the other hand, is lossless.
86         thumbnail_ext = os.path.splitext(thumbnail_filename)[1][1:]
87         if thumbnail_ext not in ('jpg', 'jpeg', 'png'):
88             thumbnail_filename = convertor.convert_thumbnail(thumbnail_filename, 'png')
89             thumbnail_ext = 'png'
90 
91         mtime = os.stat(encodeFilename(filename)).st_mtime
92 
93         success = True
94         if info['ext'] == 'mp3':
95             options = [
96                 '-c', 'copy', '-map', '0:0', '-map', '1:0', '-write_id3v1', '1', '-id3v2_version', '3',
97                 '-metadata:s:v', 'title="Album cover"', '-metadata:s:v', 'comment="Cover (front)"']
98 
99             self._report_run('ffmpeg', filename)
100             self.run_ffmpeg_multiple_files([filename, thumbnail_filename], temp_filename, options)
101 
102         elif info['ext'] in ['mkv', 'mka']:
103             options = list(self.stream_copy_opts())
104 
105             mimetype = 'image/%s' % ('png' if thumbnail_ext == 'png' else 'jpeg')
106             old_stream, new_stream = self.get_stream_number(
107                 filename, ('tags', 'mimetype'), mimetype)
108             if old_stream is not None:
109                 options.extend(['-map', '-0:%d' % old_stream])
110                 new_stream -= 1
111             options.extend([
112                 '-attach', thumbnail_filename,
113                 '-metadata:s:%d' % new_stream, 'mimetype=%s' % mimetype,
114                 '-metadata:s:%d' % new_stream, 'filename=cover.%s' % thumbnail_ext])
115 
116             self._report_run('ffmpeg', filename)
117             self.run_ffmpeg(filename, temp_filename, options)
118 
119         elif info['ext'] in ['m4a', 'mp4', 'mov']:
120             prefer_atomicparsley = 'embed-thumbnail-atomicparsley' in self.get_param('compat_opts', [])
121             # Method 1: Use mutagen
122             if not mutagen or prefer_atomicparsley:
123                 success = False
124             else:
125                 try:
126                     self._report_run('mutagen', filename)
127                     meta = MP4(filename)
128                     # NOTE: the 'covr' atom is a non-standard MPEG-4 atom,
129                     # Apple iTunes 'M4A' files include the 'moov.udta.meta.ilst' atom.
130                     f = {'jpeg': MP4Cover.FORMAT_JPEG, 'png': MP4Cover.FORMAT_PNG}[imghdr.what(thumbnail_filename)]
131                     with open(thumbnail_filename, 'rb') as thumbfile:
132                         thumb_data = thumbfile.read()
133                     meta.tags['covr'] = [MP4Cover(data=thumb_data, imageformat=f)]
134                     meta.save()
135                     temp_filename = filename
136                 except Exception as err:
137                     self.report_warning('unable to embed using mutagen; %s' % error_to_compat_str(err))
138                     success = False
139 
140             # Method 2: Use AtomicParsley
141             if not success:
142                 success = True
143                 atomicparsley = next((
144                     x for x in ['AtomicParsley', 'atomicparsley']
145                     if check_executable(x, ['-v'])), None)
146                 if atomicparsley is None:
147                     self.to_screen('Neither mutagen nor AtomicParsley was found. Falling back to ffmpeg')
148                     success = False
149                 else:
150                     if not prefer_atomicparsley:
151                         self.to_screen('mutagen was not found. Falling back to AtomicParsley')
152                     cmd = [encodeFilename(atomicparsley, True),
153                            encodeFilename(filename, True),
154                            encodeArgument('--artwork'),
155                            encodeFilename(thumbnail_filename, True),
156                            encodeArgument('-o'),
157                            encodeFilename(temp_filename, True)]
158                     cmd += [encodeArgument(o) for o in self._configuration_args('AtomicParsley')]
159 
160                     self._report_run('atomicparsley', filename)
161                     self.write_debug('AtomicParsley command line: %s' % shell_quote(cmd))
162                     p = Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
163                     stdout, stderr = p.communicate_or_kill()
164                     if p.returncode != 0:
165                         msg = stderr.decode('utf-8', 'replace').strip()
166                         self.report_warning(f'Unable to embed thumbnails using AtomicParsley; {msg}')
167                     # for formats that don't support thumbnails (like 3gp) AtomicParsley
168                     # won't create to the temporary file
169                     if b'No changes' in stdout:
170                         self.report_warning('The file format doesn\'t support embedding a thumbnail')
171                         success = False
172 
173             # Method 3: Use ffmpeg+ffprobe
174             # Thumbnails attached using this method doesn't show up as cover in some cases
175             # See https://github.com/yt-dlp/yt-dlp/issues/2125, https://github.com/yt-dlp/yt-dlp/issues/411
176             if not success:
177                 success = True
178                 try:
179                     options = [*self.stream_copy_opts(), '-map', '1']
180 
181                     old_stream, new_stream = self.get_stream_number(
182                         filename, ('disposition', 'attached_pic'), 1)
183                     if old_stream is not None:
184                         options.extend(['-map', '-0:%d' % old_stream])
185                         new_stream -= 1
186                     options.extend(['-disposition:%s' % new_stream, 'attached_pic'])
187 
188                     self._report_run('ffmpeg', filename)
189                     self.run_ffmpeg_multiple_files([filename, thumbnail_filename], temp_filename, options)
190                 except PostProcessingError as err:
191                     success = False
192                     raise EmbedThumbnailPPError(f'Unable to embed using ffprobe & ffmpeg; {err}')
193 
194         elif info['ext'] in ['ogg', 'opus', 'flac']:
195             if not mutagen:
196                 raise EmbedThumbnailPPError('module mutagen was not found. Please install using `python -m pip install mutagen`')
197 
198             self._report_run('mutagen', filename)
199             f = {'opus': OggOpus, 'flac': FLAC, 'ogg': OggVorbis}[info['ext']](filename)
200 
201             pic = Picture()
202             pic.mime = 'image/%s' % imghdr.what(thumbnail_filename)
203             with open(thumbnail_filename, 'rb') as thumbfile:
204                 pic.data = thumbfile.read()
205             pic.type = 3  # front cover
206             res = self._get_thumbnail_resolution(thumbnail_filename, info['thumbnails'][idx])
207             if res is not None:
208                 pic.width, pic.height = res
209 
210             if info['ext'] == 'flac':
211                 f.add_picture(pic)
212             else:
213                 # https://wiki.xiph.org/VorbisComment#METADATA_BLOCK_PICTURE
214                 f['METADATA_BLOCK_PICTURE'] = base64.b64encode(pic.write()).decode('ascii')
215             f.save()
216             temp_filename = filename
217 
218         else:
219             raise EmbedThumbnailPPError('Supported filetypes for thumbnail embedding are: mp3, mkv/mka, ogg/opus/flac, m4a/mp4/mov')
220 
221         if success and temp_filename != filename:
222             os.replace(temp_filename, filename)
223 
224         self.try_utime(filename, mtime, mtime)
225 
226         files_to_delete = [thumbnail_filename]
227         if self._already_have_thumbnail:
228             if original_thumbnail == thumbnail_filename:
229                 files_to_delete = []
230         elif original_thumbnail != thumbnail_filename:
231             files_to_delete.append(original_thumbnail)
232         return files_to_delete, info
233
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/yt_dlp/postprocessor/embedthumbnail.py b/yt_dlp/postprocessor/embedthumbnail.py
--- a/yt_dlp/postprocessor/embedthumbnail.py
+++ b/yt_dlp/postprocessor/embedthumbnail.py
@@ -79,12 +79,10 @@
 
         original_thumbnail = thumbnail_filename = info['thumbnails'][idx]['filepath']
 
-        # Convert unsupported thumbnail formats to PNG (see #25687, #25717)
-        # Original behavior was to convert to JPG, but since JPG is a lossy
-        # format, there will be some additional data loss.
-        # PNG, on the other hand, is lossless.
         thumbnail_ext = os.path.splitext(thumbnail_filename)[1][1:]
-        if thumbnail_ext not in ('jpg', 'jpeg', 'png'):
+        # Convert unsupported thumbnail formats (see #25687, #25717)
+        # PNG is preferred since JPEG is lossy
+        if info['ext'] not in ('mkv', 'mka') and thumbnail_ext not in ('jpg', 'jpeg', 'png'):
             thumbnail_filename = convertor.convert_thumbnail(thumbnail_filename, 'png')
             thumbnail_ext = 'png'
 
@@ -102,7 +100,7 @@
         elif info['ext'] in ['mkv', 'mka']:
             options = list(self.stream_copy_opts())
 
-            mimetype = 'image/%s' % ('png' if thumbnail_ext == 'png' else 'jpeg')
+            mimetype = 'image/%s' % ('jpeg' if thumbnail_ext in ('jpg', 'jpeg') else thumbnail_ext)
             old_stream, new_stream = self.get_stream_number(
                 filename, ('tags', 'mimetype'), mimetype)
             if old_stream is not None:

{"golden_diff": "diff --git a/yt_dlp/postprocessor/embedthumbnail.py b/yt_dlp/postprocessor/embedthumbnail.py\n--- a/yt_dlp/postprocessor/embedthumbnail.py\n+++ b/yt_dlp/postprocessor/embedthumbnail.py\n@@ -79,12 +79,10 @@\n \n         original_thumbnail = thumbnail_filename = info['thumbnails'][idx]['filepath']\n \n-        # Convert unsupported thumbnail formats to PNG (see #25687, #25717)\n-        # Original behavior was to convert to JPG, but since JPG is a lossy\n-        # format, there will be some additional data loss.\n-        # PNG, on the other hand, is lossless.\n         thumbnail_ext = os.path.splitext(thumbnail_filename)[1][1:]\n-        if thumbnail_ext not in ('jpg', 'jpeg', 'png'):\n+        # Convert unsupported thumbnail formats (see #25687, #25717)\n+        # PNG is preferred since JPEG is lossy\n+        if info['ext'] not in ('mkv', 'mka') and thumbnail_ext not in ('jpg', 'jpeg', 'png'):\n             thumbnail_filename = convertor.convert_thumbnail(thumbnail_filename, 'png')\n             thumbnail_ext = 'png'\n \n@@ -102,7 +100,7 @@\n         elif info['ext'] in ['mkv', 'mka']:\n             options = list(self.stream_copy_opts())\n \n-            mimetype = 'image/%s' % ('png' if thumbnail_ext == 'png' else 'jpeg')\n+            mimetype = 'image/%s' % ('jpeg' if thumbnail_ext in ('jpg', 'jpeg') else thumbnail_ext)\n             old_stream, new_stream = self.get_stream_number(\n                 filename, ('tags', 'mimetype'), mimetype)\n             if old_stream is not None:\n", "issue": "Disable thumbnails conversion\n### Checklist\r\n\r\n- [X] I'm reporting a feature request\r\n- [X] I've looked through the [README](https://github.com/yt-dlp/yt-dlp#readme)\r\n- [X] I've verified that I'm running yt-dlp version **2022.03.08.1**. ([update instructions](https://github.com/yt-dlp/yt-dlp#update))\r\n- [X] I've searched the [bugtracker](https://github.com/yt-dlp/yt-dlp/issues?q=) for similar issues including closed ones. DO NOT post duplicates\r\n- [X] I've read the [guidelines for opening an issue](https://github.com/yt-dlp/yt-dlp/blob/master/CONTRIBUTING.md#opening-an-issue)\r\n\r\n### Description\r\n\r\nWhen embedding thumbnails using `--embed-thumbnail`, they get automatically converted to `.png`\r\nPeople like me would like to keep them in the original format. (i.e. `webp`), which is compatible with the `.mkv` container when inserted as attachment.\r\n\r\nactual output\r\n```\r\n[ThumbnailsConvertor] Converting thumbnail \"/path/to/thumbnail.webp\" to png\r\n[EmbedThumbnail] ffmpeg: Adding thumbnail to \"/path/to/video.mkv\"\r\n```\r\n\r\nexpected output\r\n```\r\n[EmbedThumbnail] ffmpeg: Adding thumbnail to \"/path/to/thumbnail.mkv\"\r\n```\n", "before_files": [{"content": "import base64\nimport imghdr\nimport os\nimport re\nimport subprocess\n\nfrom .common import PostProcessor\nfrom .ffmpeg import FFmpegPostProcessor, FFmpegThumbnailsConvertorPP\nfrom ..dependencies import mutagen\nfrom ..utils import (\n    Popen,\n    PostProcessingError,\n    check_executable,\n    encodeArgument,\n    encodeFilename,\n    error_to_compat_str,\n    prepend_extension,\n    shell_quote,\n)\n\nif mutagen:\n    from mutagen.flac import FLAC, Picture\n    from mutagen.mp4 import MP4, MP4Cover\n    from mutagen.oggopus import OggOpus\n    from mutagen.oggvorbis import OggVorbis\n\n\nclass EmbedThumbnailPPError(PostProcessingError):\n    pass\n\n\nclass EmbedThumbnailPP(FFmpegPostProcessor):\n\n    def __init__(self, downloader=None, already_have_thumbnail=False):\n        FFmpegPostProcessor.__init__(self, downloader)\n        self._already_have_thumbnail = already_have_thumbnail\n\n    def _get_thumbnail_resolution(self, filename, thumbnail_dict):\n        def guess():\n            width, height = thumbnail_dict.get('width'), thumbnail_dict.get('height')\n            if width and height:\n                return width, height\n\n        try:\n            size_regex = r',\\s*(?P<w>\\d+)x(?P<h>\\d+)\\s*[,\\[]'\n            size_result = self.run_ffmpeg(filename, None, ['-hide_banner'], expected_retcodes=(1,))\n            mobj = re.search(size_regex, size_result)\n            if mobj is None:\n                return guess()\n        except PostProcessingError as err:\n            self.report_warning('unable to find the thumbnail resolution; %s' % error_to_compat_str(err))\n            return guess()\n        return int(mobj.group('w')), int(mobj.group('h'))\n\n    def _report_run(self, exe, filename):\n        self.to_screen(f'{exe}: Adding thumbnail to \"{filename}\"')\n\n    @PostProcessor._restrict_to(images=False)\n    def run(self, info):\n        filename = info['filepath']\n        temp_filename = prepend_extension(filename, 'temp')\n\n        if not info.get('thumbnails'):\n            self.to_screen('There aren\\'t any thumbnails to embed')\n            return [], info\n\n        idx = next((-i for i, t in enumerate(info['thumbnails'][::-1], 1) if t.get('filepath')), None)\n        if idx is None:\n            self.to_screen('There are no thumbnails on disk')\n            return [], info\n        thumbnail_filename = info['thumbnails'][idx]['filepath']\n        if not os.path.exists(encodeFilename(thumbnail_filename)):\n            self.report_warning('Skipping embedding the thumbnail because the file is missing.')\n            return [], info\n\n        # Correct extension for WebP file with wrong extension (see #25687, #25717)\n        convertor = FFmpegThumbnailsConvertorPP(self._downloader)\n        convertor.fixup_webp(info, idx)\n\n        original_thumbnail = thumbnail_filename = info['thumbnails'][idx]['filepath']\n\n        # Convert unsupported thumbnail formats to PNG (see #25687, #25717)\n        # Original behavior was to convert to JPG, but since JPG is a lossy\n        # format, there will be some additional data loss.\n        # PNG, on the other hand, is lossless.\n        thumbnail_ext = os.path.splitext(thumbnail_filename)[1][1:]\n        if thumbnail_ext not in ('jpg', 'jpeg', 'png'):\n            thumbnail_filename = convertor.convert_thumbnail(thumbnail_filename, 'png')\n            thumbnail_ext = 'png'\n\n        mtime = os.stat(encodeFilename(filename)).st_mtime\n\n        success = True\n        if info['ext'] == 'mp3':\n            options = [\n                '-c', 'copy', '-map', '0:0', '-map', '1:0', '-write_id3v1', '1', '-id3v2_version', '3',\n                '-metadata:s:v', 'title=\"Album cover\"', '-metadata:s:v', 'comment=\"Cover (front)\"']\n\n            self._report_run('ffmpeg', filename)\n            self.run_ffmpeg_multiple_files([filename, thumbnail_filename], temp_filename, options)\n\n        elif info['ext'] in ['mkv', 'mka']:\n            options = list(self.stream_copy_opts())\n\n            mimetype = 'image/%s' % ('png' if thumbnail_ext == 'png' else 'jpeg')\n            old_stream, new_stream = self.get_stream_number(\n                filename, ('tags', 'mimetype'), mimetype)\n            if old_stream is not None:\n                options.extend(['-map', '-0:%d' % old_stream])\n                new_stream -= 1\n            options.extend([\n                '-attach', thumbnail_filename,\n                '-metadata:s:%d' % new_stream, 'mimetype=%s' % mimetype,\n                '-metadata:s:%d' % new_stream, 'filename=cover.%s' % thumbnail_ext])\n\n            self._report_run('ffmpeg', filename)\n            self.run_ffmpeg(filename, temp_filename, options)\n\n        elif info['ext'] in ['m4a', 'mp4', 'mov']:\n            prefer_atomicparsley = 'embed-thumbnail-atomicparsley' in self.get_param('compat_opts', [])\n            # Method 1: Use mutagen\n            if not mutagen or prefer_atomicparsley:\n                success = False\n            else:\n                try:\n                    self._report_run('mutagen', filename)\n                    meta = MP4(filename)\n                    # NOTE: the 'covr' atom is a non-standard MPEG-4 atom,\n                    # Apple iTunes 'M4A' files include the 'moov.udta.meta.ilst' atom.\n                    f = {'jpeg': MP4Cover.FORMAT_JPEG, 'png': MP4Cover.FORMAT_PNG}[imghdr.what(thumbnail_filename)]\n                    with open(thumbnail_filename, 'rb') as thumbfile:\n                        thumb_data = thumbfile.read()\n                    meta.tags['covr'] = [MP4Cover(data=thumb_data, imageformat=f)]\n                    meta.save()\n                    temp_filename = filename\n                except Exception as err:\n                    self.report_warning('unable to embed using mutagen; %s' % error_to_compat_str(err))\n                    success = False\n\n            # Method 2: Use AtomicParsley\n            if not success:\n                success = True\n                atomicparsley = next((\n                    x for x in ['AtomicParsley', 'atomicparsley']\n                    if check_executable(x, ['-v'])), None)\n                if atomicparsley is None:\n                    self.to_screen('Neither mutagen nor AtomicParsley was found. Falling back to ffmpeg')\n                    success = False\n                else:\n                    if not prefer_atomicparsley:\n                        self.to_screen('mutagen was not found. Falling back to AtomicParsley')\n                    cmd = [encodeFilename(atomicparsley, True),\n                           encodeFilename(filename, True),\n                           encodeArgument('--artwork'),\n                           encodeFilename(thumbnail_filename, True),\n                           encodeArgument('-o'),\n                           encodeFilename(temp_filename, True)]\n                    cmd += [encodeArgument(o) for o in self._configuration_args('AtomicParsley')]\n\n                    self._report_run('atomicparsley', filename)\n                    self.write_debug('AtomicParsley command line: %s' % shell_quote(cmd))\n                    p = Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n                    stdout, stderr = p.communicate_or_kill()\n                    if p.returncode != 0:\n                        msg = stderr.decode('utf-8', 'replace').strip()\n                        self.report_warning(f'Unable to embed thumbnails using AtomicParsley; {msg}')\n                    # for formats that don't support thumbnails (like 3gp) AtomicParsley\n                    # won't create to the temporary file\n                    if b'No changes' in stdout:\n                        self.report_warning('The file format doesn\\'t support embedding a thumbnail')\n                        success = False\n\n            # Method 3: Use ffmpeg+ffprobe\n            # Thumbnails attached using this method doesn't show up as cover in some cases\n            # See https://github.com/yt-dlp/yt-dlp/issues/2125, https://github.com/yt-dlp/yt-dlp/issues/411\n            if not success:\n                success = True\n                try:\n                    options = [*self.stream_copy_opts(), '-map', '1']\n\n                    old_stream, new_stream = self.get_stream_number(\n                        filename, ('disposition', 'attached_pic'), 1)\n                    if old_stream is not None:\n                        options.extend(['-map', '-0:%d' % old_stream])\n                        new_stream -= 1\n                    options.extend(['-disposition:%s' % new_stream, 'attached_pic'])\n\n                    self._report_run('ffmpeg', filename)\n                    self.run_ffmpeg_multiple_files([filename, thumbnail_filename], temp_filename, options)\n                except PostProcessingError as err:\n                    success = False\n                    raise EmbedThumbnailPPError(f'Unable to embed using ffprobe & ffmpeg; {err}')\n\n        elif info['ext'] in ['ogg', 'opus', 'flac']:\n            if not mutagen:\n                raise EmbedThumbnailPPError('module mutagen was not found. Please install using `python -m pip install mutagen`')\n\n            self._report_run('mutagen', filename)\n            f = {'opus': OggOpus, 'flac': FLAC, 'ogg': OggVorbis}[info['ext']](filename)\n\n            pic = Picture()\n            pic.mime = 'image/%s' % imghdr.what(thumbnail_filename)\n            with open(thumbnail_filename, 'rb') as thumbfile:\n                pic.data = thumbfile.read()\n            pic.type = 3  # front cover\n            res = self._get_thumbnail_resolution(thumbnail_filename, info['thumbnails'][idx])\n            if res is not None:\n                pic.width, pic.height = res\n\n            if info['ext'] == 'flac':\n                f.add_picture(pic)\n            else:\n                # https://wiki.xiph.org/VorbisComment#METADATA_BLOCK_PICTURE\n                f['METADATA_BLOCK_PICTURE'] = base64.b64encode(pic.write()).decode('ascii')\n            f.save()\n            temp_filename = filename\n\n        else:\n            raise EmbedThumbnailPPError('Supported filetypes for thumbnail embedding are: mp3, mkv/mka, ogg/opus/flac, m4a/mp4/mov')\n\n        if success and temp_filename != filename:\n            os.replace(temp_filename, filename)\n\n        self.try_utime(filename, mtime, mtime)\n\n        files_to_delete = [thumbnail_filename]\n        if self._already_have_thumbnail:\n            if original_thumbnail == thumbnail_filename:\n                files_to_delete = []\n        elif original_thumbnail != thumbnail_filename:\n            files_to_delete.append(original_thumbnail)\n        return files_to_delete, info\n", "path": "yt_dlp/postprocessor/embedthumbnail.py"}], "after_files": [{"content": "import base64\nimport imghdr\nimport os\nimport re\nimport subprocess\n\nfrom .common import PostProcessor\nfrom .ffmpeg import FFmpegPostProcessor, FFmpegThumbnailsConvertorPP\nfrom ..dependencies import mutagen\nfrom ..utils import (\n    Popen,\n    PostProcessingError,\n    check_executable,\n    encodeArgument,\n    encodeFilename,\n    error_to_compat_str,\n    prepend_extension,\n    shell_quote,\n)\n\nif mutagen:\n    from mutagen.flac import FLAC, Picture\n    from mutagen.mp4 import MP4, MP4Cover\n    from mutagen.oggopus import OggOpus\n    from mutagen.oggvorbis import OggVorbis\n\n\nclass EmbedThumbnailPPError(PostProcessingError):\n    pass\n\n\nclass EmbedThumbnailPP(FFmpegPostProcessor):\n\n    def __init__(self, downloader=None, already_have_thumbnail=False):\n        FFmpegPostProcessor.__init__(self, downloader)\n        self._already_have_thumbnail = already_have_thumbnail\n\n    def _get_thumbnail_resolution(self, filename, thumbnail_dict):\n        def guess():\n            width, height = thumbnail_dict.get('width'), thumbnail_dict.get('height')\n            if width and height:\n                return width, height\n\n        try:\n            size_regex = r',\\s*(?P<w>\\d+)x(?P<h>\\d+)\\s*[,\\[]'\n            size_result = self.run_ffmpeg(filename, None, ['-hide_banner'], expected_retcodes=(1,))\n            mobj = re.search(size_regex, size_result)\n            if mobj is None:\n                return guess()\n        except PostProcessingError as err:\n            self.report_warning('unable to find the thumbnail resolution; %s' % error_to_compat_str(err))\n            return guess()\n        return int(mobj.group('w')), int(mobj.group('h'))\n\n    def _report_run(self, exe, filename):\n        self.to_screen(f'{exe}: Adding thumbnail to \"{filename}\"')\n\n    @PostProcessor._restrict_to(images=False)\n    def run(self, info):\n        filename = info['filepath']\n        temp_filename = prepend_extension(filename, 'temp')\n\n        if not info.get('thumbnails'):\n            self.to_screen('There aren\\'t any thumbnails to embed')\n            return [], info\n\n        idx = next((-i for i, t in enumerate(info['thumbnails'][::-1], 1) if t.get('filepath')), None)\n        if idx is None:\n            self.to_screen('There are no thumbnails on disk')\n            return [], info\n        thumbnail_filename = info['thumbnails'][idx]['filepath']\n        if not os.path.exists(encodeFilename(thumbnail_filename)):\n            self.report_warning('Skipping embedding the thumbnail because the file is missing.')\n            return [], info\n\n        # Correct extension for WebP file with wrong extension (see #25687, #25717)\n        convertor = FFmpegThumbnailsConvertorPP(self._downloader)\n        convertor.fixup_webp(info, idx)\n\n        original_thumbnail = thumbnail_filename = info['thumbnails'][idx]['filepath']\n\n        thumbnail_ext = os.path.splitext(thumbnail_filename)[1][1:]\n        # Convert unsupported thumbnail formats (see #25687, #25717)\n        # PNG is preferred since JPEG is lossy\n        if info['ext'] not in ('mkv', 'mka') and thumbnail_ext not in ('jpg', 'jpeg', 'png'):\n            thumbnail_filename = convertor.convert_thumbnail(thumbnail_filename, 'png')\n            thumbnail_ext = 'png'\n\n        mtime = os.stat(encodeFilename(filename)).st_mtime\n\n        success = True\n        if info['ext'] == 'mp3':\n            options = [\n                '-c', 'copy', '-map', '0:0', '-map', '1:0', '-write_id3v1', '1', '-id3v2_version', '3',\n                '-metadata:s:v', 'title=\"Album cover\"', '-metadata:s:v', 'comment=\"Cover (front)\"']\n\n            self._report_run('ffmpeg', filename)\n            self.run_ffmpeg_multiple_files([filename, thumbnail_filename], temp_filename, options)\n\n        elif info['ext'] in ['mkv', 'mka']:\n            options = list(self.stream_copy_opts())\n\n            mimetype = 'image/%s' % ('jpeg' if thumbnail_ext in ('jpg', 'jpeg') else thumbnail_ext)\n            old_stream, new_stream = self.get_stream_number(\n                filename, ('tags', 'mimetype'), mimetype)\n            if old_stream is not None:\n                options.extend(['-map', '-0:%d' % old_stream])\n                new_stream -= 1\n            options.extend([\n                '-attach', thumbnail_filename,\n                '-metadata:s:%d' % new_stream, 'mimetype=%s' % mimetype,\n                '-metadata:s:%d' % new_stream, 'filename=cover.%s' % thumbnail_ext])\n\n            self._report_run('ffmpeg', filename)\n            self.run_ffmpeg(filename, temp_filename, options)\n\n        elif info['ext'] in ['m4a', 'mp4', 'mov']:\n            prefer_atomicparsley = 'embed-thumbnail-atomicparsley' in self.get_param('compat_opts', [])\n            # Method 1: Use mutagen\n            if not mutagen or prefer_atomicparsley:\n                success = False\n            else:\n                try:\n                    self._report_run('mutagen', filename)\n                    meta = MP4(filename)\n                    # NOTE: the 'covr' atom is a non-standard MPEG-4 atom,\n                    # Apple iTunes 'M4A' files include the 'moov.udta.meta.ilst' atom.\n                    f = {'jpeg': MP4Cover.FORMAT_JPEG, 'png': MP4Cover.FORMAT_PNG}[imghdr.what(thumbnail_filename)]\n                    with open(thumbnail_filename, 'rb') as thumbfile:\n                        thumb_data = thumbfile.read()\n                    meta.tags['covr'] = [MP4Cover(data=thumb_data, imageformat=f)]\n                    meta.save()\n                    temp_filename = filename\n                except Exception as err:\n                    self.report_warning('unable to embed using mutagen; %s' % error_to_compat_str(err))\n                    success = False\n\n            # Method 2: Use AtomicParsley\n            if not success:\n                success = True\n                atomicparsley = next((\n                    x for x in ['AtomicParsley', 'atomicparsley']\n                    if check_executable(x, ['-v'])), None)\n                if atomicparsley is None:\n                    self.to_screen('Neither mutagen nor AtomicParsley was found. Falling back to ffmpeg')\n                    success = False\n                else:\n                    if not prefer_atomicparsley:\n                        self.to_screen('mutagen was not found. Falling back to AtomicParsley')\n                    cmd = [encodeFilename(atomicparsley, True),\n                           encodeFilename(filename, True),\n                           encodeArgument('--artwork'),\n                           encodeFilename(thumbnail_filename, True),\n                           encodeArgument('-o'),\n                           encodeFilename(temp_filename, True)]\n                    cmd += [encodeArgument(o) for o in self._configuration_args('AtomicParsley')]\n\n                    self._report_run('atomicparsley', filename)\n                    self.write_debug('AtomicParsley command line: %s' % shell_quote(cmd))\n                    p = Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n                    stdout, stderr = p.communicate_or_kill()\n                    if p.returncode != 0:\n                        msg = stderr.decode('utf-8', 'replace').strip()\n                        self.report_warning(f'Unable to embed thumbnails using AtomicParsley; {msg}')\n                    # for formats that don't support thumbnails (like 3gp) AtomicParsley\n                    # won't create to the temporary file\n                    if b'No changes' in stdout:\n                        self.report_warning('The file format doesn\\'t support embedding a thumbnail')\n                        success = False\n\n            # Method 3: Use ffmpeg+ffprobe\n            # Thumbnails attached using this method doesn't show up as cover in some cases\n            # See https://github.com/yt-dlp/yt-dlp/issues/2125, https://github.com/yt-dlp/yt-dlp/issues/411\n            if not success:\n                success = True\n                try:\n                    options = [*self.stream_copy_opts(), '-map', '1']\n\n                    old_stream, new_stream = self.get_stream_number(\n                        filename, ('disposition', 'attached_pic'), 1)\n                    if old_stream is not None:\n                        options.extend(['-map', '-0:%d' % old_stream])\n                        new_stream -= 1\n                    options.extend(['-disposition:%s' % new_stream, 'attached_pic'])\n\n                    self._report_run('ffmpeg', filename)\n                    self.run_ffmpeg_multiple_files([filename, thumbnail_filename], temp_filename, options)\n                except PostProcessingError as err:\n                    success = False\n                    raise EmbedThumbnailPPError(f'Unable to embed using ffprobe & ffmpeg; {err}')\n\n        elif info['ext'] in ['ogg', 'opus', 'flac']:\n            if not mutagen:\n                raise EmbedThumbnailPPError('module mutagen was not found. Please install using `python -m pip install mutagen`')\n\n            self._report_run('mutagen', filename)\n            f = {'opus': OggOpus, 'flac': FLAC, 'ogg': OggVorbis}[info['ext']](filename)\n\n            pic = Picture()\n            pic.mime = 'image/%s' % imghdr.what(thumbnail_filename)\n            with open(thumbnail_filename, 'rb') as thumbfile:\n                pic.data = thumbfile.read()\n            pic.type = 3  # front cover\n            res = self._get_thumbnail_resolution(thumbnail_filename, info['thumbnails'][idx])\n            if res is not None:\n                pic.width, pic.height = res\n\n            if info['ext'] == 'flac':\n                f.add_picture(pic)\n            else:\n                # https://wiki.xiph.org/VorbisComment#METADATA_BLOCK_PICTURE\n                f['METADATA_BLOCK_PICTURE'] = base64.b64encode(pic.write()).decode('ascii')\n            f.save()\n            temp_filename = filename\n\n        else:\n            raise EmbedThumbnailPPError('Supported filetypes for thumbnail embedding are: mp3, mkv/mka, ogg/opus/flac, m4a/mp4/mov')\n\n        if success and temp_filename != filename:\n            os.replace(temp_filename, filename)\n\n        self.try_utime(filename, mtime, mtime)\n\n        files_to_delete = [thumbnail_filename]\n        if self._already_have_thumbnail:\n            if original_thumbnail == thumbnail_filename:\n                files_to_delete = []\n        elif original_thumbnail != thumbnail_filename:\n            files_to_delete.append(original_thumbnail)\n        return files_to_delete, info\n", "path": "yt_dlp/postprocessor/embedthumbnail.py"}]}