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
):
240 os
.stat(encodeFilename(path
)).st_mtime
for path
in input_paths
)
242 opts
+= self
._configuration
_args
(exe
=self
.basename
)
245 for path
in input_paths
:
247 encodeArgument('-i'),
248 encodeFilename(self
._ffmpeg
_filename
_argument
(path
), True)
250 cmd
= [encodeFilename(self
.executable
, True), encodeArgument('-y')]
251 # avconv does not have repeat option
252 if self
.basename
== 'ffmpeg':
253 cmd
+= [encodeArgument('-loglevel'), encodeArgument('repeat+info')]
255 + [encodeArgument(o
) for o
in opts
]
256 + [encodeFilename(self
._ffmpeg
_filename
_argument
(out_path
), True)])
258 self
.write_debug('ffmpeg command line: %s' % shell_quote(cmd
))
259 p
= subprocess
.Popen(cmd
, stdout
=subprocess
.PIPE
, stderr
=subprocess
.PIPE
, stdin
=subprocess
.PIPE
)
260 stdout
, stderr
= process_communicate_or_kill(p
)
261 if p
.returncode
!= 0:
262 stderr
= stderr
.decode('utf-8', 'replace').strip()
263 if self
.get_param('verbose', False):
264 self
.report_error(stderr
)
265 raise FFmpegPostProcessorError(stderr
.split('\n')[-1])
266 self
.try_utime(out_path
, oldest_mtime
, oldest_mtime
)
267 return stderr
.decode('utf-8', 'replace')
269 def run_ffmpeg(self
, path
, out_path
, opts
):
270 return self
.run_ffmpeg_multiple_files([path
], out_path
, opts
)
272 def _ffmpeg_filename_argument(self
, fn
):
273 # Always use 'file:' because the filename may contain ':' (ffmpeg
274 # interprets that as a protocol) or can start with '-' (-- is broken in
275 # ffmpeg, see https://ffmpeg.org/trac/ffmpeg/ticket/2127 for details)
276 # Also leave '-' intact in order not to break streaming to stdout.
277 if fn
.startswith(('http://', 'https://')):
279 return 'file:' + fn
if fn
!= '-' else fn
282 class FFmpegExtractAudioPP(FFmpegPostProcessor
):
283 COMMON_AUDIO_EXTENSIONS
= ('wav', 'flac', 'm4a', 'aiff', 'mp3', 'ogg', 'mka', 'opus', 'wma')
285 def __init__(self
, downloader
=None, preferredcodec
=None, preferredquality
=None, nopostoverwrites
=False):
286 FFmpegPostProcessor
.__init
__(self
, downloader
)
287 if preferredcodec
is None:
288 preferredcodec
= 'best'
289 self
._preferredcodec
= preferredcodec
290 self
._preferredquality
= preferredquality
291 self
._nopostoverwrites
= nopostoverwrites
293 def run_ffmpeg(self
, path
, out_path
, codec
, more_opts
):
297 acodec_opts
= ['-acodec', codec
]
298 opts
= ['-vn'] + acodec_opts
+ more_opts
300 FFmpegPostProcessor
.run_ffmpeg(self
, path
, out_path
, opts
)
301 except FFmpegPostProcessorError
as err
:
302 raise AudioConversionError(err
.msg
)
304 def run(self
, information
):
305 path
= information
['filepath']
306 orig_ext
= information
['ext']
308 if self
._preferredcodec
== 'best' and orig_ext
in self
.COMMON_AUDIO_EXTENSIONS
:
309 self
.to_screen('Skipping audio extraction since the file is already in a common audio format')
310 return [], information
312 filecodec
= self
.get_audio_codec(path
)
313 if filecodec
is None:
314 raise PostProcessingError('WARNING: unable to obtain file audio codec with ffprobe')
317 if self
._preferredcodec
== 'best' or self
._preferredcodec
== filecodec
or (self
._preferredcodec
== 'm4a' and filecodec
== 'aac'):
318 if filecodec
== 'aac' and self
._preferredcodec
in ['m4a', 'best']:
319 # Lossless, but in another container
322 more_opts
= ['-bsf:a', 'aac_adtstoasc']
323 elif filecodec
in ['aac', 'flac', 'mp3', 'vorbis', 'opus']:
324 # Lossless if possible
326 extension
= filecodec
327 if filecodec
== 'aac':
328 more_opts
= ['-f', 'adts']
329 if filecodec
== 'vorbis':
333 acodec
= 'libmp3lame'
336 if self
._preferredquality
is not None:
337 if int(self
._preferredquality
) < 10:
338 more_opts
+= ['-q:a', self
._preferredquality
]
340 more_opts
+= ['-b:a', self
._preferredquality
+ 'k']
342 # We convert the audio (lossy if codec is lossy)
343 acodec
= ACODECS
[self
._preferredcodec
]
344 extension
= self
._preferredcodec
346 if self
._preferredquality
is not None:
347 # The opus codec doesn't support the -aq option
348 if int(self
._preferredquality
) < 10 and extension
!= 'opus':
349 more_opts
+= ['-q:a', self
._preferredquality
]
351 more_opts
+= ['-b:a', self
._preferredquality
+ 'k']
352 if self
._preferredcodec
== 'aac':
353 more_opts
+= ['-f', 'adts']
354 if self
._preferredcodec
== 'm4a':
355 more_opts
+= ['-bsf:a', 'aac_adtstoasc']
356 if self
._preferredcodec
== 'vorbis':
358 if self
._preferredcodec
== 'wav':
360 more_opts
+= ['-f', 'wav']
362 prefix
, sep
, ext
= path
.rpartition('.') # not os.path.splitext, since the latter does not work on unicode in all setups
363 new_path
= prefix
+ sep
+ extension
365 information
['filepath'] = new_path
366 information
['ext'] = extension
368 # If we download foo.mp3 and convert it to... foo.mp3, then don't delete foo.mp3, silly.
370 or (self
._nopostoverwrites
and os
.path
.exists(encodeFilename(new_path
)))):
371 self
.to_screen('Post-process file %s exists, skipping' % new_path
)
372 return [], information
375 self
.to_screen('Destination: ' + new_path
)
376 self
.run_ffmpeg(path
, new_path
, acodec
, more_opts
)
377 except AudioConversionError
as e
:
378 raise PostProcessingError(
379 'audio conversion failed: ' + e
.msg
)
381 raise PostProcessingError('error running ' + self
.basename
)
383 # Try to update the date time for extracted audio file.
384 if information
.get('filetime') is not None:
386 new_path
, time
.time(), information
['filetime'],
387 errnote
='Cannot update utime of audio file')
389 return [path
], information
392 class FFmpegVideoRemuxerPP(FFmpegPostProcessor
):
393 def __init__(self
, downloader
=None, preferedformat
=None):
394 super(FFmpegVideoRemuxerPP
, self
).__init
__(downloader
)
395 self
._preferedformats
= preferedformat
.lower().split('/')
397 def run(self
, information
):
398 path
= information
['filepath']
399 sourceext
, targetext
= information
['ext'].lower(), None
400 for pair
in self
._preferedformats
:
402 if len(kv
) == 1 or kv
[0].strip() == sourceext
:
403 targetext
= kv
[-1].strip()
407 'could not find a mapping for %s' if not targetext
408 else 'already is in target format %s' if sourceext
== targetext
411 self
.to_screen('Not remuxing media file %s; %s' % (path
, _skip_msg
% sourceext
))
412 return [], information
414 options
= ['-c', 'copy', '-map', '0', '-dn']
415 if targetext
in ['mp4', 'm4a', 'mov']:
416 options
.extend(['-movflags', '+faststart'])
417 prefix
, sep
, oldext
= path
.rpartition('.')
418 outpath
= prefix
+ sep
+ targetext
419 self
.to_screen('Remuxing video from %s to %s; Destination: %s' % (sourceext
, targetext
, outpath
))
420 self
.run_ffmpeg(path
, outpath
, options
)
421 information
['filepath'] = outpath
422 information
['format'] = targetext
423 information
['ext'] = targetext
424 return [path
], information
427 class FFmpegVideoConvertorPP(FFmpegPostProcessor
):
428 def __init__(self
, downloader
=None, preferedformat
=None):
429 super(FFmpegVideoConvertorPP
, self
).__init
__(downloader
)
430 self
._preferedformat
= preferedformat
432 def run(self
, information
):
433 path
= information
['filepath']
434 if information
['ext'] == self
._preferedformat
:
435 self
.to_screen('Not converting video file %s - already is in target format %s' % (path
, self
._preferedformat
))
436 return [], information
438 if self
._preferedformat
== 'avi':
439 options
.extend(['-c:v', 'libxvid', '-vtag', 'XVID'])
440 prefix
, sep
, ext
= path
.rpartition('.')
441 outpath
= prefix
+ sep
+ self
._preferedformat
442 self
.to_screen('Converting video from %s to %s, Destination: ' % (information
['ext'], self
._preferedformat
) + outpath
)
443 self
.run_ffmpeg(path
, outpath
, options
)
444 information
['filepath'] = outpath
445 information
['format'] = self
._preferedformat
446 information
['ext'] = self
._preferedformat
447 return [path
], information
450 class FFmpegEmbedSubtitlePP(FFmpegPostProcessor
):
451 def __init__(self
, downloader
=None, already_have_subtitle
=False):
452 super(FFmpegEmbedSubtitlePP
, self
).__init
__(downloader
)
453 self
._already
_have
_subtitle
= already_have_subtitle
455 def run(self
, information
):
456 if information
['ext'] not in ('mp4', 'webm', 'mkv'):
457 self
.to_screen('Subtitles can only be embedded in mp4, webm or mkv files')
458 return [], information
459 subtitles
= information
.get('requested_subtitles')
461 self
.to_screen('There aren\'t any subtitles to embed')
462 return [], information
464 filename
= information
['filepath']
466 ext
= information
['ext']
469 webm_vtt_warn
= False
472 for lang
, sub_info
in subtitles
.items():
473 sub_ext
= sub_info
['ext']
474 if sub_ext
== 'json':
475 self
.report_warning('JSON subtitles cannot be embedded')
476 elif ext
!= 'webm' or ext
== 'webm' and sub_ext
== 'vtt':
477 sub_langs
.append(lang
)
478 sub_filenames
.append(subtitles_filename(filename
, lang
, sub_ext
, ext
))
480 if not webm_vtt_warn
and ext
== 'webm' and sub_ext
!= 'vtt':
482 self
.report_warning('Only WebVTT subtitles can be embedded in webm files')
483 if not mp4_ass_warn
and ext
== 'mp4' and sub_ext
== 'ass':
485 self
.report_warning('ASS subtitles cannot be properly embedded in mp4 files; expect issues')
488 return [], information
490 input_files
= [filename
] + sub_filenames
493 '-c', 'copy', '-map', '0', '-dn',
494 # Don't copy the existing subtitles, we may be running the
495 # postprocessor a second time
497 # Don't copy Apple TV chapters track, bin_data (see #19042, #19024,
498 # https://trac.ffmpeg.org/ticket/6016)
501 if information
['ext'] == 'mp4':
502 opts
+= ['-c:s', 'mov_text']
503 for (i
, lang
) in enumerate(sub_langs
):
504 opts
.extend(['-map', '%d:0' % (i
+ 1)])
505 lang_code
= ISO639Utils
.short2long(lang
) or lang
506 opts
.extend(['-metadata:s:s:%d' % i
, 'language=%s' % lang_code
])
508 temp_filename
= prepend_extension(filename
, 'temp')
509 self
.to_screen('Embedding subtitles in "%s"' % filename
)
510 self
.run_ffmpeg_multiple_files(input_files
, temp_filename
, opts
)
511 os
.remove(encodeFilename(filename
))
512 os
.rename(encodeFilename(temp_filename
), encodeFilename(filename
))
514 files_to_delete
= [] if self
._already
_have
_subtitle
else sub_filenames
515 return files_to_delete
, information
518 class FFmpegMetadataPP(FFmpegPostProcessor
):
522 def add(meta_list
, info_list
=None):
524 info_list
= meta_list
525 if not isinstance(meta_list
, (list, tuple)):
526 meta_list
= (meta_list
,)
527 if not isinstance(info_list
, (list, tuple)):
528 info_list
= (info_list
,)
529 for info_f
in info_list
:
530 if info
.get(info_f
) is not None:
531 for meta_f
in meta_list
:
532 metadata
[meta_f
] = info
[info_f
]
535 # See [1-4] for some info on media metadata/metadata supported
537 # 1. https://kdenlive.org/en/project/adding-meta-data-to-mp4-video/
538 # 2. https://wiki.multimedia.cx/index.php/FFmpeg_Metadata
539 # 3. https://kodi.wiki/view/Video_file_tagging
541 add('title', ('track', 'title'))
542 add('date', 'upload_date')
543 add(('description', 'comment'), 'description')
544 add('purl', 'webpage_url')
545 add('track', 'track_number')
546 add('artist', ('artist', 'creator', 'uploader', 'uploader_id'))
550 add('disc', 'disc_number')
551 add('show', 'series')
553 add('episode_id', ('episode', 'episode_id'))
554 add('episode_sort', 'episode_number')
557 self
.to_screen('There isn\'t any metadata to add')
560 filename
= info
['filepath']
561 temp_filename
= prepend_extension(filename
, 'temp')
562 in_filenames
= [filename
]
563 options
= ['-map', '0', '-dn']
565 if info
['ext'] == 'm4a':
566 options
.extend(['-vn', '-acodec', 'copy'])
568 options
.extend(['-c', 'copy'])
570 for (name
, value
) in metadata
.items():
571 options
.extend(['-metadata', '%s=%s' % (name
, value
)])
573 chapters
= info
.get('chapters', [])
575 metadata_filename
= replace_extension(filename
, 'meta')
576 with io
.open(metadata_filename
, 'wt', encoding
='utf-8') as f
:
577 def ffmpeg_escape(text
):
578 return re
.sub(r
'(=|;|#|\\|\n)', r
'\\\1', text
)
580 metadata_file_content
= ';FFMETADATA1\n'
581 for chapter
in chapters
:
582 metadata_file_content
+= '[CHAPTER]\nTIMEBASE=1/1000\n'
583 metadata_file_content
+= 'START=%d\n' % (chapter
['start_time'] * 1000)
584 metadata_file_content
+= 'END=%d\n' % (chapter
['end_time'] * 1000)
585 chapter_title
= chapter
.get('title')
587 metadata_file_content
+= 'title=%s\n' % ffmpeg_escape(chapter_title
)
588 f
.write(metadata_file_content
)
589 in_filenames
.append(metadata_filename
)
590 options
.extend(['-map_metadata', '1'])
592 if '__infojson_filename' in info
and info
['ext'] in ('mkv', 'mka'):
593 old_stream
, new_stream
= self
.get_stream_number(
594 filename
, ('tags', 'mimetype'), 'application/json')
595 if old_stream
is not None:
596 options
.extend(['-map', '-0:%d' % old_stream
])
600 '-attach', info
['__infojson_filename'],
601 '-metadata:s:%d' % new_stream
, 'mimetype=application/json'
604 self
.to_screen('Adding metadata to \'%s\'' % filename
)
605 self
.run_ffmpeg_multiple_files(in_filenames
, temp_filename
, options
)
607 os
.remove(metadata_filename
)
608 os
.remove(encodeFilename(filename
))
609 os
.rename(encodeFilename(temp_filename
), encodeFilename(filename
))
613 class FFmpegMergerPP(FFmpegPostProcessor
):
615 filename
= info
['filepath']
616 temp_filename
= prepend_extension(filename
, 'temp')
617 args
= ['-c', 'copy']
618 for (i
, fmt
) in enumerate(info
['requested_formats']):
619 if fmt
.get('acodec') != 'none':
620 args
.extend(['-map', '%u:a:0' % (i
)])
621 if fmt
.get('vcodec') != 'none':
622 args
.extend(['-map', '%u:v:0' % (i
)])
623 self
.to_screen('Merging formats into "%s"' % filename
)
624 self
.run_ffmpeg_multiple_files(info
['__files_to_merge'], temp_filename
, args
)
625 os
.rename(encodeFilename(temp_filename
), encodeFilename(filename
))
626 return info
['__files_to_merge'], info
629 # TODO: figure out merge-capable ffmpeg version
630 if self
.basename
!= 'avconv':
633 required_version
= '10-0'
634 if is_outdated_version(
635 self
._versions
[self
.basename
], required_version
):
636 warning
= ('Your copy of %s is outdated and unable to properly mux separate video and audio files, '
637 'youtube-dlc will download single file media. '
638 'Update %s to version %s or newer to fix this.') % (
639 self
.basename
, self
.basename
, required_version
)
640 self
.report_warning(warning
)
645 class FFmpegFixupStretchedPP(FFmpegPostProcessor
):
647 stretched_ratio
= info
.get('stretched_ratio')
648 if stretched_ratio
is None or stretched_ratio
== 1:
651 filename
= info
['filepath']
652 temp_filename
= prepend_extension(filename
, 'temp')
654 options
= ['-c', 'copy', '-map', '0', '-dn', '-aspect', '%f' % stretched_ratio
]
655 self
.to_screen('Fixing aspect ratio in "%s"' % filename
)
656 self
.run_ffmpeg(filename
, temp_filename
, options
)
658 os
.remove(encodeFilename(filename
))
659 os
.rename(encodeFilename(temp_filename
), encodeFilename(filename
))
664 class FFmpegFixupM4aPP(FFmpegPostProcessor
):
666 if info
.get('container') != 'm4a_dash':
669 filename
= info
['filepath']
670 temp_filename
= prepend_extension(filename
, 'temp')
672 options
= ['-c', 'copy', '-map', '0', '-dn', '-f', 'mp4']
673 self
.to_screen('Correcting container in "%s"' % filename
)
674 self
.run_ffmpeg(filename
, temp_filename
, options
)
676 os
.remove(encodeFilename(filename
))
677 os
.rename(encodeFilename(temp_filename
), encodeFilename(filename
))
682 class FFmpegFixupM3u8PP(FFmpegPostProcessor
):
684 filename
= info
['filepath']
685 if self
.get_audio_codec(filename
) == 'aac':
686 temp_filename
= prepend_extension(filename
, 'temp')
688 options
= ['-c', 'copy', '-map', '0', '-dn', '-f', 'mp4', '-bsf:a', 'aac_adtstoasc']
689 self
.to_screen('Fixing malformed AAC bitstream in "%s"' % filename
)
690 self
.run_ffmpeg(filename
, temp_filename
, options
)
692 os
.remove(encodeFilename(filename
))
693 os
.rename(encodeFilename(temp_filename
), encodeFilename(filename
))
697 class FFmpegSubtitlesConvertorPP(FFmpegPostProcessor
):
698 def __init__(self
, downloader
=None, format
=None):
699 super(FFmpegSubtitlesConvertorPP
, self
).__init
__(downloader
)
703 subs
= info
.get('requested_subtitles')
704 filename
= info
['filepath']
705 new_ext
= self
.format
707 if new_format
== 'vtt':
708 new_format
= 'webvtt'
710 self
.to_screen('There aren\'t any subtitles to convert')
712 self
.to_screen('Converting subtitles')
714 for lang
, sub
in subs
.items():
717 self
.to_screen('Subtitle file for %s is already in the requested format' % new_ext
)
721 'You have requested to convert json subtitles into another format, '
722 'which is currently not possible')
724 old_file
= subtitles_filename(filename
, lang
, ext
, info
.get('ext'))
725 sub_filenames
.append(old_file
)
726 new_file
= subtitles_filename(filename
, lang
, new_ext
, info
.get('ext'))
728 if ext
in ('dfxp', 'ttml', 'tt'):
730 'You have requested to convert dfxp (TTML) subtitles into another format, '
731 'which results in style information loss')
734 srt_file
= subtitles_filename(filename
, lang
, 'srt', info
.get('ext'))
736 with open(dfxp_file
, 'rb') as f
:
737 srt_data
= dfxp2srt(f
.read())
739 with io
.open(srt_file
, 'wt', encoding
='utf-8') as f
:
751 sub_filenames
.append(srt_file
)
753 self
.run_ffmpeg(old_file
, new_file
, ['-f', new_format
])
755 with io
.open(new_file
, 'rt', encoding
='utf-8') as f
:
761 return sub_filenames
, info