1 from __future__
import unicode_literals
9 from .common
import AudioConversionError
, PostProcessor
11 from ..compat
import (
12 compat_subprocess_get_DEVNULL
,
26 class FFmpegPostProcessorError(PostProcessingError
):
30 class FFmpegPostProcessor(PostProcessor
):
31 def __init__(self
, downloader
=None):
32 PostProcessor
.__init
__(self
, downloader
)
33 self
._determine
_executables
()
35 def check_version(self
):
36 if not self
.available
:
37 raise FFmpegPostProcessorError('ffmpeg or avconv not found. Please install one.')
39 required_version
= '10-0' if self
.basename
== 'avconv' else '1.0'
40 if is_outdated_version(
41 self
._versions
[self
.basename
], required_version
):
42 warning
= 'Your copy of %s is outdated, update %s to version %s or newer if you encounter any errors.' % (
43 self
.basename
, self
.basename
, required_version
)
45 self
._downloader
.report_warning(warning
)
48 def get_versions(downloader
=None):
49 return FFmpegPostProcessor(downloader
)._versions
51 def _determine_executables(self
):
52 programs
= ['avprobe', 'avconv', 'ffmpeg', 'ffprobe']
53 prefer_ffmpeg
= self
._downloader
.params
.get('prefer_ffmpeg', False)
56 self
.probe_basename
= None
61 location
= self
._downloader
.params
.get('ffmpeg_location')
62 if location
is not None:
63 if not os
.path
.exists(location
):
64 self
._downloader
.report_warning(
65 'ffmpeg-location %s does not exist! '
66 'Continuing without avconv/ffmpeg.' % (location
))
69 elif not os
.path
.isdir(location
):
70 basename
= os
.path
.splitext(os
.path
.basename(location
))[0]
71 if basename
not in programs
:
72 self
._downloader
.report_warning(
73 'Cannot identify executable %s, its basename should be one of %s. '
74 'Continuing without avconv/ffmpeg.' %
75 (location
, ', '.join(programs
)))
78 location
= os
.path
.dirname(os
.path
.abspath(location
))
79 if basename
in ('ffmpeg', 'ffprobe'):
83 (p
, os
.path
.join(location
, p
)) for p
in programs
)
84 self
._versions
= dict(
85 (p
, get_exe_version(self
._paths
[p
], args
=['-version']))
87 if self
._versions
is None:
88 self
._versions
= dict(
89 (p
, get_exe_version(p
, args
=['-version'])) for p
in programs
)
90 self
._paths
= dict((p
, p
) for p
in programs
)
93 prefs
= ('ffmpeg', 'avconv')
95 prefs
= ('avconv', 'ffmpeg')
102 prefs
= ('ffprobe', 'avprobe')
104 prefs
= ('avprobe', 'ffprobe')
106 if self
._versions
[p
]:
107 self
.probe_basename
= p
112 return self
.basename
is not None
115 def executable(self
):
116 return self
._paths
[self
.basename
]
119 def probe_available(self
):
120 return self
.probe_basename
is not None
123 def probe_executable(self
):
124 return self
._paths
[self
.probe_basename
]
126 def run_ffmpeg_multiple_files(self
, input_paths
, out_path
, opts
):
130 os
.stat(encodeFilename(path
)).st_mtime
for path
in input_paths
)
133 for path
in input_paths
:
134 files_cmd
.extend([encodeArgument('-i'), encodeFilename(path
, True)])
135 cmd
= ([encodeFilename(self
.executable
, True), encodeArgument('-y')] +
137 [encodeArgument(o
) for o
in opts
] +
138 [encodeFilename(self
._ffmpeg
_filename
_argument
(out_path
), True)])
140 if self
._downloader
.params
.get('verbose', False):
141 self
._downloader
.to_screen('[debug] ffmpeg command line: %s' % shell_quote(cmd
))
142 p
= subprocess
.Popen(cmd
, stdout
=subprocess
.PIPE
, stderr
=subprocess
.PIPE
, stdin
=subprocess
.PIPE
)
143 stdout
, stderr
= p
.communicate()
144 if p
.returncode
!= 0:
145 stderr
= stderr
.decode('utf-8', 'replace')
146 msg
= stderr
.strip().split('\n')[-1]
147 raise FFmpegPostProcessorError(msg
)
148 self
.try_utime(out_path
, oldest_mtime
, oldest_mtime
)
150 def run_ffmpeg(self
, path
, out_path
, opts
):
151 self
.run_ffmpeg_multiple_files([path
], out_path
, opts
)
153 def _ffmpeg_filename_argument(self
, fn
):
154 # ffmpeg broke --, see https://ffmpeg.org/trac/ffmpeg/ticket/2127 for details
155 if fn
.startswith('-'):
160 class FFmpegExtractAudioPP(FFmpegPostProcessor
):
161 def __init__(self
, downloader
=None, preferredcodec
=None, preferredquality
=None, nopostoverwrites
=False):
162 FFmpegPostProcessor
.__init
__(self
, downloader
)
163 if preferredcodec
is None:
164 preferredcodec
= 'best'
165 self
._preferredcodec
= preferredcodec
166 self
._preferredquality
= preferredquality
167 self
._nopostoverwrites
= nopostoverwrites
169 def get_audio_codec(self
, path
):
171 if not self
.probe_available
:
172 raise PostProcessingError('ffprobe or avprobe not found. Please install one.')
175 encodeFilename(self
.probe_executable
, True),
176 encodeArgument('-show_streams'),
177 encodeFilename(self
._ffmpeg
_filename
_argument
(path
), True)]
178 if self
._downloader
.params
.get('verbose', False):
179 self
._downloader
.to_screen('[debug] %s command line: %s' % (self
.basename
, shell_quote(cmd
)))
180 handle
= subprocess
.Popen(cmd
, stderr
=compat_subprocess_get_DEVNULL(), stdout
=subprocess
.PIPE
, stdin
=subprocess
.PIPE
)
181 output
= handle
.communicate()[0]
182 if handle
.wait() != 0:
184 except (IOError, OSError):
187 for line
in output
.decode('ascii', 'ignore').split('\n'):
188 if line
.startswith('codec_name='):
189 audio_codec
= line
.split('=')[1].strip()
190 elif line
.strip() == 'codec_type=audio' and audio_codec
is not None:
194 def run_ffmpeg(self
, path
, out_path
, codec
, more_opts
):
198 acodec_opts
= ['-acodec', codec
]
199 opts
= ['-vn'] + acodec_opts
+ more_opts
201 FFmpegPostProcessor
.run_ffmpeg(self
, path
, out_path
, opts
)
202 except FFmpegPostProcessorError
as err
:
203 raise AudioConversionError(err
.msg
)
205 def run(self
, information
):
206 path
= information
['filepath']
208 filecodec
= self
.get_audio_codec(path
)
209 if filecodec
is None:
210 raise PostProcessingError('WARNING: unable to obtain file audio codec with ffprobe')
213 if self
._preferredcodec
== 'best' or self
._preferredcodec
== filecodec
or (self
._preferredcodec
== 'm4a' and filecodec
== 'aac'):
214 if filecodec
== 'aac' and self
._preferredcodec
in ['m4a', 'best']:
215 # Lossless, but in another container
218 more_opts
= ['-bsf:a', 'aac_adtstoasc']
219 elif filecodec
in ['aac', 'mp3', 'vorbis', 'opus']:
220 # Lossless if possible
222 extension
= filecodec
223 if filecodec
== 'aac':
224 more_opts
= ['-f', 'adts']
225 if filecodec
== 'vorbis':
229 acodec
= 'libmp3lame'
232 if self
._preferredquality
is not None:
233 if int(self
._preferredquality
) < 10:
234 more_opts
+= ['-q:a', self
._preferredquality
]
236 more_opts
+= ['-b:a', self
._preferredquality
+ 'k']
238 # We convert the audio (lossy)
239 acodec
= {'mp3': 'libmp3lame', 'aac': 'aac', 'm4a': 'aac', 'opus': 'opus', 'vorbis': 'libvorbis', 'wav': None}
[self
._preferredcodec
]
240 extension
= self
._preferredcodec
242 if self
._preferredquality
is not None:
243 # The opus codec doesn't support the -aq option
244 if int(self
._preferredquality
) < 10 and extension
!= 'opus':
245 more_opts
+= ['-q:a', self
._preferredquality
]
247 more_opts
+= ['-b:a', self
._preferredquality
+ 'k']
248 if self
._preferredcodec
== 'aac':
249 more_opts
+= ['-f', 'adts']
250 if self
._preferredcodec
== 'm4a':
251 more_opts
+= ['-bsf:a', 'aac_adtstoasc']
252 if self
._preferredcodec
== 'vorbis':
254 if self
._preferredcodec
== 'wav':
256 more_opts
+= ['-f', 'wav']
258 prefix
, sep
, ext
= path
.rpartition('.') # not os.path.splitext, since the latter does not work on unicode in all setups
259 new_path
= prefix
+ sep
+ extension
261 # If we download foo.mp3 and convert it to... foo.mp3, then don't delete foo.mp3, silly.
262 if (new_path
== path
or
263 (self
._nopostoverwrites
and os
.path
.exists(encodeFilename(new_path
)))):
264 self
._downloader
.to_screen('[youtube] Post-process file %s exists, skipping' % new_path
)
265 return [], information
268 self
._downloader
.to_screen('[' + self
.basename
+ '] Destination: ' + new_path
)
269 self
.run_ffmpeg(path
, new_path
, acodec
, more_opts
)
270 except AudioConversionError
as e
:
271 raise PostProcessingError(
272 'audio conversion failed: ' + e
.msg
)
274 raise PostProcessingError('error running ' + self
.basename
)
276 # Try to update the date time for extracted audio file.
277 if information
.get('filetime') is not None:
279 new_path
, time
.time(), information
['filetime'],
280 errnote
='Cannot update utime of audio file')
282 information
['filepath'] = new_path
283 return [path
], information
286 class FFmpegVideoConvertorPP(FFmpegPostProcessor
):
287 def __init__(self
, downloader
=None, preferedformat
=None):
288 super(FFmpegVideoConvertorPP
, self
).__init
__(downloader
)
289 self
._preferedformat
= preferedformat
291 def run(self
, information
):
292 path
= information
['filepath']
293 prefix
, sep
, ext
= path
.rpartition('.')
294 outpath
= prefix
+ sep
+ self
._preferedformat
295 if information
['ext'] == self
._preferedformat
:
296 self
._downloader
.to_screen('[ffmpeg] Not converting video file %s - already is in target format %s' % (path
, self
._preferedformat
))
297 return [], information
298 self
._downloader
.to_screen('[' + 'ffmpeg' + '] Converting video from %s to %s, Destination: ' % (information
['ext'], self
._preferedformat
) + outpath
)
299 self
.run_ffmpeg(path
, outpath
, [])
300 information
['filepath'] = outpath
301 information
['format'] = self
._preferedformat
302 information
['ext'] = self
._preferedformat
303 return [path
], information
306 class FFmpegEmbedSubtitlePP(FFmpegPostProcessor
):
307 # See http://www.loc.gov/standards/iso639-2/ISO-639-2_utf-8.txt
496 def _conver_lang_code(cls
, code
):
497 """Convert language code from ISO 639-1 to ISO 639-2/T"""
498 return cls
._lang
_map
.get(code
[:2])
500 def run(self
, information
):
501 if information
['ext'] != 'mp4':
502 self
._downloader
.to_screen('[ffmpeg] Subtitles can only be embedded in mp4 files')
503 return [], information
504 subtitles
= information
.get('requested_subtitles')
506 self
._downloader
.to_screen('[ffmpeg] There aren\'t any subtitles to embed')
507 return [], information
509 sub_langs
= list(subtitles
.keys())
510 filename
= information
['filepath']
511 sub_filenames
= [subtitles_filename(filename
, lang
, sub_info
['ext']) for lang
, sub_info
in subtitles
.items()]
512 input_files
= [filename
] + sub_filenames
517 # Don't copy the existing subtitles, we may be running the
518 # postprocessor a second time
522 for (i
, lang
) in enumerate(sub_langs
):
523 opts
.extend(['-map', '%d:0' % (i
+ 1)])
524 lang_code
= self
._conver
_lang
_code
(lang
)
525 if lang_code
is not None:
526 opts
.extend(['-metadata:s:s:%d' % i
, 'language=%s' % lang_code
])
528 temp_filename
= prepend_extension(filename
, 'temp')
529 self
._downloader
.to_screen('[ffmpeg] Embedding subtitles in \'%s\'' % filename
)
530 self
.run_ffmpeg_multiple_files(input_files
, temp_filename
, opts
)
531 os
.remove(encodeFilename(filename
))
532 os
.rename(encodeFilename(temp_filename
), encodeFilename(filename
))
534 return sub_filenames
, information
537 class FFmpegMetadataPP(FFmpegPostProcessor
):
540 if info
.get('title') is not None:
541 metadata
['title'] = info
['title']
542 if info
.get('upload_date') is not None:
543 metadata
['date'] = info
['upload_date']
544 if info
.get('artist') is not None:
545 metadata
['artist'] = info
['artist']
546 elif info
.get('uploader') is not None:
547 metadata
['artist'] = info
['uploader']
548 elif info
.get('uploader_id') is not None:
549 metadata
['artist'] = info
['uploader_id']
550 if info
.get('description') is not None:
551 metadata
['description'] = info
['description']
552 metadata
['comment'] = info
['description']
553 if info
.get('webpage_url') is not None:
554 metadata
['purl'] = info
['webpage_url']
555 if info
.get('album') is not None:
556 metadata
['album'] = info
['album']
559 self
._downloader
.to_screen('[ffmpeg] There isn\'t any metadata to add')
562 filename
= info
['filepath']
563 temp_filename
= prepend_extension(filename
, 'temp')
565 if info
['ext'] == 'm4a':
566 options
= ['-vn', '-acodec', 'copy']
568 options
= ['-c', 'copy']
570 for (name
, value
) in metadata
.items():
571 options
.extend(['-metadata', '%s=%s' % (name
, value
)])
573 self
._downloader
.to_screen('[ffmpeg] Adding metadata to \'%s\'' % filename
)
574 self
.run_ffmpeg(filename
, temp_filename
, options
)
575 os
.remove(encodeFilename(filename
))
576 os
.rename(encodeFilename(temp_filename
), encodeFilename(filename
))
580 class FFmpegMergerPP(FFmpegPostProcessor
):
582 filename
= info
['filepath']
583 args
= ['-c', 'copy', '-map', '0:v:0', '-map', '1:a:0']
584 self
._downloader
.to_screen('[ffmpeg] Merging formats into "%s"' % filename
)
585 self
.run_ffmpeg_multiple_files(info
['__files_to_merge'], filename
, args
)
586 return info
['__files_to_merge'], info
589 class FFmpegAudioFixPP(FFmpegPostProcessor
):
591 filename
= info
['filepath']
592 temp_filename
= prepend_extension(filename
, 'temp')
594 options
= ['-vn', '-acodec', 'copy']
595 self
._downloader
.to_screen('[ffmpeg] Fixing audio file "%s"' % filename
)
596 self
.run_ffmpeg(filename
, temp_filename
, options
)
598 os
.remove(encodeFilename(filename
))
599 os
.rename(encodeFilename(temp_filename
), encodeFilename(filename
))
604 class FFmpegFixupStretchedPP(FFmpegPostProcessor
):
606 stretched_ratio
= info
.get('stretched_ratio')
607 if stretched_ratio
is None or stretched_ratio
== 1:
610 filename
= info
['filepath']
611 temp_filename
= prepend_extension(filename
, 'temp')
613 options
= ['-c', 'copy', '-aspect', '%f' % stretched_ratio
]
614 self
._downloader
.to_screen('[ffmpeg] Fixing aspect ratio in "%s"' % filename
)
615 self
.run_ffmpeg(filename
, temp_filename
, options
)
617 os
.remove(encodeFilename(filename
))
618 os
.rename(encodeFilename(temp_filename
), encodeFilename(filename
))
623 class FFmpegFixupM4aPP(FFmpegPostProcessor
):
625 if info
.get('container') != 'm4a_dash':
628 filename
= info
['filepath']
629 temp_filename
= prepend_extension(filename
, 'temp')
631 options
= ['-c', 'copy', '-f', 'mp4']
632 self
._downloader
.to_screen('[ffmpeg] Correcting container in "%s"' % filename
)
633 self
.run_ffmpeg(filename
, temp_filename
, options
)
635 os
.remove(encodeFilename(filename
))
636 os
.rename(encodeFilename(temp_filename
), encodeFilename(filename
))
641 class FFmpegSubtitlesConvertorPP(FFmpegPostProcessor
):
642 def __init__(self
, downloader
=None, format
=None):
643 super(FFmpegSubtitlesConvertorPP
, self
).__init
__(downloader
)
647 subs
= info
.get('requested_subtitles')
648 filename
= info
['filepath']
649 new_ext
= self
.format
651 if new_format
== 'vtt':
652 new_format
= 'webvtt'
654 self
._downloader
.to_screen('[ffmpeg] There aren\'t any subtitles to convert')
656 self
._downloader
.to_screen('[ffmpeg] Converting subtitles')
657 for lang
, sub
in subs
.items():
660 self
._downloader
.to_screen(
661 '[ffmpeg] Subtitle file for %s is already in the requested'
664 new_file
= subtitles_filename(filename
, lang
, new_ext
)
666 subtitles_filename(filename
, lang
, ext
),
667 new_file
, ['-f', new_format
])
669 with io
.open(new_file
, 'rt', encoding
='utf-8') as f
: