-
-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Expand file tree
/
Copy pathyoutube.py
More file actions
430 lines (381 loc) · 15.9 KB
/
Copy pathyoutube.py
File metadata and controls
430 lines (381 loc) · 15.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
"""
$description Global live-streaming and video hosting social platform owned by Google.
$url youtube.com
$url youtu.be
$type live
$metadata id
$metadata author
$metadata category
$metadata title
$notes VOD content and protected videos are not supported
"""
import re
from urllib.parse import urlparse, urlunparse
from streamlink.logger import getLogger
from streamlink.plugin import Plugin, PluginError, pluginmatcher
from streamlink.plugin.api import useragents, validate
from streamlink.stream.ffmpegmux import MuxedStream
from streamlink.stream.hls import HLSStream
from streamlink.stream.http import HTTPStream
from streamlink.utils.data import search_dict
from streamlink.utils.parse import parse_json
log = getLogger(__name__)
@pluginmatcher(
name="default",
pattern=re.compile(
r"https?://(?:\w+\.)?youtube\.com/(?:v/|live/|watch\?(?:.*&)?v=)(?P<video_id>[\w-]{11})",
),
)
@pluginmatcher(
name="channel",
pattern=re.compile(
r"https?://(?:\w+\.)?youtube\.com/(?:@|c(?:hannel)?/|user/)?(?P<channel>[^/?]+)(?P<live>/live)?/?$",
),
)
@pluginmatcher(
name="embed",
pattern=re.compile(
r"https?://(?:\w+\.)?youtube\.com/embed/(?:live_stream\?channel=(?P<live>[^/?&]+)|(?P<video_id>[\w-]{11}))",
),
)
@pluginmatcher(
name="shorthand",
pattern=re.compile(
r"https?://youtu\.be/(?P<video_id>[\w-]{11})",
),
)
class YouTube(Plugin):
_re_ytInitialData = re.compile(r"""var\s+ytInitialData\s*=\s*({.*?})\s*;\s*</script>""", re.DOTALL)
_re_ytInitialPlayerResponse = re.compile(r"""var\s+ytInitialPlayerResponse\s*=\s*({.*?});\s*var\s+\w+\s*=""", re.DOTALL)
_url_canonical = "https://www.youtube.com/watch?v={video_id}"
_url_channelid_live = "https://www.youtube.com/channel/{channel_id}/live"
# There are missing itags
adp_video = {
137: "1080p",
299: "1080p60", # HFR
264: "1440p",
308: "1440p60", # HFR
266: "2160p",
315: "2160p60", # HFR
138: "2160p",
302: "720p60", # HFR
135: "480p",
133: "240p",
160: "144p",
}
adp_audio = {
140: 128,
141: 256,
171: 128,
249: 48,
250: 64,
251: 160,
256: 256,
258: 258,
}
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
parsed = urlparse(self.url)
# translate input URLs to be able to find embedded data and to avoid unnecessary HTTP redirects
if parsed.netloc == "gaming.youtube.com":
self.url = urlunparse(parsed._replace(scheme="https", netloc="www.youtube.com"))
elif self.matches["shorthand"]:
self.url = self._url_canonical.format(video_id=self.match["video_id"])
elif self.matches["embed"] and self.match["video_id"]:
self.url = self._url_canonical.format(video_id=self.match["video_id"])
elif self.matches["embed"] and self.match["live"]:
self.url = self._url_channelid_live.format(channel_id=self.match["live"])
elif parsed.scheme != "https":
self.url = urlunparse(parsed._replace(scheme="https"))
self.session.http.headers.update({"User-Agent": useragents.CHROME})
@classmethod
def stream_weight(cls, stream: str) -> tuple[float, str]:
match_3d = re.match(r"(\w+)_3d", stream)
match_hfr = re.match(r"(\d+p)(\d+)", stream)
if match_3d:
weight, group = Plugin.stream_weight(match_3d.group(1))
weight -= 1
group = "youtube_3d"
elif match_hfr:
weight, group = Plugin.stream_weight(match_hfr.group(1))
weight += 1
group = "high_frame_rate"
else:
weight, group = Plugin.stream_weight(stream)
return weight, group
@staticmethod
def _schema_consent(data):
schema_consent = validate.Schema(
validate.parse_html(),
validate.any(
validate.xml_find(".//form[@action='https://consent.youtube.com/s']"),
validate.all(
validate.xml_xpath(".//form[@action='https://consent.youtube.com/save']"),
validate.filter(lambda elem: elem.xpath(".//input[@type='hidden'][@name='set_ytc'][@value='true']")),
validate.get(0),
),
),
validate.union((
validate.get("action"),
validate.xml_xpath(".//input[@type='hidden']"),
)),
)
return schema_consent.validate(data)
def _schema_canonical(self, data):
schema_canonical = validate.Schema(
validate.parse_html(),
validate.xml_xpath_string(".//link[@rel='canonical'][1]/@href"),
validate.regex(self.matchers["default"].pattern),
validate.get("video_id"),
)
return schema_canonical.validate(data)
@classmethod
def _schema_playabilitystatus(cls, data):
schema = validate.Schema(
{
"playabilityStatus": {
"status": str,
validate.optional("reason"): validate.any(str, None),
},
},
validate.get("playabilityStatus"),
validate.union_get("status", "reason"),
)
return schema.validate(data)
@classmethod
def _schema_videodetails(cls, data):
schema = validate.Schema(
{
"videoDetails": {
"videoId": str,
"author": str,
"title": str,
validate.optional("isLive"): validate.transform(bool),
validate.optional("isLiveContent"): validate.transform(bool),
validate.optional("isLiveDvrEnabled"): validate.transform(bool),
validate.optional("isLowLatencyLiveStream"): validate.transform(bool),
validate.optional("isPrivate"): validate.transform(bool),
},
"microformat": validate.all(
validate.any(
validate.all(
{"playerMicroformatRenderer": dict},
validate.get("playerMicroformatRenderer"),
),
validate.all(
{"microformatDataRenderer": dict},
validate.get("microformatDataRenderer"),
),
),
{
"category": str,
},
),
},
validate.union_get(
("videoDetails", "videoId"),
("videoDetails", "author"),
("microformat", "category"),
("videoDetails", "title"),
("videoDetails", "isLive"),
),
)
videoDetails = schema.validate(data)
log.trace("videoDetails = %r", videoDetails)
return videoDetails
@classmethod
def _schema_streamingdata(cls, data):
schema = validate.Schema(
{
"streamingData": {
validate.optional("hlsManifestUrl"): str,
validate.optional("formats"): [
validate.all(
{
"itag": int,
"qualityLabel": str,
validate.optional("url"): validate.url(scheme="http"),
},
validate.union_get("url", "qualityLabel"),
),
],
validate.optional("adaptiveFormats"): [
validate.all(
{
"itag": int,
"mimeType": validate.all(
str,
validate.regex(
re.compile(r"""^(?P<type>\w+)/(?P<container>\w+); codecs="(?P<codecs>.+)"$"""),
),
validate.union_get("type", "codecs"),
),
validate.optional("url"): validate.url(scheme="http"),
validate.optional("qualityLabel"): str,
},
validate.union_get("url", "qualityLabel", "itag", "mimeType"),
),
],
},
},
validate.get("streamingData"),
validate.union_get("hlsManifestUrl", "formats", "adaptiveFormats"),
)
hls_manifest, formats, adaptive_formats = schema.validate(data)
return hls_manifest, formats or [], adaptive_formats or []
def _create_adaptive_streams(self, adaptive_formats):
streams = {}
adaptive_streams = {}
audio_streams = {}
best_audio_itag = None
# Extract audio streams from the adaptive format list
for url, _label, itag, mimeType in adaptive_formats:
if url is None:
continue
# extract any high quality streams only available in adaptive formats
adaptive_streams[itag] = url
stream_type, stream_codec = mimeType
stream_codec = re.sub(r"^(\w+).*$", r"\1", stream_codec)
if stream_type == "audio" and itag in self.adp_audio:
audio_bitrate = self.adp_audio[itag]
if stream_codec not in audio_streams or audio_bitrate > self.adp_audio[audio_streams[stream_codec]]:
audio_streams[stream_codec] = itag
# find the best quality audio stream m4a, opus or vorbis
if best_audio_itag is None or audio_bitrate > self.adp_audio[best_audio_itag]:
best_audio_itag = itag
if (
not best_audio_itag
or self.session.http.head(adaptive_streams[best_audio_itag], raise_for_status=False).status_code >= 400
):
return {}
streams.update({
f"audio_{stream_codec}": HTTPStream(self.session, adaptive_streams[itag])
for stream_codec, itag in audio_streams.items()
})
if best_audio_itag and adaptive_streams and MuxedStream.is_usable(self.session):
aurl = adaptive_streams[best_audio_itag]
for itag, name in self.adp_video.items():
if itag not in adaptive_streams:
continue
vurl = adaptive_streams[itag]
log.debug(f"MuxedStream: v {itag} a {best_audio_itag} = {name}")
streams[name] = MuxedStream(
self.session,
HTTPStream(self.session, vurl),
HTTPStream(self.session, aurl),
)
return streams
def _get_res(self, url):
res = self.session.http.get(url)
if urlparse(res.url).netloc == "consent.youtube.com":
target, elems = self._schema_consent(res.text)
c_data = {
elem.attrib.get("name"): elem.attrib.get("value")
for elem in elems
} # fmt: skip
log.debug(f"consent target: {target}")
log.debug(f"consent data: {', '.join(c_data.keys())}")
res = self.session.http.post(target, data=c_data)
return res
@staticmethod
def _get_data_from_regex(res, regex, descr):
match = re.search(regex, res.text)
if not match:
log.debug(f"Missing {descr}")
return
return parse_json(match.group(1))
def _get_data_from_api(self, res):
try:
video_id = self.match["video_id"]
except IndexError:
video_id = None
if video_id is None:
try:
video_id = self._schema_canonical(res.text)
except (PluginError, TypeError):
return
if m := re.search(r"""(?P<q1>["'])INNERTUBE_API_KEY(?P=q1)\s*:\s*(?P<q2>["'])(?P<data>.+?)(?P=q2)""", res.text):
api_key = m.group("data")
else:
api_key = "AIzaSyAO_FJ2SlqU8Q4STEHLGCilw_Y9_11qcW8"
return self.session.http.post(
"https://www.youtube.com/youtubei/v1/player",
headers={"Content-Type": "application/json"},
params={"key": api_key},
json={
"videoId": video_id,
"contentCheckOk": True,
"racyCheckOk": True,
"context": {
"client": {
"clientName": "ANDROID",
"clientVersion": "21.08.266",
"platform": "DESKTOP",
"clientScreen": "EMBED",
"clientFormFactor": "UNKNOWN_FORM_FACTOR",
"browserName": "Chrome",
},
"user": {"lockedSafetyMode": "false"},
"request": {"useSsl": "true"},
},
},
schema=validate.Schema(
validate.parse_json(),
),
)
@staticmethod
def _data_video_id(data):
if not data:
return None
for key in ("videoRenderer", "gridVideoRenderer"):
for videoRenderer in search_dict(data, key):
videoId = videoRenderer.get("videoId")
if videoId is not None:
return videoId
def _get_streams(self):
res = self._get_res(self.url)
if self.matches["channel"] and not self.match["live"]:
initial = self._get_data_from_regex(res, self._re_ytInitialData, "initial data")
video_id = self._data_video_id(initial)
if video_id is None:
log.error("Could not find videoId on channel page")
return
self.url = self._url_canonical.format(video_id=video_id)
res = self._get_res(self.url)
# TODO: clean up the validation schemas and how they're applied
if not (data := self._get_data_from_api(res)):
return
status, reason = self._schema_playabilitystatus(data)
# assume that there's an error if reason is set (status will still be "OK" for some reason)
if status != "OK" or reason:
log.error(f"Could not get video info - {status}: {reason}")
return
# the initial player response contains the category data, which the API response does not
init_player_response = self._get_data_from_regex(res, self._re_ytInitialPlayerResponse, "initial player response")
self.id, self.author, self.category, self.title, is_live = self._schema_videodetails(init_player_response)
log.debug(f"Using video ID: {self.id}")
if is_live:
log.debug("This video is live.")
# TODO: remove parsing of non-HLS stuff, as we don't support this
streams = {}
hls_manifest, formats, adaptive_formats = self._schema_streamingdata(data)
protected = any(url is None for url, *_ in formats + adaptive_formats)
if protected:
log.debug("This video may be protected.")
for url, label in formats:
if url is None:
continue
if self.session.http.head(url, raise_for_status=False).status_code >= 400:
break
streams[label] = HTTPStream(self.session, url)
if not is_live:
streams.update(self._create_adaptive_streams(adaptive_formats))
if hls_manifest:
streams.update(HLSStream.parse_variant_playlist(self.session, hls_manifest, name_key="pixels"))
if not streams:
if protected:
raise PluginError("This plugin does not support protected videos, try yt-dlp instead")
if formats or adaptive_formats:
raise PluginError("This plugin does not support VOD content, try yt-dlp instead")
return streams
__plugin__ = YouTube