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 if self
._downloader
.params
.get('verbose', False):
225 self
._downloader
.to_screen('[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
):
241 os
.stat(encodeFilename(path
)).st_mtime
for path
in input_paths
)
243 opts
+= self
._configuration
_args
(exe
=self
.basename
)
246 for path
in input_paths
:
248 encodeArgument('-i'),
249 encodeFilename(self
._ffmpeg
_filename
_argument
(path
), True)
251 cmd
= [encodeFilename(self
.executable
, True), encodeArgument('-y')]
252 # avconv does not have repeat option
253 if self
.basename
== 'ffmpeg':
254 cmd
+= [encodeArgument('-loglevel'), encodeArgument('repeat+info')]
256 + [encodeArgument(o
) for o
in opts
]
257 + [encodeFilename(self
._ffmpeg
_filename
_argument
(out_path
), True)])
259 self
.write_debug('ffmpeg command line: %s' % shell_quote(cmd
))
260 p
= subprocess
.Popen(cmd
, stdout
=subprocess
.PIPE
, stderr
=subprocess
.PIPE
, stdin
=subprocess
.PIPE
)
261 stdout
, stderr
= process_communicate_or_kill(p
)
262 if p
.returncode
!= 0:
263 stderr
= stderr
.decode('utf-8', 'replace').strip()
264 if self
._downloader
.params
.get('verbose', False):
265 self
.report_error(stderr
)
266 raise FFmpegPostProcessorError(stderr
.split('\n')[-1])
267 self
.try_utime(out_path
, oldest_mtime
, oldest_mtime
)
268 return stderr
.decode('utf-8', 'replace')
270 def run_ffmpeg(self
, path
, out_path
, opts
):
271 return self
.run_ffmpeg_multiple_files([path
], out_path
, opts
)
273 def _ffmpeg_filename_argument(self
, fn
):
274 # Always use 'file:' because the filename may contain ':' (ffmpeg
275 # interprets that as a protocol) or can start with '-' (-- is broken in
276 # ffmpeg, see https://ffmpeg.org/trac/ffmpeg/ticket/2127 for details)
277 # Also leave '-' intact in order not to break streaming to stdout.
278 if fn
.startswith(('http://', 'https://')):
280 return 'file:' + fn
if fn
!= '-' else fn
283 class FFmpegExtractAudioPP(FFmpegPostProcessor
):
284 def __init__(self
, downloader
=None, preferredcodec
=None, preferredquality
=None, nopostoverwrites
=False):
285 FFmpegPostProcessor
.__init
__(self
, downloader
)
286 if preferredcodec
is None:
287 preferredcodec
= 'best'
288 self
._preferredcodec
= preferredcodec
289 self
._preferredquality
= preferredquality
290 self
._nopostoverwrites
= nopostoverwrites
292 def run_ffmpeg(self
, path
, out_path
, codec
, more_opts
):
296 acodec_opts
= ['-acodec', codec
]
297 opts
= ['-vn'] + acodec_opts
+ more_opts
299 FFmpegPostProcessor
.run_ffmpeg(self
, path
, out_path
, opts
)
300 except FFmpegPostProcessorError
as err
:
301 raise AudioConversionError(err
.msg
)
303 def run(self
, information
):
304 path
= information
['filepath']
306 filecodec
= self
.get_audio_codec(path
)
307 if filecodec
is None:
308 raise PostProcessingError('WARNING: unable to obtain file audio codec with ffprobe')
311 if self
._preferredcodec
== 'best' or self
._preferredcodec
== filecodec
or (self
._preferredcodec
== 'm4a' and filecodec
== 'aac'):
312 if filecodec
== 'aac' and self
._preferredcodec
in ['m4a', 'best']:
313 # Lossless, but in another container
316 more_opts
= ['-bsf:a', 'aac_adtstoasc']
317 elif filecodec
in ['aac', 'flac', 'mp3', 'vorbis', 'opus']:
318 # Lossless if possible
320 extension
= filecodec
321 if filecodec
== 'aac':
322 more_opts
= ['-f', 'adts']
323 if filecodec
== 'vorbis':
327 acodec
= 'libmp3lame'
330 if self
._preferredquality
is not None:
331 if int(self
._preferredquality
) < 10:
332 more_opts
+= ['-q:a', self
._preferredquality
]
334 more_opts
+= ['-b:a', self
._preferredquality
+ 'k']
336 # We convert the audio (lossy if codec is lossy)
337 acodec
= ACODECS
[self
._preferredcodec
]
338 extension
= self
._preferredcodec
340 if self
._preferredquality
is not None:
341 # The opus codec doesn't support the -aq option
342 if int(self
._preferredquality
) < 10 and extension
!= 'opus':
343 more_opts
+= ['-q:a', self
._preferredquality
]
345 more_opts
+= ['-b:a', self
._preferredquality
+ 'k']
346 if self
._preferredcodec
== 'aac':
347 more_opts
+= ['-f', 'adts']
348 if self
._preferredcodec
== 'm4a':
349 more_opts
+= ['-bsf:a', 'aac_adtstoasc']
350 if self
._preferredcodec
== 'vorbis':
352 if self
._preferredcodec
== 'wav':
354 more_opts
+= ['-f', 'wav']
356 prefix
, sep
, ext
= path
.rpartition('.') # not os.path.splitext, since the latter does not work on unicode in all setups
357 new_path
= prefix
+ sep
+ extension
359 information
['filepath'] = new_path
360 information
['ext'] = extension
362 # If we download foo.mp3 and convert it to... foo.mp3, then don't delete foo.mp3, silly.
364 or (self
._nopostoverwrites
and os
.path
.exists(encodeFilename(new_path
)))):
365 self
.to_screen('Post-process file %s exists, skipping' % new_path
)
366 return [], information
369 self
.to_screen('Destination: ' + new_path
)
370 self
.run_ffmpeg(path
, new_path
, acodec
, more_opts
)
371 except AudioConversionError
as e
:
372 raise PostProcessingError(
373 'audio conversion failed: ' + e
.msg
)
375 raise PostProcessingError('error running ' + self
.basename
)
377 # Try to update the date time for extracted audio file.
378 if information
.get('filetime') is not None:
380 new_path
, time
.time(), information
['filetime'],
381 errnote
='Cannot update utime of audio file')
383 return [path
], information
386 class FFmpegVideoRemuxerPP(FFmpegPostProcessor
):
387 def __init__(self
, downloader
=None, preferedformat
=None):
388 super(FFmpegVideoRemuxerPP
, self
).__init
__(downloader
)
389 self
._preferedformats
= preferedformat
.lower().split('/')
391 def run(self
, information
):
392 path
= information
['filepath']
393 sourceext
, targetext
= information
['ext'].lower(), None
394 for pair
in self
._preferedformats
:
396 if len(kv
) == 1 or kv
[0].strip() == sourceext
:
397 targetext
= kv
[-1].strip()
401 'could not find a mapping for %s' if not targetext
402 else 'already is in target format %s' if sourceext
== targetext
405 self
.to_screen('Not remuxing media file %s; %s' % (path
, _skip_msg
% sourceext
))
406 return [], information
408 options
= ['-c', 'copy', '-map', '0', '-dn']
409 if targetext
in ['mp4', 'm4a', 'mov']:
410 options
.extend(['-movflags', '+faststart'])
411 prefix
, sep
, oldext
= path
.rpartition('.')
412 outpath
= prefix
+ sep
+ targetext
413 self
.to_screen('Remuxing video from %s to %s; Destination: %s' % (sourceext
, targetext
, outpath
))
414 self
.run_ffmpeg(path
, outpath
, options
)
415 information
['filepath'] = outpath
416 information
['format'] = targetext
417 information
['ext'] = targetext
418 return [path
], information
421 class FFmpegVideoConvertorPP(FFmpegPostProcessor
):
422 def __init__(self
, downloader
=None, preferedformat
=None):
423 super(FFmpegVideoConvertorPP
, self
).__init
__(downloader
)
424 self
._preferedformat
= preferedformat
426 def run(self
, information
):
427 path
= information
['filepath']
428 if information
['ext'] == self
._preferedformat
:
429 self
.to_screen('Not converting video file %s - already is in target format %s' % (path
, self
._preferedformat
))
430 return [], information
432 if self
._preferedformat
== 'avi':
433 options
.extend(['-c:v', 'libxvid', '-vtag', 'XVID'])
434 prefix
, sep
, ext
= path
.rpartition('.')
435 outpath
= prefix
+ sep
+ self
._preferedformat
436 self
.to_screen('Converting video from %s to %s, Destination: ' % (information
['ext'], self
._preferedformat
) + outpath
)
437 self
.run_ffmpeg(path
, outpath
, options
)
438 information
['filepath'] = outpath
439 information
['format'] = self
._preferedformat
440 information
['ext'] = self
._preferedformat
441 return [path
], information
444 class FFmpegEmbedSubtitlePP(FFmpegPostProcessor
):
445 def __init__(self
, downloader
=None, already_have_subtitle
=False):
446 super(FFmpegEmbedSubtitlePP
, self
).__init
__(downloader
)
447 self
._already
_have
_subtitle
= already_have_subtitle
449 def run(self
, information
):
450 if information
['ext'] not in ('mp4', 'webm', 'mkv'):
451 self
.to_screen('Subtitles can only be embedded in mp4, webm or mkv files')
452 return [], information
453 subtitles
= information
.get('requested_subtitles')
455 self
.to_screen('There aren\'t any subtitles to embed')
456 return [], information
458 filename
= information
['filepath']
460 ext
= information
['ext']
463 webm_vtt_warn
= False
466 for lang
, sub_info
in subtitles
.items():
467 sub_ext
= sub_info
['ext']
468 if sub_ext
== 'json':
469 self
.report_warning('JSON subtitles cannot be embedded')
470 elif ext
!= 'webm' or ext
== 'webm' and sub_ext
== 'vtt':
471 sub_langs
.append(lang
)
472 sub_filenames
.append(subtitles_filename(filename
, lang
, sub_ext
, ext
))
474 if not webm_vtt_warn
and ext
== 'webm' and sub_ext
!= 'vtt':
476 self
.report_warning('Only WebVTT subtitles can be embedded in webm files')
477 if not mp4_ass_warn
and ext
== 'mp4' and sub_ext
== 'ass':
479 self
.report_warning('ASS subtitles cannot be properly embedded in mp4 files; expect issues')
482 return [], information
484 input_files
= [filename
] + sub_filenames
487 '-c', 'copy', '-map', '0', '-dn',
488 # Don't copy the existing subtitles, we may be running the
489 # postprocessor a second time
491 # Don't copy Apple TV chapters track, bin_data (see #19042, #19024,
492 # https://trac.ffmpeg.org/ticket/6016)
495 if information
['ext'] == 'mp4':
496 opts
+= ['-c:s', 'mov_text']
497 for (i
, lang
) in enumerate(sub_langs
):
498 opts
.extend(['-map', '%d:0' % (i
+ 1)])
499 lang_code
= ISO639Utils
.short2long(lang
) or lang
500 opts
.extend(['-metadata:s:s:%d' % i
, 'language=%s' % lang_code
])
502 temp_filename
= prepend_extension(filename
, 'temp')
503 self
.to_screen('Embedding subtitles in "%s"' % filename
)
504 self
.run_ffmpeg_multiple_files(input_files
, temp_filename
, opts
)
505 os
.remove(encodeFilename(filename
))
506 os
.rename(encodeFilename(temp_filename
), encodeFilename(filename
))
508 files_to_delete
= [] if self
._already
_have
_subtitle
else sub_filenames
509 return files_to_delete
, information
512 class FFmpegMetadataPP(FFmpegPostProcessor
):
516 def add(meta_list
, info_list
=None):
518 info_list
= meta_list
519 if not isinstance(meta_list
, (list, tuple)):
520 meta_list
= (meta_list
,)
521 if not isinstance(info_list
, (list, tuple)):
522 info_list
= (info_list
,)
523 for info_f
in info_list
:
524 if info
.get(info_f
) is not None:
525 for meta_f
in meta_list
:
526 metadata
[meta_f
] = info
[info_f
]
529 # See [1-4] for some info on media metadata/metadata supported
531 # 1. https://kdenlive.org/en/project/adding-meta-data-to-mp4-video/
532 # 2. https://wiki.multimedia.cx/index.php/FFmpeg_Metadata
533 # 3. https://kodi.wiki/view/Video_file_tagging
535 add('title', ('track', 'title'))
536 add('date', 'upload_date')
537 add(('description', 'comment'), 'description')
538 add('purl', 'webpage_url')
539 add('track', 'track_number')
540 add('artist', ('artist', 'creator', 'uploader', 'uploader_id'))
544 add('disc', 'disc_number')
545 add('show', 'series')
547 add('episode_id', ('episode', 'episode_id'))
548 add('episode_sort', 'episode_number')
551 self
.to_screen('There isn\'t any metadata to add')
554 filename
= info
['filepath']
555 temp_filename
= prepend_extension(filename
, 'temp')
556 in_filenames
= [filename
]
557 options
= ['-map', '0', '-dn']
559 if info
['ext'] == 'm4a':
560 options
.extend(['-vn', '-acodec', 'copy'])
562 options
.extend(['-c', 'copy'])
564 for (name
, value
) in metadata
.items():
565 options
.extend(['-metadata', '%s=%s' % (name
, value
)])
567 chapters
= info
.get('chapters', [])
569 metadata_filename
= replace_extension(filename
, 'meta')
570 with io
.open(metadata_filename
, 'wt', encoding
='utf-8') as f
:
571 def ffmpeg_escape(text
):
572 return re
.sub(r
'(=|;|#|\\|\n)', r
'\\\1', text
)
574 metadata_file_content
= ';FFMETADATA1\n'
575 for chapter
in chapters
:
576 metadata_file_content
+= '[CHAPTER]\nTIMEBASE=1/1000\n'
577 metadata_file_content
+= 'START=%d\n' % (chapter
['start_time'] * 1000)
578 metadata_file_content
+= 'END=%d\n' % (chapter
['end_time'] * 1000)
579 chapter_title
= chapter
.get('title')
581 metadata_file_content
+= 'title=%s\n' % ffmpeg_escape(chapter_title
)
582 f
.write(metadata_file_content
)
583 in_filenames
.append(metadata_filename
)
584 options
.extend(['-map_metadata', '1'])
586 if '__infojson_filename' in info
and info
['ext'] in ('mkv', 'mka'):
587 old_stream
, new_stream
= self
.get_stream_number(
588 filename
, ('tags', 'mimetype'), 'application/json')
589 if old_stream
is not None:
590 options
.extend(['-map', '-0:%d' % old_stream
])
594 '-attach', info
['__infojson_filename'],
595 '-metadata:s:%d' % new_stream
, 'mimetype=application/json'
598 self
.to_screen('Adding metadata to \'%s\'' % filename
)
599 self
.run_ffmpeg_multiple_files(in_filenames
, temp_filename
, options
)
601 os
.remove(metadata_filename
)
602 os
.remove(encodeFilename(filename
))
603 os
.rename(encodeFilename(temp_filename
), encodeFilename(filename
))
607 class FFmpegMergerPP(FFmpegPostProcessor
):
609 filename
= info
['filepath']
610 temp_filename
= prepend_extension(filename
, 'temp')
611 args
= ['-c', 'copy']
612 for (i
, fmt
) in enumerate(info
['requested_formats']):
613 if fmt
.get('acodec') != 'none':
614 args
.extend(['-map', '%u:a:0' % (i
)])
615 if fmt
.get('vcodec') != 'none':
616 args
.extend(['-map', '%u:v:0' % (i
)])
617 self
.to_screen('Merging formats into "%s"' % filename
)
618 self
.run_ffmpeg_multiple_files(info
['__files_to_merge'], temp_filename
, args
)
619 os
.rename(encodeFilename(temp_filename
), encodeFilename(filename
))
620 return info
['__files_to_merge'], info
623 # TODO: figure out merge-capable ffmpeg version
624 if self
.basename
!= 'avconv':
627 required_version
= '10-0'
628 if is_outdated_version(
629 self
._versions
[self
.basename
], required_version
):
630 warning
= ('Your copy of %s is outdated and unable to properly mux separate video and audio files, '
631 'youtube-dlc will download single file media. '
632 'Update %s to version %s or newer to fix this.') % (
633 self
.basename
, self
.basename
, required_version
)
634 self
.report_warning(warning
)
639 class FFmpegFixupStretchedPP(FFmpegPostProcessor
):
641 stretched_ratio
= info
.get('stretched_ratio')
642 if stretched_ratio
is None or stretched_ratio
== 1:
645 filename
= info
['filepath']
646 temp_filename
= prepend_extension(filename
, 'temp')
648 options
= ['-c', 'copy', '-map', '0', '-dn', '-aspect', '%f' % stretched_ratio
]
649 self
.to_screen('Fixing aspect ratio in "%s"' % filename
)
650 self
.run_ffmpeg(filename
, temp_filename
, options
)
652 os
.remove(encodeFilename(filename
))
653 os
.rename(encodeFilename(temp_filename
), encodeFilename(filename
))
658 class FFmpegFixupM4aPP(FFmpegPostProcessor
):
660 if info
.get('container') != 'm4a_dash':
663 filename
= info
['filepath']
664 temp_filename
= prepend_extension(filename
, 'temp')
666 options
= ['-c', 'copy', '-map', '0', '-dn', '-f', 'mp4']
667 self
.to_screen('Correcting container in "%s"' % filename
)
668 self
.run_ffmpeg(filename
, temp_filename
, options
)
670 os
.remove(encodeFilename(filename
))
671 os
.rename(encodeFilename(temp_filename
), encodeFilename(filename
))
676 class FFmpegFixupM3u8PP(FFmpegPostProcessor
):
678 filename
= info
['filepath']
679 if self
.get_audio_codec(filename
) == 'aac':
680 temp_filename
= prepend_extension(filename
, 'temp')
682 options
= ['-c', 'copy', '-map', '0', '-dn', '-f', 'mp4', '-bsf:a', 'aac_adtstoasc']
683 self
.to_screen('Fixing malformed AAC bitstream in "%s"' % filename
)
684 self
.run_ffmpeg(filename
, temp_filename
, options
)
686 os
.remove(encodeFilename(filename
))
687 os
.rename(encodeFilename(temp_filename
), encodeFilename(filename
))
691 class FFmpegSubtitlesConvertorPP(FFmpegPostProcessor
):
692 def __init__(self
, downloader
=None, format
=None):
693 super(FFmpegSubtitlesConvertorPP
, self
).__init
__(downloader
)
697 subs
= info
.get('requested_subtitles')
698 filename
= info
['filepath']
699 new_ext
= self
.format
701 if new_format
== 'vtt':
702 new_format
= 'webvtt'
704 self
.to_screen('There aren\'t any subtitles to convert')
706 self
.to_screen('Converting subtitles')
708 for lang
, sub
in subs
.items():
711 self
.to_screen('Subtitle file for %s is already in the requested format' % new_ext
)
715 'You have requested to convert json subtitles into another format, '
716 'which is currently not possible')
718 old_file
= subtitles_filename(filename
, lang
, ext
, info
.get('ext'))
719 sub_filenames
.append(old_file
)
720 new_file
= subtitles_filename(filename
, lang
, new_ext
, info
.get('ext'))
722 if ext
in ('dfxp', 'ttml', 'tt'):
724 'You have requested to convert dfxp (TTML) subtitles into another format, '
725 'which results in style information loss')
728 srt_file
= subtitles_filename(filename
, lang
, 'srt', info
.get('ext'))
730 with open(dfxp_file
, 'rb') as f
:
731 srt_data
= dfxp2srt(f
.read())
733 with io
.open(srt_file
, 'wt', encoding
='utf-8') as f
:
745 sub_filenames
.append(srt_file
)
747 self
.run_ffmpeg(old_file
, new_file
, ['-f', new_format
])
749 with io
.open(new_file
, 'rt', encoding
='utf-8') as f
:
755 return sub_filenames
, info