7 from .common
import AudioConversionError
, PostProcessor
11 compat_subprocess_get_DEVNULL
,
21 class FFmpegPostProcessorError(PostProcessingError
):
24 class FFmpegPostProcessor(PostProcessor
):
25 def __init__(self
,downloader
=None):
26 PostProcessor
.__init
__(self
, downloader
)
27 self
._exes
= self
.detect_executables()
30 def detect_executables():
31 programs
= ['avprobe', 'avconv', 'ffmpeg', 'ffprobe']
32 return dict((program
, check_executable(program
, ['-version'])) for program
in programs
)
34 def _get_executable(self
):
35 if self
._downloader
.params
.get('prefer_ffmpeg', False):
36 return self
._exes
['ffmpeg'] or self
._exes
['avconv']
38 return self
._exes
['avconv'] or self
._exes
['ffmpeg']
40 def _uses_avconv(self
):
41 return self
._get
_executable
() == self
._exes
['avconv']
43 def run_ffmpeg_multiple_files(self
, input_paths
, out_path
, opts
):
44 if not self
._get
_executable
():
45 raise FFmpegPostProcessorError(u
'ffmpeg or avconv not found. Please install one.')
48 for path
in input_paths
:
49 files_cmd
.extend(['-i', encodeFilename(path
, True)])
50 cmd
= ([self
._get
_executable
(), '-y'] + files_cmd
52 [encodeFilename(self
._ffmpeg
_filename
_argument
(out_path
), True)])
54 if self
._downloader
.params
.get('verbose', False):
55 self
._downloader
.to_screen(u
'[debug] ffmpeg command line: %s' % shell_quote(cmd
))
56 p
= subprocess
.Popen(cmd
, stdout
=subprocess
.PIPE
, stderr
=subprocess
.PIPE
)
57 stdout
,stderr
= p
.communicate()
59 stderr
= stderr
.decode('utf-8', 'replace')
60 msg
= stderr
.strip().split('\n')[-1]
61 raise FFmpegPostProcessorError(msg
)
63 def run_ffmpeg(self
, path
, out_path
, opts
):
64 self
.run_ffmpeg_multiple_files([path
], out_path
, opts
)
66 def _ffmpeg_filename_argument(self
, fn
):
67 # ffmpeg broke --, see https://ffmpeg.org/trac/ffmpeg/ticket/2127 for details
68 if fn
.startswith(u
'-'):
73 class FFmpegExtractAudioPP(FFmpegPostProcessor
):
74 def __init__(self
, downloader
=None, preferredcodec
=None, preferredquality
=None, nopostoverwrites
=False):
75 FFmpegPostProcessor
.__init
__(self
, downloader
)
76 if preferredcodec
is None:
77 preferredcodec
= 'best'
78 self
._preferredcodec
= preferredcodec
79 self
._preferredquality
= preferredquality
80 self
._nopostoverwrites
= nopostoverwrites
82 def get_audio_codec(self
, path
):
83 if not self
._exes
['ffprobe'] and not self
._exes
['avprobe']:
84 raise PostProcessingError(u
'ffprobe or avprobe not found. Please install one.')
87 self
._exes
['avprobe'] or self
._exes
['ffprobe'],
89 encodeFilename(self
._ffmpeg
_filename
_argument
(path
), True)]
90 handle
= subprocess
.Popen(cmd
, stderr
=compat_subprocess_get_DEVNULL(), stdout
=subprocess
.PIPE
)
91 output
= handle
.communicate()[0]
92 if handle
.wait() != 0:
94 except (IOError, OSError):
97 for line
in output
.decode('ascii', 'ignore').split('\n'):
98 if line
.startswith('codec_name='):
99 audio_codec
= line
.split('=')[1].strip()
100 elif line
.strip() == 'codec_type=audio' and audio_codec
is not None:
104 def run_ffmpeg(self
, path
, out_path
, codec
, more_opts
):
108 acodec_opts
= ['-acodec', codec
]
109 opts
= ['-vn'] + acodec_opts
+ more_opts
111 FFmpegPostProcessor
.run_ffmpeg(self
, path
, out_path
, opts
)
112 except FFmpegPostProcessorError
as err
:
113 raise AudioConversionError(err
.msg
)
115 def run(self
, information
):
116 path
= information
['filepath']
118 filecodec
= self
.get_audio_codec(path
)
119 if filecodec
is None:
120 raise PostProcessingError(u
'WARNING: unable to obtain file audio codec with ffprobe')
122 uses_avconv
= self
._uses
_avconv
()
124 if self
._preferredcodec
== 'best' or self
._preferredcodec
== filecodec
or (self
._preferredcodec
== 'm4a' and filecodec
== 'aac'):
125 if filecodec
== 'aac' and self
._preferredcodec
in ['m4a', 'best']:
126 # Lossless, but in another container
129 more_opts
= ['-bsf:a' if uses_avconv
else '-absf', 'aac_adtstoasc']
130 elif filecodec
in ['aac', 'mp3', 'vorbis', 'opus']:
131 # Lossless if possible
133 extension
= filecodec
134 if filecodec
== 'aac':
135 more_opts
= ['-f', 'adts']
136 if filecodec
== 'vorbis':
140 acodec
= 'libmp3lame'
143 if self
._preferredquality
is not None:
144 if int(self
._preferredquality
) < 10:
145 more_opts
+= ['-q:a' if uses_avconv
else '-aq', self
._preferredquality
]
147 more_opts
+= ['-b:a' if uses_avconv
else '-ab', self
._preferredquality
+ 'k']
149 # We convert the audio (lossy)
150 acodec
= {'mp3': 'libmp3lame', 'aac': 'aac', 'm4a': 'aac', 'opus': 'opus', 'vorbis': 'libvorbis', 'wav': None}[self
._preferredcodec
]
151 extension
= self
._preferredcodec
153 if self
._preferredquality
is not None:
154 # The opus codec doesn't support the -aq option
155 if int(self
._preferredquality
) < 10 and extension
!= 'opus':
156 more_opts
+= ['-q:a' if uses_avconv
else '-aq', self
._preferredquality
]
158 more_opts
+= ['-b:a' if uses_avconv
else '-ab', self
._preferredquality
+ 'k']
159 if self
._preferredcodec
== 'aac':
160 more_opts
+= ['-f', 'adts']
161 if self
._preferredcodec
== 'm4a':
162 more_opts
+= ['-bsf:a' if uses_avconv
else '-absf', 'aac_adtstoasc']
163 if self
._preferredcodec
== 'vorbis':
165 if self
._preferredcodec
== 'wav':
167 more_opts
+= ['-f', 'wav']
169 prefix
, sep
, ext
= path
.rpartition(u
'.') # not os.path.splitext, since the latter does not work on unicode in all setups
170 new_path
= prefix
+ sep
+ extension
172 # If we download foo.mp3 and convert it to... foo.mp3, then don't delete foo.mp3, silly.
174 self
._nopostoverwrites
= True
177 if self
._nopostoverwrites
and os
.path
.exists(encodeFilename(new_path
)):
178 self
._downloader
.to_screen(u
'[youtube] Post-process file %s exists, skipping' % new_path
)
180 self
._downloader
.to_screen(u
'[' + self
._get
_executable
() + '] Destination: ' + new_path
)
181 self
.run_ffmpeg(path
, new_path
, acodec
, more_opts
)
183 etype
,e
,tb
= sys
.exc_info()
184 if isinstance(e
, AudioConversionError
):
185 msg
= u
'audio conversion failed: ' + e
.msg
187 msg
= u
'error running ' + self
._get
_executable
()
188 raise PostProcessingError(msg
)
190 # Try to update the date time for extracted audio file.
191 if information
.get('filetime') is not None:
193 os
.utime(encodeFilename(new_path
), (time
.time(), information
['filetime']))
195 self
._downloader
.report_warning(u
'Cannot update utime of audio file')
197 information
['filepath'] = new_path
198 return self
._nopostoverwrites
,information
201 class FFmpegVideoConvertor(FFmpegPostProcessor
):
202 def __init__(self
, downloader
=None,preferedformat
=None):
203 super(FFmpegVideoConvertor
, self
).__init
__(downloader
)
204 self
._preferedformat
=preferedformat
206 def run(self
, information
):
207 path
= information
['filepath']
208 prefix
, sep
, ext
= path
.rpartition(u
'.')
209 outpath
= prefix
+ sep
+ self
._preferedformat
210 if information
['ext'] == self
._preferedformat
:
211 self
._downloader
.to_screen(u
'[ffmpeg] Not converting video file %s - already is in target format %s' % (path
, self
._preferedformat
))
212 return True,information
213 self
._downloader
.to_screen(u
'['+'ffmpeg'+'] Converting video from %s to %s, Destination: ' % (information
['ext'], self
._preferedformat
) +outpath
)
214 self
.run_ffmpeg(path
, outpath
, [])
215 information
['filepath'] = outpath
216 information
['format'] = self
._preferedformat
217 information
['ext'] = self
._preferedformat
218 return False,information
221 class FFmpegEmbedSubtitlePP(FFmpegPostProcessor
):
222 # See http://www.loc.gov/standards/iso639-2/ISO-639-2_utf-8.txt
410 def __init__(self
, downloader
=None, subtitlesformat
='srt'):
411 super(FFmpegEmbedSubtitlePP
, self
).__init
__(downloader
)
412 self
._subformat
= subtitlesformat
415 def _conver_lang_code(cls
, code
):
416 """Convert language code from ISO 639-1 to ISO 639-2/T"""
417 return cls
._lang
_map
.get(code
[:2])
419 def run(self
, information
):
420 if information
['ext'] != u
'mp4':
421 self
._downloader
.to_screen(u
'[ffmpeg] Subtitles can only be embedded in mp4 files')
422 return True, information
423 if not information
.get('subtitles'):
424 self
._downloader
.to_screen(u
'[ffmpeg] There aren\'t any subtitles to embed')
425 return True, information
427 sub_langs
= [key
for key
in information
['subtitles']]
428 filename
= information
['filepath']
429 input_files
= [filename
] + [subtitles_filename(filename
, lang
, self
._subformat
) for lang
in sub_langs
]
431 opts
= ['-map', '0:0', '-map', '0:1', '-c:v', 'copy', '-c:a', 'copy']
432 for (i
, lang
) in enumerate(sub_langs
):
433 opts
.extend(['-map', '%d:0' % (i
+1), '-c:s:%d' % i
, 'mov_text'])
434 lang_code
= self
._conver
_lang
_code
(lang
)
435 if lang_code
is not None:
436 opts
.extend(['-metadata:s:s:%d' % i
, 'language=%s' % lang_code
])
437 opts
.extend(['-f', 'mp4'])
439 temp_filename
= filename
+ u
'.temp'
440 self
._downloader
.to_screen(u
'[ffmpeg] Embedding subtitles in \'%s\'' % filename
)
441 self
.run_ffmpeg_multiple_files(input_files
, temp_filename
, opts
)
442 os
.remove(encodeFilename(filename
))
443 os
.rename(encodeFilename(temp_filename
), encodeFilename(filename
))
445 return True, information
448 class FFmpegMetadataPP(FFmpegPostProcessor
):
451 if info
.get('title') is not None:
452 metadata
['title'] = info
['title']
453 if info
.get('upload_date') is not None:
454 metadata
['date'] = info
['upload_date']
455 if info
.get('uploader') is not None:
456 metadata
['artist'] = info
['uploader']
457 elif info
.get('uploader_id') is not None:
458 metadata
['artist'] = info
['uploader_id']
461 self
._downloader
.to_screen(u
'[ffmpeg] There isn\'t any metadata to add')
464 filename
= info
['filepath']
465 temp_filename
= prepend_extension(filename
, 'temp')
467 options
= ['-c', 'copy']
468 for (name
, value
) in metadata
.items():
469 options
.extend(['-metadata', '%s=%s' % (name
, value
)])
471 self
._downloader
.to_screen(u
'[ffmpeg] Adding metadata to \'%s\'' % filename
)
472 self
.run_ffmpeg(filename
, temp_filename
, options
)
473 os
.remove(encodeFilename(filename
))
474 os
.rename(encodeFilename(temp_filename
), encodeFilename(filename
))
478 class FFmpegMergerPP(FFmpegPostProcessor
):
480 filename
= info
['filepath']
481 args
= ['-c', 'copy']
482 self
._downloader
.to_screen(u
'[ffmpeg] Merging formats into "%s"' % filename
)
483 self
.run_ffmpeg_multiple_files(info
['__files_to_merge'], filename
, args
)