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
= '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
)
54 def _executable(self
):
55 if self
._downloader
.params
.get('prefer_ffmpeg', False):
56 prefs
= ('ffmpeg', 'avconv')
58 prefs
= ('avconv', 'ffmpeg')
65 def _probe_executable(self
):
66 if self
._downloader
.params
.get('prefer_ffmpeg', False):
67 prefs
= ('ffprobe', 'avprobe')
69 prefs
= ('avprobe', 'ffprobe')
75 def _uses_avconv(self
):
76 return self
._executable
== 'avconv'
78 def run_ffmpeg_multiple_files(self
, input_paths
, out_path
, opts
):
82 for path
in input_paths
:
83 files_cmd
.extend(['-i', encodeFilename(path
, True)])
84 cmd
= ([self
._executable
, '-y'] + files_cmd
85 + [encodeArgument(o
) for o
in opts
] +
86 [encodeFilename(self
._ffmpeg
_filename
_argument
(out_path
), True)])
88 if self
._downloader
.params
.get('verbose', False):
89 self
._downloader
.to_screen('[debug] ffmpeg command line: %s' % shell_quote(cmd
))
90 p
= subprocess
.Popen(cmd
, stdout
=subprocess
.PIPE
, stderr
=subprocess
.PIPE
)
91 stdout
, stderr
= p
.communicate()
93 stderr
= stderr
.decode('utf-8', 'replace')
94 msg
= stderr
.strip().split('\n')[-1]
95 raise FFmpegPostProcessorError(msg
)
96 if self
._deletetempfiles
:
97 for ipath
in input_paths
:
100 def run_ffmpeg(self
, path
, out_path
, opts
):
101 self
.run_ffmpeg_multiple_files([path
], out_path
, opts
)
103 def _ffmpeg_filename_argument(self
, fn
):
104 # ffmpeg broke --, see https://ffmpeg.org/trac/ffmpeg/ticket/2127 for details
105 if fn
.startswith('-'):
110 class FFmpegExtractAudioPP(FFmpegPostProcessor
):
111 def __init__(self
, downloader
=None, preferredcodec
=None, preferredquality
=None, nopostoverwrites
=False):
112 FFmpegPostProcessor
.__init
__(self
, downloader
)
113 if preferredcodec
is None:
114 preferredcodec
= 'best'
115 self
._preferredcodec
= preferredcodec
116 self
._preferredquality
= preferredquality
117 self
._nopostoverwrites
= nopostoverwrites
119 def get_audio_codec(self
, path
):
121 if not self
._probe
_executable
:
122 raise PostProcessingError('ffprobe or avprobe not found. Please install one.')
125 self
._probe
_executable
,
127 encodeFilename(self
._ffmpeg
_filename
_argument
(path
), True)]
128 handle
= subprocess
.Popen(cmd
, stderr
=compat_subprocess_get_DEVNULL(), stdout
=subprocess
.PIPE
)
129 output
= handle
.communicate()[0]
130 if handle
.wait() != 0:
132 except (IOError, OSError):
135 for line
in output
.decode('ascii', 'ignore').split('\n'):
136 if line
.startswith('codec_name='):
137 audio_codec
= line
.split('=')[1].strip()
138 elif line
.strip() == 'codec_type=audio' and audio_codec
is not None:
142 def run_ffmpeg(self
, path
, out_path
, codec
, more_opts
):
146 acodec_opts
= ['-acodec', codec
]
147 opts
= ['-vn'] + acodec_opts
+ more_opts
149 FFmpegPostProcessor
.run_ffmpeg(self
, path
, out_path
, opts
)
150 except FFmpegPostProcessorError
as err
:
151 raise AudioConversionError(err
.msg
)
153 def run(self
, information
):
154 path
= information
['filepath']
156 filecodec
= self
.get_audio_codec(path
)
157 if filecodec
is None:
158 raise PostProcessingError('WARNING: unable to obtain file audio codec with ffprobe')
160 uses_avconv
= self
._uses
_avconv
()
162 if self
._preferredcodec
== 'best' or self
._preferredcodec
== filecodec
or (self
._preferredcodec
== 'm4a' and filecodec
== 'aac'):
163 if filecodec
== 'aac' and self
._preferredcodec
in ['m4a', 'best']:
164 # Lossless, but in another container
167 more_opts
= ['-bsf:a' if uses_avconv
else '-absf', 'aac_adtstoasc']
168 elif filecodec
in ['aac', 'mp3', 'vorbis', 'opus']:
169 # Lossless if possible
171 extension
= filecodec
172 if filecodec
== 'aac':
173 more_opts
= ['-f', 'adts']
174 if filecodec
== 'vorbis':
178 acodec
= 'libmp3lame'
181 if self
._preferredquality
is not None:
182 if int(self
._preferredquality
) < 10:
183 more_opts
+= ['-q:a' if uses_avconv
else '-aq', self
._preferredquality
]
185 more_opts
+= ['-b:a' if uses_avconv
else '-ab', self
._preferredquality
+ 'k']
187 # We convert the audio (lossy)
188 acodec
= {'mp3': 'libmp3lame', 'aac': 'aac', 'm4a': 'aac', 'opus': 'opus', 'vorbis': 'libvorbis', 'wav': None}[self
._preferredcodec
]
189 extension
= self
._preferredcodec
191 if self
._preferredquality
is not None:
192 # The opus codec doesn't support the -aq option
193 if int(self
._preferredquality
) < 10 and extension
!= 'opus':
194 more_opts
+= ['-q:a' if uses_avconv
else '-aq', self
._preferredquality
]
196 more_opts
+= ['-b:a' if uses_avconv
else '-ab', self
._preferredquality
+ 'k']
197 if self
._preferredcodec
== 'aac':
198 more_opts
+= ['-f', 'adts']
199 if self
._preferredcodec
== 'm4a':
200 more_opts
+= ['-bsf:a' if uses_avconv
else '-absf', 'aac_adtstoasc']
201 if self
._preferredcodec
== 'vorbis':
203 if self
._preferredcodec
== 'wav':
205 more_opts
+= ['-f', 'wav']
207 prefix
, sep
, ext
= path
.rpartition('.') # not os.path.splitext, since the latter does not work on unicode in all setups
208 new_path
= prefix
+ sep
+ extension
210 # If we download foo.mp3 and convert it to... foo.mp3, then don't delete foo.mp3, silly.
212 self
._nopostoverwrites
= True
215 if self
._nopostoverwrites
and os
.path
.exists(encodeFilename(new_path
)):
216 self
._downloader
.to_screen('[youtube] Post-process file %s exists, skipping' % new_path
)
218 self
._downloader
.to_screen('[' + self
._executable
+ '] Destination: ' + new_path
)
219 self
.run_ffmpeg(path
, new_path
, acodec
, more_opts
)
221 etype
, e
, tb
= sys
.exc_info()
222 if isinstance(e
, AudioConversionError
):
223 msg
= 'audio conversion failed: ' + e
.msg
225 msg
= 'error running ' + self
._executable
226 raise PostProcessingError(msg
)
228 # Try to update the date time for extracted audio file.
229 if information
.get('filetime') is not None:
231 os
.utime(encodeFilename(new_path
), (time
.time(), information
['filetime']))
233 self
._downloader
.report_warning('Cannot update utime of audio file')
235 information
['filepath'] = new_path
236 return self
._nopostoverwrites
, information
239 class FFmpegVideoConvertor(FFmpegPostProcessor
):
240 def __init__(self
, downloader
=None, preferedformat
=None):
241 super(FFmpegVideoConvertor
, self
).__init
__(downloader
)
242 self
._preferedformat
= preferedformat
244 def run(self
, information
):
245 path
= information
['filepath']
246 prefix
, sep
, ext
= path
.rpartition('.')
247 outpath
= prefix
+ sep
+ self
._preferedformat
248 if information
['ext'] == self
._preferedformat
:
249 self
._downloader
.to_screen('[ffmpeg] Not converting video file %s - already is in target format %s' % (path
, self
._preferedformat
))
250 return True, information
251 self
._downloader
.to_screen('[' + 'ffmpeg' + '] Converting video from %s to %s, Destination: ' % (information
['ext'], self
._preferedformat
) + outpath
)
252 self
.run_ffmpeg(path
, outpath
, [])
253 information
['filepath'] = outpath
254 information
['format'] = self
._preferedformat
255 information
['ext'] = self
._preferedformat
256 return False, information
259 class FFmpegEmbedSubtitlePP(FFmpegPostProcessor
):
260 # See http://www.loc.gov/standards/iso639-2/ISO-639-2_utf-8.txt
448 def __init__(self
, downloader
=None, subtitlesformat
='srt'):
449 super(FFmpegEmbedSubtitlePP
, self
).__init
__(downloader
)
450 self
._subformat
= subtitlesformat
453 def _conver_lang_code(cls
, code
):
454 """Convert language code from ISO 639-1 to ISO 639-2/T"""
455 return cls
._lang
_map
.get(code
[:2])
457 def run(self
, information
):
458 if information
['ext'] != 'mp4':
459 self
._downloader
.to_screen('[ffmpeg] Subtitles can only be embedded in mp4 files')
460 return True, information
461 if not information
.get('subtitles'):
462 self
._downloader
.to_screen('[ffmpeg] There aren\'t any subtitles to embed')
463 return True, information
465 sub_langs
= [key
for key
in information
['subtitles']]
466 filename
= information
['filepath']
467 input_files
= [filename
] + [subtitles_filename(filename
, lang
, self
._subformat
) for lang
in sub_langs
]
469 opts
= ['-map', '0:0', '-map', '0:1', '-c:v', 'copy', '-c:a', 'copy']
470 for (i
, lang
) in enumerate(sub_langs
):
471 opts
.extend(['-map', '%d:0' % (i
+ 1), '-c:s:%d' % i
, 'mov_text'])
472 lang_code
= self
._conver
_lang
_code
(lang
)
473 if lang_code
is not None:
474 opts
.extend(['-metadata:s:s:%d' % i
, 'language=%s' % lang_code
])
475 opts
.extend(['-f', 'mp4'])
477 temp_filename
= filename
+ '.temp'
478 self
._downloader
.to_screen('[ffmpeg] Embedding subtitles in \'%s\'' % filename
)
479 self
.run_ffmpeg_multiple_files(input_files
, temp_filename
, opts
)
480 os
.remove(encodeFilename(filename
))
481 os
.rename(encodeFilename(temp_filename
), encodeFilename(filename
))
483 return True, information
486 class FFmpegMetadataPP(FFmpegPostProcessor
):
489 if info
.get('title') is not None:
490 metadata
['title'] = info
['title']
491 if info
.get('upload_date') is not None:
492 metadata
['date'] = info
['upload_date']
493 if info
.get('uploader') is not None:
494 metadata
['artist'] = info
['uploader']
495 elif info
.get('uploader_id') is not None:
496 metadata
['artist'] = info
['uploader_id']
499 self
._downloader
.to_screen('[ffmpeg] There isn\'t any metadata to add')
502 filename
= info
['filepath']
503 temp_filename
= prepend_extension(filename
, 'temp')
505 if info
['ext'] == 'm4a':
506 options
= ['-vn', '-acodec', 'copy']
508 options
= ['-c', 'copy']
510 for (name
, value
) in metadata
.items():
511 options
.extend(['-metadata', '%s=%s' % (name
, value
)])
513 self
._downloader
.to_screen('[ffmpeg] Adding metadata to \'%s\'' % filename
)
514 self
.run_ffmpeg(filename
, temp_filename
, options
)
515 os
.remove(encodeFilename(filename
))
516 os
.rename(encodeFilename(temp_filename
), encodeFilename(filename
))
520 class FFmpegMergerPP(FFmpegPostProcessor
):
522 filename
= info
['filepath']
523 args
= ['-c', 'copy', '-map', '0:v:0', '-map', '1:a:0', '-shortest']
524 self
._downloader
.to_screen('[ffmpeg] Merging formats into "%s"' % filename
)
525 self
.run_ffmpeg_multiple_files(info
['__files_to_merge'], filename
, args
)
529 class FFmpegAudioFixPP(FFmpegPostProcessor
):
531 filename
= info
['filepath']
532 temp_filename
= prepend_extension(filename
, 'temp')
534 options
= ['-vn', '-acodec', 'copy']
535 self
._downloader
.to_screen('[ffmpeg] Fixing audio file "%s"' % filename
)
536 self
.run_ffmpeg(filename
, temp_filename
, options
)
538 os
.remove(encodeFilename(filename
))
539 os
.rename(encodeFilename(temp_filename
), encodeFilename(filename
))