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, deletetempfiles
=False):
32 PostProcessor
.__init
__(self
, downloader
)
33 self
._versions
= self
.get_versions()
34 self
._deletetempfiles
= deletetempfiles
36 def check_version(self
):
37 if not self
._executable
:
38 raise FFmpegPostProcessorError('ffmpeg or avconv not found. Please install one.')
40 required_version
= '10-0' if self
._uses
_avconv
() else '1.0'
41 if is_outdated_version(
42 self
._versions
[self
._executable
], required_version
):
43 warning
= 'Your copy of %s is outdated, update %s to version %s or newer if you encounter any errors.' % (
44 self
._executable
, self
._executable
, required_version
)
46 self
._downloader
.report_warning(warning
)
50 programs
= ['avprobe', 'avconv', 'ffmpeg', 'ffprobe']
51 return dict((p
, get_exe_version(p
, args
=['-version'])) for p
in programs
)
55 return self
._executable
is not None
58 def _executable(self
):
59 if self
._downloader
.params
.get('prefer_ffmpeg', False):
60 prefs
= ('ffmpeg', 'avconv')
62 prefs
= ('avconv', 'ffmpeg')
69 def _probe_executable(self
):
70 if self
._downloader
.params
.get('prefer_ffmpeg', False):
71 prefs
= ('ffprobe', 'avprobe')
73 prefs
= ('avprobe', 'ffprobe')
79 def _uses_avconv(self
):
80 return self
._executable
== 'avconv'
82 def run_ffmpeg_multiple_files(self
, input_paths
, out_path
, opts
):
86 os
.stat(encodeFilename(path
)).st_mtime
for path
in input_paths
)
89 for path
in input_paths
:
90 files_cmd
.extend([encodeArgument('-i'), encodeFilename(path
, True)])
91 cmd
= ([encodeFilename(self
._executable
, True), encodeArgument('-y')] +
93 [encodeArgument(o
) for o
in opts
] +
94 [encodeFilename(self
._ffmpeg
_filename
_argument
(out_path
), True)])
96 if self
._downloader
.params
.get('verbose', False):
97 self
._downloader
.to_screen('[debug] ffmpeg command line: %s' % shell_quote(cmd
))
98 p
= subprocess
.Popen(cmd
, stdout
=subprocess
.PIPE
, stderr
=subprocess
.PIPE
)
99 stdout
, stderr
= p
.communicate()
100 if p
.returncode
!= 0:
101 stderr
= stderr
.decode('utf-8', 'replace')
102 msg
= stderr
.strip().split('\n')[-1]
103 raise FFmpegPostProcessorError(msg
)
104 os
.utime(encodeFilename(out_path
), (oldest_mtime
, oldest_mtime
))
105 if self
._deletetempfiles
:
106 for ipath
in input_paths
:
109 def run_ffmpeg(self
, path
, out_path
, opts
):
110 self
.run_ffmpeg_multiple_files([path
], out_path
, opts
)
112 def _ffmpeg_filename_argument(self
, fn
):
113 # ffmpeg broke --, see https://ffmpeg.org/trac/ffmpeg/ticket/2127 for details
114 if fn
.startswith('-'):
119 class FFmpegExtractAudioPP(FFmpegPostProcessor
):
120 def __init__(self
, downloader
=None, preferredcodec
=None, preferredquality
=None, nopostoverwrites
=False):
121 FFmpegPostProcessor
.__init
__(self
, downloader
)
122 if preferredcodec
is None:
123 preferredcodec
= 'best'
124 self
._preferredcodec
= preferredcodec
125 self
._preferredquality
= preferredquality
126 self
._nopostoverwrites
= nopostoverwrites
128 def get_audio_codec(self
, path
):
130 if not self
._probe
_executable
:
131 raise PostProcessingError('ffprobe or avprobe not found. Please install one.')
134 encodeFilename(self
._probe
_executable
, True),
135 encodeArgument('-show_streams'),
136 encodeFilename(self
._ffmpeg
_filename
_argument
(path
), True)]
137 handle
= subprocess
.Popen(cmd
, stderr
=compat_subprocess_get_DEVNULL(), stdout
=subprocess
.PIPE
)
138 output
= handle
.communicate()[0]
139 if handle
.wait() != 0:
141 except (IOError, OSError):
144 for line
in output
.decode('ascii', 'ignore').split('\n'):
145 if line
.startswith('codec_name='):
146 audio_codec
= line
.split('=')[1].strip()
147 elif line
.strip() == 'codec_type=audio' and audio_codec
is not None:
151 def run_ffmpeg(self
, path
, out_path
, codec
, more_opts
):
155 acodec_opts
= ['-acodec', codec
]
156 opts
= ['-vn'] + acodec_opts
+ more_opts
158 FFmpegPostProcessor
.run_ffmpeg(self
, path
, out_path
, opts
)
159 except FFmpegPostProcessorError
as err
:
160 raise AudioConversionError(err
.msg
)
162 def run(self
, information
):
163 path
= information
['filepath']
165 filecodec
= self
.get_audio_codec(path
)
166 if filecodec
is None:
167 raise PostProcessingError('WARNING: unable to obtain file audio codec with ffprobe')
169 uses_avconv
= self
._uses
_avconv
()
171 if self
._preferredcodec
== 'best' or self
._preferredcodec
== filecodec
or (self
._preferredcodec
== 'm4a' and filecodec
== 'aac'):
172 if filecodec
== 'aac' and self
._preferredcodec
in ['m4a', 'best']:
173 # Lossless, but in another container
176 more_opts
= ['-bsf:a' if uses_avconv
else '-absf', 'aac_adtstoasc']
177 elif filecodec
in ['aac', 'mp3', 'vorbis', 'opus']:
178 # Lossless if possible
180 extension
= filecodec
181 if filecodec
== 'aac':
182 more_opts
= ['-f', 'adts']
183 if filecodec
== 'vorbis':
187 acodec
= 'libmp3lame'
190 if self
._preferredquality
is not None:
191 if int(self
._preferredquality
) < 10:
192 more_opts
+= ['-q:a' if uses_avconv
else '-aq', self
._preferredquality
]
194 more_opts
+= ['-b:a' if uses_avconv
else '-ab', self
._preferredquality
+ 'k']
196 # We convert the audio (lossy)
197 acodec
= {'mp3': 'libmp3lame', 'aac': 'aac', 'm4a': 'aac', 'opus': 'opus', 'vorbis': 'libvorbis', 'wav': None}[self
._preferredcodec
]
198 extension
= self
._preferredcodec
200 if self
._preferredquality
is not None:
201 # The opus codec doesn't support the -aq option
202 if int(self
._preferredquality
) < 10 and extension
!= 'opus':
203 more_opts
+= ['-q:a' if uses_avconv
else '-aq', self
._preferredquality
]
205 more_opts
+= ['-b:a' if uses_avconv
else '-ab', self
._preferredquality
+ 'k']
206 if self
._preferredcodec
== 'aac':
207 more_opts
+= ['-f', 'adts']
208 if self
._preferredcodec
== 'm4a':
209 more_opts
+= ['-bsf:a' if uses_avconv
else '-absf', 'aac_adtstoasc']
210 if self
._preferredcodec
== 'vorbis':
212 if self
._preferredcodec
== 'wav':
214 more_opts
+= ['-f', 'wav']
216 prefix
, sep
, ext
= path
.rpartition('.') # not os.path.splitext, since the latter does not work on unicode in all setups
217 new_path
= prefix
+ sep
+ extension
219 # If we download foo.mp3 and convert it to... foo.mp3, then don't delete foo.mp3, silly.
221 self
._nopostoverwrites
= True
224 if self
._nopostoverwrites
and os
.path
.exists(encodeFilename(new_path
)):
225 self
._downloader
.to_screen('[youtube] Post-process file %s exists, skipping' % new_path
)
227 self
._downloader
.to_screen('[' + self
._executable
+ '] Destination: ' + new_path
)
228 self
.run_ffmpeg(path
, new_path
, acodec
, more_opts
)
230 etype
, e
, tb
= sys
.exc_info()
231 if isinstance(e
, AudioConversionError
):
232 msg
= 'audio conversion failed: ' + e
.msg
234 msg
= 'error running ' + self
._executable
235 raise PostProcessingError(msg
)
237 # Try to update the date time for extracted audio file.
238 if information
.get('filetime') is not None:
240 os
.utime(encodeFilename(new_path
), (time
.time(), information
['filetime']))
242 self
._downloader
.report_warning('Cannot update utime of audio file')
244 information
['filepath'] = new_path
245 return self
._nopostoverwrites
, information
248 class FFmpegVideoConvertorPP(FFmpegPostProcessor
):
249 def __init__(self
, downloader
=None, preferedformat
=None):
250 super(FFmpegVideoConvertorPP
, self
).__init
__(downloader
)
251 self
._preferedformat
= preferedformat
253 def run(self
, information
):
254 path
= information
['filepath']
255 prefix
, sep
, ext
= path
.rpartition('.')
256 outpath
= prefix
+ sep
+ self
._preferedformat
257 if information
['ext'] == self
._preferedformat
:
258 self
._downloader
.to_screen('[ffmpeg] Not converting video file %s - already is in target format %s' % (path
, self
._preferedformat
))
259 return True, information
260 self
._downloader
.to_screen('[' + 'ffmpeg' + '] Converting video from %s to %s, Destination: ' % (information
['ext'], self
._preferedformat
) + outpath
)
261 self
.run_ffmpeg(path
, outpath
, [])
262 information
['filepath'] = outpath
263 information
['format'] = self
._preferedformat
264 information
['ext'] = self
._preferedformat
265 return False, information
268 class FFmpegEmbedSubtitlePP(FFmpegPostProcessor
):
269 # See http://www.loc.gov/standards/iso639-2/ISO-639-2_utf-8.txt
457 def __init__(self
, downloader
=None, subtitlesformat
='srt'):
458 super(FFmpegEmbedSubtitlePP
, self
).__init
__(downloader
)
459 self
._subformat
= subtitlesformat
462 def _conver_lang_code(cls
, code
):
463 """Convert language code from ISO 639-1 to ISO 639-2/T"""
464 return cls
._lang
_map
.get(code
[:2])
466 def run(self
, information
):
467 if information
['ext'] != 'mp4':
468 self
._downloader
.to_screen('[ffmpeg] Subtitles can only be embedded in mp4 files')
469 return True, information
470 if not information
.get('subtitles'):
471 self
._downloader
.to_screen('[ffmpeg] There aren\'t any subtitles to embed')
472 return True, information
474 sub_langs
= [key
for key
in information
['subtitles']]
475 filename
= information
['filepath']
476 input_files
= [filename
] + [subtitles_filename(filename
, lang
, self
._subformat
) for lang
in sub_langs
]
481 # Don't copy the existing subtitles, we may be running the
482 # postprocessor a second time
486 for (i
, lang
) in enumerate(sub_langs
):
487 opts
.extend(['-map', '%d:0' % (i
+ 1)])
488 lang_code
= self
._conver
_lang
_code
(lang
)
489 if lang_code
is not None:
490 opts
.extend(['-metadata:s:s:%d' % i
, 'language=%s' % lang_code
])
492 temp_filename
= prepend_extension(filename
, 'temp')
493 self
._downloader
.to_screen('[ffmpeg] Embedding subtitles in \'%s\'' % filename
)
494 self
.run_ffmpeg_multiple_files(input_files
, temp_filename
, opts
)
495 os
.remove(encodeFilename(filename
))
496 os
.rename(encodeFilename(temp_filename
), encodeFilename(filename
))
498 return True, information
501 class FFmpegMetadataPP(FFmpegPostProcessor
):
504 if info
.get('title') is not None:
505 metadata
['title'] = info
['title']
506 if info
.get('upload_date') is not None:
507 metadata
['date'] = info
['upload_date']
508 if info
.get('uploader') is not None:
509 metadata
['artist'] = info
['uploader']
510 elif info
.get('uploader_id') is not None:
511 metadata
['artist'] = info
['uploader_id']
512 if info
.get('description') is not None:
513 metadata
['description'] = info
['description']
514 metadata
['comment'] = info
['description']
515 if info
.get('webpage_url') is not None:
516 metadata
['purl'] = info
['webpage_url']
519 self
._downloader
.to_screen('[ffmpeg] There isn\'t any metadata to add')
522 filename
= info
['filepath']
523 temp_filename
= prepend_extension(filename
, 'temp')
525 if info
['ext'] == 'm4a':
526 options
= ['-vn', '-acodec', 'copy']
528 options
= ['-c', 'copy']
530 for (name
, value
) in metadata
.items():
531 options
.extend(['-metadata', '%s=%s' % (name
, value
)])
533 self
._downloader
.to_screen('[ffmpeg] Adding metadata to \'%s\'' % filename
)
534 self
.run_ffmpeg(filename
, temp_filename
, options
)
535 os
.remove(encodeFilename(filename
))
536 os
.rename(encodeFilename(temp_filename
), encodeFilename(filename
))
540 class FFmpegMergerPP(FFmpegPostProcessor
):
542 filename
= info
['filepath']
543 args
= ['-c', 'copy', '-map', '0:v:0', '-map', '1:a:0']
544 self
._downloader
.to_screen('[ffmpeg] Merging formats into "%s"' % filename
)
545 self
.run_ffmpeg_multiple_files(info
['__files_to_merge'], filename
, args
)
549 class FFmpegAudioFixPP(FFmpegPostProcessor
):
551 filename
= info
['filepath']
552 temp_filename
= prepend_extension(filename
, 'temp')
554 options
= ['-vn', '-acodec', 'copy']
555 self
._downloader
.to_screen('[ffmpeg] Fixing audio file "%s"' % filename
)
556 self
.run_ffmpeg(filename
, temp_filename
, options
)
558 os
.remove(encodeFilename(filename
))
559 os
.rename(encodeFilename(temp_filename
), encodeFilename(filename
))
564 class FFmpegFixupStretchedPP(FFmpegPostProcessor
):
566 stretched_ratio
= info
.get('stretched_ratio')
567 if stretched_ratio
is None or stretched_ratio
== 1:
570 filename
= info
['filepath']
571 temp_filename
= prepend_extension(filename
, 'temp')
573 options
= ['-c', 'copy', '-aspect', '%f' % stretched_ratio
]
574 self
._downloader
.to_screen('[ffmpeg] Fixing aspect ratio in "%s"' % filename
)
575 self
.run_ffmpeg(filename
, temp_filename
, options
)
577 os
.remove(encodeFilename(filename
))
578 os
.rename(encodeFilename(temp_filename
), encodeFilename(filename
))
583 class FFmpegFixupM4aPP(FFmpegPostProcessor
):
585 if info
.get('container') != 'm4a_dash':
588 filename
= info
['filepath']
589 temp_filename
= prepend_extension(filename
, 'temp')
591 options
= ['-c', 'copy', '-f', 'mp4']
592 self
._downloader
.to_screen('[ffmpeg] Correcting container in "%s"' % filename
)
593 self
.run_ffmpeg(filename
, temp_filename
, options
)
595 os
.remove(encodeFilename(filename
))
596 os
.rename(encodeFilename(temp_filename
), encodeFilename(filename
))