1 from __future__
import unicode_literals
11 from .common
import AudioConversionError
, PostProcessor
13 from ..compat
import compat_str
, compat_numeric_types
24 process_communicate_or_kill
,
30 EXT_TO_OUT_FORMATS
= {
48 'vorbis': 'libvorbis',
53 class FFmpegPostProcessorError(PostProcessingError
):
57 class FFmpegPostProcessor(PostProcessor
):
58 def __init__(self
, downloader
=None):
59 PostProcessor
.__init
__(self
, downloader
)
60 self
._determine
_executables
()
62 def check_version(self
):
63 if not self
.available
:
64 raise FFmpegPostProcessorError('ffmpeg not found. Please install or provide the path using --ffmpeg-location')
66 required_version
= '10-0' if self
.basename
== 'avconv' else '1.0'
67 if is_outdated_version(
68 self
._versions
[self
.basename
], required_version
):
69 warning
= 'Your copy of %s is outdated, update %s to version %s or newer if you encounter any errors.' % (
70 self
.basename
, self
.basename
, required_version
)
71 self
.report_warning(warning
)
74 def get_versions(downloader
=None):
75 return FFmpegPostProcessor(downloader
)._versions
77 def _determine_executables(self
):
78 programs
= ['avprobe', 'avconv', 'ffmpeg', 'ffprobe']
81 def get_ffmpeg_version(path
):
82 ver
= get_exe_version(path
, args
=['-version'])
85 r
'(?:\d+:)?([0-9.]+)-[0-9]+ubuntu[0-9.]+$', # Ubuntu, see [1]
86 r
'n([0-9.]+)$', # Arch Linux
87 # 1. http://www.ducea.com/2006/06/17/ubuntu-package-version-naming-explanation/
90 mobj
= re
.match(regex
, ver
)
96 self
.probe_basename
= None
101 prefer_ffmpeg
= self
.get_param('prefer_ffmpeg', True)
102 location
= self
.get_param('ffmpeg_location')
103 if location
is not None:
104 if not os
.path
.exists(location
):
106 'ffmpeg-location %s does not exist! '
107 'Continuing without ffmpeg.' % (location
))
110 elif not os
.path
.isdir(location
):
111 basename
= os
.path
.splitext(os
.path
.basename(location
))[0]
112 if basename
not in programs
:
114 'Cannot identify executable %s, its basename should be one of %s. '
115 'Continuing without ffmpeg.' %
116 (location
, ', '.join(programs
)))
119 location
= os
.path
.dirname(os
.path
.abspath(location
))
120 if basename
in ('ffmpeg', 'ffprobe'):
124 (p
, os
.path
.join(location
, p
)) for p
in programs
)
125 self
._versions
= dict(
126 (p
, get_ffmpeg_version(self
._paths
[p
])) for p
in programs
)
127 if self
._versions
is None:
128 self
._versions
= dict(
129 (p
, get_ffmpeg_version(p
)) for p
in programs
)
130 self
._paths
= dict((p
, p
) for p
in programs
)
132 if prefer_ffmpeg
is False:
133 prefs
= ('avconv', 'ffmpeg')
135 prefs
= ('ffmpeg', 'avconv')
137 if self
._versions
[p
]:
141 if prefer_ffmpeg
is False:
142 prefs
= ('avprobe', 'ffprobe')
144 prefs
= ('ffprobe', 'avprobe')
146 if self
._versions
[p
]:
147 self
.probe_basename
= p
152 return self
.basename
is not None
155 def executable(self
):
156 return self
._paths
[self
.basename
]
159 def probe_available(self
):
160 return self
.probe_basename
is not None
163 def probe_executable(self
):
164 return self
._paths
[self
.probe_basename
]
166 def get_audio_codec(self
, path
):
167 if not self
.probe_available
and not self
.available
:
168 raise PostProcessingError('ffprobe and ffmpeg not found. Please install or provide the path using --ffmpeg-location')
170 if self
.probe_available
:
172 encodeFilename(self
.probe_executable
, True),
173 encodeArgument('-show_streams')]
176 encodeFilename(self
.executable
, True),
177 encodeArgument('-i')]
178 cmd
.append(encodeFilename(self
._ffmpeg
_filename
_argument
(path
), True))
179 self
.write_debug('%s command line: %s' % (self
.basename
, shell_quote(cmd
)))
180 handle
= subprocess
.Popen(
181 cmd
, stderr
=subprocess
.PIPE
,
182 stdout
=subprocess
.PIPE
, stdin
=subprocess
.PIPE
)
183 stdout_data
, stderr_data
= process_communicate_or_kill(handle
)
184 expected_ret
= 0 if self
.probe_available
else 1
185 if handle
.wait() != expected_ret
:
187 except (IOError, OSError):
189 output
= (stdout_data
if self
.probe_available
else stderr_data
).decode('ascii', 'ignore')
190 if self
.probe_available
:
192 for line
in output
.split('\n'):
193 if line
.startswith('codec_name='):
194 audio_codec
= line
.split('=')[1].strip()
195 elif line
.strip() == 'codec_type=audio' and audio_codec
is not None:
198 # Stream #FILE_INDEX:STREAM_INDEX[STREAM_ID](LANGUAGE): CODEC_TYPE: CODEC_NAME
200 r
'Stream\s*#\d+:\d+(?:\[0x[0-9a-f]+\])?(?:\([a-z]{3}\))?:\s*Audio:\s*([0-9a-z]+)',
206 def get_metadata_object(self
, path
, opts
=[]):
207 if self
.probe_basename
!= 'ffprobe':
208 if self
.probe_available
:
209 self
.report_warning('Only ffprobe is supported for metadata extraction')
210 raise PostProcessingError('ffprobe not found. Please install or provide the path using --ffmpeg-location')
214 encodeFilename(self
.probe_executable
, True),
215 encodeArgument('-hide_banner'),
216 encodeArgument('-show_format'),
217 encodeArgument('-show_streams'),
218 encodeArgument('-print_format'),
219 encodeArgument('json'),
223 cmd
.append(encodeFilename(self
._ffmpeg
_filename
_argument
(path
), True))
224 self
.write_debug('ffprobe command line: %s' % shell_quote(cmd
))
225 p
= subprocess
.Popen(cmd
, stdout
=subprocess
.PIPE
, stderr
=subprocess
.PIPE
, stdin
=subprocess
.PIPE
)
226 stdout
, stderr
= p
.communicate()
227 return json
.loads(stdout
.decode('utf-8', 'replace'))
229 def get_stream_number(self
, path
, keys
, value
):
230 streams
= self
.get_metadata_object(path
)['streams']
232 (i
for i
, stream
in enumerate(streams
) if traverse_dict(stream
, keys
, casesense
=False) == value
),
234 return num
, len(streams
)
236 def run_ffmpeg_multiple_files(self
, input_paths
, out_path
, opts
):
237 return self
.real_run_ffmpeg(
238 [(path
, []) for path
in input_paths
],
241 def real_run_ffmpeg(self
, input_path_opts
, output_path_opts
):
245 os
.stat(encodeFilename(path
)).st_mtime
for path
, _
in input_path_opts
)
247 cmd
= [encodeFilename(self
.executable
, True), encodeArgument('-y')]
248 # avconv does not have repeat option
249 if self
.basename
== 'ffmpeg':
250 cmd
+= [encodeArgument('-loglevel'), encodeArgument('repeat+info')]
252 def make_args(file, args
, name
, number
):
253 keys
= ['_%s%d' % (name
, number
), '_%s' % name
]
254 if name
== 'o' and number
== 1:
256 args
+= self
._configuration
_args
(self
.basename
, keys
)
260 [encodeArgument(arg
) for arg
in args
]
261 + [encodeFilename(self
._ffmpeg
_filename
_argument
(file), True)])
263 for arg_type
, path_opts
in (('i', input_path_opts
), ('o', output_path_opts
)):
264 cmd
+= [arg
for i
, o
in enumerate(path_opts
)
265 for arg
in make_args(o
[0], o
[1], arg_type
, i
+ 1)]
267 self
.write_debug('ffmpeg command line: %s' % shell_quote(cmd
))
268 p
= subprocess
.Popen(cmd
, stdout
=subprocess
.PIPE
, stderr
=subprocess
.PIPE
, stdin
=subprocess
.PIPE
)
269 stdout
, stderr
= process_communicate_or_kill(p
)
270 if p
.returncode
!= 0:
271 stderr
= stderr
.decode('utf-8', 'replace').strip()
272 if self
.get_param('verbose', False):
273 self
.report_error(stderr
)
274 raise FFmpegPostProcessorError(stderr
.split('\n')[-1])
275 for out_path
, _
in output_path_opts
:
276 self
.try_utime(out_path
, oldest_mtime
, oldest_mtime
)
277 return stderr
.decode('utf-8', 'replace')
279 def run_ffmpeg(self
, path
, out_path
, opts
):
280 return self
.run_ffmpeg_multiple_files([path
], out_path
, opts
)
282 def _ffmpeg_filename_argument(self
, fn
):
283 # Always use 'file:' because the filename may contain ':' (ffmpeg
284 # interprets that as a protocol) or can start with '-' (-- is broken in
285 # ffmpeg, see https://ffmpeg.org/trac/ffmpeg/ticket/2127 for details)
286 # Also leave '-' intact in order not to break streaming to stdout.
287 if fn
.startswith(('http://', 'https://')):
289 return 'file:' + fn
if fn
!= '-' else fn
292 class FFmpegExtractAudioPP(FFmpegPostProcessor
):
293 COMMON_AUDIO_EXTS
= ('wav', 'flac', 'm4a', 'aiff', 'mp3', 'ogg', 'mka', 'opus', 'wma')
294 SUPPORTED_EXTS
= ('best', 'aac', 'flac', 'mp3', 'm4a', 'opus', 'vorbis', 'wav')
296 def __init__(self
, downloader
=None, preferredcodec
=None, preferredquality
=None, nopostoverwrites
=False):
297 FFmpegPostProcessor
.__init
__(self
, downloader
)
298 self
._preferredcodec
= preferredcodec
or 'best'
299 self
._preferredquality
= preferredquality
300 self
._nopostoverwrites
= nopostoverwrites
302 def run_ffmpeg(self
, path
, out_path
, codec
, more_opts
):
306 acodec_opts
= ['-acodec', codec
]
307 opts
= ['-vn'] + acodec_opts
+ more_opts
309 FFmpegPostProcessor
.run_ffmpeg(self
, path
, out_path
, opts
)
310 except FFmpegPostProcessorError
as err
:
311 raise AudioConversionError(err
.msg
)
313 def run(self
, information
):
314 path
= information
['filepath']
315 orig_ext
= information
['ext']
317 if self
._preferredcodec
== 'best' and orig_ext
in self
.COMMON_AUDIO_EXTS
:
318 self
.to_screen('Skipping audio extraction since the file is already in a common audio format')
319 return [], information
321 filecodec
= self
.get_audio_codec(path
)
322 if filecodec
is None:
323 raise PostProcessingError('WARNING: unable to obtain file audio codec with ffprobe')
326 if self
._preferredcodec
== 'best' or self
._preferredcodec
== filecodec
or (self
._preferredcodec
== 'm4a' and filecodec
== 'aac'):
327 if filecodec
== 'aac' and self
._preferredcodec
in ['m4a', 'best']:
328 # Lossless, but in another container
331 more_opts
= ['-bsf:a', 'aac_adtstoasc']
332 elif filecodec
in ['aac', 'flac', 'mp3', 'vorbis', 'opus']:
333 # Lossless if possible
335 extension
= filecodec
336 if filecodec
== 'aac':
337 more_opts
= ['-f', 'adts']
338 if filecodec
== 'vorbis':
342 acodec
= 'libmp3lame'
345 if self
._preferredquality
is not None:
346 if int(self
._preferredquality
) < 10:
347 more_opts
+= ['-q:a', self
._preferredquality
]
349 more_opts
+= ['-b:a', self
._preferredquality
+ 'k']
351 # We convert the audio (lossy if codec is lossy)
352 acodec
= ACODECS
[self
._preferredcodec
]
353 extension
= self
._preferredcodec
355 if self
._preferredquality
is not None:
356 # The opus codec doesn't support the -aq option
357 if int(self
._preferredquality
) < 10 and extension
!= 'opus':
358 more_opts
+= ['-q:a', self
._preferredquality
]
360 more_opts
+= ['-b:a', self
._preferredquality
+ 'k']
361 if self
._preferredcodec
== 'aac':
362 more_opts
+= ['-f', 'adts']
363 if self
._preferredcodec
== 'm4a':
364 more_opts
+= ['-bsf:a', 'aac_adtstoasc']
365 if self
._preferredcodec
== 'vorbis':
367 if self
._preferredcodec
== 'wav':
369 more_opts
+= ['-f', 'wav']
371 prefix
, sep
, ext
= path
.rpartition('.') # not os.path.splitext, since the latter does not work on unicode in all setups
372 new_path
= prefix
+ sep
+ extension
374 information
['filepath'] = new_path
375 information
['ext'] = extension
377 # If we download foo.mp3 and convert it to... foo.mp3, then don't delete foo.mp3, silly.
379 or (self
._nopostoverwrites
and os
.path
.exists(encodeFilename(new_path
)))):
380 self
.to_screen('Post-process file %s exists, skipping' % new_path
)
381 return [], information
384 self
.to_screen('Destination: ' + new_path
)
385 self
.run_ffmpeg(path
, new_path
, acodec
, more_opts
)
386 except AudioConversionError
as e
:
387 raise PostProcessingError(
388 'audio conversion failed: ' + e
.msg
)
390 raise PostProcessingError('error running ' + self
.basename
)
392 # Try to update the date time for extracted audio file.
393 if information
.get('filetime') is not None:
395 new_path
, time
.time(), information
['filetime'],
396 errnote
='Cannot update utime of audio file')
398 return [path
], information
401 class FFmpegVideoConvertorPP(FFmpegPostProcessor
):
402 SUPPORTED_EXTS
= ('mp4', 'mkv', 'flv', 'webm', 'mov', 'avi', 'mp3', 'mka', 'm4a', 'ogg', 'opus')
403 FORMAT_RE
= re
.compile(r
'{0}(?:/{0})*$'.format(r
'(?:\w+>)?(?:%s)' % '|'.join(SUPPORTED_EXTS
)))
404 _action
= 'converting'
406 def __init__(self
, downloader
=None, preferedformat
=None):
407 super(FFmpegVideoConvertorPP
, self
).__init
__(downloader
)
408 self
._preferedformats
= preferedformat
.lower().split('/')
410 def _target_ext(self
, source_ext
):
411 for pair
in self
._preferedformats
:
413 if len(kv
) == 1 or kv
[0].strip() == source_ext
:
414 return kv
[-1].strip()
417 def _options(target_ext
):
418 if target_ext
== 'avi':
419 return ['-c:v', 'libxvid', '-vtag', 'XVID']
422 def run(self
, information
):
423 path
, source_ext
= information
['filepath'], information
['ext'].lower()
424 target_ext
= self
._target
_ext
(source_ext
)
426 'could not find a mapping for %s' if not target_ext
427 else 'already is in target format %s' if source_ext
== target_ext
430 self
.to_screen('Not %s media file "%s"; %s' % (self
._action
, path
, _skip_msg
% source_ext
))
431 return [], information
433 prefix
, sep
, oldext
= path
.rpartition('.')
434 outpath
= prefix
+ sep
+ target_ext
435 self
.to_screen('%s video from %s to %s; Destination: %s' % (self
._action
.title(), source_ext
, target_ext
, outpath
))
436 self
.run_ffmpeg(path
, outpath
, self
._options
(target_ext
))
438 information
['filepath'] = outpath
439 information
['format'] = information
['ext'] = target_ext
440 return [path
], information
443 class FFmpegVideoRemuxerPP(FFmpegVideoConvertorPP
):
447 def _options(target_ext
):
448 options
= ['-c', 'copy', '-map', '0', '-dn']
449 if target_ext
in ['mp4', 'm4a', 'mov']:
450 options
.extend(['-movflags', '+faststart'])
454 class FFmpegEmbedSubtitlePP(FFmpegPostProcessor
):
455 def __init__(self
, downloader
=None, already_have_subtitle
=False):
456 super(FFmpegEmbedSubtitlePP
, self
).__init
__(downloader
)
457 self
._already
_have
_subtitle
= already_have_subtitle
459 def run(self
, information
):
460 if information
['ext'] not in ('mp4', 'webm', 'mkv'):
461 self
.to_screen('Subtitles can only be embedded in mp4, webm or mkv files')
462 return [], information
463 subtitles
= information
.get('requested_subtitles')
465 self
.to_screen('There aren\'t any subtitles to embed')
466 return [], information
468 filename
= information
['filepath']
470 ext
= information
['ext']
471 sub_langs
, sub_names
, sub_filenames
= [], [], []
472 webm_vtt_warn
= False
475 for lang
, sub_info
in subtitles
.items():
476 sub_ext
= sub_info
['ext']
477 if sub_ext
== 'json':
478 self
.report_warning('JSON subtitles cannot be embedded')
479 elif ext
!= 'webm' or ext
== 'webm' and sub_ext
== 'vtt':
480 sub_langs
.append(lang
)
481 sub_names
.append(sub_info
.get('name'))
482 sub_filenames
.append(sub_info
['filepath'])
484 if not webm_vtt_warn
and ext
== 'webm' and sub_ext
!= 'vtt':
486 self
.report_warning('Only WebVTT subtitles can be embedded in webm files')
487 if not mp4_ass_warn
and ext
== 'mp4' and sub_ext
== 'ass':
489 self
.report_warning('ASS subtitles cannot be properly embedded in mp4 files; expect issues')
492 return [], information
494 input_files
= [filename
] + sub_filenames
497 '-c', 'copy', '-map', '0', '-dn',
498 # Don't copy the existing subtitles, we may be running the
499 # postprocessor a second time
501 # Don't copy Apple TV chapters track, bin_data (see #19042, #19024,
502 # https://trac.ffmpeg.org/ticket/6016)
505 if information
['ext'] == 'mp4':
506 opts
+= ['-c:s', 'mov_text']
507 for i
, (lang
, name
) in enumerate(zip(sub_langs
, sub_names
)):
508 opts
.extend(['-map', '%d:0' % (i
+ 1)])
509 lang_code
= ISO639Utils
.short2long(lang
) or lang
510 opts
.extend(['-metadata:s:s:%d' % i
, 'language=%s' % lang_code
])
512 opts
.extend(['-metadata:s:s:%d' % i
, 'handler_name=%s' % name
,
513 '-metadata:s:s:%d' % i
, 'title=%s' % name
])
515 temp_filename
= prepend_extension(filename
, 'temp')
516 self
.to_screen('Embedding subtitles in "%s"' % filename
)
517 self
.run_ffmpeg_multiple_files(input_files
, temp_filename
, opts
)
518 os
.remove(encodeFilename(filename
))
519 os
.rename(encodeFilename(temp_filename
), encodeFilename(filename
))
521 files_to_delete
= [] if self
._already
_have
_subtitle
else sub_filenames
522 return files_to_delete
, information
525 class FFmpegMetadataPP(FFmpegPostProcessor
):
529 def add(meta_list
, info_list
=None):
533 info_list
= meta_list
534 if not isinstance(meta_list
, (list, tuple)):
535 meta_list
= (meta_list
,)
536 if not isinstance(info_list
, (list, tuple)):
537 info_list
= (info_list
,)
538 for info_f
in info_list
:
539 if isinstance(info
.get(info_f
), (compat_str
, compat_numeric_types
)):
540 for meta_f
in meta_list
:
541 metadata
[meta_f
] = info
[info_f
]
544 # See [1-4] for some info on media metadata/metadata supported
546 # 1. https://kdenlive.org/en/project/adding-meta-data-to-mp4-video/
547 # 2. https://wiki.multimedia.cx/index.php/FFmpeg_Metadata
548 # 3. https://kodi.wiki/view/Video_file_tagging
550 add('title', ('track', 'title'))
551 add('date', 'upload_date')
552 add(('description', 'synopsis'), 'description')
553 add(('purl', 'comment'), 'webpage_url')
554 add('track', 'track_number')
555 add('artist', ('artist', 'creator', 'uploader', 'uploader_id'))
559 add('disc', 'disc_number')
560 add('show', 'series')
562 add('episode_id', ('episode', 'episode_id'))
563 add('episode_sort', 'episode_number')
566 for key
in filter(lambda k
: k
.startswith(prefix
), info
.keys()):
567 add(key
[len(prefix
):], key
)
570 self
.to_screen('There isn\'t any metadata to add')
573 filename
= info
['filepath']
574 temp_filename
= prepend_extension(filename
, 'temp')
575 in_filenames
= [filename
]
576 options
= ['-map', '0', '-dn']
578 if info
['ext'] == 'm4a':
579 options
.extend(['-vn', '-acodec', 'copy'])
581 options
.extend(['-c', 'copy'])
583 for name
, value
in metadata
.items():
584 options
.extend(['-metadata', '%s=%s' % (name
, value
)])
586 chapters
= info
.get('chapters', [])
588 metadata_filename
= replace_extension(filename
, 'meta')
589 with io
.open(metadata_filename
, 'wt', encoding
='utf-8') as f
:
590 def ffmpeg_escape(text
):
591 return re
.sub(r
'(=|;|#|\\|\n)', r
'\\\1', text
)
593 metadata_file_content
= ';FFMETADATA1\n'
594 for chapter
in chapters
:
595 metadata_file_content
+= '[CHAPTER]\nTIMEBASE=1/1000\n'
596 metadata_file_content
+= 'START=%d\n' % (chapter
['start_time'] * 1000)
597 metadata_file_content
+= 'END=%d\n' % (chapter
['end_time'] * 1000)
598 chapter_title
= chapter
.get('title')
600 metadata_file_content
+= 'title=%s\n' % ffmpeg_escape(chapter_title
)
601 f
.write(metadata_file_content
)
602 in_filenames
.append(metadata_filename
)
603 options
.extend(['-map_metadata', '1'])
605 if ('no-attach-info-json' not in self
.get_param('compat_opts', [])
606 and '__infojson_filename' in info
and info
['ext'] in ('mkv', 'mka')):
607 old_stream
, new_stream
= self
.get_stream_number(
608 filename
, ('tags', 'mimetype'), 'application/json')
609 if old_stream
is not None:
610 options
.extend(['-map', '-0:%d' % old_stream
])
614 '-attach', info
['__infojson_filename'],
615 '-metadata:s:%d' % new_stream
, 'mimetype=application/json'
618 self
.to_screen('Adding metadata to \'%s\'' % filename
)
619 self
.run_ffmpeg_multiple_files(in_filenames
, temp_filename
, options
)
621 os
.remove(metadata_filename
)
622 os
.remove(encodeFilename(filename
))
623 os
.rename(encodeFilename(temp_filename
), encodeFilename(filename
))
627 class FFmpegMergerPP(FFmpegPostProcessor
):
629 filename
= info
['filepath']
630 temp_filename
= prepend_extension(filename
, 'temp')
631 args
= ['-c', 'copy']
632 for (i
, fmt
) in enumerate(info
['requested_formats']):
633 if fmt
.get('acodec') != 'none':
634 args
.extend(['-map', '%u:a:0' % (i
)])
635 if fmt
.get('vcodec') != 'none':
636 args
.extend(['-map', '%u:v:0' % (i
)])
637 self
.to_screen('Merging formats into "%s"' % filename
)
638 self
.run_ffmpeg_multiple_files(info
['__files_to_merge'], temp_filename
, args
)
639 os
.rename(encodeFilename(temp_filename
), encodeFilename(filename
))
640 return info
['__files_to_merge'], info
643 # TODO: figure out merge-capable ffmpeg version
644 if self
.basename
!= 'avconv':
647 required_version
= '10-0'
648 if is_outdated_version(
649 self
._versions
[self
.basename
], required_version
):
650 warning
= ('Your copy of %s is outdated and unable to properly mux separate video and audio files, '
651 'yt-dlp will download single file media. '
652 'Update %s to version %s or newer to fix this.') % (
653 self
.basename
, self
.basename
, required_version
)
654 self
.report_warning(warning
)
659 class FFmpegFixupStretchedPP(FFmpegPostProcessor
):
661 stretched_ratio
= info
.get('stretched_ratio')
662 if stretched_ratio
is None or stretched_ratio
== 1:
665 filename
= info
['filepath']
666 temp_filename
= prepend_extension(filename
, 'temp')
668 options
= ['-c', 'copy', '-map', '0', '-dn', '-aspect', '%f' % stretched_ratio
]
669 self
.to_screen('Fixing aspect ratio in "%s"' % filename
)
670 self
.run_ffmpeg(filename
, temp_filename
, options
)
672 os
.remove(encodeFilename(filename
))
673 os
.rename(encodeFilename(temp_filename
), encodeFilename(filename
))
678 class FFmpegFixupM4aPP(FFmpegPostProcessor
):
680 if info
.get('container') != 'm4a_dash':
683 filename
= info
['filepath']
684 temp_filename
= prepend_extension(filename
, 'temp')
686 options
= ['-c', 'copy', '-map', '0', '-dn', '-f', 'mp4']
687 self
.to_screen('Correcting container in "%s"' % filename
)
688 self
.run_ffmpeg(filename
, temp_filename
, options
)
690 os
.remove(encodeFilename(filename
))
691 os
.rename(encodeFilename(temp_filename
), encodeFilename(filename
))
696 class FFmpegFixupM3u8PP(FFmpegPostProcessor
):
698 filename
= info
['filepath']
699 if self
.get_audio_codec(filename
) == 'aac':
700 temp_filename
= prepend_extension(filename
, 'temp')
702 options
= ['-c', 'copy', '-map', '0', '-dn', '-f', 'mp4', '-bsf:a', 'aac_adtstoasc']
703 self
.to_screen('Fixing malformed AAC bitstream in "%s"' % filename
)
704 self
.run_ffmpeg(filename
, temp_filename
, options
)
706 os
.remove(encodeFilename(filename
))
707 os
.rename(encodeFilename(temp_filename
), encodeFilename(filename
))
711 class FFmpegSubtitlesConvertorPP(FFmpegPostProcessor
):
712 SUPPORTED_EXTS
= ('srt', 'vtt', 'ass', 'lrc')
714 def __init__(self
, downloader
=None, format
=None):
715 super(FFmpegSubtitlesConvertorPP
, self
).__init
__(downloader
)
719 subs
= info
.get('requested_subtitles')
720 new_ext
= self
.format
722 if new_format
== 'vtt':
723 new_format
= 'webvtt'
725 self
.to_screen('There aren\'t any subtitles to convert')
727 self
.to_screen('Converting subtitles')
729 for lang
, sub
in subs
.items():
732 self
.to_screen('Subtitle file for %s is already in the requested format' % new_ext
)
736 'You have requested to convert json subtitles into another format, '
737 'which is currently not possible')
739 old_file
= sub
['filepath']
740 sub_filenames
.append(old_file
)
741 new_file
= replace_extension(old_file
, new_ext
)
743 if ext
in ('dfxp', 'ttml', 'tt'):
745 'You have requested to convert dfxp (TTML) subtitles into another format, '
746 'which results in style information loss')
749 srt_file
= replace_extension(old_file
, 'srt')
751 with open(dfxp_file
, 'rb') as f
:
752 srt_data
= dfxp2srt(f
.read())
754 with io
.open(srt_file
, 'wt', encoding
='utf-8') as f
:
761 'filepath': srt_file
,
767 sub_filenames
.append(srt_file
)
769 self
.run_ffmpeg(old_file
, new_file
, ['-f', new_format
])
771 with io
.open(new_file
, 'rt', encoding
='utf-8') as f
:
775 'filepath': new_file
,
778 info
['__files_to_move'][new_file
] = replace_extension(
779 info
['__files_to_move'][old_file
], new_ext
)
781 return sub_filenames
, info
784 class FFmpegSplitChaptersPP(FFmpegPostProcessor
):
786 def _prepare_filename(self
, number
, chapter
, info
):
789 'section_number': number
,
790 'section_title': chapter
.get('title'),
791 'section_start': chapter
.get('start_time'),
792 'section_end': chapter
.get('end_time'),
794 return self
._downloader
.prepare_filename(info
, 'chapter')
796 def _ffmpeg_args_for_chapter(self
, number
, chapter
, info
):
797 destination
= self
._prepare
_filename
(number
, chapter
, info
)
798 if not self
._downloader
._ensure
_dir
_exists
(encodeFilename(destination
)):
801 chapter
['filepath'] = destination
802 self
.to_screen('Chapter %03d; Destination: %s' % (number
, destination
))
805 ['-ss', compat_str(chapter
['start_time']),
806 '-t', compat_str(chapter
['end_time'] - chapter
['start_time'])])
809 chapters
= info
.get('chapters') or []
811 self
.report_warning('Chapter information is unavailable')
814 self
.to_screen('Splitting video by chapters; %d chapters found' % len(chapters
))
815 for idx
, chapter
in enumerate(chapters
):
816 destination
, opts
= self
._ffmpeg
_args
_for
_chapter
(idx
+ 1, chapter
, info
)
817 self
.real_run_ffmpeg([(info
['filepath'], opts
)], [(destination
, ['-c', 'copy'])])
821 class FFmpegThumbnailsConvertorPP(FFmpegPostProcessor
):
822 SUPPORTED_EXTS
= ('jpg', 'png')
824 def __init__(self
, downloader
=None, format
=None):
825 super(FFmpegThumbnailsConvertorPP
, self
).__init
__(downloader
)
830 with open(encodeFilename(path
), 'rb') as f
:
832 return b
[0:4] == b
'RIFF' and b
[8:] == b
'WEBP'
834 def fixup_webp(self
, info
, idx
=-1):
835 thumbnail_filename
= info
['thumbnails'][idx
]['filepath']
836 _
, thumbnail_ext
= os
.path
.splitext(thumbnail_filename
)
838 thumbnail_ext
= thumbnail_ext
[1:].lower()
839 if thumbnail_ext
!= 'webp' and self
.is_webp(thumbnail_filename
):
840 self
.to_screen('Correcting thumbnail "%s" extension to webp' % thumbnail_filename
)
841 webp_filename
= replace_extension(thumbnail_filename
, 'webp')
842 if os
.path
.exists(webp_filename
):
843 os
.remove(webp_filename
)
844 os
.rename(encodeFilename(thumbnail_filename
), encodeFilename(webp_filename
))
845 info
['thumbnails'][idx
]['filepath'] = webp_filename
846 info
['__files_to_move'][webp_filename
] = replace_extension(
847 info
['__files_to_move'].pop(thumbnail_filename
), 'webp')
850 def _options(target_ext
):
851 if target_ext
== 'jpg':
852 return ['-bsf:v', 'mjpeg2jpeg']
855 def convert_thumbnail(self
, thumbnail_filename
, target_ext
):
856 thumbnail_conv_filename
= replace_extension(thumbnail_filename
, target_ext
)
858 self
.to_screen('Converting thumbnail "%s" to %s' % (thumbnail_filename
, target_ext
))
859 self
.real_run_ffmpeg(
860 [(thumbnail_filename
, ['-f', 'image2', '-pattern_type', 'none'])],
861 [(thumbnail_conv_filename
.replace('%', '%%'), self
._options
(target_ext
))])
862 return thumbnail_conv_filename
866 has_thumbnail
= False
868 for idx
, thumbnail_dict
in enumerate(info
['thumbnails']):
869 if 'filepath' not in thumbnail_dict
:
872 self
.fixup_webp(info
, idx
)
873 original_thumbnail
= thumbnail_dict
['filepath']
874 _
, thumbnail_ext
= os
.path
.splitext(original_thumbnail
)
876 thumbnail_ext
= thumbnail_ext
[1:].lower()
877 if thumbnail_ext
== self
.format
:
878 self
.to_screen('Thumbnail "%s" is already in the requested format' % original_thumbnail
)
880 thumbnail_dict
['filepath'] = self
.convert_thumbnail(original_thumbnail
, self
.format
)
881 files_to_delete
.append(original_thumbnail
)
882 info
['__files_to_move'][thumbnail_dict
['filepath']] = replace_extension(
883 info
['__files_to_move'][original_thumbnail
], self
.format
)
885 if not has_thumbnail
:
886 self
.to_screen('There aren\'t any thumbnails to convert')
887 return files_to_delete
, info