1 from __future__
import unicode_literals
11 from .common
import AudioConversionError
, PostProcessor
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')
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')
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.')
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_EXTENSIONS
= ('wav', 'flac', 'm4a', 'aiff', 'mp3', 'ogg', 'mka', 'opus', 'wma')
295 def __init__(self
, downloader
=None, preferredcodec
=None, preferredquality
=None, nopostoverwrites
=False):
296 FFmpegPostProcessor
.__init
__(self
, downloader
)
297 if preferredcodec
is None:
298 preferredcodec
= 'best'
299 self
._preferredcodec
= preferredcodec
300 self
._preferredquality
= preferredquality
301 self
._nopostoverwrites
= nopostoverwrites
303 def run_ffmpeg(self
, path
, out_path
, codec
, more_opts
):
307 acodec_opts
= ['-acodec', codec
]
308 opts
= ['-vn'] + acodec_opts
+ more_opts
310 FFmpegPostProcessor
.run_ffmpeg(self
, path
, out_path
, opts
)
311 except FFmpegPostProcessorError
as err
:
312 raise AudioConversionError(err
.msg
)
314 def run(self
, information
):
315 path
= information
['filepath']
316 orig_ext
= information
['ext']
318 if self
._preferredcodec
== 'best' and orig_ext
in self
.COMMON_AUDIO_EXTENSIONS
:
319 self
.to_screen('Skipping audio extraction since the file is already in a common audio format')
320 return [], information
322 filecodec
= self
.get_audio_codec(path
)
323 if filecodec
is None:
324 raise PostProcessingError('WARNING: unable to obtain file audio codec with ffprobe')
327 if self
._preferredcodec
== 'best' or self
._preferredcodec
== filecodec
or (self
._preferredcodec
== 'm4a' and filecodec
== 'aac'):
328 if filecodec
== 'aac' and self
._preferredcodec
in ['m4a', 'best']:
329 # Lossless, but in another container
332 more_opts
= ['-bsf:a', 'aac_adtstoasc']
333 elif filecodec
in ['aac', 'flac', 'mp3', 'vorbis', 'opus']:
334 # Lossless if possible
336 extension
= filecodec
337 if filecodec
== 'aac':
338 more_opts
= ['-f', 'adts']
339 if filecodec
== 'vorbis':
343 acodec
= 'libmp3lame'
346 if self
._preferredquality
is not None:
347 if int(self
._preferredquality
) < 10:
348 more_opts
+= ['-q:a', self
._preferredquality
]
350 more_opts
+= ['-b:a', self
._preferredquality
+ 'k']
352 # We convert the audio (lossy if codec is lossy)
353 acodec
= ACODECS
[self
._preferredcodec
]
354 extension
= self
._preferredcodec
356 if self
._preferredquality
is not None:
357 # The opus codec doesn't support the -aq option
358 if int(self
._preferredquality
) < 10 and extension
!= 'opus':
359 more_opts
+= ['-q:a', self
._preferredquality
]
361 more_opts
+= ['-b:a', self
._preferredquality
+ 'k']
362 if self
._preferredcodec
== 'aac':
363 more_opts
+= ['-f', 'adts']
364 if self
._preferredcodec
== 'm4a':
365 more_opts
+= ['-bsf:a', 'aac_adtstoasc']
366 if self
._preferredcodec
== 'vorbis':
368 if self
._preferredcodec
== 'wav':
370 more_opts
+= ['-f', 'wav']
372 prefix
, sep
, ext
= path
.rpartition('.') # not os.path.splitext, since the latter does not work on unicode in all setups
373 new_path
= prefix
+ sep
+ extension
375 information
['filepath'] = new_path
376 information
['ext'] = extension
378 # If we download foo.mp3 and convert it to... foo.mp3, then don't delete foo.mp3, silly.
380 or (self
._nopostoverwrites
and os
.path
.exists(encodeFilename(new_path
)))):
381 self
.to_screen('Post-process file %s exists, skipping' % new_path
)
382 return [], information
385 self
.to_screen('Destination: ' + new_path
)
386 self
.run_ffmpeg(path
, new_path
, acodec
, more_opts
)
387 except AudioConversionError
as e
:
388 raise PostProcessingError(
389 'audio conversion failed: ' + e
.msg
)
391 raise PostProcessingError('error running ' + self
.basename
)
393 # Try to update the date time for extracted audio file.
394 if information
.get('filetime') is not None:
396 new_path
, time
.time(), information
['filetime'],
397 errnote
='Cannot update utime of audio file')
399 return [path
], information
402 class FFmpegVideoRemuxerPP(FFmpegPostProcessor
):
403 def __init__(self
, downloader
=None, preferedformat
=None):
404 super(FFmpegVideoRemuxerPP
, self
).__init
__(downloader
)
405 self
._preferedformats
= preferedformat
.lower().split('/')
407 def run(self
, information
):
408 path
= information
['filepath']
409 sourceext
, targetext
= information
['ext'].lower(), None
410 for pair
in self
._preferedformats
:
412 if len(kv
) == 1 or kv
[0].strip() == sourceext
:
413 targetext
= kv
[-1].strip()
417 'could not find a mapping for %s' if not targetext
418 else 'already is in target format %s' if sourceext
== targetext
421 self
.to_screen('Not remuxing media file %s; %s' % (path
, _skip_msg
% sourceext
))
422 return [], information
424 options
= ['-c', 'copy', '-map', '0', '-dn']
425 if targetext
in ['mp4', 'm4a', 'mov']:
426 options
.extend(['-movflags', '+faststart'])
427 prefix
, sep
, oldext
= path
.rpartition('.')
428 outpath
= prefix
+ sep
+ targetext
429 self
.to_screen('Remuxing video from %s to %s; Destination: %s' % (sourceext
, targetext
, outpath
))
430 self
.run_ffmpeg(path
, outpath
, options
)
431 information
['filepath'] = outpath
432 information
['format'] = targetext
433 information
['ext'] = targetext
434 return [path
], information
437 class FFmpegVideoConvertorPP(FFmpegPostProcessor
):
438 def __init__(self
, downloader
=None, preferedformat
=None):
439 super(FFmpegVideoConvertorPP
, self
).__init
__(downloader
)
440 self
._preferedformat
= preferedformat
442 def run(self
, information
):
443 path
= information
['filepath']
444 if information
['ext'] == self
._preferedformat
:
445 self
.to_screen('Not converting video file %s - already is in target format %s' % (path
, self
._preferedformat
))
446 return [], information
448 if self
._preferedformat
== 'avi':
449 options
.extend(['-c:v', 'libxvid', '-vtag', 'XVID'])
450 prefix
, sep
, ext
= path
.rpartition('.')
451 outpath
= prefix
+ sep
+ self
._preferedformat
452 self
.to_screen('Converting video from %s to %s, Destination: ' % (information
['ext'], self
._preferedformat
) + outpath
)
453 self
.run_ffmpeg(path
, outpath
, options
)
454 information
['filepath'] = outpath
455 information
['format'] = self
._preferedformat
456 information
['ext'] = self
._preferedformat
457 return [path
], information
460 class FFmpegEmbedSubtitlePP(FFmpegPostProcessor
):
461 def __init__(self
, downloader
=None, already_have_subtitle
=False):
462 super(FFmpegEmbedSubtitlePP
, self
).__init
__(downloader
)
463 self
._already
_have
_subtitle
= already_have_subtitle
465 def run(self
, information
):
466 if information
['ext'] not in ('mp4', 'webm', 'mkv'):
467 self
.to_screen('Subtitles can only be embedded in mp4, webm or mkv files')
468 return [], information
469 subtitles
= information
.get('requested_subtitles')
471 self
.to_screen('There aren\'t any subtitles to embed')
472 return [], information
474 filename
= information
['filepath']
476 ext
= information
['ext']
479 webm_vtt_warn
= False
482 for lang
, sub_info
in subtitles
.items():
483 sub_ext
= sub_info
['ext']
484 if sub_ext
== 'json':
485 self
.report_warning('JSON subtitles cannot be embedded')
486 elif ext
!= 'webm' or ext
== 'webm' and sub_ext
== 'vtt':
487 sub_langs
.append(lang
)
488 sub_filenames
.append(subtitles_filename(filename
, lang
, sub_ext
, ext
))
490 if not webm_vtt_warn
and ext
== 'webm' and sub_ext
!= 'vtt':
492 self
.report_warning('Only WebVTT subtitles can be embedded in webm files')
493 if not mp4_ass_warn
and ext
== 'mp4' and sub_ext
== 'ass':
495 self
.report_warning('ASS subtitles cannot be properly embedded in mp4 files; expect issues')
498 return [], information
500 input_files
= [filename
] + sub_filenames
503 '-c', 'copy', '-map', '0', '-dn',
504 # Don't copy the existing subtitles, we may be running the
505 # postprocessor a second time
507 # Don't copy Apple TV chapters track, bin_data (see #19042, #19024,
508 # https://trac.ffmpeg.org/ticket/6016)
511 if information
['ext'] == 'mp4':
512 opts
+= ['-c:s', 'mov_text']
513 for (i
, lang
) in enumerate(sub_langs
):
514 opts
.extend(['-map', '%d:0' % (i
+ 1)])
515 lang_code
= ISO639Utils
.short2long(lang
) or lang
516 opts
.extend(['-metadata:s:s:%d' % i
, 'language=%s' % lang_code
])
518 temp_filename
= prepend_extension(filename
, 'temp')
519 self
.to_screen('Embedding subtitles in "%s"' % filename
)
520 self
.run_ffmpeg_multiple_files(input_files
, temp_filename
, opts
)
521 os
.remove(encodeFilename(filename
))
522 os
.rename(encodeFilename(temp_filename
), encodeFilename(filename
))
524 files_to_delete
= [] if self
._already
_have
_subtitle
else sub_filenames
525 return files_to_delete
, information
528 class FFmpegMetadataPP(FFmpegPostProcessor
):
532 def add(meta_list
, info_list
=None):
534 info_list
= meta_list
535 if not isinstance(meta_list
, (list, tuple)):
536 meta_list
= (meta_list
,)
537 if not isinstance(info_list
, (list, tuple)):
538 info_list
= (info_list
,)
539 for info_f
in info_list
:
540 if info
.get(info_f
) is not None:
541 for meta_f
in meta_list
:
542 metadata
[meta_f
] = info
[info_f
]
545 # See [1-4] for some info on media metadata/metadata supported
547 # 1. https://kdenlive.org/en/project/adding-meta-data-to-mp4-video/
548 # 2. https://wiki.multimedia.cx/index.php/FFmpeg_Metadata
549 # 3. https://kodi.wiki/view/Video_file_tagging
551 add('title', ('track', 'title'))
552 add('date', 'upload_date')
553 add(('description', 'comment'), 'description')
554 add('purl', 'webpage_url')
555 add('track', 'track_number')
556 add('artist', ('artist', 'creator', 'uploader', 'uploader_id'))
560 add('disc', 'disc_number')
561 add('show', 'series')
563 add('episode_id', ('episode', 'episode_id'))
564 add('episode_sort', 'episode_number')
567 self
.to_screen('There isn\'t any metadata to add')
570 filename
= info
['filepath']
571 temp_filename
= prepend_extension(filename
, 'temp')
572 in_filenames
= [filename
]
573 options
= ['-map', '0', '-dn']
575 if info
['ext'] == 'm4a':
576 options
.extend(['-vn', '-acodec', 'copy'])
578 options
.extend(['-c', 'copy'])
580 for (name
, value
) in metadata
.items():
581 options
.extend(['-metadata', '%s=%s' % (name
, value
)])
583 chapters
= info
.get('chapters', [])
585 metadata_filename
= replace_extension(filename
, 'meta')
586 with io
.open(metadata_filename
, 'wt', encoding
='utf-8') as f
:
587 def ffmpeg_escape(text
):
588 return re
.sub(r
'(=|;|#|\\|\n)', r
'\\\1', text
)
590 metadata_file_content
= ';FFMETADATA1\n'
591 for chapter
in chapters
:
592 metadata_file_content
+= '[CHAPTER]\nTIMEBASE=1/1000\n'
593 metadata_file_content
+= 'START=%d\n' % (chapter
['start_time'] * 1000)
594 metadata_file_content
+= 'END=%d\n' % (chapter
['end_time'] * 1000)
595 chapter_title
= chapter
.get('title')
597 metadata_file_content
+= 'title=%s\n' % ffmpeg_escape(chapter_title
)
598 f
.write(metadata_file_content
)
599 in_filenames
.append(metadata_filename
)
600 options
.extend(['-map_metadata', '1'])
602 if '__infojson_filename' in info
and info
['ext'] in ('mkv', 'mka'):
603 old_stream
, new_stream
= self
.get_stream_number(
604 filename
, ('tags', 'mimetype'), 'application/json')
605 if old_stream
is not None:
606 options
.extend(['-map', '-0:%d' % old_stream
])
610 '-attach', info
['__infojson_filename'],
611 '-metadata:s:%d' % new_stream
, 'mimetype=application/json'
614 self
.to_screen('Adding metadata to \'%s\'' % filename
)
615 self
.run_ffmpeg_multiple_files(in_filenames
, temp_filename
, options
)
617 os
.remove(metadata_filename
)
618 os
.remove(encodeFilename(filename
))
619 os
.rename(encodeFilename(temp_filename
), encodeFilename(filename
))
623 class FFmpegMergerPP(FFmpegPostProcessor
):
625 filename
= info
['filepath']
626 temp_filename
= prepend_extension(filename
, 'temp')
627 args
= ['-c', 'copy']
628 for (i
, fmt
) in enumerate(info
['requested_formats']):
629 if fmt
.get('acodec') != 'none':
630 args
.extend(['-map', '%u:a:0' % (i
)])
631 if fmt
.get('vcodec') != 'none':
632 args
.extend(['-map', '%u:v:0' % (i
)])
633 self
.to_screen('Merging formats into "%s"' % filename
)
634 self
.run_ffmpeg_multiple_files(info
['__files_to_merge'], temp_filename
, args
)
635 os
.rename(encodeFilename(temp_filename
), encodeFilename(filename
))
636 return info
['__files_to_merge'], info
639 # TODO: figure out merge-capable ffmpeg version
640 if self
.basename
!= 'avconv':
643 required_version
= '10-0'
644 if is_outdated_version(
645 self
._versions
[self
.basename
], required_version
):
646 warning
= ('Your copy of %s is outdated and unable to properly mux separate video and audio files, '
647 'yt-dlp will download single file media. '
648 'Update %s to version %s or newer to fix this.') % (
649 self
.basename
, self
.basename
, required_version
)
650 self
.report_warning(warning
)
655 class FFmpegFixupStretchedPP(FFmpegPostProcessor
):
657 stretched_ratio
= info
.get('stretched_ratio')
658 if stretched_ratio
is None or stretched_ratio
== 1:
661 filename
= info
['filepath']
662 temp_filename
= prepend_extension(filename
, 'temp')
664 options
= ['-c', 'copy', '-map', '0', '-dn', '-aspect', '%f' % stretched_ratio
]
665 self
.to_screen('Fixing aspect ratio in "%s"' % filename
)
666 self
.run_ffmpeg(filename
, temp_filename
, options
)
668 os
.remove(encodeFilename(filename
))
669 os
.rename(encodeFilename(temp_filename
), encodeFilename(filename
))
674 class FFmpegFixupM4aPP(FFmpegPostProcessor
):
676 if info
.get('container') != 'm4a_dash':
679 filename
= info
['filepath']
680 temp_filename
= prepend_extension(filename
, 'temp')
682 options
= ['-c', 'copy', '-map', '0', '-dn', '-f', 'mp4']
683 self
.to_screen('Correcting container in "%s"' % filename
)
684 self
.run_ffmpeg(filename
, temp_filename
, options
)
686 os
.remove(encodeFilename(filename
))
687 os
.rename(encodeFilename(temp_filename
), encodeFilename(filename
))
692 class FFmpegFixupM3u8PP(FFmpegPostProcessor
):
694 filename
= info
['filepath']
695 if self
.get_audio_codec(filename
) == 'aac':
696 temp_filename
= prepend_extension(filename
, 'temp')
698 options
= ['-c', 'copy', '-map', '0', '-dn', '-f', 'mp4', '-bsf:a', 'aac_adtstoasc']
699 self
.to_screen('Fixing malformed AAC bitstream in "%s"' % filename
)
700 self
.run_ffmpeg(filename
, temp_filename
, options
)
702 os
.remove(encodeFilename(filename
))
703 os
.rename(encodeFilename(temp_filename
), encodeFilename(filename
))
707 class FFmpegSubtitlesConvertorPP(FFmpegPostProcessor
):
708 def __init__(self
, downloader
=None, format
=None):
709 super(FFmpegSubtitlesConvertorPP
, self
).__init
__(downloader
)
713 subs
= info
.get('requested_subtitles')
714 filename
= info
['filepath']
715 new_ext
= self
.format
717 if new_format
== 'vtt':
718 new_format
= 'webvtt'
720 self
.to_screen('There aren\'t any subtitles to convert')
722 self
.to_screen('Converting subtitles')
724 for lang
, sub
in subs
.items():
727 self
.to_screen('Subtitle file for %s is already in the requested format' % new_ext
)
731 'You have requested to convert json subtitles into another format, '
732 'which is currently not possible')
734 old_file
= subtitles_filename(filename
, lang
, ext
, info
.get('ext'))
735 sub_filenames
.append(old_file
)
736 new_file
= subtitles_filename(filename
, lang
, new_ext
, info
.get('ext'))
738 if ext
in ('dfxp', 'ttml', 'tt'):
740 'You have requested to convert dfxp (TTML) subtitles into another format, '
741 'which results in style information loss')
744 srt_file
= subtitles_filename(filename
, lang
, 'srt', info
.get('ext'))
746 with open(dfxp_file
, 'rb') as f
:
747 srt_data
= dfxp2srt(f
.read())
749 with io
.open(srt_file
, 'wt', encoding
='utf-8') as f
:
761 sub_filenames
.append(srt_file
)
763 self
.run_ffmpeg(old_file
, new_file
, ['-f', new_format
])
765 with io
.open(new_file
, 'rt', encoding
='utf-8') as f
:
771 return sub_filenames
, info