8 from .common
import AudioConversionError
, PostProcessor
11 compat_subprocess_get_DEVNULL
,
22 def get_version(executable
):
23 """ Returns the version of the specified executable,
24 or False if the executable is not present """
26 out
, err
= subprocess
.Popen(
27 [executable
, '-version'],
28 stdout
=subprocess
.PIPE
, stderr
=subprocess
.STDOUT
).communicate()
31 firstline
= out
.partition(b
'\n')[0].decode('ascii', 'ignore')
32 m
= re
.search(r
'version\s+([0-9._-a-zA-Z]+)', firstline
)
39 class FFmpegPostProcessorError(PostProcessingError
):
43 class FFmpegPostProcessor(PostProcessor
):
44 def __init__(self
, downloader
=None, deletetempfiles
=False):
45 PostProcessor
.__init
__(self
, downloader
)
46 self
._versions
= self
.get_versions()
47 self
._deletetempfiles
= deletetempfiles
49 def check_version(self
):
50 if not self
._executable
:
51 raise FFmpegPostProcessorError(u
'ffmpeg or avconv not found. Please install one.')
53 REQUIRED_VERSION
= '1.0'
54 if is_outdated_version(
55 self
._versions
[self
._executable
], REQUIRED_VERSION
):
56 warning
= u
'Your copy of %s is outdated, update %s to version %s or newer if you encounter any errors.' % (
57 self
._executable
, self
._executable
, REQUIRED_VERSION
)
59 self
._downloader
.report_warning(warning
)
63 programs
= ['avprobe', 'avconv', 'ffmpeg', 'ffprobe']
64 return dict((program
, get_version(program
)) for program
in programs
)
67 def _executable(self
):
68 if self
._downloader
.params
.get('prefer_ffmpeg', False):
69 prefs
= ('ffmpeg', 'avconv')
71 prefs
= ('avconv', 'ffmpeg')
78 def _probe_executable(self
):
79 if self
._downloader
.params
.get('prefer_ffmpeg', False):
80 prefs
= ('ffprobe', 'avprobe')
82 prefs
= ('avprobe', 'ffprobe')
88 def _uses_avconv(self
):
89 return self
._executable
== 'avconv'
91 def run_ffmpeg_multiple_files(self
, input_paths
, out_path
, opts
):
95 for path
in input_paths
:
96 files_cmd
.extend(['-i', encodeFilename(path
, True)])
97 cmd
= ([self
._executable
, '-y'] + files_cmd
98 + [encodeArgument(o
) for o
in opts
] +
99 [encodeFilename(self
._ffmpeg
_filename
_argument
(out_path
), True)])
101 if self
._downloader
.params
.get('verbose', False):
102 self
._downloader
.to_screen(u
'[debug] ffmpeg command line: %s' % shell_quote(cmd
))
103 p
= subprocess
.Popen(cmd
, stdout
=subprocess
.PIPE
, stderr
=subprocess
.PIPE
)
104 stdout
, stderr
= p
.communicate()
105 if p
.returncode
!= 0:
106 stderr
= stderr
.decode('utf-8', 'replace')
107 msg
= stderr
.strip().split('\n')[-1]
108 raise FFmpegPostProcessorError(msg
)
109 if self
._deletetempfiles
:
110 for ipath
in input_paths
:
113 def run_ffmpeg(self
, path
, out_path
, opts
):
114 self
.run_ffmpeg_multiple_files([path
], out_path
, opts
)
116 def _ffmpeg_filename_argument(self
, fn
):
117 # ffmpeg broke --, see https://ffmpeg.org/trac/ffmpeg/ticket/2127 for details
118 if fn
.startswith(u
'-'):
123 class FFmpegExtractAudioPP(FFmpegPostProcessor
):
124 def __init__(self
, downloader
=None, preferredcodec
=None, preferredquality
=None, nopostoverwrites
=False):
125 FFmpegPostProcessor
.__init
__(self
, downloader
)
126 if preferredcodec
is None:
127 preferredcodec
= 'best'
128 self
._preferredcodec
= preferredcodec
129 self
._preferredquality
= preferredquality
130 self
._nopostoverwrites
= nopostoverwrites
132 def get_audio_codec(self
, path
):
134 if not self
._probe
_executable
:
135 raise PostProcessingError(u
'ffprobe or avprobe not found. Please install one.')
138 self
._probe
_executable
,
140 encodeFilename(self
._ffmpeg
_filename
_argument
(path
), True)]
141 handle
= subprocess
.Popen(cmd
, stderr
=compat_subprocess_get_DEVNULL(), stdout
=subprocess
.PIPE
)
142 output
= handle
.communicate()[0]
143 if handle
.wait() != 0:
145 except (IOError, OSError):
148 for line
in output
.decode('ascii', 'ignore').split('\n'):
149 if line
.startswith('codec_name='):
150 audio_codec
= line
.split('=')[1].strip()
151 elif line
.strip() == 'codec_type=audio' and audio_codec
is not None:
155 def run_ffmpeg(self
, path
, out_path
, codec
, more_opts
):
159 acodec_opts
= ['-acodec', codec
]
160 opts
= ['-vn'] + acodec_opts
+ more_opts
162 FFmpegPostProcessor
.run_ffmpeg(self
, path
, out_path
, opts
)
163 except FFmpegPostProcessorError
as err
:
164 raise AudioConversionError(err
.msg
)
166 def run(self
, information
):
167 path
= information
['filepath']
169 filecodec
= self
.get_audio_codec(path
)
170 if filecodec
is None:
171 raise PostProcessingError(u
'WARNING: unable to obtain file audio codec with ffprobe')
173 uses_avconv
= self
._uses
_avconv
()
175 if self
._preferredcodec
== 'best' or self
._preferredcodec
== filecodec
or (self
._preferredcodec
== 'm4a' and filecodec
== 'aac'):
176 if filecodec
== 'aac' and self
._preferredcodec
in ['m4a', 'best']:
177 # Lossless, but in another container
180 more_opts
= ['-bsf:a' if uses_avconv
else '-absf', 'aac_adtstoasc']
181 elif filecodec
in ['aac', 'mp3', 'vorbis', 'opus']:
182 # Lossless if possible
184 extension
= filecodec
185 if filecodec
== 'aac':
186 more_opts
= ['-f', 'adts']
187 if filecodec
== 'vorbis':
191 acodec
= 'libmp3lame'
194 if self
._preferredquality
is not None:
195 if int(self
._preferredquality
) < 10:
196 more_opts
+= ['-q:a' if uses_avconv
else '-aq', self
._preferredquality
]
198 more_opts
+= ['-b:a' if uses_avconv
else '-ab', self
._preferredquality
+ 'k']
200 # We convert the audio (lossy)
201 acodec
= {'mp3': 'libmp3lame', 'aac': 'aac', 'm4a': 'aac', 'opus': 'opus', 'vorbis': 'libvorbis', 'wav': None}[self
._preferredcodec
]
202 extension
= self
._preferredcodec
204 if self
._preferredquality
is not None:
205 # The opus codec doesn't support the -aq option
206 if int(self
._preferredquality
) < 10 and extension
!= 'opus':
207 more_opts
+= ['-q:a' if uses_avconv
else '-aq', self
._preferredquality
]
209 more_opts
+= ['-b:a' if uses_avconv
else '-ab', self
._preferredquality
+ 'k']
210 if self
._preferredcodec
== 'aac':
211 more_opts
+= ['-f', 'adts']
212 if self
._preferredcodec
== 'm4a':
213 more_opts
+= ['-bsf:a' if uses_avconv
else '-absf', 'aac_adtstoasc']
214 if self
._preferredcodec
== 'vorbis':
216 if self
._preferredcodec
== 'wav':
218 more_opts
+= ['-f', 'wav']
220 prefix
, sep
, ext
= path
.rpartition(u
'.') # not os.path.splitext, since the latter does not work on unicode in all setups
221 new_path
= prefix
+ sep
+ extension
223 # If we download foo.mp3 and convert it to... foo.mp3, then don't delete foo.mp3, silly.
225 self
._nopostoverwrites
= True
228 if self
._nopostoverwrites
and os
.path
.exists(encodeFilename(new_path
)):
229 self
._downloader
.to_screen(u
'[youtube] Post-process file %s exists, skipping' % new_path
)
231 self
._downloader
.to_screen(u
'[' + self
._executable
+ '] Destination: ' + new_path
)
232 self
.run_ffmpeg(path
, new_path
, acodec
, more_opts
)
234 etype
,e
,tb
= sys
.exc_info()
235 if isinstance(e
, AudioConversionError
):
236 msg
= u
'audio conversion failed: ' + e
.msg
238 msg
= u
'error running ' + self
._executable
239 raise PostProcessingError(msg
)
241 # Try to update the date time for extracted audio file.
242 if information
.get('filetime') is not None:
244 os
.utime(encodeFilename(new_path
), (time
.time(), information
['filetime']))
246 self
._downloader
.report_warning(u
'Cannot update utime of audio file')
248 information
['filepath'] = new_path
249 return self
._nopostoverwrites
,information
252 class FFmpegVideoConvertor(FFmpegPostProcessor
):
253 def __init__(self
, downloader
=None,preferedformat
=None):
254 super(FFmpegVideoConvertor
, self
).__init
__(downloader
)
255 self
._preferedformat
=preferedformat
257 def run(self
, information
):
258 path
= information
['filepath']
259 prefix
, sep
, ext
= path
.rpartition(u
'.')
260 outpath
= prefix
+ sep
+ self
._preferedformat
261 if information
['ext'] == self
._preferedformat
:
262 self
._downloader
.to_screen(u
'[ffmpeg] Not converting video file %s - already is in target format %s' % (path
, self
._preferedformat
))
263 return True,information
264 self
._downloader
.to_screen(u
'['+'ffmpeg'+'] Converting video from %s to %s, Destination: ' % (information
['ext'], self
._preferedformat
) +outpath
)
265 self
.run_ffmpeg(path
, outpath
, [])
266 information
['filepath'] = outpath
267 information
['format'] = self
._preferedformat
268 information
['ext'] = self
._preferedformat
269 return False,information
272 class FFmpegEmbedSubtitlePP(FFmpegPostProcessor
):
273 # See http://www.loc.gov/standards/iso639-2/ISO-639-2_utf-8.txt
461 def __init__(self
, downloader
=None, subtitlesformat
='srt'):
462 super(FFmpegEmbedSubtitlePP
, self
).__init
__(downloader
)
463 self
._subformat
= subtitlesformat
466 def _conver_lang_code(cls
, code
):
467 """Convert language code from ISO 639-1 to ISO 639-2/T"""
468 return cls
._lang
_map
.get(code
[:2])
470 def run(self
, information
):
471 if information
['ext'] != u
'mp4':
472 self
._downloader
.to_screen(u
'[ffmpeg] Subtitles can only be embedded in mp4 files')
473 return True, information
474 if not information
.get('subtitles'):
475 self
._downloader
.to_screen(u
'[ffmpeg] There aren\'t any subtitles to embed')
476 return True, information
478 sub_langs
= [key
for key
in information
['subtitles']]
479 filename
= information
['filepath']
480 input_files
= [filename
] + [subtitles_filename(filename
, lang
, self
._subformat
) for lang
in sub_langs
]
482 opts
= ['-map', '0:0', '-map', '0:1', '-c:v', 'copy', '-c:a', 'copy']
483 for (i
, lang
) in enumerate(sub_langs
):
484 opts
.extend(['-map', '%d:0' % (i
+1), '-c:s:%d' % i
, 'mov_text'])
485 lang_code
= self
._conver
_lang
_code
(lang
)
486 if lang_code
is not None:
487 opts
.extend(['-metadata:s:s:%d' % i
, 'language=%s' % lang_code
])
488 opts
.extend(['-f', 'mp4'])
490 temp_filename
= filename
+ u
'.temp'
491 self
._downloader
.to_screen(u
'[ffmpeg] Embedding subtitles in \'%s\'' % filename
)
492 self
.run_ffmpeg_multiple_files(input_files
, temp_filename
, opts
)
493 os
.remove(encodeFilename(filename
))
494 os
.rename(encodeFilename(temp_filename
), encodeFilename(filename
))
496 return True, information
499 class FFmpegMetadataPP(FFmpegPostProcessor
):
502 if info
.get('title') is not None:
503 metadata
['title'] = info
['title']
504 if info
.get('upload_date') is not None:
505 metadata
['date'] = info
['upload_date']
506 if info
.get('uploader') is not None:
507 metadata
['artist'] = info
['uploader']
508 elif info
.get('uploader_id') is not None:
509 metadata
['artist'] = info
['uploader_id']
512 self
._downloader
.to_screen(u
'[ffmpeg] There isn\'t any metadata to add')
515 filename
= info
['filepath']
516 temp_filename
= prepend_extension(filename
, 'temp')
518 if info
['ext'] == u
'm4a':
519 options
= ['-vn', '-acodec', 'copy']
521 options
= ['-c', 'copy']
523 for (name
, value
) in metadata
.items():
524 options
.extend(['-metadata', '%s=%s' % (name
, value
)])
526 self
._downloader
.to_screen(u
'[ffmpeg] Adding metadata to \'%s\'' % filename
)
527 self
.run_ffmpeg(filename
, temp_filename
, options
)
528 os
.remove(encodeFilename(filename
))
529 os
.rename(encodeFilename(temp_filename
), encodeFilename(filename
))
533 class FFmpegMergerPP(FFmpegPostProcessor
):
535 filename
= info
['filepath']
536 args
= ['-c', 'copy', '-map', '0:v:0', '-map', '1:a:0', '-shortest']
537 self
._downloader
.to_screen(u
'[ffmpeg] Merging formats into "%s"' % filename
)
538 self
.run_ffmpeg_multiple_files(info
['__files_to_merge'], filename
, args
)
542 class FFmpegAudioFixPP(FFmpegPostProcessor
):
544 filename
= info
['filepath']
545 temp_filename
= prepend_extension(filename
, 'temp')
547 options
= ['-vn', '-acodec', 'copy']
548 self
._downloader
.to_screen(u
'[ffmpeg] Fixing audio file "%s"' % filename
)
549 self
.run_ffmpeg(filename
, temp_filename
, options
)
551 os
.remove(encodeFilename(filename
))
552 os
.rename(encodeFilename(temp_filename
), encodeFilename(filename
))