]> jfr.im git - yt-dlp.git/blame - youtube_dl/__init__.py
[YoutubeDL] Include rtmpdump in exe versions -v output
[yt-dlp.git] / youtube_dl / __init__.py
CommitLineData
235b3ba4
PH
1#!/usr/bin/env python
2# -*- coding: utf-8 -*-
3
235b3ba4 4__license__ = 'Public Domain'
235b3ba4 5
0d94f247 6import codecs
8f563f32 7import io
235b3ba4 8import os
0f818663 9import random
235b3ba4 10import sys
235b3ba4 11
c496ca96 12
2daabe49
PH
13from .options import (
14 parseOpts,
15)
a4fd0415 16from .utils import (
4644ac55 17 compat_expanduser,
e68301af 18 compat_getpass,
a4fd0415 19 compat_print,
a4fd0415 20 DateRange,
acd69589 21 DEFAULT_OUTTMPL,
a4fd0415 22 decodeOption,
a4fd0415 23 DownloadError,
a4fd0415 24 MaxDownloadsReached,
a4fd0415 25 preferredencoding,
62e609ab 26 read_batch_urls,
a4fd0415 27 SameFileError,
e3946f98 28 setproctitle,
a4fd0415
PH
29 std_headers,
30 write_string,
a4fd0415 31)
d5ed35b6 32from .update import update_self
92a86f4c 33from .downloader import (
a4fd0415
PH
34 FileDownloader,
35)
0824c28c 36from .extractor import gen_extractors
8222d8de 37from .YoutubeDL import YoutubeDL
56327689 38from .postprocessor import (
0c14e2fb 39 AtomicParsleyPP,
149254d0 40 FFmpegAudioFixPP,
a4fd0415
PH
41 FFmpegMetadataPP,
42 FFmpegVideoConvertor,
43 FFmpegExtractAudioPP,
44 FFmpegEmbedSubtitlePP,
e63fc1be 45 XAttrMetadataPP,
a2360a4c 46 ExecAfterDownloadPP,
a4fd0415
PH
47)
48
235b3ba4 49
b8ad4f02 50def _real_main(argv=None):
0d94f247
PH
51 # Compatibility fixes for Windows
52 if sys.platform == 'win32':
53 # https://github.com/rg3/youtube-dl/issues/820
54 codecs.register(lambda name: codecs.lookup('utf-8') if name == 'cp65001' else None)
55
e3946f98
PH
56 setproctitle(u'youtube-dl')
57
b8ad4f02 58 parser, opts, args = parseOpts(argv)
59ae15a5 59
59ae15a5
PH
60 # Set user agent
61 if opts.user_agent is not None:
62 std_headers['User-Agent'] = opts.user_agent
1865ed31 63
28535652
BH
64 # Set referer
65 if opts.referer is not None:
66 std_headers['Referer'] = opts.referer
59ae15a5 67
410afb20
AA
68 # Custom HTTP headers
69 if opts.headers is not None:
70 for h in opts.headers:
71 if h.find(':', 1) < 0:
72 parser.error(u'wrong header formatting, it should be key:value, not "%s"'%h)
73 key, value = h.split(':', 2)
74 if opts.verbose:
75 write_string(u'[debug] Adding header from command line option %s:%s\n'%(key, value))
76 std_headers[key] = value
77
59ae15a5
PH
78 # Dump user agent
79 if opts.dump_user_agent:
93eb15c5 80 compat_print(std_headers['User-Agent'])
59ae15a5
PH
81 sys.exit(0)
82
83 # Batch file verification
62e609ab 84 batch_urls = []
59ae15a5
PH
85 if opts.batchfile is not None:
86 try:
87 if opts.batchfile == '-':
88 batchfd = sys.stdin
89 else:
62e609ab
PH
90 batchfd = io.open(opts.batchfile, 'r', encoding='utf-8', errors='ignore')
91 batch_urls = read_batch_urls(batchfd)
05afc96b 92 if opts.verbose:
62e609ab 93 write_string(u'[debug] Batch file urls: ' + repr(batch_urls) + u'\n')
59ae15a5
PH
94 except IOError:
95 sys.exit(u'ERROR: batch file could not be read')
62e609ab 96 all_urls = batch_urls + args
59ae15a5 97 all_urls = [url.strip() for url in all_urls]
c774b3c6 98 _enc = preferredencoding()
41292a38 99 all_urls = [url.decode(_enc, 'ignore') if isinstance(url, bytes) else url for url in all_urls]
59ae15a5 100
59ae15a5
PH
101 extractors = gen_extractors()
102
103 if opts.list_extractors:
7dba9cd0 104 for ie in sorted(extractors, key=lambda ie: ie.IE_NAME.lower()):
93eb15c5 105 compat_print(ie.IE_NAME + (' (CURRENTLY BROKEN)' if not ie._WORKING else ''))
1a2c3c0f 106 matchedUrls = [url for url in all_urls if ie.suitable(url)]
59ae15a5 107 for mu in matchedUrls:
93eb15c5 108 compat_print(u' ' + mu)
59ae15a5 109 sys.exit(0)
0f818663
PH
110 if opts.list_extractor_descriptions:
111 for ie in sorted(extractors, key=lambda ie: ie.IE_NAME.lower()):
112 if not ie._WORKING:
113 continue
114 desc = getattr(ie, 'IE_DESC', ie.IE_NAME)
15870e90
PH
115 if desc is False:
116 continue
0f818663 117 if hasattr(ie, 'SEARCH_KEY'):
53eb2176 118 _SEARCHES = (u'cute kittens', u'slithering pythons', u'falling cat', u'angry poodle', u'purple fish', u'running tortoise', u'sleeping bunny')
0f818663
PH
119 _COUNTS = (u'', u'5', u'10', u'all')
120 desc += u' (Example: "%s%s:%s" )' % (ie.SEARCH_KEY, random.choice(_COUNTS), random.choice(_SEARCHES))
121 compat_print(desc)
122 sys.exit(0)
123
59ae15a5
PH
124
125 # Conflicting, missing and erroneous options
126 if opts.usenetrc and (opts.username is not None or opts.password is not None):
127 parser.error(u'using .netrc conflicts with giving username/password')
128 if opts.password is not None and opts.username is None:
67d28bff 129 parser.error(u'account username missing\n')
59ae15a5
PH
130 if opts.outtmpl is not None and (opts.usetitle or opts.autonumber or opts.useid):
131 parser.error(u'using output template conflicts with using title, video ID or auto number')
132 if opts.usetitle and opts.useid:
133 parser.error(u'using title conflicts with using video ID')
134 if opts.username is not None and opts.password is None:
e68301af 135 opts.password = compat_getpass(u'Type account password and press [Return]: ')
59ae15a5
PH
136 if opts.ratelimit is not None:
137 numeric_limit = FileDownloader.parse_bytes(opts.ratelimit)
138 if numeric_limit is None:
139 parser.error(u'invalid rate limit specified')
140 opts.ratelimit = numeric_limit
9e982f9e
JC
141 if opts.min_filesize is not None:
142 numeric_limit = FileDownloader.parse_bytes(opts.min_filesize)
143 if numeric_limit is None:
144 parser.error(u'invalid min_filesize specified')
145 opts.min_filesize = numeric_limit
146 if opts.max_filesize is not None:
147 numeric_limit = FileDownloader.parse_bytes(opts.max_filesize)
148 if numeric_limit is None:
149 parser.error(u'invalid max_filesize specified')
150 opts.max_filesize = numeric_limit
59ae15a5
PH
151 if opts.retries is not None:
152 try:
153 opts.retries = int(opts.retries)
dca08720 154 except (TypeError, ValueError):
59ae15a5
PH
155 parser.error(u'invalid retry count specified')
156 if opts.buffersize is not None:
157 numeric_buffersize = FileDownloader.parse_bytes(opts.buffersize)
158 if numeric_buffersize is None:
159 parser.error(u'invalid buffer size specified')
160 opts.buffersize = numeric_buffersize
a19fd00c
PH
161 if opts.playliststart <= 0:
162 raise ValueError(u'Playlist start must be positive')
163 if opts.playlistend not in (-1, None) and opts.playlistend < opts.playliststart:
164 raise ValueError(u'Playlist end must be greater than playlist start')
59ae15a5 165 if opts.extractaudio:
510e6f6d 166 if opts.audioformat not in ['best', 'aac', 'mp3', 'm4a', 'opus', 'vorbis', 'wav']:
59ae15a5
PH
167 parser.error(u'invalid audio format specified')
168 if opts.audioquality:
169 opts.audioquality = opts.audioquality.strip('k').strip('K')
170 if not opts.audioquality.isdigit():
171 parser.error(u'invalid audio quality specified')
7851b379 172 if opts.recodevideo is not None:
b7d73595 173 if opts.recodevideo not in ['mp4', 'flv', 'webm', 'ogg', 'mkv']:
7851b379 174 parser.error(u'invalid video recode format specified')
bd558525
JMF
175 if opts.date is not None:
176 date = DateRange.day(opts.date)
177 else:
178 date = DateRange(opts.dateafter, opts.datebefore)
59ae15a5 179
de3ef3ed
PH
180 # Do not download videos when there are audio-only formats
181 if opts.extractaudio and not opts.keepvideo and opts.format is None:
182 opts.format = 'bestaudio/best'
183
0b7f3118
JMF
184 # --all-sub automatically sets --write-sub if --write-auto-sub is not given
185 # this was the old behaviour if only --all-sub was given.
186 if opts.allsubtitles and (opts.writeautomaticsub == False):
187 opts.writesubtitles = True
188
5cb9c312
PH
189 if sys.version_info < (3,):
190 # In Python 2, sys.argv is a bytestring (also note http://bugs.python.org/issue2128 for Windows systems)
0be41ec2
PH
191 if opts.outtmpl is not None:
192 opts.outtmpl = opts.outtmpl.decode(preferredencoding())
5cb9c312
PH
193 outtmpl =((opts.outtmpl is not None and opts.outtmpl)
194 or (opts.format == '-1' and opts.usetitle and u'%(title)s-%(id)s-%(format)s.%(ext)s')
195 or (opts.format == '-1' and u'%(id)s-%(format)s.%(ext)s')
196 or (opts.usetitle and opts.autonumber and u'%(autonumber)s-%(title)s-%(id)s.%(ext)s')
197 or (opts.usetitle and u'%(title)s-%(id)s.%(ext)s')
198 or (opts.useid and u'%(id)s.%(ext)s')
199 or (opts.autonumber and u'%(autonumber)s-%(id)s.%(ext)s')
acd69589 200 or DEFAULT_OUTTMPL)
dca02c80 201 if not os.path.splitext(outtmpl)[1] and opts.extractaudio:
b61067fa 202 parser.error(u'Cannot download a video and extract audio into the same'
dca02c80
JMF
203 u' file! Use "{0}.%(ext)s" instead of "{0}" as the output'
204 u' template'.format(outtmpl))
29c7a63d 205
63e0be34 206 any_printing = opts.geturl or opts.gettitle or opts.getid or opts.getthumbnail or opts.getdescription or opts.getfilename or opts.getformat or opts.getduration or opts.dumpjson or opts.dump_single_json
4644ac55 207 download_archive_fn = compat_expanduser(opts.download_archive) if opts.download_archive is not None else opts.download_archive
525ef922 208
bdde425c 209 ydl_opts = {
59ae15a5
PH
210 'usenetrc': opts.usenetrc,
211 'username': opts.username,
212 'password': opts.password,
83317f69 213 'twofactor': opts.twofactor,
c6c19746 214 'videopassword': opts.videopassword,
525ef922 215 'quiet': (opts.quiet or any_printing),
ad8915b7 216 'no_warnings': opts.no_warnings,
59ae15a5
PH
217 'forceurl': opts.geturl,
218 'forcetitle': opts.gettitle,
1a2adf3f 219 'forceid': opts.getid,
59ae15a5
PH
220 'forcethumbnail': opts.getthumbnail,
221 'forcedescription': opts.getdescription,
525ef922 222 'forceduration': opts.getduration,
59ae15a5
PH
223 'forcefilename': opts.getfilename,
224 'forceformat': opts.getformat,
9d153818 225 'forcejson': opts.dumpjson,
63e0be34 226 'dump_single_json': opts.dump_single_json,
1bdeb7be
JMF
227 'simulate': opts.simulate or any_printing,
228 'skip_download': opts.skip_download,
59ae15a5
PH
229 'format': opts.format,
230 'format_limit': opts.format_limit,
231 'listformats': opts.listformats,
5cb9c312 232 'outtmpl': outtmpl,
213c31ae 233 'autonumber_size': opts.autonumber_size,
59ae15a5
PH
234 'restrictfilenames': opts.restrictfilenames,
235 'ignoreerrors': opts.ignoreerrors,
236 'ratelimit': opts.ratelimit,
237 'nooverwrites': opts.nooverwrites,
238 'retries': opts.retries,
239 'buffersize': opts.buffersize,
240 'noresizebuffer': opts.noresizebuffer,
241 'continuedl': opts.continue_dl,
242 'noprogress': opts.noprogress,
5717d91a 243 'progress_with_newline': opts.progress_with_newline,
59ae15a5
PH
244 'playliststart': opts.playliststart,
245 'playlistend': opts.playlistend,
47192f92 246 'noplaylist': opts.noplaylist,
59ae15a5
PH
247 'logtostderr': opts.outtmpl == '-',
248 'consoletitle': opts.consoletitle,
249 'nopart': opts.nopart,
250 'updatetime': opts.updatetime,
251 'writedescription': opts.writedescription,
1fb07d10 252 'writeannotations': opts.writeannotations,
59ae15a5 253 'writeinfojson': opts.writeinfojson,
11d9224e 254 'writethumbnail': opts.writethumbnail,
59ae15a5 255 'writesubtitles': opts.writesubtitles,
b004821f 256 'writeautomaticsub': opts.writeautomaticsub,
ae608b80 257 'allsubtitles': opts.allsubtitles,
2a4093ea 258 'listsubtitles': opts.listsubtitles,
9e62bc44 259 'subtitlesformat': opts.subtitlesformat,
d6e203b3 260 'subtitleslangs': opts.subtitleslangs,
8271226a
PH
261 'matchtitle': decodeOption(opts.matchtitle),
262 'rejecttitle': decodeOption(opts.rejecttitle),
59ae15a5
PH
263 'max_downloads': opts.max_downloads,
264 'prefer_free_formats': opts.prefer_free_formats,
265 'verbose': opts.verbose,
855703e5 266 'dump_intermediate_pages': opts.dump_intermediate_pages,
d41e6efc 267 'write_pages': opts.write_pages,
8d5d3a5d 268 'test': opts.test,
7851b379 269 'keepvideo': opts.keepvideo,
9e982f9e 270 'min_filesize': opts.min_filesize,
bd558525 271 'max_filesize': opts.max_filesize,
5fe18bdb
PH
272 'min_views': opts.min_views,
273 'max_views': opts.max_views,
11d9224e 274 'daterange': date,
7f747732 275 'cachedir': opts.cachedir,
f8061589 276 'youtube_print_sig_code': opts.youtube_print_sig_code,
8dbe9899 277 'age_limit': opts.age_limit,
17093b83 278 'download_archive': download_archive_fn,
dca08720
PH
279 'cookiefile': opts.cookiefile,
280 'nocheckcertificate': opts.no_check_certificate,
7e8c0af0 281 'prefer_insecure': opts.prefer_insecure,
c2e52508 282 'proxy': opts.proxy,
6ad14cab 283 'socket_timeout': opts.socket_timeout,
0783b09b 284 'bidi_workaround': opts.bidi_workaround,
a0ddb8a2 285 'debug_printtraffic': opts.debug_printtraffic,
76b1bd67 286 'prefer_ffmpeg': opts.prefer_ffmpeg,
7b0817e8 287 'include_ads': opts.include_ads,
04b4d394 288 'default_search': opts.default_search,
4919603f 289 'youtube_include_dash_manifest': opts.youtube_include_dash_manifest,
62fec3b2 290 'encoding': opts.encoding,
8d31fa3c 291 'exec_cmd': opts.exec_cmd,
057a5206 292 'extract_flat': opts.extract_flat,
bdde425c 293 }
59ae15a5 294
bdde425c 295 with YoutubeDL(ydl_opts) as ydl:
bdde425c
PH
296 # PostProcessors
297 # Add the metadata pp first, the other pps will copy it
298 if opts.addmetadata:
299 ydl.add_post_processor(FFmpegMetadataPP())
300 if opts.extractaudio:
301 ydl.add_post_processor(FFmpegExtractAudioPP(preferredcodec=opts.audioformat, preferredquality=opts.audioquality, nopostoverwrites=opts.nopostoverwrites))
302 if opts.recodevideo:
303 ydl.add_post_processor(FFmpegVideoConvertor(preferedformat=opts.recodevideo))
304 if opts.embedsubtitles:
305 ydl.add_post_processor(FFmpegEmbedSubtitlePP(subtitlesformat=opts.subtitlesformat))
e63fc1be 306 if opts.xattrs:
307 ydl.add_post_processor(XAttrMetadataPP())
0c14e2fb 308 if opts.embedthumbnail:
784763c5 309 if not opts.addmetadata:
310 ydl.add_post_processor(FFmpegAudioFixPP())
0c14e2fb 311 ydl.add_post_processor(AtomicParsleyPP())
bdde425c 312
a7cacbca 313
314 # Please keep ExecAfterDownload towards the bottom as it allows the user to modify the final file in any way.
315 # So if the user is able to remove the file before your postprocessor runs it might cause a few problems.
8d31fa3c
PH
316 if opts.exec_cmd:
317 ydl.add_post_processor(ExecAfterDownloadPP(
318 verboseOutput=opts.verbose, exec_cmd=opts.exec_cmd))
a7cacbca 319
bdde425c
PH
320 # Update version
321 if opts.update_self:
322 update_self(ydl.to_screen, opts.verbose)
323
052421ff
PH
324 # Remove cache dir
325 if opts.rm_cachedir:
a0e07d31 326 ydl.cache.remove()
052421ff 327
bdde425c 328 # Maybe do nothing
1dcc4c0c 329 if (len(all_urls) < 1) and (opts.load_info_filename is None):
052421ff 330 if not (opts.update_self or opts.rm_cachedir):
bdde425c
PH
331 parser.error(u'you must provide at least one URL')
332 else:
333 sys.exit()
59ae15a5 334
bdde425c 335 try:
1dcc4c0c
JMF
336 if opts.load_info_filename is not None:
337 retcode = ydl.download_with_info_file(opts.load_info_filename)
338 else:
339 retcode = ydl.download(all_urls)
bdde425c
PH
340 except MaxDownloadsReached:
341 ydl.to_screen(u'--max-download limit reached, aborting.')
342 retcode = 101
59ae15a5 343
59ae15a5 344 sys.exit(retcode)
235b3ba4 345
a27b9e8b 346
b8ad4f02 347def main(argv=None):
59ae15a5 348 try:
b8ad4f02 349 _real_main(argv)
59ae15a5
PH
350 except DownloadError:
351 sys.exit(1)
352 except SameFileError:
353 sys.exit(u'ERROR: fixed output name but more than one file to download')
354 except KeyboardInterrupt:
355 sys.exit(u'\nERROR: Interrupted by user')