]>
Commit | Line | Data |
---|---|---|
3aa578ca PH |
1 | from __future__ import unicode_literals |
2 | ||
e9fade72 | 3 | import io |
496c1923 PH |
4 | import os |
5 | import subprocess | |
496c1923 PH |
6 | import time |
7 | ||
8 | ||
9 | from .common import AudioConversionError, PostProcessor | |
10 | ||
8c25f81b | 11 | from ..compat import ( |
496c1923 | 12 | compat_subprocess_get_DEVNULL, |
8c25f81b PH |
13 | ) |
14 | from ..utils import ( | |
f07b74fc | 15 | encodeArgument, |
496c1923 | 16 | encodeFilename, |
95807118 | 17 | get_exe_version, |
48844745 | 18 | is_outdated_version, |
496c1923 PH |
19 | PostProcessingError, |
20 | prepend_extension, | |
21 | shell_quote, | |
22 | subtitles_filename, | |
bf6427d2 | 23 | dfxp2srt, |
39672624 | 24 | ISO639Utils, |
496c1923 PH |
25 | ) |
26 | ||
27 | ||
a755f825 | 28 | EXT_TO_OUT_FORMATS = { |
21bfcd3d PH |
29 | 'aac': 'adts', |
30 | 'flac': 'flac', | |
31 | 'm4a': 'ipod', | |
32 | 'mka': 'matroska', | |
33 | 'mkv': 'matroska', | |
34 | 'mpg': 'mpeg', | |
35 | 'ogv': 'ogg', | |
36 | 'ts': 'mpegts', | |
37 | 'wma': 'asf', | |
38 | 'wmv': 'asf', | |
39 | } | |
40 | ACODECS = { | |
41 | 'mp3': 'libmp3lame', | |
42 | 'aac': 'aac', | |
43 | 'flac': 'flac', | |
44 | 'm4a': 'aac', | |
45 | 'opus': 'opus', | |
46 | 'vorbis': 'libvorbis', | |
47 | 'wav': None, | |
a755f825 | 48 | } |
49 | ||
50 | ||
496c1923 PH |
51 | class FFmpegPostProcessorError(PostProcessingError): |
52 | pass | |
53 | ||
d799b47b | 54 | |
496c1923 | 55 | class FFmpegPostProcessor(PostProcessor): |
d47aeb22 | 56 | def __init__(self, downloader=None): |
496c1923 | 57 | PostProcessor.__init__(self, downloader) |
73fac4e9 | 58 | self._determine_executables() |
496c1923 | 59 | |
48844745 | 60 | def check_version(self): |
f740fae2 | 61 | if not self.available: |
3aa578ca | 62 | raise FFmpegPostProcessorError('ffmpeg or avconv not found. Please install one.') |
48844745 | 63 | |
65bf37ef | 64 | required_version = '10-0' if self.basename == 'avconv' else '1.0' |
48844745 | 65 | if is_outdated_version( |
73fac4e9 | 66 | self._versions[self.basename], required_version): |
3aa578ca | 67 | warning = 'Your copy of %s is outdated, update %s to version %s or newer if you encounter any errors.' % ( |
73fac4e9 | 68 | self.basename, self.basename, required_version) |
6194bb14 PH |
69 | if self._downloader: |
70 | self._downloader.report_warning(warning) | |
48844745 | 71 | |
496c1923 | 72 | @staticmethod |
73fac4e9 PH |
73 | def get_versions(downloader=None): |
74 | return FFmpegPostProcessor(downloader)._versions | |
6271f1ca | 75 | |
73fac4e9 PH |
76 | def _determine_executables(self): |
77 | programs = ['avprobe', 'avconv', 'ffmpeg', 'ffprobe'] | |
374c761e | 78 | prefer_ffmpeg = False |
73fac4e9 PH |
79 | |
80 | self.basename = None | |
81 | self.probe_basename = None | |
82 | ||
83 | self._paths = None | |
84 | self._versions = None | |
85 | if self._downloader: | |
374c761e | 86 | prefer_ffmpeg = self._downloader.params.get('prefer_ffmpeg', False) |
73fac4e9 PH |
87 | location = self._downloader.params.get('ffmpeg_location') |
88 | if location is not None: | |
89 | if not os.path.exists(location): | |
90 | self._downloader.report_warning( | |
91 | 'ffmpeg-location %s does not exist! ' | |
92 | 'Continuing without avconv/ffmpeg.' % (location)) | |
93 | self._versions = {} | |
94 | return | |
95 | elif not os.path.isdir(location): | |
96 | basename = os.path.splitext(os.path.basename(location))[0] | |
97 | if basename not in programs: | |
98 | self._downloader.report_warning( | |
99 | 'Cannot identify executable %s, its basename should be one of %s. ' | |
100 | 'Continuing without avconv/ffmpeg.' % | |
101 | (location, ', '.join(programs))) | |
102 | self._versions = {} | |
103 | return None | |
104 | location = os.path.dirname(os.path.abspath(location)) | |
105 | if basename in ('ffmpeg', 'ffprobe'): | |
106 | prefer_ffmpeg = True | |
107 | ||
108 | self._paths = dict( | |
109 | (p, os.path.join(location, p)) for p in programs) | |
110 | self._versions = dict( | |
111 | (p, get_exe_version(self._paths[p], args=['-version'])) | |
112 | for p in programs) | |
113 | if self._versions is None: | |
114 | self._versions = dict( | |
115 | (p, get_exe_version(p, args=['-version'])) for p in programs) | |
116 | self._paths = dict((p, p) for p in programs) | |
117 | ||
118 | if prefer_ffmpeg: | |
d28b5171 | 119 | prefs = ('ffmpeg', 'avconv') |
76b1bd67 | 120 | else: |
d28b5171 PH |
121 | prefs = ('avconv', 'ffmpeg') |
122 | for p in prefs: | |
123 | if self._versions[p]: | |
73fac4e9 PH |
124 | self.basename = p |
125 | break | |
76b1bd67 | 126 | |
73fac4e9 | 127 | if prefer_ffmpeg: |
50b51830 | 128 | prefs = ('ffprobe', 'avprobe') |
1a253e13 PH |
129 | else: |
130 | prefs = ('avprobe', 'ffprobe') | |
131 | for p in prefs: | |
132 | if self._versions[p]: | |
73fac4e9 PH |
133 | self.probe_basename = p |
134 | break | |
135 | ||
f740fae2 | 136 | @property |
73fac4e9 PH |
137 | def available(self): |
138 | return self.basename is not None | |
1a253e13 | 139 | |
73fac4e9 PH |
140 | @property |
141 | def executable(self): | |
142 | return self._paths[self.basename] | |
143 | ||
3da4b313 JMF |
144 | @property |
145 | def probe_available(self): | |
146 | return self.probe_basename is not None | |
147 | ||
73fac4e9 PH |
148 | @property |
149 | def probe_executable(self): | |
150 | return self._paths[self.probe_basename] | |
76b1bd67 | 151 | |
30d9e209 RA |
152 | def get_audio_codec(self, path): |
153 | if not self.probe_available: | |
154 | raise PostProcessingError('ffprobe or avprobe not found. Please install one.') | |
155 | try: | |
156 | cmd = [ | |
157 | encodeFilename(self.probe_executable, True), | |
158 | encodeArgument('-show_streams'), | |
159 | encodeFilename(self._ffmpeg_filename_argument(path), True)] | |
160 | if self._downloader.params.get('verbose', False): | |
161 | self._downloader.to_screen('[debug] %s command line: %s' % (self.basename, shell_quote(cmd))) | |
162 | handle = subprocess.Popen(cmd, stderr=compat_subprocess_get_DEVNULL(), stdout=subprocess.PIPE, stdin=subprocess.PIPE) | |
163 | output = handle.communicate()[0] | |
164 | if handle.wait() != 0: | |
165 | return None | |
166 | except (IOError, OSError): | |
167 | return None | |
168 | audio_codec = None | |
169 | for line in output.decode('ascii', 'ignore').split('\n'): | |
170 | if line.startswith('codec_name='): | |
171 | audio_codec = line.split('=')[1].strip() | |
172 | elif line.strip() == 'codec_type=audio' and audio_codec is not None: | |
173 | return audio_codec | |
174 | return None | |
175 | ||
496c1923 | 176 | def run_ffmpeg_multiple_files(self, input_paths, out_path, opts): |
48844745 | 177 | self.check_version() |
496c1923 | 178 | |
52afb2ac PH |
179 | oldest_mtime = min( |
180 | os.stat(encodeFilename(path)).st_mtime for path in input_paths) | |
43bc8890 | 181 | |
15006fed S |
182 | opts += self._configuration_args() |
183 | ||
496c1923 PH |
184 | files_cmd = [] |
185 | for path in input_paths: | |
8a7bbd16 JMF |
186 | files_cmd.extend([ |
187 | encodeArgument('-i'), | |
188 | encodeFilename(self._ffmpeg_filename_argument(path), True) | |
189 | ]) | |
73fac4e9 | 190 | cmd = ([encodeFilename(self.executable, True), encodeArgument('-y')] + |
43bc8890 PH |
191 | files_cmd + |
192 | [encodeArgument(o) for o in opts] + | |
496c1923 PH |
193 | [encodeFilename(self._ffmpeg_filename_argument(out_path), True)]) |
194 | ||
195 | if self._downloader.params.get('verbose', False): | |
3aa578ca | 196 | self._downloader.to_screen('[debug] ffmpeg command line: %s' % shell_quote(cmd)) |
cffcbc02 | 197 | p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE) |
62fec3b2 | 198 | stdout, stderr = p.communicate() |
496c1923 PH |
199 | if p.returncode != 0: |
200 | stderr = stderr.decode('utf-8', 'replace') | |
201 | msg = stderr.strip().split('\n')[-1] | |
202 | raise FFmpegPostProcessorError(msg) | |
dd29eb7f | 203 | self.try_utime(out_path, oldest_mtime, oldest_mtime) |
cc55d088 | 204 | |
496c1923 PH |
205 | def run_ffmpeg(self, path, out_path, opts): |
206 | self.run_ffmpeg_multiple_files([path], out_path, opts) | |
207 | ||
208 | def _ffmpeg_filename_argument(self, fn): | |
8a7bbd16 JMF |
209 | # Always use 'file:' because the filename may contain ':' (ffmpeg |
210 | # interprets that as a protocol) or can start with '-' (-- is broken in | |
211 | # ffmpeg, see https://ffmpeg.org/trac/ffmpeg/ticket/2127 for details) | |
b9f2fdd3 | 212 | # Also leave '-' intact in order not to break streaming to stdout. |
d868f43c | 213 | return 'file:' + fn if fn != '-' else fn |
496c1923 PH |
214 | |
215 | ||
216 | class FFmpegExtractAudioPP(FFmpegPostProcessor): | |
217 | def __init__(self, downloader=None, preferredcodec=None, preferredquality=None, nopostoverwrites=False): | |
218 | FFmpegPostProcessor.__init__(self, downloader) | |
219 | if preferredcodec is None: | |
220 | preferredcodec = 'best' | |
221 | self._preferredcodec = preferredcodec | |
222 | self._preferredquality = preferredquality | |
223 | self._nopostoverwrites = nopostoverwrites | |
224 | ||
496c1923 | 225 | def run_ffmpeg(self, path, out_path, codec, more_opts): |
496c1923 PH |
226 | if codec is None: |
227 | acodec_opts = [] | |
228 | else: | |
229 | acodec_opts = ['-acodec', codec] | |
230 | opts = ['-vn'] + acodec_opts + more_opts | |
231 | try: | |
232 | FFmpegPostProcessor.run_ffmpeg(self, path, out_path, opts) | |
233 | except FFmpegPostProcessorError as err: | |
234 | raise AudioConversionError(err.msg) | |
235 | ||
236 | def run(self, information): | |
237 | path = information['filepath'] | |
238 | ||
239 | filecodec = self.get_audio_codec(path) | |
240 | if filecodec is None: | |
3aa578ca | 241 | raise PostProcessingError('WARNING: unable to obtain file audio codec with ffprobe') |
496c1923 PH |
242 | |
243 | more_opts = [] | |
244 | if self._preferredcodec == 'best' or self._preferredcodec == filecodec or (self._preferredcodec == 'm4a' and filecodec == 'aac'): | |
245 | if filecodec == 'aac' and self._preferredcodec in ['m4a', 'best']: | |
246 | # Lossless, but in another container | |
247 | acodec = 'copy' | |
248 | extension = 'm4a' | |
467d3c9a | 249 | more_opts = ['-bsf:a', 'aac_adtstoasc'] |
21bfcd3d | 250 | elif filecodec in ['aac', 'flac', 'mp3', 'vorbis', 'opus']: |
496c1923 PH |
251 | # Lossless if possible |
252 | acodec = 'copy' | |
253 | extension = filecodec | |
254 | if filecodec == 'aac': | |
255 | more_opts = ['-f', 'adts'] | |
256 | if filecodec == 'vorbis': | |
257 | extension = 'ogg' | |
258 | else: | |
259 | # MP3 otherwise. | |
260 | acodec = 'libmp3lame' | |
261 | extension = 'mp3' | |
262 | more_opts = [] | |
263 | if self._preferredquality is not None: | |
264 | if int(self._preferredquality) < 10: | |
467d3c9a | 265 | more_opts += ['-q:a', self._preferredquality] |
496c1923 | 266 | else: |
467d3c9a | 267 | more_opts += ['-b:a', self._preferredquality + 'k'] |
496c1923 | 268 | else: |
21bfcd3d PH |
269 | # We convert the audio (lossy if codec is lossy) |
270 | acodec = ACODECS[self._preferredcodec] | |
496c1923 PH |
271 | extension = self._preferredcodec |
272 | more_opts = [] | |
273 | if self._preferredquality is not None: | |
274 | # The opus codec doesn't support the -aq option | |
275 | if int(self._preferredquality) < 10 and extension != 'opus': | |
467d3c9a | 276 | more_opts += ['-q:a', self._preferredquality] |
496c1923 | 277 | else: |
467d3c9a | 278 | more_opts += ['-b:a', self._preferredquality + 'k'] |
496c1923 PH |
279 | if self._preferredcodec == 'aac': |
280 | more_opts += ['-f', 'adts'] | |
281 | if self._preferredcodec == 'm4a': | |
467d3c9a | 282 | more_opts += ['-bsf:a', 'aac_adtstoasc'] |
496c1923 PH |
283 | if self._preferredcodec == 'vorbis': |
284 | extension = 'ogg' | |
285 | if self._preferredcodec == 'wav': | |
286 | extension = 'wav' | |
287 | more_opts += ['-f', 'wav'] | |
288 | ||
3aa578ca | 289 | prefix, sep, ext = path.rpartition('.') # not os.path.splitext, since the latter does not work on unicode in all setups |
496c1923 | 290 | new_path = prefix + sep + extension |
0b94dbb1 | 291 | |
2273e2c5 PM |
292 | information['filepath'] = new_path |
293 | information['ext'] = extension | |
496c1923 PH |
294 | |
295 | # If we download foo.mp3 and convert it to... foo.mp3, then don't delete foo.mp3, silly. | |
ce81b141 JMF |
296 | if (new_path == path or |
297 | (self._nopostoverwrites and os.path.exists(encodeFilename(new_path)))): | |
9750e7d7 | 298 | self._downloader.to_screen('[ffmpeg] Post-process file %s exists, skipping' % new_path) |
592e97e8 | 299 | return [], information |
496c1923 PH |
300 | |
301 | try: | |
deb85c32 | 302 | self._downloader.to_screen('[ffmpeg] Destination: ' + new_path) |
ce81b141 | 303 | self.run_ffmpeg(path, new_path, acodec, more_opts) |
70a1165b JMF |
304 | except AudioConversionError as e: |
305 | raise PostProcessingError( | |
306 | 'audio conversion failed: ' + e.msg) | |
307 | except Exception: | |
308 | raise PostProcessingError('error running ' + self.basename) | |
496c1923 PH |
309 | |
310 | # Try to update the date time for extracted audio file. | |
311 | if information.get('filetime') is not None: | |
dd29eb7f S |
312 | self.try_utime( |
313 | new_path, time.time(), information['filetime'], | |
314 | errnote='Cannot update utime of audio file') | |
496c1923 | 315 | |
592e97e8 | 316 | return [path], information |
496c1923 PH |
317 | |
318 | ||
4f026faf | 319 | class FFmpegVideoConvertorPP(FFmpegPostProcessor): |
5f6a1245 | 320 | def __init__(self, downloader=None, preferedformat=None): |
4f026faf | 321 | super(FFmpegVideoConvertorPP, self).__init__(downloader) |
5f6a1245 | 322 | self._preferedformat = preferedformat |
496c1923 PH |
323 | |
324 | def run(self, information): | |
325 | path = information['filepath'] | |
496c1923 | 326 | if information['ext'] == self._preferedformat: |
3aa578ca | 327 | self._downloader.to_screen('[ffmpeg] Not converting video file %s - already is in target format %s' % (path, self._preferedformat)) |
592e97e8 | 328 | return [], information |
15006fed S |
329 | options = [] |
330 | if self._preferedformat == 'avi': | |
331 | options.extend(['-c:v', 'libxvid', '-vtag', 'XVID']) | |
332 | prefix, sep, ext = path.rpartition('.') | |
333 | outpath = prefix + sep + self._preferedformat | |
3aa578ca | 334 | self._downloader.to_screen('[' + 'ffmpeg' + '] Converting video from %s to %s, Destination: ' % (information['ext'], self._preferedformat) + outpath) |
d84f1d14 | 335 | self.run_ffmpeg(path, outpath, options) |
496c1923 PH |
336 | information['filepath'] = outpath |
337 | information['format'] = self._preferedformat | |
f72b0a60 | 338 | information['ext'] = self._preferedformat |
592e97e8 | 339 | return [path], information |
496c1923 PH |
340 | |
341 | ||
342 | class FFmpegEmbedSubtitlePP(FFmpegPostProcessor): | |
496c1923 | 343 | def run(self, information): |
40025ee2 S |
344 | if information['ext'] not in ('mp4', 'webm', 'mkv'): |
345 | self._downloader.to_screen('[ffmpeg] Subtitles can only be embedded in mp4, webm or mkv files') | |
592e97e8 | 346 | return [], information |
c84dd8a9 JMF |
347 | subtitles = information.get('requested_subtitles') |
348 | if not subtitles: | |
3aa578ca | 349 | self._downloader.to_screen('[ffmpeg] There aren\'t any subtitles to embed') |
592e97e8 | 350 | return [], information |
496c1923 | 351 | |
496c1923 | 352 | filename = information['filepath'] |
40025ee2 S |
353 | |
354 | ext = information['ext'] | |
355 | sub_langs = [] | |
356 | sub_filenames = [] | |
357 | webm_vtt_warn = False | |
358 | ||
359 | for lang, sub_info in subtitles.items(): | |
360 | sub_ext = sub_info['ext'] | |
361 | if ext != 'webm' or ext == 'webm' and sub_ext == 'vtt': | |
362 | sub_langs.append(lang) | |
363 | sub_filenames.append(subtitles_filename(filename, lang, sub_ext)) | |
364 | else: | |
365 | if not webm_vtt_warn and ext == 'webm' and sub_ext != 'vtt': | |
366 | webm_vtt_warn = True | |
367 | self._downloader.to_screen('[ffmpeg] Only WebVTT subtitles can be embedded in webm files') | |
368 | ||
369 | if not sub_langs: | |
370 | return [], information | |
371 | ||
14523ed9 | 372 | input_files = [filename] + sub_filenames |
496c1923 | 373 | |
e205db3b | 374 | opts = [ |
23495d6a YCH |
375 | '-map', '0', |
376 | '-c', 'copy', | |
e205db3b JMF |
377 | # Don't copy the existing subtitles, we may be running the |
378 | # postprocessor a second time | |
379 | '-map', '-0:s', | |
380 | ] | |
083c1bb9 N |
381 | if information['ext'] == 'mp4': |
382 | opts += ['-c:s', 'mov_text'] | |
496c1923 | 383 | for (i, lang) in enumerate(sub_langs): |
2875cf01 | 384 | opts.extend(['-map', '%d:0' % (i + 1)]) |
39672624 | 385 | lang_code = ISO639Utils.short2long(lang) |
496c1923 PH |
386 | if lang_code is not None: |
387 | opts.extend(['-metadata:s:s:%d' % i, 'language=%s' % lang_code]) | |
496c1923 | 388 | |
2875cf01 | 389 | temp_filename = prepend_extension(filename, 'temp') |
3aa578ca | 390 | self._downloader.to_screen('[ffmpeg] Embedding subtitles in \'%s\'' % filename) |
496c1923 PH |
391 | self.run_ffmpeg_multiple_files(input_files, temp_filename, opts) |
392 | os.remove(encodeFilename(filename)) | |
393 | os.rename(encodeFilename(temp_filename), encodeFilename(filename)) | |
394 | ||
14523ed9 | 395 | return sub_filenames, information |
496c1923 PH |
396 | |
397 | ||
398 | class FFmpegMetadataPP(FFmpegPostProcessor): | |
399 | def run(self, info): | |
400 | metadata = {} | |
4bd143a3 S |
401 | |
402 | def add(meta_list, info_list=None): | |
403 | if not info_list: | |
404 | info_list = meta_list | |
405 | if not isinstance(meta_list, (list, tuple)): | |
406 | meta_list = (meta_list,) | |
407 | if not isinstance(info_list, (list, tuple)): | |
408 | info_list = (info_list,) | |
409 | for info_f in info_list: | |
410 | if info.get(info_f) is not None: | |
411 | for meta_f in meta_list: | |
412 | metadata[meta_f] = info[info_f] | |
413 | break | |
414 | ||
415 | add('title', ('track', 'title')) | |
416 | add('date', 'upload_date') | |
417 | add(('description', 'comment'), 'description') | |
418 | add('purl', 'webpage_url') | |
419 | add('track', 'track_number') | |
420 | add('artist', ('artist', 'creator', 'uploader', 'uploader_id')) | |
421 | add('genre') | |
422 | add('album') | |
423 | add('album_artist') | |
424 | add('disc', 'disc_number') | |
496c1923 PH |
425 | |
426 | if not metadata: | |
3aa578ca | 427 | self._downloader.to_screen('[ffmpeg] There isn\'t any metadata to add') |
592e97e8 | 428 | return [], info |
496c1923 PH |
429 | |
430 | filename = info['filepath'] | |
431 | temp_filename = prepend_extension(filename, 'temp') | |
432 | ||
3aa578ca | 433 | if info['ext'] == 'm4a': |
39c68260 | 434 | options = ['-vn', '-acodec', 'copy'] |
435 | else: | |
436 | options = ['-c', 'copy'] | |
437 | ||
496c1923 PH |
438 | for (name, value) in metadata.items(): |
439 | options.extend(['-metadata', '%s=%s' % (name, value)]) | |
440 | ||
3aa578ca | 441 | self._downloader.to_screen('[ffmpeg] Adding metadata to \'%s\'' % filename) |
496c1923 PH |
442 | self.run_ffmpeg(filename, temp_filename, options) |
443 | os.remove(encodeFilename(filename)) | |
444 | os.rename(encodeFilename(temp_filename), encodeFilename(filename)) | |
592e97e8 | 445 | return [], info |
496c1923 PH |
446 | |
447 | ||
448 | class FFmpegMergerPP(FFmpegPostProcessor): | |
449 | def run(self, info): | |
450 | filename = info['filepath'] | |
5b5fbc08 | 451 | temp_filename = prepend_extension(filename, 'temp') |
bc3e582f | 452 | args = ['-c', 'copy', '-map', '0:v:0', '-map', '1:a:0'] |
3aa578ca | 453 | self._downloader.to_screen('[ffmpeg] Merging formats into "%s"' % filename) |
5b5fbc08 JMF |
454 | self.run_ffmpeg_multiple_files(info['__files_to_merge'], temp_filename, args) |
455 | os.rename(encodeFilename(temp_filename), encodeFilename(filename)) | |
d47aeb22 | 456 | return info['__files_to_merge'], info |
496c1923 | 457 | |
13763ce5 S |
458 | def can_merge(self): |
459 | # TODO: figure out merge-capable ffmpeg version | |
460 | if self.basename != 'avconv': | |
461 | return True | |
462 | ||
463 | required_version = '10-0' | |
464 | if is_outdated_version( | |
465 | self._versions[self.basename], required_version): | |
466 | warning = ('Your copy of %s is outdated and unable to properly mux separate video and audio files, ' | |
467 | 'youtube-dl will download single file media. ' | |
468 | 'Update %s to version %s or newer to fix this.') % ( | |
469 | self.basename, self.basename, required_version) | |
470 | if self._downloader: | |
471 | self._downloader.report_warning(warning) | |
472 | return False | |
473 | return True | |
474 | ||
0c14e2fb | 475 | |
6271f1ca PH |
476 | class FFmpegFixupStretchedPP(FFmpegPostProcessor): |
477 | def run(self, info): | |
478 | stretched_ratio = info.get('stretched_ratio') | |
479 | if stretched_ratio is None or stretched_ratio == 1: | |
592e97e8 | 480 | return [], info |
6271f1ca PH |
481 | |
482 | filename = info['filepath'] | |
483 | temp_filename = prepend_extension(filename, 'temp') | |
484 | ||
485 | options = ['-c', 'copy', '-aspect', '%f' % stretched_ratio] | |
486 | self._downloader.to_screen('[ffmpeg] Fixing aspect ratio in "%s"' % filename) | |
487 | self.run_ffmpeg(filename, temp_filename, options) | |
488 | ||
489 | os.remove(encodeFilename(filename)) | |
490 | os.rename(encodeFilename(temp_filename), encodeFilename(filename)) | |
491 | ||
592e97e8 | 492 | return [], info |
62cd676c PH |
493 | |
494 | ||
495 | class FFmpegFixupM4aPP(FFmpegPostProcessor): | |
496 | def run(self, info): | |
497 | if info.get('container') != 'm4a_dash': | |
592e97e8 | 498 | return [], info |
62cd676c PH |
499 | |
500 | filename = info['filepath'] | |
501 | temp_filename = prepend_extension(filename, 'temp') | |
502 | ||
503 | options = ['-c', 'copy', '-f', 'mp4'] | |
504 | self._downloader.to_screen('[ffmpeg] Correcting container in "%s"' % filename) | |
505 | self.run_ffmpeg(filename, temp_filename, options) | |
506 | ||
507 | os.remove(encodeFilename(filename)) | |
508 | os.rename(encodeFilename(temp_filename), encodeFilename(filename)) | |
509 | ||
592e97e8 | 510 | return [], info |
e9fade72 JMF |
511 | |
512 | ||
f17f8651 | 513 | class FFmpegFixupM3u8PP(FFmpegPostProcessor): |
514 | def run(self, info): | |
515 | filename = info['filepath'] | |
30d9e209 RA |
516 | if self.get_audio_codec(filename) == 'aac': |
517 | temp_filename = prepend_extension(filename, 'temp') | |
f17f8651 | 518 | |
30d9e209 RA |
519 | options = ['-c', 'copy', '-f', 'mp4', '-bsf:a', 'aac_adtstoasc'] |
520 | self._downloader.to_screen('[ffmpeg] Fixing malformated aac bitstream in "%s"' % filename) | |
521 | self.run_ffmpeg(filename, temp_filename, options) | |
f17f8651 | 522 | |
30d9e209 RA |
523 | os.remove(encodeFilename(filename)) |
524 | os.rename(encodeFilename(temp_filename), encodeFilename(filename)) | |
f17f8651 | 525 | return [], info |
526 | ||
527 | ||
e9fade72 JMF |
528 | class FFmpegSubtitlesConvertorPP(FFmpegPostProcessor): |
529 | def __init__(self, downloader=None, format=None): | |
530 | super(FFmpegSubtitlesConvertorPP, self).__init__(downloader) | |
531 | self.format = format | |
532 | ||
533 | def run(self, info): | |
534 | subs = info.get('requested_subtitles') | |
535 | filename = info['filepath'] | |
536 | new_ext = self.format | |
537 | new_format = new_ext | |
538 | if new_format == 'vtt': | |
539 | new_format = 'webvtt' | |
540 | if subs is None: | |
541 | self._downloader.to_screen('[ffmpeg] There aren\'t any subtitles to convert') | |
592e97e8 | 542 | return [], info |
e9fade72 | 543 | self._downloader.to_screen('[ffmpeg] Converting subtitles') |
e04398e3 | 544 | sub_filenames = [] |
e9fade72 JMF |
545 | for lang, sub in subs.items(): |
546 | ext = sub['ext'] | |
547 | if ext == new_ext: | |
548 | self._downloader.to_screen( | |
0f57447d | 549 | '[ffmpeg] Subtitle file for %s is already in the requested format' % new_ext) |
e9fade72 | 550 | continue |
e04398e3 JMF |
551 | old_file = subtitles_filename(filename, lang, ext) |
552 | sub_filenames.append(old_file) | |
e9fade72 | 553 | new_file = subtitles_filename(filename, lang, new_ext) |
bf6427d2 | 554 | |
0750b249 | 555 | if ext == 'dfxp' or ext == 'ttml' or ext == 'tt': |
bf6427d2 YCH |
556 | self._downloader.report_warning( |
557 | 'You have requested to convert dfxp (TTML) subtitles into another format, ' | |
558 | 'which results in style information loss') | |
559 | ||
e04398e3 | 560 | dfxp_file = old_file |
bf6427d2 YCH |
561 | srt_file = subtitles_filename(filename, lang, 'srt') |
562 | ||
563 | with io.open(dfxp_file, 'rt', encoding='utf-8') as f: | |
564 | srt_data = dfxp2srt(f.read()) | |
565 | ||
566 | with io.open(srt_file, 'wt', encoding='utf-8') as f: | |
567 | f.write(srt_data) | |
7e62c2eb | 568 | old_file = srt_file |
bf6427d2 | 569 | |
bf6427d2 YCH |
570 | subs[lang] = { |
571 | 'ext': 'srt', | |
572 | 'data': srt_data | |
573 | } | |
574 | ||
575 | if new_ext == 'srt': | |
576 | continue | |
7b8b007c JMF |
577 | else: |
578 | sub_filenames.append(srt_file) | |
bf6427d2 | 579 | |
e04398e3 | 580 | self.run_ffmpeg(old_file, new_file, ['-f', new_format]) |
e9fade72 JMF |
581 | |
582 | with io.open(new_file, 'rt', encoding='utf-8') as f: | |
583 | subs[lang] = { | |
3547d265 | 584 | 'ext': new_ext, |
e9fade72 JMF |
585 | 'data': f.read(), |
586 | } | |
587 | ||
e04398e3 | 588 | return sub_filenames, info |