1 from __future__
import unicode_literals
11 from .common
import AudioConversionError
, PostProcessor
13 from ..compat
import compat_str
25 process_communicate_or_kill
,
31 EXT_TO_OUT_FORMATS
= {
49 'vorbis': 'libvorbis',
54 class FFmpegPostProcessorError(PostProcessingError
):
58 class FFmpegPostProcessor(PostProcessor
):
59 def __init__(self
, downloader
=None):
60 PostProcessor
.__init
__(self
, downloader
)
61 self
._determine
_executables
()
63 def check_version(self
):
64 if not self
.available
:
65 raise FFmpegPostProcessorError('ffmpeg not found. Please install')
67 required_version
= '10-0' if self
.basename
== 'avconv' else '1.0'
68 if is_outdated_version(
69 self
._versions
[self
.basename
], required_version
):
70 warning
= 'Your copy of %s is outdated, update %s to version %s or newer if you encounter any errors.' % (
71 self
.basename
, self
.basename
, required_version
)
72 self
.report_warning(warning
)
75 def get_versions(downloader
=None):
76 return FFmpegPostProcessor(downloader
)._versions
78 def _determine_executables(self
):
79 programs
= ['avprobe', 'avconv', 'ffmpeg', 'ffprobe']
82 def get_ffmpeg_version(path
):
83 ver
= get_exe_version(path
, args
=['-version'])
86 r
'(?:\d+:)?([0-9.]+)-[0-9]+ubuntu[0-9.]+$', # Ubuntu, see [1]
87 r
'n([0-9.]+)$', # Arch Linux
88 # 1. http://www.ducea.com/2006/06/17/ubuntu-package-version-naming-explanation/
91 mobj
= re
.match(regex
, ver
)
97 self
.probe_basename
= None
100 self
._versions
= None
102 prefer_ffmpeg
= self
.get_param('prefer_ffmpeg', True)
103 location
= self
.get_param('ffmpeg_location')
104 if location
is not None:
105 if not os
.path
.exists(location
):
107 'ffmpeg-location %s does not exist! '
108 'Continuing without ffmpeg.' % (location
))
111 elif not os
.path
.isdir(location
):
112 basename
= os
.path
.splitext(os
.path
.basename(location
))[0]
113 if basename
not in programs
:
115 'Cannot identify executable %s, its basename should be one of %s. '
116 'Continuing without ffmpeg.' %
117 (location
, ', '.join(programs
)))
120 location
= os
.path
.dirname(os
.path
.abspath(location
))
121 if basename
in ('ffmpeg', 'ffprobe'):
125 (p
, os
.path
.join(location
, p
)) for p
in programs
)
126 self
._versions
= dict(
127 (p
, get_ffmpeg_version(self
._paths
[p
])) for p
in programs
)
128 if self
._versions
is None:
129 self
._versions
= dict(
130 (p
, get_ffmpeg_version(p
)) for p
in programs
)
131 self
._paths
= dict((p
, p
) for p
in programs
)
133 if prefer_ffmpeg
is False:
134 prefs
= ('avconv', 'ffmpeg')
136 prefs
= ('ffmpeg', 'avconv')
138 if self
._versions
[p
]:
142 if prefer_ffmpeg
is False:
143 prefs
= ('avprobe', 'ffprobe')
145 prefs
= ('ffprobe', 'avprobe')
147 if self
._versions
[p
]:
148 self
.probe_basename
= p
153 return self
.basename
is not None
156 def executable(self
):
157 return self
._paths
[self
.basename
]
160 def probe_available(self
):
161 return self
.probe_basename
is not None
164 def probe_executable(self
):
165 return self
._paths
[self
.probe_basename
]
167 def get_audio_codec(self
, path
):
168 if not self
.probe_available
and not self
.available
:
169 raise PostProcessingError('ffprobe and ffmpeg not found. Please install')
171 if self
.probe_available
:
173 encodeFilename(self
.probe_executable
, True),
174 encodeArgument('-show_streams')]
177 encodeFilename(self
.executable
, True),
178 encodeArgument('-i')]
179 cmd
.append(encodeFilename(self
._ffmpeg
_filename
_argument
(path
), True))
180 self
.write_debug('%s command line: %s' % (self
.basename
, shell_quote(cmd
)))
181 handle
= subprocess
.Popen(
182 cmd
, stderr
=subprocess
.PIPE
,
183 stdout
=subprocess
.PIPE
, stdin
=subprocess
.PIPE
)
184 stdout_data
, stderr_data
= process_communicate_or_kill(handle
)
185 expected_ret
= 0 if self
.probe_available
else 1
186 if handle
.wait() != expected_ret
:
188 except (IOError, OSError):
190 output
= (stdout_data
if self
.probe_available
else stderr_data
).decode('ascii', 'ignore')
191 if self
.probe_available
:
193 for line
in output
.split('\n'):
194 if line
.startswith('codec_name='):
195 audio_codec
= line
.split('=')[1].strip()
196 elif line
.strip() == 'codec_type=audio' and audio_codec
is not None:
199 # Stream #FILE_INDEX:STREAM_INDEX[STREAM_ID](LANGUAGE): CODEC_TYPE: CODEC_NAME
201 r
'Stream\s*#\d+:\d+(?:\[0x[0-9a-f]+\])?(?:\([a-z]{3}\))?:\s*Audio:\s*([0-9a-z]+)',
207 def get_metadata_object(self
, path
, opts
=[]):
208 if self
.probe_basename
!= 'ffprobe':
209 if self
.probe_available
:
210 self
.report_warning('Only ffprobe is supported for metadata extraction')
211 raise PostProcessingError('ffprobe not found. Please install.')
215 encodeFilename(self
.probe_executable
, True),
216 encodeArgument('-hide_banner'),
217 encodeArgument('-show_format'),
218 encodeArgument('-show_streams'),
219 encodeArgument('-print_format'),
220 encodeArgument('json'),
224 cmd
.append(encodeFilename(self
._ffmpeg
_filename
_argument
(path
), True))
225 self
.write_debug('ffprobe command line: %s' % shell_quote(cmd
))
226 p
= subprocess
.Popen(cmd
, stdout
=subprocess
.PIPE
, stderr
=subprocess
.PIPE
, stdin
=subprocess
.PIPE
)
227 stdout
, stderr
= p
.communicate()
228 return json
.loads(stdout
.decode('utf-8', 'replace'))
230 def get_stream_number(self
, path
, keys
, value
):
231 streams
= self
.get_metadata_object(path
)['streams']
233 (i
for i
, stream
in enumerate(streams
) if traverse_dict(stream
, keys
, casesense
=False) == value
),
235 return num
, len(streams
)
237 def run_ffmpeg_multiple_files(self
, input_paths
, out_path
, opts
):
238 return self
.real_run_ffmpeg(
239 [(path
, []) for path
in input_paths
],
242 def real_run_ffmpeg(self
, input_path_opts
, output_path_opts
):
246 os
.stat(encodeFilename(path
)).st_mtime
for path
, _
in input_path_opts
)
248 cmd
= [encodeFilename(self
.executable
, True), encodeArgument('-y')]
249 # avconv does not have repeat option
250 if self
.basename
== 'ffmpeg':
251 cmd
+= [encodeArgument('-loglevel'), encodeArgument('repeat+info')]
253 def make_args(file, args
, name
, number
):
254 keys
= ['_%s%d' % (name
, number
), '_%s' % name
]
255 if name
== 'o' and number
== 1:
257 args
+= self
._configuration
_args
(self
.basename
, keys
)
261 [encodeArgument(arg
) for arg
in args
]
262 + [encodeFilename(self
._ffmpeg
_filename
_argument
(file), True)])
264 for arg_type
, path_opts
in (('i', input_path_opts
), ('o', output_path_opts
)):
265 cmd
+= [arg
for i
, o
in enumerate(path_opts
)
266 for arg
in make_args(o
[0], o
[1], arg_type
, i
+ 1)]
268 self
.write_debug('ffmpeg command line: %s' % shell_quote(cmd
))
269 p
= subprocess
.Popen(cmd
, stdout
=subprocess
.PIPE
, stderr
=subprocess
.PIPE
, stdin
=subprocess
.PIPE
)
270 stdout
, stderr
= process_communicate_or_kill(p
)
271 if p
.returncode
!= 0:
272 stderr
= stderr
.decode('utf-8', 'replace').strip()
273 if self
.get_param('verbose', False):
274 self
.report_error(stderr
)
275 raise FFmpegPostProcessorError(stderr
.split('\n')[-1])
276 for out_path
, _
in output_path_opts
:
277 self
.try_utime(out_path
, oldest_mtime
, oldest_mtime
)
278 return stderr
.decode('utf-8', 'replace')
280 def run_ffmpeg(self
, path
, out_path
, opts
):
281 return self
.run_ffmpeg_multiple_files([path
], out_path
, opts
)
283 def _ffmpeg_filename_argument(self
, fn
):
284 # Always use 'file:' because the filename may contain ':' (ffmpeg
285 # interprets that as a protocol) or can start with '-' (-- is broken in
286 # ffmpeg, see https://ffmpeg.org/trac/ffmpeg/ticket/2127 for details)
287 # Also leave '-' intact in order not to break streaming to stdout.
288 if fn
.startswith(('http://', 'https://')):
290 return 'file:' + fn
if fn
!= '-' else fn
293 class FFmpegExtractAudioPP(FFmpegPostProcessor
):
294 COMMON_AUDIO_EXTENSIONS
= ('wav', 'flac', 'm4a', 'aiff', 'mp3', 'ogg', 'mka', 'opus', 'wma')
296 def __init__(self
, downloader
=None, preferredcodec
=None, preferredquality
=None, nopostoverwrites
=False):
297 FFmpegPostProcessor
.__init
__(self
, downloader
)
298 if preferredcodec
is None:
299 preferredcodec
= 'best'
300 self
._preferredcodec
= preferredcodec
301 self
._preferredquality
= preferredquality
302 self
._nopostoverwrites
= nopostoverwrites
304 def run_ffmpeg(self
, path
, out_path
, codec
, more_opts
):
308 acodec_opts
= ['-acodec', codec
]
309 opts
= ['-vn'] + acodec_opts
+ more_opts
311 FFmpegPostProcessor
.run_ffmpeg(self
, path
, out_path
, opts
)
312 except FFmpegPostProcessorError
as err
:
313 raise AudioConversionError(err
.msg
)
315 def run(self
, information
):
316 path
= information
['filepath']
317 orig_ext
= information
['ext']
319 if self
._preferredcodec
== 'best' and orig_ext
in self
.COMMON_AUDIO_EXTENSIONS
:
320 self
.to_screen('Skipping audio extraction since the file is already in a common audio format')
321 return [], information
323 filecodec
= self
.get_audio_codec(path
)
324 if filecodec
is None:
325 raise PostProcessingError('WARNING: unable to obtain file audio codec with ffprobe')
328 if self
._preferredcodec
== 'best' or self
._preferredcodec
== filecodec
or (self
._preferredcodec
== 'm4a' and filecodec
== 'aac'):
329 if filecodec
== 'aac' and self
._preferredcodec
in ['m4a', 'best']:
330 # Lossless, but in another container
333 more_opts
= ['-bsf:a', 'aac_adtstoasc']
334 elif filecodec
in ['aac', 'flac', 'mp3', 'vorbis', 'opus']:
335 # Lossless if possible
337 extension
= filecodec
338 if filecodec
== 'aac':
339 more_opts
= ['-f', 'adts']
340 if filecodec
== 'vorbis':
344 acodec
= 'libmp3lame'
347 if self
._preferredquality
is not None:
348 if int(self
._preferredquality
) < 10:
349 more_opts
+= ['-q:a', self
._preferredquality
]
351 more_opts
+= ['-b:a', self
._preferredquality
+ 'k']
353 # We convert the audio (lossy if codec is lossy)
354 acodec
= ACODECS
[self
._preferredcodec
]
355 extension
= self
._preferredcodec
357 if self
._preferredquality
is not None:
358 # The opus codec doesn't support the -aq option
359 if int(self
._preferredquality
) < 10 and extension
!= 'opus':
360 more_opts
+= ['-q:a', self
._preferredquality
]
362 more_opts
+= ['-b:a', self
._preferredquality
+ 'k']
363 if self
._preferredcodec
== 'aac':
364 more_opts
+= ['-f', 'adts']
365 if self
._preferredcodec
== 'm4a':
366 more_opts
+= ['-bsf:a', 'aac_adtstoasc']
367 if self
._preferredcodec
== 'vorbis':
369 if self
._preferredcodec
== 'wav':
371 more_opts
+= ['-f', 'wav']
373 prefix
, sep
, ext
= path
.rpartition('.') # not os.path.splitext, since the latter does not work on unicode in all setups
374 new_path
= prefix
+ sep
+ extension
376 information
['filepath'] = new_path
377 information
['ext'] = extension
379 # If we download foo.mp3 and convert it to... foo.mp3, then don't delete foo.mp3, silly.
381 or (self
._nopostoverwrites
and os
.path
.exists(encodeFilename(new_path
)))):
382 self
.to_screen('Post-process file %s exists, skipping' % new_path
)
383 return [], information
386 self
.to_screen('Destination: ' + new_path
)
387 self
.run_ffmpeg(path
, new_path
, acodec
, more_opts
)
388 except AudioConversionError
as e
:
389 raise PostProcessingError(
390 'audio conversion failed: ' + e
.msg
)
392 raise PostProcessingError('error running ' + self
.basename
)
394 # Try to update the date time for extracted audio file.
395 if information
.get('filetime') is not None:
397 new_path
, time
.time(), information
['filetime'],
398 errnote
='Cannot update utime of audio file')
400 return [path
], information
403 class FFmpegVideoRemuxerPP(FFmpegPostProcessor
):
404 def __init__(self
, downloader
=None, preferedformat
=None):
405 super(FFmpegVideoRemuxerPP
, self
).__init
__(downloader
)
406 self
._preferedformats
= preferedformat
.lower().split('/')
408 def run(self
, information
):
409 path
= information
['filepath']
410 sourceext
, targetext
= information
['ext'].lower(), None
411 for pair
in self
._preferedformats
:
413 if len(kv
) == 1 or kv
[0].strip() == sourceext
:
414 targetext
= kv
[-1].strip()
418 'could not find a mapping for %s' if not targetext
419 else 'already is in target format %s' if sourceext
== targetext
422 self
.to_screen('Not remuxing media file %s; %s' % (path
, _skip_msg
% sourceext
))
423 return [], information
425 options
= ['-c', 'copy', '-map', '0', '-dn']
426 if targetext
in ['mp4', 'm4a', 'mov']:
427 options
.extend(['-movflags', '+faststart'])
428 prefix
, sep
, oldext
= path
.rpartition('.')
429 outpath
= prefix
+ sep
+ targetext
430 self
.to_screen('Remuxing video from %s to %s; Destination: %s' % (sourceext
, targetext
, outpath
))
431 self
.run_ffmpeg(path
, outpath
, options
)
432 information
['filepath'] = outpath
433 information
['format'] = targetext
434 information
['ext'] = targetext
435 return [path
], information
438 class FFmpegVideoConvertorPP(FFmpegPostProcessor
):
439 def __init__(self
, downloader
=None, preferedformat
=None):
440 super(FFmpegVideoConvertorPP
, self
).__init
__(downloader
)
441 self
._preferedformat
= preferedformat
443 def run(self
, information
):
444 path
= information
['filepath']
445 if information
['ext'] == self
._preferedformat
:
446 self
.to_screen('Not converting video file %s - already is in target format %s' % (path
, self
._preferedformat
))
447 return [], information
449 if self
._preferedformat
== 'avi':
450 options
.extend(['-c:v', 'libxvid', '-vtag', 'XVID'])
451 prefix
, sep
, ext
= path
.rpartition('.')
452 outpath
= prefix
+ sep
+ self
._preferedformat
453 self
.to_screen('Converting video from %s to %s, Destination: ' % (information
['ext'], self
._preferedformat
) + outpath
)
454 self
.run_ffmpeg(path
, outpath
, options
)
455 information
['filepath'] = outpath
456 information
['format'] = self
._preferedformat
457 information
['ext'] = self
._preferedformat
458 return [path
], information
461 class FFmpegEmbedSubtitlePP(FFmpegPostProcessor
):
462 def __init__(self
, downloader
=None, already_have_subtitle
=False):
463 super(FFmpegEmbedSubtitlePP
, self
).__init
__(downloader
)
464 self
._already
_have
_subtitle
= already_have_subtitle
466 def run(self
, information
):
467 if information
['ext'] not in ('mp4', 'webm', 'mkv'):
468 self
.to_screen('Subtitles can only be embedded in mp4, webm or mkv files')
469 return [], information
470 subtitles
= information
.get('requested_subtitles')
472 self
.to_screen('There aren\'t any subtitles to embed')
473 return [], information
475 filename
= information
['filepath']
477 ext
= information
['ext']
480 webm_vtt_warn
= False
483 for lang
, sub_info
in subtitles
.items():
484 sub_ext
= sub_info
['ext']
485 if sub_ext
== 'json':
486 self
.report_warning('JSON subtitles cannot be embedded')
487 elif ext
!= 'webm' or ext
== 'webm' and sub_ext
== 'vtt':
488 sub_langs
.append(lang
)
489 sub_filenames
.append(sub_info
['filepath'])
491 if not webm_vtt_warn
and ext
== 'webm' and sub_ext
!= 'vtt':
493 self
.report_warning('Only WebVTT subtitles can be embedded in webm files')
494 if not mp4_ass_warn
and ext
== 'mp4' and sub_ext
== 'ass':
496 self
.report_warning('ASS subtitles cannot be properly embedded in mp4 files; expect issues')
499 return [], information
501 input_files
= [filename
] + sub_filenames
504 '-c', 'copy', '-map', '0', '-dn',
505 # Don't copy the existing subtitles, we may be running the
506 # postprocessor a second time
508 # Don't copy Apple TV chapters track, bin_data (see #19042, #19024,
509 # https://trac.ffmpeg.org/ticket/6016)
512 if information
['ext'] == 'mp4':
513 opts
+= ['-c:s', 'mov_text']
514 for (i
, lang
) in enumerate(sub_langs
):
515 opts
.extend(['-map', '%d:0' % (i
+ 1)])
516 lang_code
= ISO639Utils
.short2long(lang
) or lang
517 opts
.extend(['-metadata:s:s:%d' % i
, 'language=%s' % lang_code
])
519 temp_filename
= prepend_extension(filename
, 'temp')
520 self
.to_screen('Embedding subtitles in "%s"' % filename
)
521 self
.run_ffmpeg_multiple_files(input_files
, temp_filename
, opts
)
522 os
.remove(encodeFilename(filename
))
523 os
.rename(encodeFilename(temp_filename
), encodeFilename(filename
))
525 files_to_delete
= [] if self
._already
_have
_subtitle
else sub_filenames
526 return files_to_delete
, information
529 class FFmpegMetadataPP(FFmpegPostProcessor
):
533 def add(meta_list
, info_list
=None):
535 info_list
= meta_list
536 if not isinstance(meta_list
, (list, tuple)):
537 meta_list
= (meta_list
,)
538 if not isinstance(info_list
, (list, tuple)):
539 info_list
= (info_list
,)
540 for info_f
in info_list
:
541 if info
.get(info_f
) is not None:
542 for meta_f
in meta_list
:
543 metadata
[meta_f
] = info
[info_f
]
546 # See [1-4] for some info on media metadata/metadata supported
548 # 1. https://kdenlive.org/en/project/adding-meta-data-to-mp4-video/
549 # 2. https://wiki.multimedia.cx/index.php/FFmpeg_Metadata
550 # 3. https://kodi.wiki/view/Video_file_tagging
552 add('title', ('track', 'title'))
553 add('date', 'upload_date')
554 add(('description', 'comment'), 'description')
555 add('purl', 'webpage_url')
556 add('track', 'track_number')
557 add('artist', ('artist', 'creator', 'uploader', 'uploader_id'))
561 add('disc', 'disc_number')
562 add('show', 'series')
564 add('episode_id', ('episode', 'episode_id'))
565 add('episode_sort', 'episode_number')
568 self
.to_screen('There isn\'t any metadata to add')
571 filename
= info
['filepath']
572 temp_filename
= prepend_extension(filename
, 'temp')
573 in_filenames
= [filename
]
574 options
= ['-map', '0', '-dn']
576 if info
['ext'] == 'm4a':
577 options
.extend(['-vn', '-acodec', 'copy'])
579 options
.extend(['-c', 'copy'])
581 for (name
, value
) in metadata
.items():
582 options
.extend(['-metadata', '%s=%s' % (name
, value
)])
584 chapters
= info
.get('chapters', [])
586 metadata_filename
= replace_extension(filename
, 'meta')
587 with io
.open(metadata_filename
, 'wt', encoding
='utf-8') as f
:
588 def ffmpeg_escape(text
):
589 return re
.sub(r
'(=|;|#|\\|\n)', r
'\\\1', text
)
591 metadata_file_content
= ';FFMETADATA1\n'
592 for chapter
in chapters
:
593 metadata_file_content
+= '[CHAPTER]\nTIMEBASE=1/1000\n'
594 metadata_file_content
+= 'START=%d\n' % (chapter
['start_time'] * 1000)
595 metadata_file_content
+= 'END=%d\n' % (chapter
['end_time'] * 1000)
596 chapter_title
= chapter
.get('title')
598 metadata_file_content
+= 'title=%s\n' % ffmpeg_escape(chapter_title
)
599 f
.write(metadata_file_content
)
600 in_filenames
.append(metadata_filename
)
601 options
.extend(['-map_metadata', '1'])
603 if '__infojson_filename' in info
and info
['ext'] in ('mkv', 'mka'):
604 old_stream
, new_stream
= self
.get_stream_number(
605 filename
, ('tags', 'mimetype'), 'application/json')
606 if old_stream
is not None:
607 options
.extend(['-map', '-0:%d' % old_stream
])
611 '-attach', info
['__infojson_filename'],
612 '-metadata:s:%d' % new_stream
, 'mimetype=application/json'
615 self
.to_screen('Adding metadata to \'%s\'' % filename
)
616 self
.run_ffmpeg_multiple_files(in_filenames
, temp_filename
, options
)
618 os
.remove(metadata_filename
)
619 os
.remove(encodeFilename(filename
))
620 os
.rename(encodeFilename(temp_filename
), encodeFilename(filename
))
624 class FFmpegMergerPP(FFmpegPostProcessor
):
626 filename
= info
['filepath']
627 temp_filename
= prepend_extension(filename
, 'temp')
628 args
= ['-c', 'copy']
629 for (i
, fmt
) in enumerate(info
['requested_formats']):
630 if fmt
.get('acodec') != 'none':
631 args
.extend(['-map', '%u:a:0' % (i
)])
632 if fmt
.get('vcodec') != 'none':
633 args
.extend(['-map', '%u:v:0' % (i
)])
634 self
.to_screen('Merging formats into "%s"' % filename
)
635 self
.run_ffmpeg_multiple_files(info
['__files_to_merge'], temp_filename
, args
)
636 os
.rename(encodeFilename(temp_filename
), encodeFilename(filename
))
637 return info
['__files_to_merge'], info
640 # TODO: figure out merge-capable ffmpeg version
641 if self
.basename
!= 'avconv':
644 required_version
= '10-0'
645 if is_outdated_version(
646 self
._versions
[self
.basename
], required_version
):
647 warning
= ('Your copy of %s is outdated and unable to properly mux separate video and audio files, '
648 'yt-dlp will download single file media. '
649 'Update %s to version %s or newer to fix this.') % (
650 self
.basename
, self
.basename
, required_version
)
651 self
.report_warning(warning
)
656 class FFmpegFixupStretchedPP(FFmpegPostProcessor
):
658 stretched_ratio
= info
.get('stretched_ratio')
659 if stretched_ratio
is None or stretched_ratio
== 1:
662 filename
= info
['filepath']
663 temp_filename
= prepend_extension(filename
, 'temp')
665 options
= ['-c', 'copy', '-map', '0', '-dn', '-aspect', '%f' % stretched_ratio
]
666 self
.to_screen('Fixing aspect ratio in "%s"' % filename
)
667 self
.run_ffmpeg(filename
, temp_filename
, options
)
669 os
.remove(encodeFilename(filename
))
670 os
.rename(encodeFilename(temp_filename
), encodeFilename(filename
))
675 class FFmpegFixupM4aPP(FFmpegPostProcessor
):
677 if info
.get('container') != 'm4a_dash':
680 filename
= info
['filepath']
681 temp_filename
= prepend_extension(filename
, 'temp')
683 options
= ['-c', 'copy', '-map', '0', '-dn', '-f', 'mp4']
684 self
.to_screen('Correcting container in "%s"' % filename
)
685 self
.run_ffmpeg(filename
, temp_filename
, options
)
687 os
.remove(encodeFilename(filename
))
688 os
.rename(encodeFilename(temp_filename
), encodeFilename(filename
))
693 class FFmpegFixupM3u8PP(FFmpegPostProcessor
):
695 filename
= info
['filepath']
696 if self
.get_audio_codec(filename
) == 'aac':
697 temp_filename
= prepend_extension(filename
, 'temp')
699 options
= ['-c', 'copy', '-map', '0', '-dn', '-f', 'mp4', '-bsf:a', 'aac_adtstoasc']
700 self
.to_screen('Fixing malformed AAC bitstream in "%s"' % filename
)
701 self
.run_ffmpeg(filename
, temp_filename
, options
)
703 os
.remove(encodeFilename(filename
))
704 os
.rename(encodeFilename(temp_filename
), encodeFilename(filename
))
708 class FFmpegSubtitlesConvertorPP(FFmpegPostProcessor
):
709 def __init__(self
, downloader
=None, format
=None):
710 super(FFmpegSubtitlesConvertorPP
, self
).__init
__(downloader
)
714 subs
= info
.get('requested_subtitles')
715 filename
= info
['filepath']
716 new_ext
= self
.format
718 if new_format
== 'vtt':
719 new_format
= 'webvtt'
721 self
.to_screen('There aren\'t any subtitles to convert')
723 self
.to_screen('Converting subtitles')
725 for lang
, sub
in subs
.items():
728 self
.to_screen('Subtitle file for %s is already in the requested format' % new_ext
)
732 'You have requested to convert json subtitles into another format, '
733 'which is currently not possible')
735 old_file
= sub
['filepath']
736 sub_filenames
.append(old_file
)
737 new_file
= replace_extension(old_file
, new_ext
)
739 if ext
in ('dfxp', 'ttml', 'tt'):
741 'You have requested to convert dfxp (TTML) subtitles into another format, '
742 'which results in style information loss')
745 srt_file
= replace_extension(old_file
, 'srt')
747 with open(dfxp_file
, 'rb') as f
:
748 srt_data
= dfxp2srt(f
.read())
750 with io
.open(srt_file
, 'wt', encoding
='utf-8') as f
:
757 'filepath': srt_file
,
763 sub_filenames
.append(srt_file
)
765 self
.run_ffmpeg(old_file
, new_file
, ['-f', new_format
])
767 with io
.open(new_file
, 'rt', encoding
='utf-8') as f
:
771 'filepath': new_file
,
774 info
['__files_to_move'][new_file
] = replace_extension(
775 info
['__files_to_move'][old_file
], new_ext
)
777 return sub_filenames
, info
780 class FFmpegSplitChaptersPP(FFmpegPostProcessor
):
782 def _prepare_filename(self
, number
, chapter
, info
):
785 'section_number': number
,
786 'section_title': chapter
.get('title'),
787 'section_start': chapter
.get('start_time'),
788 'section_end': chapter
.get('end_time'),
790 return self
._downloader
.prepare_filename(info
, 'chapter')
792 def _ffmpeg_args_for_chapter(self
, number
, chapter
, info
):
793 destination
= self
._prepare
_filename
(number
, chapter
, info
)
794 if not self
._downloader
._ensure
_dir
_exists
(encodeFilename(destination
)):
797 chapter
['filepath'] = destination
798 self
.to_screen('Chapter %03d; Destination: %s' % (number
, destination
))
801 ['-ss', compat_str(chapter
['start_time']),
802 '-to', compat_str(chapter
['end_time'])])
805 chapters
= info
.get('chapters') or []
807 self
.report_warning('There are no tracks to extract')
810 self
.to_screen('Splitting video by chapters; %d chapters found' % len(chapters
))
811 for idx
, chapter
in enumerate(chapters
):
812 destination
, opts
= self
._ffmpeg
_args
_for
_chapter
(idx
+ 1, chapter
, info
)
813 self
.real_run_ffmpeg([(info
['filepath'], opts
)], [(destination
, ['-c', 'copy'])])