9 from .common
import AudioConversionError
, PostProcessor
10 from ..compat
import imghdr
15 _get_exe_version_output
,
33 EXT_TO_OUT_FORMATS
= {
52 'vorbis': 'libvorbis',
58 class FFmpegPostProcessorError(PostProcessingError
):
62 class FFmpegPostProcessor(PostProcessor
):
63 def __init__(self
, downloader
=None):
64 PostProcessor
.__init
__(self
, downloader
)
65 self
._determine
_executables
()
67 def check_version(self
):
68 if not self
.available
:
69 raise FFmpegPostProcessorError('ffmpeg not found. Please install or provide the path using --ffmpeg-location')
71 required_version
= '10-0' if self
.basename
== 'avconv' else '1.0'
72 if is_outdated_version(self
._versions
[self
.basename
], required_version
):
73 self
.report_warning(f
'Your copy of {self.basename} is outdated, update {self.basename} '
74 f
'to version {required_version} or newer if you encounter any errors')
77 def get_versions_and_features(downloader
=None):
78 pp
= FFmpegPostProcessor(downloader
)
79 return pp
._versions
, pp
._features
82 def get_versions(downloader
=None):
83 return FFmpegPostProcessor
.get_versions_and_features(downloader
)[0]
85 _version_cache
, _features_cache
= {}, {}
87 def _determine_executables(self
):
88 programs
= ['avprobe', 'avconv', 'ffmpeg', 'ffprobe']
90 def get_ffmpeg_version(path
, prog
):
91 if path
in self
._version
_cache
:
92 self
._versions
[prog
], self
._features
= self
._version
_cache
[path
], self
._features
_cache
.get(path
, {})
94 out
= _get_exe_version_output(path
, ['-bsfs'], to_screen
=self
.write_debug
)
95 ver
= detect_exe_version(out
) if out
else False
98 r
'(?:\d+:)?([0-9.]+)-[0-9]+ubuntu[0-9.]+$', # Ubuntu, see [1]
99 r
'n([0-9.]+)$', # Arch Linux
100 # 1. http://www.ducea.com/2006/06/17/ubuntu-package-version-naming-explanation/
103 mobj
= re
.match(regex
, ver
)
106 self
._versions
[prog
] = self
._version
_cache
[path
] = ver
107 if prog
!= 'ffmpeg' or not out
:
110 mobj
= re
.search(r
'(?m)^\s+libavformat\s+(?:[0-9. ]+)\s+/\s+(?P<runtime>[0-9. ]+)', out
)
111 lavf_runtime_version
= mobj
.group('runtime').replace(' ', '') if mobj
else None
112 self
._features
= self
._features
_cache
[path
] = {
113 'fdk': '--enable-libfdk-aac' in out
,
114 'setts': 'setts' in out
.splitlines(),
115 'needs_adtstoasc': is_outdated_version(lavf_runtime_version
, '57.56.100', False),
119 self
.probe_basename
= None
121 self
._versions
= None
124 prefer_ffmpeg
= self
.get_param('prefer_ffmpeg', True)
125 location
= self
.get_param('ffmpeg_location')
127 self
._paths
= {p: p for p in programs}
129 if not os
.path
.exists(location
):
131 'ffmpeg-location %s does not exist! '
132 'Continuing without ffmpeg.' % (location
))
135 elif os
.path
.isdir(location
):
136 dirname
, basename
= location
, None
138 basename
= os
.path
.splitext(os
.path
.basename(location
))[0]
139 basename
= next((p
for p
in programs
if basename
.startswith(p
)), 'ffmpeg')
140 dirname
= os
.path
.dirname(os
.path
.abspath(location
))
141 if basename
in ('ffmpeg', 'ffprobe'):
145 p
: os
.path
.join(dirname
, p
) for p
in programs
}
147 self
._paths
[basename
] = location
150 # NB: probe must be first for _features to be poulated correctly
151 executables
= {'probe_basename': ('ffprobe', 'avprobe'), 'basename': ('ffmpeg', 'avconv')}
152 if prefer_ffmpeg
is False:
153 executables
= {k: v[::-1] for k, v in executables.items()}
154 for var
, prefs
in executables
.items():
156 get_ffmpeg_version(self
._paths
[p
], p
)
157 if self
._versions
[p
]:
158 setattr(self
, var
, p
)
161 if self
.basename
== 'avconv':
162 self
.deprecation_warning(
163 'Support for avconv is deprecated and may be removed in a future version. Use ffmpeg instead')
164 if self
.probe_basename
== 'avprobe':
165 self
.deprecation_warning(
166 'Support for avprobe is deprecated and may be removed in a future version. Use ffprobe instead')
170 return self
.basename
is not None
173 def executable(self
):
174 return self
._paths
[self
.basename
]
177 def probe_available(self
):
178 return self
.probe_basename
is not None
181 def probe_executable(self
):
182 return self
._paths
[self
.probe_basename
]
185 def stream_copy_opts(copy
=True, *, ext
=None):
186 yield from ('-map', '0')
187 # Don't copy Apple TV chapters track, bin_data
188 # See https://github.com/yt-dlp/yt-dlp/issues/2, #19042, #19024, https://trac.ffmpeg.org/ticket/6016
189 yield from ('-dn', '-ignore_unknown')
191 yield from ('-c', 'copy')
192 if ext
in ('mp4', 'mov', 'm4a'):
193 yield from ('-c:s', 'mov_text')
195 def get_audio_codec(self
, path
):
196 if not self
.probe_available
and not self
.available
:
197 raise PostProcessingError('ffprobe and ffmpeg not found. Please install or provide the path using --ffmpeg-location')
199 if self
.probe_available
:
201 encodeFilename(self
.probe_executable
, True),
202 encodeArgument('-show_streams')]
205 encodeFilename(self
.executable
, True),
206 encodeArgument('-i')]
207 cmd
.append(encodeFilename(self
._ffmpeg
_filename
_argument
(path
), True))
208 self
.write_debug(f
'{self.basename} command line: {shell_quote(cmd)}')
209 handle
= Popen(cmd
, stdin
=subprocess
.PIPE
, stdout
=subprocess
.PIPE
, stderr
=subprocess
.PIPE
)
210 stdout_data
, stderr_data
= handle
.communicate_or_kill()
211 expected_ret
= 0 if self
.probe_available
else 1
212 if handle
.wait() != expected_ret
:
216 output
= (stdout_data
if self
.probe_available
else stderr_data
).decode('ascii', 'ignore')
217 if self
.probe_available
:
219 for line
in output
.split('\n'):
220 if line
.startswith('codec_name='):
221 audio_codec
= line
.split('=')[1].strip()
222 elif line
.strip() == 'codec_type=audio' and audio_codec
is not None:
225 # Stream #FILE_INDEX:STREAM_INDEX[STREAM_ID](LANGUAGE): CODEC_TYPE: CODEC_NAME
227 r
'Stream\s*#\d+:\d+(?:\[0x[0-9a-f]+\])?(?:\([a-z]{3}\))?:\s*Audio:\s*([0-9a-z]+)',
233 def get_metadata_object(self
, path
, opts
=[]):
234 if self
.probe_basename
!= 'ffprobe':
235 if self
.probe_available
:
236 self
.report_warning('Only ffprobe is supported for metadata extraction')
237 raise PostProcessingError('ffprobe not found. Please install or provide the path using --ffmpeg-location')
241 encodeFilename(self
.probe_executable
, True),
242 encodeArgument('-hide_banner'),
243 encodeArgument('-show_format'),
244 encodeArgument('-show_streams'),
245 encodeArgument('-print_format'),
246 encodeArgument('json'),
250 cmd
.append(encodeFilename(self
._ffmpeg
_filename
_argument
(path
), True))
251 self
.write_debug('ffprobe command line: %s' % shell_quote(cmd
))
252 p
= Popen(cmd
, stdout
=subprocess
.PIPE
, stderr
=subprocess
.PIPE
, stdin
=subprocess
.PIPE
)
253 stdout
, stderr
= p
.communicate()
254 return json
.loads(stdout
.decode('utf-8', 'replace'))
256 def get_stream_number(self
, path
, keys
, value
):
257 streams
= self
.get_metadata_object(path
)['streams']
259 (i
for i
, stream
in enumerate(streams
) if traverse_obj(stream
, keys
, casesense
=False) == value
),
261 return num
, len(streams
)
263 def _get_real_video_duration(self
, filepath
, fatal
=True):
265 duration
= float_or_none(
266 traverse_obj(self
.get_metadata_object(filepath
), ('format', 'duration')))
268 raise PostProcessingError('ffprobe returned empty duration')
270 except PostProcessingError
as e
:
272 raise PostProcessingError(f
'Unable to determine video duration: {e.msg}')
274 def _duration_mismatch(self
, d1
, d2
):
277 # The duration is often only known to nearest second. So there can be <1sec disparity natually.
278 # Further excuse an additional <1sec difference.
279 return abs(d1
- d2
) > 2
281 def run_ffmpeg_multiple_files(self
, input_paths
, out_path
, opts
, **kwargs
):
282 return self
.real_run_ffmpeg(
283 [(path
, []) for path
in input_paths
],
284 [(out_path
, opts
)], **kwargs
)
286 def real_run_ffmpeg(self
, input_path_opts
, output_path_opts
, *, expected_retcodes
=(0,)):
290 os
.stat(encodeFilename(path
)).st_mtime
for path
, _
in input_path_opts
if path
)
292 cmd
= [encodeFilename(self
.executable
, True), encodeArgument('-y')]
293 # avconv does not have repeat option
294 if self
.basename
== 'ffmpeg':
295 cmd
+= [encodeArgument('-loglevel'), encodeArgument('repeat+info')]
297 def make_args(file, args
, name
, number
):
298 keys
= ['_%s%d' % (name
, number
), '_%s' % name
]
300 args
+= ['-movflags', '+faststart']
303 args
+= self
._configuration
_args
(self
.basename
, keys
)
307 [encodeArgument(arg
) for arg
in args
]
308 + [encodeFilename(self
._ffmpeg
_filename
_argument
(file), True)])
310 for arg_type
, path_opts
in (('i', input_path_opts
), ('o', output_path_opts
)):
311 cmd
+= itertools
.chain
.from_iterable(
312 make_args(path
, list(opts
), arg_type
, i
+ 1)
313 for i
, (path
, opts
) in enumerate(path_opts
) if path
)
315 self
.write_debug('ffmpeg command line: %s' % shell_quote(cmd
))
316 p
= Popen(cmd
, stdout
=subprocess
.PIPE
, stderr
=subprocess
.PIPE
, stdin
=subprocess
.PIPE
)
317 stdout
, stderr
= p
.communicate_or_kill()
318 if p
.returncode
not in variadic(expected_retcodes
):
319 stderr
= stderr
.decode('utf-8', 'replace').strip()
320 self
.write_debug(stderr
)
321 raise FFmpegPostProcessorError(stderr
.split('\n')[-1])
322 for out_path
, _
in output_path_opts
:
324 self
.try_utime(out_path
, oldest_mtime
, oldest_mtime
)
325 return stderr
.decode('utf-8', 'replace')
327 def run_ffmpeg(self
, path
, out_path
, opts
, **kwargs
):
328 return self
.run_ffmpeg_multiple_files([path
], out_path
, opts
, **kwargs
)
331 def _ffmpeg_filename_argument(fn
):
332 # Always use 'file:' because the filename may contain ':' (ffmpeg
333 # interprets that as a protocol) or can start with '-' (-- is broken in
334 # ffmpeg, see https://ffmpeg.org/trac/ffmpeg/ticket/2127 for details)
335 # Also leave '-' intact in order not to break streaming to stdout.
336 if fn
.startswith(('http://', 'https://')):
338 return 'file:' + fn
if fn
!= '-' else fn
341 def _quote_for_ffmpeg(string
):
342 # See https://ffmpeg.org/ffmpeg-utils.html#toc-Quoting-and-escaping
343 # A sequence of '' produces '\'''\'';
344 # final replace removes the empty '' between \' \'.
345 string
= string
.replace("'", r
"'\''").replace("'''", "'")
346 # Handle potential ' at string boundaries.
347 string
= string
[1:] if string
[0] == "'" else "'" + string
348 return string
[:-1] if string
[-1] == "'" else string
+ "'"
350 def force_keyframes(self
, filename
, timestamps
):
351 timestamps
= orderedSet(timestamps
)
352 if timestamps
[0] == 0:
353 timestamps
= timestamps
[1:]
354 keyframe_file
= prepend_extension(filename
, 'keyframes.temp')
355 self
.to_screen(f
'Re-encoding "{filename}" with appropriate keyframes')
356 self
.run_ffmpeg(filename
, keyframe_file
, [
357 *self
.stream_copy_opts(False, ext
=determine_ext(filename
)),
358 '-force_key_frames', ','.join(f
'{t:.6f}' for t
in timestamps
)])
361 def concat_files(self
, in_files
, out_file
, concat_opts
=None):
363 Use concat demuxer to concatenate multiple files having identical streams.
365 Only inpoint, outpoint, and duration concat options are supported.
366 See https://ffmpeg.org/ffmpeg-formats.html#concat-1 for details
368 concat_file
= f
'{out_file}.concat'
369 self
.write_debug(f
'Writing concat spec to {concat_file}')
370 with open(concat_file
, 'wt', encoding
='utf-8') as f
:
371 f
.writelines(self
._concat
_spec
(in_files
, concat_opts
))
373 out_flags
= list(self
.stream_copy_opts(ext
=determine_ext(out_file
)))
375 self
.real_run_ffmpeg(
376 [(concat_file
, ['-hide_banner', '-nostdin', '-f', 'concat', '-safe', '0'])],
377 [(out_file
, out_flags
)])
378 self
._delete
_downloaded
_files
(concat_file
)
381 def _concat_spec(cls
, in_files
, concat_opts
=None):
382 if concat_opts
is None:
383 concat_opts
= [{}] * len(in_files
)
384 yield 'ffconcat version 1.0\n'
385 for file, opts
in zip(in_files
, concat_opts
):
386 yield f
'file {cls._quote_for_ffmpeg(cls._ffmpeg_filename_argument(file))}\n'
387 # Iterate explicitly to yield the following directives in order, ignoring the rest.
388 for directive
in 'inpoint', 'outpoint', 'duration':
389 if directive
in opts
:
390 yield f
'{directive} {opts[directive]}\n'
393 class FFmpegExtractAudioPP(FFmpegPostProcessor
):
394 COMMON_AUDIO_EXTS
= ('wav', 'flac', 'm4a', 'aiff', 'mp3', 'ogg', 'mka', 'opus', 'wma')
395 SUPPORTED_EXTS
= ('aac', 'flac', 'mp3', 'm4a', 'opus', 'vorbis', 'wav', 'alac')
397 def __init__(self
, downloader
=None, preferredcodec
=None, preferredquality
=None, nopostoverwrites
=False):
398 FFmpegPostProcessor
.__init
__(self
, downloader
)
399 self
._preferredcodec
= preferredcodec
or 'best'
400 self
._preferredquality
= float_or_none(preferredquality
)
401 self
._nopostoverwrites
= nopostoverwrites
403 def _quality_args(self
, codec
):
404 if self
._preferredquality
is None:
406 elif self
._preferredquality
> 10:
407 return ['-b:a', f
'{self._preferredquality}k']
410 'libmp3lame': (10, 0),
411 'libvorbis': (0, 10),
412 # FFmpeg's AAC encoder does not have an upper limit for the value of -q:a.
413 # Experimentally, with values over 4, bitrate changes were minimal or non-existent
415 'libfdk_aac': (1, 5),
420 q
= limits
[1] + (limits
[0] - limits
[1]) * (self
._preferredquality
/ 10)
421 if codec
== 'libfdk_aac':
422 return ['-vbr', f
'{int(q)}']
423 return ['-q:a', f
'{q}']
425 def run_ffmpeg(self
, path
, out_path
, codec
, more_opts
):
429 acodec_opts
= ['-acodec', codec
]
430 opts
= ['-vn'] + acodec_opts
+ more_opts
432 FFmpegPostProcessor
.run_ffmpeg(self
, path
, out_path
, opts
)
433 except FFmpegPostProcessorError
as err
:
434 raise AudioConversionError(err
.msg
)
436 @PostProcessor._restrict_to(images
=False)
437 def run(self
, information
):
438 orig_path
= path
= information
['filepath']
439 orig_ext
= information
['ext']
441 if self
._preferredcodec
== 'best' and orig_ext
in self
.COMMON_AUDIO_EXTS
:
442 self
.to_screen('Skipping audio extraction since the file is already in a common audio format')
443 return [], information
445 filecodec
= self
.get_audio_codec(path
)
446 if filecodec
is None:
447 raise PostProcessingError('WARNING: unable to obtain file audio codec with ffprobe')
450 if self
._preferredcodec
== 'best' or self
._preferredcodec
== filecodec
or (self
._preferredcodec
== 'm4a' and filecodec
== 'aac'):
451 if filecodec
== 'aac' and self
._preferredcodec
in ['m4a', 'best']:
452 # Lossless, but in another container
455 more_opts
= ['-bsf:a', 'aac_adtstoasc']
456 elif filecodec
in ['aac', 'flac', 'mp3', 'vorbis', 'opus']:
457 # Lossless if possible
459 extension
= filecodec
460 if filecodec
== 'aac':
461 more_opts
= ['-f', 'adts']
462 if filecodec
== 'vorbis':
464 elif filecodec
== 'alac':
467 more_opts
+= ['-acodec', 'alac']
470 acodec
= 'libmp3lame'
472 more_opts
= self
._quality
_args
(acodec
)
474 # We convert the audio (lossy if codec is lossy)
475 acodec
= ACODECS
[self
._preferredcodec
]
476 if acodec
== 'aac' and self
._features
.get('fdk'):
477 acodec
= 'libfdk_aac'
478 extension
= self
._preferredcodec
479 more_opts
= self
._quality
_args
(acodec
)
480 if self
._preferredcodec
== 'aac':
481 more_opts
+= ['-f', 'adts']
482 elif self
._preferredcodec
== 'm4a':
483 more_opts
+= ['-bsf:a', 'aac_adtstoasc']
484 elif self
._preferredcodec
== 'vorbis':
486 elif self
._preferredcodec
== 'wav':
488 more_opts
+= ['-f', 'wav']
489 elif self
._preferredcodec
== 'alac':
491 more_opts
+= ['-acodec', 'alac']
493 prefix
, sep
, ext
= path
.rpartition('.') # not os.path.splitext, since the latter does not work on unicode in all setups
494 temp_path
= new_path
= prefix
+ sep
+ extension
498 self
.to_screen(f
'File is already in target format {self._preferredcodec}, skipping')
499 return [], information
500 orig_path
= prepend_extension(path
, 'orig')
501 temp_path
= prepend_extension(path
, 'temp')
502 if (self
._nopostoverwrites
and os
.path
.exists(encodeFilename(new_path
))
503 and os
.path
.exists(encodeFilename(orig_path
))):
504 self
.to_screen('Post-process file %s exists, skipping' % new_path
)
505 return [], information
508 self
.to_screen(f
'Destination: {new_path}')
509 self
.run_ffmpeg(path
, temp_path
, acodec
, more_opts
)
510 except AudioConversionError
as e
:
511 raise PostProcessingError(
512 'audio conversion failed: ' + e
.msg
)
514 raise PostProcessingError('error running ' + self
.basename
)
516 os
.replace(path
, orig_path
)
517 os
.replace(temp_path
, new_path
)
518 information
['filepath'] = new_path
519 information
['ext'] = extension
521 # Try to update the date time for extracted audio file.
522 if information
.get('filetime') is not None:
524 new_path
, time
.time(), information
['filetime'],
525 errnote
='Cannot update utime of audio file')
527 return [orig_path
], information
530 class FFmpegVideoConvertorPP(FFmpegPostProcessor
):
531 SUPPORTED_EXTS
= ('mp4', 'mkv', 'flv', 'webm', 'mov', 'avi', 'mka', 'ogg', *FFmpegExtractAudioPP
.SUPPORTED_EXTS
)
532 FORMAT_RE
= re
.compile(r
'{0}(?:/{0})*$'.format(r
'(?:\w+>)?(?:%s)' % '|'.join(SUPPORTED_EXTS
)))
533 _ACTION
= 'converting'
535 def __init__(self
, downloader
=None, preferedformat
=None):
536 super().__init
__(downloader
)
537 self
._preferedformats
= preferedformat
.lower().split('/')
539 def _target_ext(self
, source_ext
):
540 for pair
in self
._preferedformats
:
542 if len(kv
) == 1 or kv
[0].strip() == source_ext
:
543 return kv
[-1].strip()
546 def _options(target_ext
):
547 yield from FFmpegPostProcessor
.stream_copy_opts(False)
548 if target_ext
== 'avi':
549 yield from ('-c:v', 'libxvid', '-vtag', 'XVID')
551 @PostProcessor._restrict_to(images
=False)
553 filename
, source_ext
= info
['filepath'], info
['ext'].lower()
554 target_ext
= self
._target
_ext
(source_ext
)
556 f
'could not find a mapping for {source_ext}' if not target_ext
557 else f
'already is in target format {source_ext}' if source_ext
== target_ext
560 self
.to_screen(f
'Not {self._ACTION} media file "{filename}"; {_skip_msg}')
563 outpath
= replace_extension(filename
, target_ext
, source_ext
)
564 self
.to_screen(f
'{self._ACTION.title()} video from {source_ext} to {target_ext}; Destination: {outpath}')
565 self
.run_ffmpeg(filename
, outpath
, self
._options
(target_ext
))
567 info
['filepath'] = outpath
568 info
['format'] = info
['ext'] = target_ext
569 return [filename
], info
572 class FFmpegVideoRemuxerPP(FFmpegVideoConvertorPP
):
576 def _options(target_ext
):
577 return FFmpegPostProcessor
.stream_copy_opts()
580 class FFmpegEmbedSubtitlePP(FFmpegPostProcessor
):
581 SUPPORTED_EXTS
= ('mp4', 'mov', 'm4a', 'webm', 'mkv', 'mka')
583 def __init__(self
, downloader
=None, already_have_subtitle
=False):
584 super().__init
__(downloader
)
585 self
._already
_have
_subtitle
= already_have_subtitle
587 @PostProcessor._restrict_to(images
=False)
589 if info
['ext'] not in self
.SUPPORTED_EXTS
:
590 self
.to_screen(f
'Subtitles can only be embedded in {", ".join(self.SUPPORTED_EXTS)} files')
592 subtitles
= info
.get('requested_subtitles')
594 self
.to_screen('There aren\'t any subtitles to embed')
597 filename
= info
['filepath']
599 # Disabled temporarily. There needs to be a way to overide this
600 # in case of duration actually mismatching in extractor
601 # See: https://github.com/yt-dlp/yt-dlp/issues/1870, https://github.com/yt-dlp/yt-dlp/issues/1385
603 if info.get('duration') and not info.get('__real_download') and self._duration_mismatch(
604 self._get_real_video_duration(filename, False), info['duration']):
605 self.to_screen(f'Skipping {self.pp_key()} since the real and expected durations mismatch')
610 sub_langs
, sub_names
, sub_filenames
= [], [], []
611 webm_vtt_warn
= False
614 for lang
, sub_info
in subtitles
.items():
615 if not os
.path
.exists(sub_info
.get('filepath', '')):
616 self
.report_warning(f
'Skipping embedding {lang} subtitle because the file is missing')
618 sub_ext
= sub_info
['ext']
619 if sub_ext
== 'json':
620 self
.report_warning('JSON subtitles cannot be embedded')
621 elif ext
!= 'webm' or ext
== 'webm' and sub_ext
== 'vtt':
622 sub_langs
.append(lang
)
623 sub_names
.append(sub_info
.get('name'))
624 sub_filenames
.append(sub_info
['filepath'])
626 if not webm_vtt_warn
and ext
== 'webm' and sub_ext
!= 'vtt':
628 self
.report_warning('Only WebVTT subtitles can be embedded in webm files')
629 if not mp4_ass_warn
and ext
== 'mp4' and sub_ext
== 'ass':
631 self
.report_warning('ASS subtitles cannot be properly embedded in mp4 files; expect issues')
636 input_files
= [filename
] + sub_filenames
639 *self
.stream_copy_opts(ext
=info
['ext']),
640 # Don't copy the existing subtitles, we may be running the
641 # postprocessor a second time
644 for i
, (lang
, name
) in enumerate(zip(sub_langs
, sub_names
)):
645 opts
.extend(['-map', '%d:0' % (i
+ 1)])
646 lang_code
= ISO639Utils
.short2long(lang
) or lang
647 opts
.extend(['-metadata:s:s:%d' % i
, 'language=%s' % lang_code
])
649 opts
.extend(['-metadata:s:s:%d' % i
, 'handler_name=%s' % name
,
650 '-metadata:s:s:%d' % i
, 'title=%s' % name
])
652 temp_filename
= prepend_extension(filename
, 'temp')
653 self
.to_screen('Embedding subtitles in "%s"' % filename
)
654 self
.run_ffmpeg_multiple_files(input_files
, temp_filename
, opts
)
655 os
.replace(temp_filename
, filename
)
657 files_to_delete
= [] if self
._already
_have
_subtitle
else sub_filenames
658 return files_to_delete
, info
661 class FFmpegMetadataPP(FFmpegPostProcessor
):
663 def __init__(self
, downloader
, add_metadata
=True, add_chapters
=True, add_infojson
='if_exists'):
664 FFmpegPostProcessor
.__init
__(self
, downloader
)
665 self
._add
_metadata
= add_metadata
666 self
._add
_chapters
= add_chapters
667 self
._add
_infojson
= add_infojson
670 def _options(target_ext
):
671 audio_only
= target_ext
== 'm4a'
672 yield from FFmpegPostProcessor
.stream_copy_opts(not audio_only
)
674 yield from ('-vn', '-acodec', 'copy')
676 @PostProcessor._restrict_to(images
=False)
678 filename
, metadata_filename
= info
['filepath'], None
679 files_to_delete
, options
= [], []
680 if self
._add
_chapters
and info
.get('chapters'):
681 metadata_filename
= replace_extension(filename
, 'meta')
682 options
.extend(self
._get
_chapter
_opts
(info
['chapters'], metadata_filename
))
683 files_to_delete
.append(metadata_filename
)
684 if self
._add
_metadata
:
685 options
.extend(self
._get
_metadata
_opts
(info
))
687 if self
._add
_infojson
:
688 if info
['ext'] in ('mkv', 'mka'):
689 infojson_filename
= info
.get('infojson_filename')
690 options
.extend(self
._get
_infojson
_opts
(info
, infojson_filename
))
691 if not infojson_filename
:
692 files_to_delete
.append(info
.get('infojson_filename'))
693 elif self
._add
_infojson
is True:
694 self
.to_screen('The info-json can only be attached to mkv/mka files')
697 self
.to_screen('There isn\'t any metadata to add')
700 temp_filename
= prepend_extension(filename
, 'temp')
701 self
.to_screen('Adding metadata to "%s"' % filename
)
702 self
.run_ffmpeg_multiple_files(
703 (filename
, metadata_filename
), temp_filename
,
704 itertools
.chain(self
._options
(info
['ext']), *options
))
705 self
._delete
_downloaded
_files
(*files_to_delete
)
706 os
.replace(temp_filename
, filename
)
710 def _get_chapter_opts(chapters
, metadata_filename
):
711 with open(metadata_filename
, 'wt', encoding
='utf-8') as f
:
712 def ffmpeg_escape(text
):
713 return re
.sub(r
'([\\=;#\n])', r
'\\\1', text
)
715 metadata_file_content
= ';FFMETADATA1\n'
716 for chapter
in chapters
:
717 metadata_file_content
+= '[CHAPTER]\nTIMEBASE=1/1000\n'
718 metadata_file_content
+= 'START=%d\n' % (chapter
['start_time'] * 1000)
719 metadata_file_content
+= 'END=%d\n' % (chapter
['end_time'] * 1000)
720 chapter_title
= chapter
.get('title')
722 metadata_file_content
+= 'title=%s\n' % ffmpeg_escape(chapter_title
)
723 f
.write(metadata_file_content
)
724 yield ('-map_metadata', '1')
726 def _get_metadata_opts(self
, info
):
728 metadata
= collections
.defaultdict(dict)
730 def add(meta_list
, info_list
=None):
732 str(info
[key
]) for key
in [f
'{meta_prefix}_'] + list(variadic(info_list
or meta_list
))
733 if info
.get(key
) is not None), None)
734 if value
not in ('', None):
735 value
= value
.replace('\0', '') # nul character cannot be passed in command line
736 metadata
['common'].update({meta_f: value for meta_f in variadic(meta_list)}
)
738 # See [1-4] for some info on media metadata/metadata supported
740 # 1. https://kdenlive.org/en/project/adding-meta-data-to-mp4-video/
741 # 2. https://wiki.multimedia.cx/index.php/FFmpeg_Metadata
742 # 3. https://kodi.wiki/view/Video_file_tagging
744 add('title', ('track', 'title'))
745 add('date', 'upload_date')
746 add(('description', 'synopsis'), 'description')
747 add(('purl', 'comment'), 'webpage_url')
748 add('track', 'track_number')
749 add('artist', ('artist', 'creator', 'uploader', 'uploader_id'))
753 add('disc', 'disc_number')
754 add('show', 'series')
756 add('episode_id', ('episode', 'episode_id'))
757 add('episode_sort', 'episode_number')
758 if 'embed-metadata' in self
.get_param('compat_opts', []):
759 add('comment', 'description')
760 metadata
['common'].pop('synopsis', None)
762 meta_regex
= rf
'{re.escape(meta_prefix)}(?P<i>\d+)?_(?P<key>.+)'
763 for key
, value
in info
.items():
764 mobj
= re
.fullmatch(meta_regex
, key
)
765 if value
is not None and mobj
:
766 metadata
[mobj
.group('i') or 'common'][mobj
.group('key')] = value
768 # Write id3v1 metadata also since Windows Explorer can't handle id3v2 tags
769 yield ('-write_id3v1', '1')
771 for name
, value
in metadata
['common'].items():
772 yield ('-metadata', f
'{name}={value}')
775 for fmt
in info
.get('requested_formats') or []:
776 stream_count
= 2 if 'none' not in (fmt
.get('vcodec'), fmt
.get('acodec')) else 1
777 lang
= ISO639Utils
.short2long(fmt
.get('language') or '') or fmt
.get('language')
778 for i
in range(stream_idx
, stream_idx
+ stream_count
):
780 metadata
[str(i
)].setdefault('language', lang
)
781 for name
, value
in metadata
[str(i
)].items():
782 yield (f
'-metadata:s:{i}', f
'{name}={value}')
783 stream_idx
+= stream_count
785 def _get_infojson_opts(self
, info
, infofn
):
786 if not infofn
or not os
.path
.exists(infofn
):
787 if self
._add
_infojson
is not True:
789 infofn
= infofn
or '%s.temp' % (
790 self
._downloader
.prepare_filename(info
, 'infojson')
791 or replace_extension(self
._downloader
.prepare_filename(info
), 'info.json', info
['ext']))
792 if not self
._downloader
._ensure
_dir
_exists
(infofn
):
794 self
.write_debug(f
'Writing info-json to: {infofn}')
795 write_json_file(self
._downloader
.sanitize_info(info
, self
.get_param('clean_infojson', True)), infofn
)
796 info
['infojson_filename'] = infofn
798 old_stream
, new_stream
= self
.get_stream_number(info
['filepath'], ('tags', 'mimetype'), 'application/json')
799 if old_stream
is not None:
800 yield ('-map', '-0:%d' % old_stream
)
805 f
'-metadata:s:{new_stream}', 'mimetype=application/json',
806 f
'-metadata:s:{new_stream}', 'filename=info.json',
810 class FFmpegMergerPP(FFmpegPostProcessor
):
811 @PostProcessor._restrict_to(images
=False)
813 filename
= info
['filepath']
814 temp_filename
= prepend_extension(filename
, 'temp')
815 args
= ['-c', 'copy']
817 for (i
, fmt
) in enumerate(info
['requested_formats']):
818 if fmt
.get('acodec') != 'none':
819 args
.extend(['-map', f
'{i}:a:0'])
820 aac_fixup
= fmt
['protocol'].startswith('m3u8') and self
.get_audio_codec(fmt
['filepath']) == 'aac'
822 args
.extend([f
'-bsf:a:{audio_streams}', 'aac_adtstoasc'])
824 if fmt
.get('vcodec') != 'none':
825 args
.extend(['-map', '%u:v:0' % (i
)])
826 self
.to_screen('Merging formats into "%s"' % filename
)
827 self
.run_ffmpeg_multiple_files(info
['__files_to_merge'], temp_filename
, args
)
828 os
.rename(encodeFilename(temp_filename
), encodeFilename(filename
))
829 return info
['__files_to_merge'], info
832 # TODO: figure out merge-capable ffmpeg version
833 if self
.basename
!= 'avconv':
836 required_version
= '10-0'
837 if is_outdated_version(
838 self
._versions
[self
.basename
], required_version
):
839 warning
= ('Your copy of %s is outdated and unable to properly mux separate video and audio files, '
840 'yt-dlp will download single file media. '
841 'Update %s to version %s or newer to fix this.') % (
842 self
.basename
, self
.basename
, required_version
)
843 self
.report_warning(warning
)
848 class FFmpegFixupPostProcessor(FFmpegPostProcessor
):
849 def _fixup(self
, msg
, filename
, options
):
850 temp_filename
= prepend_extension(filename
, 'temp')
852 self
.to_screen(f
'{msg} of "{filename}"')
853 self
.run_ffmpeg(filename
, temp_filename
, options
)
855 os
.replace(temp_filename
, filename
)
858 class FFmpegFixupStretchedPP(FFmpegFixupPostProcessor
):
859 @PostProcessor._restrict_to(images
=False, audio
=False)
861 stretched_ratio
= info
.get('stretched_ratio')
862 if stretched_ratio
not in (None, 1):
863 self
._fixup
('Fixing aspect ratio', info
['filepath'], [
864 *self
.stream_copy_opts(), '-aspect', '%f' % stretched_ratio
])
868 class FFmpegFixupM4aPP(FFmpegFixupPostProcessor
):
869 @PostProcessor._restrict_to(images
=False, video
=False)
871 if info
.get('container') == 'm4a_dash':
872 self
._fixup
('Correcting container', info
['filepath'], [*self
.stream_copy_opts(), '-f', 'mp4'])
876 class FFmpegFixupM3u8PP(FFmpegFixupPostProcessor
):
877 def _needs_fixup(self
, info
):
878 yield info
['ext'] in ('mp4', 'm4a')
879 yield info
['protocol'].startswith('m3u8')
881 metadata
= self
.get_metadata_object(info
['filepath'])
882 except PostProcessingError
as e
:
883 self
.report_warning(f
'Unable to extract metadata: {e.msg}')
886 yield traverse_obj(metadata
, ('format', 'format_name'), casesense
=False) == 'mpegts'
888 @PostProcessor._restrict_to(images
=False)
890 if all(self
._needs
_fixup
(info
)):
891 self
._fixup
('Fixing MPEG-TS in MP4 container', info
['filepath'], [
892 *self
.stream_copy_opts(), '-f', 'mp4', '-bsf:a', 'aac_adtstoasc'])
896 class FFmpegFixupTimestampPP(FFmpegFixupPostProcessor
):
898 def __init__(self
, downloader
=None, trim
=0.001):
899 # "trim" should be used when the video contains unintended packets
900 super().__init
__(downloader
)
901 assert isinstance(trim
, (int, float))
902 self
.trim
= str(trim
)
904 @PostProcessor._restrict_to(images
=False)
906 if not self
._features
.get('setts'):
908 'A re-encode is needed to fix timestamps in older versions of ffmpeg. '
909 'Please install ffmpeg 4.4 or later to fixup without re-encoding')
910 opts
= ['-vf', 'setpts=PTS-STARTPTS']
912 opts
= ['-c', 'copy', '-bsf', 'setts=ts=TS-STARTPTS']
913 self
._fixup
('Fixing frame timestamp', info
['filepath'], opts
+ [*self
.stream_copy_opts(False), '-ss', self
.trim
])
917 class FFmpegCopyStreamPP(FFmpegFixupPostProcessor
):
918 MESSAGE
= 'Copying stream'
920 @PostProcessor._restrict_to(images
=False)
922 self
._fixup
(self
.MESSAGE
, info
['filepath'], self
.stream_copy_opts())
926 class FFmpegFixupDurationPP(FFmpegCopyStreamPP
):
927 MESSAGE
= 'Fixing video duration'
930 class FFmpegFixupDuplicateMoovPP(FFmpegCopyStreamPP
):
931 MESSAGE
= 'Fixing duplicate MOOV atoms'
934 class FFmpegSubtitlesConvertorPP(FFmpegPostProcessor
):
935 SUPPORTED_EXTS
= ('srt', 'vtt', 'ass', 'lrc')
937 def __init__(self
, downloader
=None, format
=None):
938 super().__init
__(downloader
)
942 subs
= info
.get('requested_subtitles')
943 new_ext
= self
.format
945 if new_format
== 'vtt':
946 new_format
= 'webvtt'
948 self
.to_screen('There aren\'t any subtitles to convert')
950 self
.to_screen('Converting subtitles')
952 for lang
, sub
in subs
.items():
953 if not os
.path
.exists(sub
.get('filepath', '')):
954 self
.report_warning(f
'Skipping embedding {lang} subtitle because the file is missing')
958 self
.to_screen('Subtitle file for %s is already in the requested format' % new_ext
)
962 'You have requested to convert json subtitles into another format, '
963 'which is currently not possible')
965 old_file
= sub
['filepath']
966 sub_filenames
.append(old_file
)
967 new_file
= replace_extension(old_file
, new_ext
)
969 if ext
in ('dfxp', 'ttml', 'tt'):
971 'You have requested to convert dfxp (TTML) subtitles into another format, '
972 'which results in style information loss')
975 srt_file
= replace_extension(old_file
, 'srt')
977 with open(dfxp_file
, 'rb') as f
:
978 srt_data
= dfxp2srt(f
.read())
980 with open(srt_file
, 'wt', encoding
='utf-8') as f
:
987 'filepath': srt_file
,
993 sub_filenames
.append(srt_file
)
995 self
.run_ffmpeg(old_file
, new_file
, ['-f', new_format
])
997 with open(new_file
, encoding
='utf-8') as f
:
1001 'filepath': new_file
,
1004 info
['__files_to_move'][new_file
] = replace_extension(
1005 info
['__files_to_move'][sub
['filepath']], new_ext
)
1007 return sub_filenames
, info
1010 class FFmpegSplitChaptersPP(FFmpegPostProcessor
):
1011 def __init__(self
, downloader
, force_keyframes
=False):
1012 FFmpegPostProcessor
.__init
__(self
, downloader
)
1013 self
._force
_keyframes
= force_keyframes
1015 def _prepare_filename(self
, number
, chapter
, info
):
1018 'section_number': number
,
1019 'section_title': chapter
.get('title'),
1020 'section_start': chapter
.get('start_time'),
1021 'section_end': chapter
.get('end_time'),
1023 return self
._downloader
.prepare_filename(info
, 'chapter')
1025 def _ffmpeg_args_for_chapter(self
, number
, chapter
, info
):
1026 destination
= self
._prepare
_filename
(number
, chapter
, info
)
1027 if not self
._downloader
._ensure
_dir
_exists
(encodeFilename(destination
)):
1030 chapter
['filepath'] = destination
1031 self
.to_screen('Chapter %03d; Destination: %s' % (number
, destination
))
1034 ['-ss', str(chapter
['start_time']),
1035 '-t', str(chapter
['end_time'] - chapter
['start_time'])])
1037 @PostProcessor._restrict_to(images
=False)
1038 def run(self
, info
):
1039 chapters
= info
.get('chapters') or []
1041 self
.to_screen('Chapter information is unavailable')
1044 in_file
= info
['filepath']
1045 if self
._force
_keyframes
and len(chapters
) > 1:
1046 in_file
= self
.force_keyframes(in_file
, (c
['start_time'] for c
in chapters
))
1047 self
.to_screen('Splitting video by chapters; %d chapters found' % len(chapters
))
1048 for idx
, chapter
in enumerate(chapters
):
1049 destination
, opts
= self
._ffmpeg
_args
_for
_chapter
(idx
+ 1, chapter
, info
)
1050 self
.real_run_ffmpeg([(in_file
, opts
)], [(destination
, self
.stream_copy_opts())])
1051 if in_file
!= info
['filepath']:
1052 self
._delete
_downloaded
_files
(in_file
, msg
=None)
1056 class FFmpegThumbnailsConvertorPP(FFmpegPostProcessor
):
1057 SUPPORTED_EXTS
= ('jpg', 'png', 'webp')
1059 def __init__(self
, downloader
=None, format
=None):
1060 super().__init
__(downloader
)
1061 self
.format
= format
1064 def is_webp(cls
, path
):
1065 write_string(f
'DeprecationWarning: {cls.__module__}.{cls.__name__}.is_webp is deprecated')
1066 return imghdr
.what(path
) == 'webp'
1068 def fixup_webp(self
, info
, idx
=-1):
1069 thumbnail_filename
= info
['thumbnails'][idx
]['filepath']
1070 _
, thumbnail_ext
= os
.path
.splitext(thumbnail_filename
)
1072 if thumbnail_ext
.lower() != '.webp' and imghdr
.what(thumbnail_filename
) == 'webp':
1073 self
.to_screen('Correcting thumbnail "%s" extension to webp' % thumbnail_filename
)
1074 webp_filename
= replace_extension(thumbnail_filename
, 'webp')
1075 os
.replace(thumbnail_filename
, webp_filename
)
1076 info
['thumbnails'][idx
]['filepath'] = webp_filename
1077 info
['__files_to_move'][webp_filename
] = replace_extension(
1078 info
['__files_to_move'].pop(thumbnail_filename
), 'webp')
1081 def _options(target_ext
):
1082 if target_ext
== 'jpg':
1083 return ['-bsf:v', 'mjpeg2jpeg']
1086 def convert_thumbnail(self
, thumbnail_filename
, target_ext
):
1087 thumbnail_conv_filename
= replace_extension(thumbnail_filename
, target_ext
)
1089 self
.to_screen(f
'Converting thumbnail "{thumbnail_filename}" to {target_ext}')
1090 self
.real_run_ffmpeg(
1091 [(thumbnail_filename
, ['-f', 'image2', '-pattern_type', 'none'])],
1092 [(thumbnail_conv_filename
.replace('%', '%%'), self
._options
(target_ext
))])
1093 return thumbnail_conv_filename
1095 def run(self
, info
):
1096 files_to_delete
= []
1097 has_thumbnail
= False
1099 for idx
, thumbnail_dict
in enumerate(info
.get('thumbnails') or []):
1100 original_thumbnail
= thumbnail_dict
.get('filepath')
1101 if not original_thumbnail
:
1103 has_thumbnail
= True
1104 self
.fixup_webp(info
, idx
)
1105 _
, thumbnail_ext
= os
.path
.splitext(original_thumbnail
)
1107 thumbnail_ext
= thumbnail_ext
[1:].lower()
1108 if thumbnail_ext
== 'jpeg':
1109 thumbnail_ext
= 'jpg'
1110 if thumbnail_ext
== self
.format
:
1111 self
.to_screen('Thumbnail "%s" is already in the requested format' % original_thumbnail
)
1113 thumbnail_dict
['filepath'] = self
.convert_thumbnail(original_thumbnail
, self
.format
)
1114 files_to_delete
.append(original_thumbnail
)
1115 info
['__files_to_move'][thumbnail_dict
['filepath']] = replace_extension(
1116 info
['__files_to_move'][original_thumbnail
], self
.format
)
1118 if not has_thumbnail
:
1119 self
.to_screen('There aren\'t any thumbnails to convert')
1120 return files_to_delete
, info
1123 class FFmpegConcatPP(FFmpegPostProcessor
):
1124 def __init__(self
, downloader
, only_multi_video
=False):
1125 self
._only
_multi
_video
= only_multi_video
1126 super().__init
__(downloader
)
1128 def _get_codecs(self
, file):
1129 codecs
= traverse_obj(self
.get_metadata_object(file), ('streams', ..., 'codec_name'))
1130 self
.write_debug(f
'Codecs = {", ".join(codecs)}')
1131 return tuple(codecs
)
1133 def concat_files(self
, in_files
, out_file
):
1134 if not self
._downloader
._ensure
_dir
_exists
(out_file
):
1136 if len(in_files
) == 1:
1137 if os
.path
.realpath(in_files
[0]) != os
.path
.realpath(out_file
):
1138 self
.to_screen(f
'Moving "{in_files[0]}" to "{out_file}"')
1139 os
.replace(in_files
[0], out_file
)
1142 if len(set(map(self
._get
_codecs
, in_files
))) > 1:
1143 raise PostProcessingError(
1144 'The files have different streams/codecs and cannot be concatenated. '
1145 'Either select different formats or --recode-video them to a common format')
1147 self
.to_screen(f
'Concatenating {len(in_files)} files; Destination: {out_file}')
1148 super().concat_files(in_files
, out_file
)
1151 @PostProcessor._restrict_to(images
=False, simulated
=False)
1152 def run(self
, info
):
1153 entries
= info
.get('entries') or []
1154 if not any(entries
) or (self
._only
_multi
_video
and info
['_type'] != 'multi_video'):
1156 elif traverse_obj(entries
, (..., lambda k
, v
: k
== 'requested_downloads' and len(v
) > 1)):
1157 raise PostProcessingError('Concatenation is not supported when downloading multiple separate formats')
1159 in_files
= traverse_obj(entries
, (..., 'requested_downloads', 0, 'filepath')) or []
1160 if len(in_files
) < len(entries
):
1161 raise PostProcessingError('Aborting concatenation because some downloads failed')
1163 ie_copy
= self
._downloader
._playlist
_infodict
(info
)
1164 exts
= traverse_obj(entries
, (..., 'requested_downloads', 0, 'ext'), (..., 'ext'))
1165 ie_copy
['ext'] = exts
[0] if len(set(exts
)) == 1 else 'mkv'
1166 out_file
= self
._downloader
.prepare_filename(ie_copy
, 'pl_video')
1168 files_to_delete
= self
.concat_files(in_files
, out_file
)
1170 info
['requested_downloads'] = [{
1171 'filepath': out_file
,
1172 'ext': ie_copy
['ext'],
1174 return files_to_delete
, info