]>
Commit | Line | Data |
---|---|---|
1 | from __future__ import unicode_literals | |
2 | ||
3 | import io | |
4 | import os | |
5 | import subprocess | |
6 | import time | |
7 | import re | |
8 | import json | |
9 | ||
10 | ||
11 | from .common import AudioConversionError, PostProcessor | |
12 | ||
13 | from ..utils import ( | |
14 | encodeArgument, | |
15 | encodeFilename, | |
16 | get_exe_version, | |
17 | is_outdated_version, | |
18 | PostProcessingError, | |
19 | prepend_extension, | |
20 | shell_quote, | |
21 | subtitles_filename, | |
22 | dfxp2srt, | |
23 | ISO639Utils, | |
24 | process_communicate_or_kill, | |
25 | replace_extension, | |
26 | traverse_dict, | |
27 | ) | |
28 | ||
29 | ||
30 | EXT_TO_OUT_FORMATS = { | |
31 | 'aac': 'adts', | |
32 | 'flac': 'flac', | |
33 | 'm4a': 'ipod', | |
34 | 'mka': 'matroska', | |
35 | 'mkv': 'matroska', | |
36 | 'mpg': 'mpeg', | |
37 | 'ogv': 'ogg', | |
38 | 'ts': 'mpegts', | |
39 | 'wma': 'asf', | |
40 | 'wmv': 'asf', | |
41 | } | |
42 | ACODECS = { | |
43 | 'mp3': 'libmp3lame', | |
44 | 'aac': 'aac', | |
45 | 'flac': 'flac', | |
46 | 'm4a': 'aac', | |
47 | 'opus': 'libopus', | |
48 | 'vorbis': 'libvorbis', | |
49 | 'wav': None, | |
50 | } | |
51 | ||
52 | ||
53 | class FFmpegPostProcessorError(PostProcessingError): | |
54 | pass | |
55 | ||
56 | ||
57 | class FFmpegPostProcessor(PostProcessor): | |
58 | def __init__(self, downloader=None): | |
59 | PostProcessor.__init__(self, downloader) | |
60 | self._determine_executables() | |
61 | ||
62 | def check_version(self): | |
63 | if not self.available: | |
64 | raise FFmpegPostProcessorError('ffmpeg not found. Please install one.') | |
65 | ||
66 | required_version = '10-0' if self.basename == 'avconv' else '1.0' | |
67 | if is_outdated_version( | |
68 | self._versions[self.basename], required_version): | |
69 | warning = 'Your copy of %s is outdated, update %s to version %s or newer if you encounter any errors.' % ( | |
70 | self.basename, self.basename, required_version) | |
71 | self.report_warning(warning) | |
72 | ||
73 | @staticmethod | |
74 | def get_versions(downloader=None): | |
75 | return FFmpegPostProcessor(downloader)._versions | |
76 | ||
77 | def _determine_executables(self): | |
78 | programs = ['avprobe', 'avconv', 'ffmpeg', 'ffprobe'] | |
79 | prefer_ffmpeg = True | |
80 | ||
81 | def get_ffmpeg_version(path): | |
82 | ver = get_exe_version(path, args=['-version']) | |
83 | if ver: | |
84 | regexs = [ | |
85 | r'(?:\d+:)?([0-9.]+)-[0-9]+ubuntu[0-9.]+$', # Ubuntu, see [1] | |
86 | r'n([0-9.]+)$', # Arch Linux | |
87 | # 1. http://www.ducea.com/2006/06/17/ubuntu-package-version-naming-explanation/ | |
88 | ] | |
89 | for regex in regexs: | |
90 | mobj = re.match(regex, ver) | |
91 | if mobj: | |
92 | ver = mobj.group(1) | |
93 | return ver | |
94 | ||
95 | self.basename = None | |
96 | self.probe_basename = None | |
97 | ||
98 | self._paths = None | |
99 | self._versions = None | |
100 | if self._downloader: | |
101 | prefer_ffmpeg = self.get_param('prefer_ffmpeg', True) | |
102 | location = self.get_param('ffmpeg_location') | |
103 | if location is not None: | |
104 | if not os.path.exists(location): | |
105 | self.report_warning( | |
106 | 'ffmpeg-location %s does not exist! ' | |
107 | 'Continuing without ffmpeg.' % (location)) | |
108 | self._versions = {} | |
109 | return | |
110 | elif not os.path.isdir(location): | |
111 | basename = os.path.splitext(os.path.basename(location))[0] | |
112 | if basename not in programs: | |
113 | self.report_warning( | |
114 | 'Cannot identify executable %s, its basename should be one of %s. ' | |
115 | 'Continuing without ffmpeg.' % | |
116 | (location, ', '.join(programs))) | |
117 | self._versions = {} | |
118 | return None | |
119 | location = os.path.dirname(os.path.abspath(location)) | |
120 | if basename in ('ffmpeg', 'ffprobe'): | |
121 | prefer_ffmpeg = True | |
122 | ||
123 | self._paths = dict( | |
124 | (p, os.path.join(location, p)) for p in programs) | |
125 | self._versions = dict( | |
126 | (p, get_ffmpeg_version(self._paths[p])) for p in programs) | |
127 | if self._versions is None: | |
128 | self._versions = dict( | |
129 | (p, get_ffmpeg_version(p)) for p in programs) | |
130 | self._paths = dict((p, p) for p in programs) | |
131 | ||
132 | if prefer_ffmpeg is False: | |
133 | prefs = ('avconv', 'ffmpeg') | |
134 | else: | |
135 | prefs = ('ffmpeg', 'avconv') | |
136 | for p in prefs: | |
137 | if self._versions[p]: | |
138 | self.basename = p | |
139 | break | |
140 | ||
141 | if prefer_ffmpeg is False: | |
142 | prefs = ('avprobe', 'ffprobe') | |
143 | else: | |
144 | prefs = ('ffprobe', 'avprobe') | |
145 | for p in prefs: | |
146 | if self._versions[p]: | |
147 | self.probe_basename = p | |
148 | break | |
149 | ||
150 | @property | |
151 | def available(self): | |
152 | return self.basename is not None | |
153 | ||
154 | @property | |
155 | def executable(self): | |
156 | return self._paths[self.basename] | |
157 | ||
158 | @property | |
159 | def probe_available(self): | |
160 | return self.probe_basename is not None | |
161 | ||
162 | @property | |
163 | def probe_executable(self): | |
164 | return self._paths[self.probe_basename] | |
165 | ||
166 | def get_audio_codec(self, path): | |
167 | if not self.probe_available and not self.available: | |
168 | raise PostProcessingError('ffprobe and ffmpeg not found. Please install one.') | |
169 | try: | |
170 | if self.probe_available: | |
171 | cmd = [ | |
172 | encodeFilename(self.probe_executable, True), | |
173 | encodeArgument('-show_streams')] | |
174 | else: | |
175 | cmd = [ | |
176 | encodeFilename(self.executable, True), | |
177 | encodeArgument('-i')] | |
178 | cmd.append(encodeFilename(self._ffmpeg_filename_argument(path), True)) | |
179 | self.write_debug('%s command line: %s' % (self.basename, shell_quote(cmd))) | |
180 | handle = subprocess.Popen( | |
181 | cmd, stderr=subprocess.PIPE, | |
182 | stdout=subprocess.PIPE, stdin=subprocess.PIPE) | |
183 | stdout_data, stderr_data = process_communicate_or_kill(handle) | |
184 | expected_ret = 0 if self.probe_available else 1 | |
185 | if handle.wait() != expected_ret: | |
186 | return None | |
187 | except (IOError, OSError): | |
188 | return None | |
189 | output = (stdout_data if self.probe_available else stderr_data).decode('ascii', 'ignore') | |
190 | if self.probe_available: | |
191 | audio_codec = None | |
192 | for line in output.split('\n'): | |
193 | if line.startswith('codec_name='): | |
194 | audio_codec = line.split('=')[1].strip() | |
195 | elif line.strip() == 'codec_type=audio' and audio_codec is not None: | |
196 | return audio_codec | |
197 | else: | |
198 | # Stream #FILE_INDEX:STREAM_INDEX[STREAM_ID](LANGUAGE): CODEC_TYPE: CODEC_NAME | |
199 | mobj = re.search( | |
200 | r'Stream\s*#\d+:\d+(?:\[0x[0-9a-f]+\])?(?:\([a-z]{3}\))?:\s*Audio:\s*([0-9a-z]+)', | |
201 | output) | |
202 | if mobj: | |
203 | return mobj.group(1) | |
204 | return None | |
205 | ||
206 | def get_metadata_object(self, path, opts=[]): | |
207 | if self.probe_basename != 'ffprobe': | |
208 | if self.probe_available: | |
209 | self.report_warning('Only ffprobe is supported for metadata extraction') | |
210 | raise PostProcessingError('ffprobe not found. Please install.') | |
211 | self.check_version() | |
212 | ||
213 | cmd = [ | |
214 | encodeFilename(self.probe_executable, True), | |
215 | encodeArgument('-hide_banner'), | |
216 | encodeArgument('-show_format'), | |
217 | encodeArgument('-show_streams'), | |
218 | encodeArgument('-print_format'), | |
219 | encodeArgument('json'), | |
220 | ] | |
221 | ||
222 | cmd += opts | |
223 | cmd.append(encodeFilename(self._ffmpeg_filename_argument(path), True)) | |
224 | if self._downloader.params.get('verbose', False): | |
225 | self._downloader.to_screen('[debug] ffprobe command line: %s' % shell_quote(cmd)) | |
226 | p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE) | |
227 | stdout, stderr = p.communicate() | |
228 | return json.loads(stdout.decode('utf-8', 'replace')) | |
229 | ||
230 | def get_stream_number(self, path, keys, value): | |
231 | streams = self.get_metadata_object(path)['streams'] | |
232 | num = next( | |
233 | (i for i, stream in enumerate(streams) if traverse_dict(stream, keys, casesense=False) == value), | |
234 | None) | |
235 | return num, len(streams) | |
236 | ||
237 | def run_ffmpeg_multiple_files(self, input_paths, out_path, opts): | |
238 | self.check_version() | |
239 | ||
240 | oldest_mtime = min( | |
241 | os.stat(encodeFilename(path)).st_mtime for path in input_paths) | |
242 | ||
243 | opts += self._configuration_args(exe=self.basename) | |
244 | ||
245 | files_cmd = [] | |
246 | for path in input_paths: | |
247 | files_cmd.extend([ | |
248 | encodeArgument('-i'), | |
249 | encodeFilename(self._ffmpeg_filename_argument(path), True) | |
250 | ]) | |
251 | cmd = [encodeFilename(self.executable, True), encodeArgument('-y')] | |
252 | # avconv does not have repeat option | |
253 | if self.basename == 'ffmpeg': | |
254 | cmd += [encodeArgument('-loglevel'), encodeArgument('repeat+info')] | |
255 | cmd += (files_cmd | |
256 | + [encodeArgument(o) for o in opts] | |
257 | + [encodeFilename(self._ffmpeg_filename_argument(out_path), True)]) | |
258 | ||
259 | self.write_debug('ffmpeg command line: %s' % shell_quote(cmd)) | |
260 | p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE) | |
261 | stdout, stderr = process_communicate_or_kill(p) | |
262 | if p.returncode != 0: | |
263 | stderr = stderr.decode('utf-8', 'replace').strip() | |
264 | if self._downloader.params.get('verbose', False): | |
265 | self.report_error(stderr) | |
266 | raise FFmpegPostProcessorError(stderr.split('\n')[-1]) | |
267 | self.try_utime(out_path, oldest_mtime, oldest_mtime) | |
268 | return stderr.decode('utf-8', 'replace') | |
269 | ||
270 | def run_ffmpeg(self, path, out_path, opts): | |
271 | self.run_ffmpeg_multiple_files([path], out_path, opts) | |
272 | ||
273 | def _ffmpeg_filename_argument(self, fn): | |
274 | # Always use 'file:' because the filename may contain ':' (ffmpeg | |
275 | # interprets that as a protocol) or can start with '-' (-- is broken in | |
276 | # ffmpeg, see https://ffmpeg.org/trac/ffmpeg/ticket/2127 for details) | |
277 | # Also leave '-' intact in order not to break streaming to stdout. | |
278 | if fn.startswith(('http://', 'https://')): | |
279 | return fn | |
280 | return 'file:' + fn if fn != '-' else fn | |
281 | ||
282 | ||
283 | class FFmpegExtractAudioPP(FFmpegPostProcessor): | |
284 | def __init__(self, downloader=None, preferredcodec=None, preferredquality=None, nopostoverwrites=False): | |
285 | FFmpegPostProcessor.__init__(self, downloader) | |
286 | if preferredcodec is None: | |
287 | preferredcodec = 'best' | |
288 | self._preferredcodec = preferredcodec | |
289 | self._preferredquality = preferredquality | |
290 | self._nopostoverwrites = nopostoverwrites | |
291 | ||
292 | def run_ffmpeg(self, path, out_path, codec, more_opts): | |
293 | if codec is None: | |
294 | acodec_opts = [] | |
295 | else: | |
296 | acodec_opts = ['-acodec', codec] | |
297 | opts = ['-vn'] + acodec_opts + more_opts | |
298 | try: | |
299 | FFmpegPostProcessor.run_ffmpeg(self, path, out_path, opts) | |
300 | except FFmpegPostProcessorError as err: | |
301 | raise AudioConversionError(err.msg) | |
302 | ||
303 | def run(self, information): | |
304 | path = information['filepath'] | |
305 | ||
306 | filecodec = self.get_audio_codec(path) | |
307 | if filecodec is None: | |
308 | raise PostProcessingError('WARNING: unable to obtain file audio codec with ffprobe') | |
309 | ||
310 | more_opts = [] | |
311 | if self._preferredcodec == 'best' or self._preferredcodec == filecodec or (self._preferredcodec == 'm4a' and filecodec == 'aac'): | |
312 | if filecodec == 'aac' and self._preferredcodec in ['m4a', 'best']: | |
313 | # Lossless, but in another container | |
314 | acodec = 'copy' | |
315 | extension = 'm4a' | |
316 | more_opts = ['-bsf:a', 'aac_adtstoasc'] | |
317 | elif filecodec in ['aac', 'flac', 'mp3', 'vorbis', 'opus']: | |
318 | # Lossless if possible | |
319 | acodec = 'copy' | |
320 | extension = filecodec | |
321 | if filecodec == 'aac': | |
322 | more_opts = ['-f', 'adts'] | |
323 | if filecodec == 'vorbis': | |
324 | extension = 'ogg' | |
325 | else: | |
326 | # MP3 otherwise. | |
327 | acodec = 'libmp3lame' | |
328 | extension = 'mp3' | |
329 | more_opts = [] | |
330 | if self._preferredquality is not None: | |
331 | if int(self._preferredquality) < 10: | |
332 | more_opts += ['-q:a', self._preferredquality] | |
333 | else: | |
334 | more_opts += ['-b:a', self._preferredquality + 'k'] | |
335 | else: | |
336 | # We convert the audio (lossy if codec is lossy) | |
337 | acodec = ACODECS[self._preferredcodec] | |
338 | extension = self._preferredcodec | |
339 | more_opts = [] | |
340 | if self._preferredquality is not None: | |
341 | # The opus codec doesn't support the -aq option | |
342 | if int(self._preferredquality) < 10 and extension != 'opus': | |
343 | more_opts += ['-q:a', self._preferredquality] | |
344 | else: | |
345 | more_opts += ['-b:a', self._preferredquality + 'k'] | |
346 | if self._preferredcodec == 'aac': | |
347 | more_opts += ['-f', 'adts'] | |
348 | if self._preferredcodec == 'm4a': | |
349 | more_opts += ['-bsf:a', 'aac_adtstoasc'] | |
350 | if self._preferredcodec == 'vorbis': | |
351 | extension = 'ogg' | |
352 | if self._preferredcodec == 'wav': | |
353 | extension = 'wav' | |
354 | more_opts += ['-f', 'wav'] | |
355 | ||
356 | prefix, sep, ext = path.rpartition('.') # not os.path.splitext, since the latter does not work on unicode in all setups | |
357 | new_path = prefix + sep + extension | |
358 | ||
359 | information['filepath'] = new_path | |
360 | information['ext'] = extension | |
361 | ||
362 | # If we download foo.mp3 and convert it to... foo.mp3, then don't delete foo.mp3, silly. | |
363 | if (new_path == path | |
364 | or (self._nopostoverwrites and os.path.exists(encodeFilename(new_path)))): | |
365 | self.to_screen('Post-process file %s exists, skipping' % new_path) | |
366 | return [], information | |
367 | ||
368 | try: | |
369 | self.to_screen('Destination: ' + new_path) | |
370 | self.run_ffmpeg(path, new_path, acodec, more_opts) | |
371 | except AudioConversionError as e: | |
372 | raise PostProcessingError( | |
373 | 'audio conversion failed: ' + e.msg) | |
374 | except Exception: | |
375 | raise PostProcessingError('error running ' + self.basename) | |
376 | ||
377 | # Try to update the date time for extracted audio file. | |
378 | if information.get('filetime') is not None: | |
379 | self.try_utime( | |
380 | new_path, time.time(), information['filetime'], | |
381 | errnote='Cannot update utime of audio file') | |
382 | ||
383 | return [path], information | |
384 | ||
385 | ||
386 | class FFmpegVideoRemuxerPP(FFmpegPostProcessor): | |
387 | def __init__(self, downloader=None, preferedformat=None): | |
388 | super(FFmpegVideoRemuxerPP, self).__init__(downloader) | |
389 | self._preferedformats = preferedformat.lower().split('/') | |
390 | ||
391 | def run(self, information): | |
392 | path = information['filepath'] | |
393 | sourceext, targetext = information['ext'].lower(), None | |
394 | for pair in self._preferedformats: | |
395 | kv = pair.split('>') | |
396 | if len(kv) == 1 or kv[0].strip() == sourceext: | |
397 | targetext = kv[-1].strip() | |
398 | break | |
399 | ||
400 | _skip_msg = ( | |
401 | 'could not find a mapping for %s' if not targetext | |
402 | else 'already is in target format %s' if sourceext == targetext | |
403 | else None) | |
404 | if _skip_msg: | |
405 | self.to_screen('Not remuxing media file %s; %s' % (path, _skip_msg % sourceext)) | |
406 | return [], information | |
407 | ||
408 | options = ['-c', 'copy', '-map', '0', '-dn'] | |
409 | if targetext in ['mp4', 'm4a', 'mov']: | |
410 | options.extend(['-movflags', '+faststart']) | |
411 | prefix, sep, oldext = path.rpartition('.') | |
412 | outpath = prefix + sep + targetext | |
413 | self.to_screen('Remuxing video from %s to %s; Destination: %s' % (sourceext, targetext, outpath)) | |
414 | self.run_ffmpeg(path, outpath, options) | |
415 | information['filepath'] = outpath | |
416 | information['format'] = targetext | |
417 | information['ext'] = targetext | |
418 | return [path], information | |
419 | ||
420 | ||
421 | class FFmpegVideoConvertorPP(FFmpegPostProcessor): | |
422 | def __init__(self, downloader=None, preferedformat=None): | |
423 | super(FFmpegVideoConvertorPP, self).__init__(downloader) | |
424 | self._preferedformat = preferedformat | |
425 | ||
426 | def run(self, information): | |
427 | path = information['filepath'] | |
428 | if information['ext'] == self._preferedformat: | |
429 | self.to_screen('Not converting video file %s - already is in target format %s' % (path, self._preferedformat)) | |
430 | return [], information | |
431 | options = [] | |
432 | if self._preferedformat == 'avi': | |
433 | options.extend(['-c:v', 'libxvid', '-vtag', 'XVID']) | |
434 | prefix, sep, ext = path.rpartition('.') | |
435 | outpath = prefix + sep + self._preferedformat | |
436 | self.to_screen('Converting video from %s to %s, Destination: ' % (information['ext'], self._preferedformat) + outpath) | |
437 | self.run_ffmpeg(path, outpath, options) | |
438 | information['filepath'] = outpath | |
439 | information['format'] = self._preferedformat | |
440 | information['ext'] = self._preferedformat | |
441 | return [path], information | |
442 | ||
443 | ||
444 | class FFmpegEmbedSubtitlePP(FFmpegPostProcessor): | |
445 | def run(self, information): | |
446 | if information['ext'] not in ('mp4', 'webm', 'mkv'): | |
447 | self.to_screen('Subtitles can only be embedded in mp4, webm or mkv files') | |
448 | return [], information | |
449 | subtitles = information.get('requested_subtitles') | |
450 | if not subtitles: | |
451 | self.to_screen('There aren\'t any subtitles to embed') | |
452 | return [], information | |
453 | ||
454 | filename = information['filepath'] | |
455 | ||
456 | ext = information['ext'] | |
457 | sub_langs = [] | |
458 | sub_filenames = [] | |
459 | webm_vtt_warn = False | |
460 | mp4_ass_warn = False | |
461 | ||
462 | for lang, sub_info in subtitles.items(): | |
463 | sub_ext = sub_info['ext'] | |
464 | if sub_ext == 'json': | |
465 | self.report_warning('JSON subtitles cannot be embedded') | |
466 | elif ext != 'webm' or ext == 'webm' and sub_ext == 'vtt': | |
467 | sub_langs.append(lang) | |
468 | sub_filenames.append(subtitles_filename(filename, lang, sub_ext, ext)) | |
469 | else: | |
470 | if not webm_vtt_warn and ext == 'webm' and sub_ext != 'vtt': | |
471 | webm_vtt_warn = True | |
472 | self.report_warning('Only WebVTT subtitles can be embedded in webm files') | |
473 | if not mp4_ass_warn and ext == 'mp4' and sub_ext == 'ass': | |
474 | mp4_ass_warn = True | |
475 | self.report_warning('ASS subtitles cannot be properly embedded in mp4 files; expect issues') | |
476 | ||
477 | if not sub_langs: | |
478 | return [], information | |
479 | ||
480 | input_files = [filename] + sub_filenames | |
481 | ||
482 | opts = [ | |
483 | '-c', 'copy', '-map', '0', '-dn', | |
484 | # Don't copy the existing subtitles, we may be running the | |
485 | # postprocessor a second time | |
486 | '-map', '-0:s', | |
487 | # Don't copy Apple TV chapters track, bin_data (see #19042, #19024, | |
488 | # https://trac.ffmpeg.org/ticket/6016) | |
489 | '-map', '-0:d', | |
490 | ] | |
491 | if information['ext'] == 'mp4': | |
492 | opts += ['-c:s', 'mov_text'] | |
493 | for (i, lang) in enumerate(sub_langs): | |
494 | opts.extend(['-map', '%d:0' % (i + 1)]) | |
495 | lang_code = ISO639Utils.short2long(lang) or lang | |
496 | opts.extend(['-metadata:s:s:%d' % i, 'language=%s' % lang_code]) | |
497 | ||
498 | temp_filename = prepend_extension(filename, 'temp') | |
499 | self.to_screen('Embedding subtitles in "%s"' % filename) | |
500 | self.run_ffmpeg_multiple_files(input_files, temp_filename, opts) | |
501 | os.remove(encodeFilename(filename)) | |
502 | os.rename(encodeFilename(temp_filename), encodeFilename(filename)) | |
503 | ||
504 | return sub_filenames, information | |
505 | ||
506 | ||
507 | class FFmpegMetadataPP(FFmpegPostProcessor): | |
508 | def run(self, info): | |
509 | metadata = {} | |
510 | ||
511 | def add(meta_list, info_list=None): | |
512 | if not info_list: | |
513 | info_list = meta_list | |
514 | if not isinstance(meta_list, (list, tuple)): | |
515 | meta_list = (meta_list,) | |
516 | if not isinstance(info_list, (list, tuple)): | |
517 | info_list = (info_list,) | |
518 | for info_f in info_list: | |
519 | if info.get(info_f) is not None: | |
520 | for meta_f in meta_list: | |
521 | metadata[meta_f] = info[info_f] | |
522 | break | |
523 | ||
524 | # See [1-4] for some info on media metadata/metadata supported | |
525 | # by ffmpeg. | |
526 | # 1. https://kdenlive.org/en/project/adding-meta-data-to-mp4-video/ | |
527 | # 2. https://wiki.multimedia.cx/index.php/FFmpeg_Metadata | |
528 | # 3. https://kodi.wiki/view/Video_file_tagging | |
529 | ||
530 | add('title', ('track', 'title')) | |
531 | add('date', 'upload_date') | |
532 | add(('description', 'comment'), 'description') | |
533 | add('purl', 'webpage_url') | |
534 | add('track', 'track_number') | |
535 | add('artist', ('artist', 'creator', 'uploader', 'uploader_id')) | |
536 | add('genre') | |
537 | add('album') | |
538 | add('album_artist') | |
539 | add('disc', 'disc_number') | |
540 | add('show', 'series') | |
541 | add('season_number') | |
542 | add('episode_id', ('episode', 'episode_id')) | |
543 | add('episode_sort', 'episode_number') | |
544 | ||
545 | if not metadata: | |
546 | self.to_screen('There isn\'t any metadata to add') | |
547 | return [], info | |
548 | ||
549 | filename = info['filepath'] | |
550 | temp_filename = prepend_extension(filename, 'temp') | |
551 | in_filenames = [filename] | |
552 | options = ['-map', '0', '-dn'] | |
553 | ||
554 | if info['ext'] == 'm4a': | |
555 | options.extend(['-vn', '-acodec', 'copy']) | |
556 | else: | |
557 | options.extend(['-c', 'copy']) | |
558 | ||
559 | for (name, value) in metadata.items(): | |
560 | options.extend(['-metadata', '%s=%s' % (name, value)]) | |
561 | ||
562 | chapters = info.get('chapters', []) | |
563 | if chapters: | |
564 | metadata_filename = replace_extension(filename, 'meta') | |
565 | with io.open(metadata_filename, 'wt', encoding='utf-8') as f: | |
566 | def ffmpeg_escape(text): | |
567 | return re.sub(r'(=|;|#|\\|\n)', r'\\\1', text) | |
568 | ||
569 | metadata_file_content = ';FFMETADATA1\n' | |
570 | for chapter in chapters: | |
571 | metadata_file_content += '[CHAPTER]\nTIMEBASE=1/1000\n' | |
572 | metadata_file_content += 'START=%d\n' % (chapter['start_time'] * 1000) | |
573 | metadata_file_content += 'END=%d\n' % (chapter['end_time'] * 1000) | |
574 | chapter_title = chapter.get('title') | |
575 | if chapter_title: | |
576 | metadata_file_content += 'title=%s\n' % ffmpeg_escape(chapter_title) | |
577 | f.write(metadata_file_content) | |
578 | in_filenames.append(metadata_filename) | |
579 | options.extend(['-map_metadata', '1']) | |
580 | ||
581 | if '__infojson_filepath' in info and info['ext'] in ('mkv', 'mka'): | |
582 | old_stream, new_stream = self.get_stream_number( | |
583 | filename, ('tags', 'mimetype'), 'application/json') | |
584 | if old_stream is not None: | |
585 | options.extend(['-map', '-0:%d' % old_stream]) | |
586 | new_stream -= 1 | |
587 | ||
588 | options.extend([ | |
589 | '-attach', info['__infojson_filepath'], | |
590 | '-metadata:s:%d' % new_stream, 'mimetype=application/json' | |
591 | ]) | |
592 | ||
593 | self.to_screen('Adding metadata to \'%s\'' % filename) | |
594 | self.run_ffmpeg_multiple_files(in_filenames, temp_filename, options) | |
595 | if chapters: | |
596 | os.remove(metadata_filename) | |
597 | os.remove(encodeFilename(filename)) | |
598 | os.rename(encodeFilename(temp_filename), encodeFilename(filename)) | |
599 | return [], info | |
600 | ||
601 | ||
602 | class FFmpegMergerPP(FFmpegPostProcessor): | |
603 | def run(self, info): | |
604 | filename = info['filepath'] | |
605 | temp_filename = prepend_extension(filename, 'temp') | |
606 | args = ['-c', 'copy'] | |
607 | for (i, fmt) in enumerate(info['requested_formats']): | |
608 | if fmt.get('acodec') != 'none': | |
609 | args.extend(['-map', '%u:a:0' % (i)]) | |
610 | if fmt.get('vcodec') != 'none': | |
611 | args.extend(['-map', '%u:v:0' % (i)]) | |
612 | self.to_screen('Merging formats into "%s"' % filename) | |
613 | self.run_ffmpeg_multiple_files(info['__files_to_merge'], temp_filename, args) | |
614 | os.rename(encodeFilename(temp_filename), encodeFilename(filename)) | |
615 | return info['__files_to_merge'], info | |
616 | ||
617 | def can_merge(self): | |
618 | # TODO: figure out merge-capable ffmpeg version | |
619 | if self.basename != 'avconv': | |
620 | return True | |
621 | ||
622 | required_version = '10-0' | |
623 | if is_outdated_version( | |
624 | self._versions[self.basename], required_version): | |
625 | warning = ('Your copy of %s is outdated and unable to properly mux separate video and audio files, ' | |
626 | 'youtube-dlc will download single file media. ' | |
627 | 'Update %s to version %s or newer to fix this.') % ( | |
628 | self.basename, self.basename, required_version) | |
629 | self.report_warning(warning) | |
630 | return False | |
631 | return True | |
632 | ||
633 | ||
634 | class FFmpegFixupStretchedPP(FFmpegPostProcessor): | |
635 | def run(self, info): | |
636 | stretched_ratio = info.get('stretched_ratio') | |
637 | if stretched_ratio is None or stretched_ratio == 1: | |
638 | return [], info | |
639 | ||
640 | filename = info['filepath'] | |
641 | temp_filename = prepend_extension(filename, 'temp') | |
642 | ||
643 | options = ['-c', 'copy', '-map', '0', '-dn', '-aspect', '%f' % stretched_ratio] | |
644 | self.to_screen('Fixing aspect ratio in "%s"' % filename) | |
645 | self.run_ffmpeg(filename, temp_filename, options) | |
646 | ||
647 | os.remove(encodeFilename(filename)) | |
648 | os.rename(encodeFilename(temp_filename), encodeFilename(filename)) | |
649 | ||
650 | return [], info | |
651 | ||
652 | ||
653 | class FFmpegFixupM4aPP(FFmpegPostProcessor): | |
654 | def run(self, info): | |
655 | if info.get('container') != 'm4a_dash': | |
656 | return [], info | |
657 | ||
658 | filename = info['filepath'] | |
659 | temp_filename = prepend_extension(filename, 'temp') | |
660 | ||
661 | options = ['-c', 'copy', '-map', '0', '-dn', '-f', 'mp4'] | |
662 | self.to_screen('Correcting container in "%s"' % filename) | |
663 | self.run_ffmpeg(filename, temp_filename, options) | |
664 | ||
665 | os.remove(encodeFilename(filename)) | |
666 | os.rename(encodeFilename(temp_filename), encodeFilename(filename)) | |
667 | ||
668 | return [], info | |
669 | ||
670 | ||
671 | class FFmpegFixupM3u8PP(FFmpegPostProcessor): | |
672 | def run(self, info): | |
673 | filename = info['filepath'] | |
674 | if self.get_audio_codec(filename) == 'aac': | |
675 | temp_filename = prepend_extension(filename, 'temp') | |
676 | ||
677 | options = ['-c', 'copy', '-map', '0', '-dn', '-f', 'mp4', '-bsf:a', 'aac_adtstoasc'] | |
678 | self.to_screen('Fixing malformed AAC bitstream in "%s"' % filename) | |
679 | self.run_ffmpeg(filename, temp_filename, options) | |
680 | ||
681 | os.remove(encodeFilename(filename)) | |
682 | os.rename(encodeFilename(temp_filename), encodeFilename(filename)) | |
683 | return [], info | |
684 | ||
685 | ||
686 | class FFmpegSubtitlesConvertorPP(FFmpegPostProcessor): | |
687 | def __init__(self, downloader=None, format=None): | |
688 | super(FFmpegSubtitlesConvertorPP, self).__init__(downloader) | |
689 | self.format = format | |
690 | ||
691 | def run(self, info): | |
692 | subs = info.get('requested_subtitles') | |
693 | filename = info['filepath'] | |
694 | new_ext = self.format | |
695 | new_format = new_ext | |
696 | if new_format == 'vtt': | |
697 | new_format = 'webvtt' | |
698 | if subs is None: | |
699 | self.to_screen('There aren\'t any subtitles to convert') | |
700 | return [], info | |
701 | self.to_screen('Converting subtitles') | |
702 | sub_filenames = [] | |
703 | for lang, sub in subs.items(): | |
704 | ext = sub['ext'] | |
705 | if ext == new_ext: | |
706 | self.to_screen('Subtitle file for %s is already in the requested format' % new_ext) | |
707 | continue | |
708 | elif ext == 'json': | |
709 | self.to_screen( | |
710 | 'You have requested to convert json subtitles into another format, ' | |
711 | 'which is currently not possible') | |
712 | continue | |
713 | old_file = subtitles_filename(filename, lang, ext, info.get('ext')) | |
714 | sub_filenames.append(old_file) | |
715 | new_file = subtitles_filename(filename, lang, new_ext, info.get('ext')) | |
716 | ||
717 | if ext in ('dfxp', 'ttml', 'tt'): | |
718 | self.report_warning( | |
719 | 'You have requested to convert dfxp (TTML) subtitles into another format, ' | |
720 | 'which results in style information loss') | |
721 | ||
722 | dfxp_file = old_file | |
723 | srt_file = subtitles_filename(filename, lang, 'srt', info.get('ext')) | |
724 | ||
725 | with open(dfxp_file, 'rb') as f: | |
726 | srt_data = dfxp2srt(f.read()) | |
727 | ||
728 | with io.open(srt_file, 'wt', encoding='utf-8') as f: | |
729 | f.write(srt_data) | |
730 | old_file = srt_file | |
731 | ||
732 | subs[lang] = { | |
733 | 'ext': 'srt', | |
734 | 'data': srt_data | |
735 | } | |
736 | ||
737 | if new_ext == 'srt': | |
738 | continue | |
739 | else: | |
740 | sub_filenames.append(srt_file) | |
741 | ||
742 | self.run_ffmpeg(old_file, new_file, ['-f', new_format]) | |
743 | ||
744 | with io.open(new_file, 'rt', encoding='utf-8') as f: | |
745 | subs[lang] = { | |
746 | 'ext': new_ext, | |
747 | 'data': f.read(), | |
748 | } | |
749 | ||
750 | return sub_filenames, info |