forked from Kethsar/ytarchive
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ytarchive.py
executable file
·2257 lines (1821 loc) · 74.8 KB
/
ytarchive.py
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
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
import ast
from enum import Enum
import faulthandler
import getopt
from html.parser import HTMLParser
import http.cookiejar
import io
import json
import logging
import os
import platform
import queue
import shlex
import shutil
import signal
import socket
import subprocess
import sys
import tempfile
import time
import threading
import urllib.parse
import urllib.request
import urllib.error
import xml.etree.ElementTree as ET
ABOUT = {
"name": "ytarchive",
"version": "0.2.1",
"date": "2021/01/27",
"description": "Download youtube livestreams, from the beginning.",
"author": "Kethsar",
"license": "MIT",
"url": "https://github.com/Kethsar/ytarchive"
}
'''
TODO: Add more comments. Lots of code added without comments again.
'''
# Constants
INFO_URL = "https://www.youtube.com/get_video_info?video_id={0}&el=detailpage&html5=1"
WATCH_URL = "https://www.youtube.com/watch?v={0}"
HTML_VIDEO_LINK_TAG = '<link rel="canonical" href="https://www.youtube.com/watch?v='
INITIAL_PLAYER_RESPONSE_DECL = "ytInitialPlayerResponse ="
PLAYABLE_OK = "OK"
PLAYABLE_OFFLINE = "LIVE_STREAM_OFFLINE"
PLAYABLE_UNPLAYABLE = "UNPLAYABLE"
PLAYABLE_ERROR = "ERROR"
BAD_CHARS = '<>:"/\\|?*'
DTYPE_AUDIO = "audio"
DTYPE_VIDEO = "video"
DEFAULT_VIDEO_QUALITY = "best"
RECHECK_TIME = 15
FRAG_MAX_TRIES = 10
HOUR = 60 * 60
BUF_SIZE = 8192
WINDOWS = sys.platform in ["win32", "msys"]
# https://gist.github.com/AgentOak/34d47c65b1d28829bb17c24c04a0096f
AUDIO_ITAG = 140
VIDEO_LABEL_ITAGS = {
"audio_only": 0,
"144p": {"h264": 160, "vp9": 278},
"240p": {"h264": 133, "vp9": 242},
"360p": {"h264": 134, "vp9": 243},
"480p": {"h264": 135, "vp9": 244},
"720p": {"h264": 136, "vp9": 247},
"720p60": {"h264": 298, "vp9": 302},
"1080p": {"h264": 137, "vp9": 248},
"1080p60": {"h264": 299, "vp9": 303},
}
class Action(Enum):
ASK = 0
DO = 1
DO_NOT = 2
# Simple class to more easily keep track of what fields are available for
# file name formatting
class FormatInfo(dict):
DEFAULT_FNAME_FORMAT = "%(title)s-%(id)s"
DISALLOWED_FNAME_FORMAT_KEYS = [
"description",
]
def __init__(self):
dict.__init__(self, {
"id": "",
"url": "",
"title": "",
"channel_id": "",
"channel": "",
"upload_date": "",
"start_date": "",
"publish_date": "",
"description": "",
})
def set_info(self, player_response):
pmfr = player_response["microformat"]["playerMicroformatRenderer"]
vid_details = player_response["videoDetails"]
vid = vid_details["videoId"]
url = "https://www.youtube.com/watch?v={0}".format(vid)
# "uploadDate" is actually when the livestream was created, not when it will start
# Grab the actual start date from "startTimestamp"
start_date = pmfr["liveBroadcastDetails"]["startTimestamp"].replace("-", "")[:8]
self["id"] = vid
self["url"] = url
self["title"] = vid_details["title"]
self["channel_id"] = vid_details["channelId"]
self["channel"] = vid_details["author"]
# upload_date: Rather than the actual upload date, stream start date is used to
# provide a better default date for youtube-dl output templates that use upload_date.
self["upload_date"] = start_date
self["start_date"] = start_date
# publish_date: uploadDate and publishDate seem to be the same for streams,
# so this can be used for actual upload date
self["publish_date"] = pmfr["publishDate"].replace("-", "")
self["description"] = vid_details["shortDescription"]
def format(self, format_str):
return format_str % self
def filename_format(self, format_str):
return format_str % {
k: sterilize_filename(v)
for k, v in self.items()
if k not in self.DISALLOWED_FNAME_FORMAT_KEYS
}
# Info to be sent through the progress queue
class ProgressInfo:
def __init__(self, dtype, byte_count, max_seq):
self.data_type = dtype
self.bytes = byte_count
self.max_seq = max_seq
# Fragment information/data
class Fragment:
def __init__(self, seq, header_seqnum, fname, data):
self.seq = seq
self.fname = fname
self.x_head_seqnum = header_seqnum
self.data = data
# Metadata for the final file
class MetaInfo(dict):
def __init__(self):
dict.__init__(self, {
# Default format templates
"title": "%(title)s",
"artist": "%(channel)s",
"date": "%(upload_date)s",
# MP4 doesn't allow for a url metadata field
# Just put it at the top of the comment by default
"comment": "%(url)s\n\n%(description)s",
})
def set_meta(self, format_info):
for k, v in self.items():
self[k] = format_info.format(v)
class MediaDLInfo:
def __init__(self):
self.active_threads = 0
self.download_url = ""
self.base_fpath = ""
self.data_type = ""
self.stopping = False
# Miscellaneous information
class DownloadInfo:
def __init__(self):
# Python may have the GIL but it's better to be safe
# RLock so we can lock multiple times in the same thread without deadlocking
self.lock = threading.RLock()
self.format_info = FormatInfo()
self.metadata = MetaInfo()
self.stopping = False
self.in_progress = False
self.is_live = False
self.vp9 = False
self.is_unavailable = False
self.gvideo_ddl = False
self.thumbnail = ""
self.vid = ""
self.url = ""
self.selected_quality = ""
self.status = ""
self.dash_manifest_url = ""
self.wait = Action.ASK
self.quality = -1
self.retry_secs = 0
self.thread_count = 1
self.last_updated = 0
self.target_duration = 5
self.expires_in_seconds = 21540 # Usual 5h 59m expiration
self.mdl_info = {
DTYPE_VIDEO: MediaDLInfo(),
DTYPE_AUDIO: MediaDLInfo()
}
def set_status(self, status):
with self.lock:
self.status = status
self.print_status()
def print_status(self):
"""
For use after logging statements, since they wipe out the current status
with how I have things set up
"""
with self.lock:
print(self.status, end="")
# Fallback to get the player response object from the watch page HTML itself
class WatchPageParser(HTMLParser):
player_response_text = ""
def handle_data(self, data):
"""
Check tag data for INITIAL_PLAYER_RESPONSE_DECL at the start.
Turns out members videos have more than just the player_response
object delcaration. Should probably do a find instead of startswith
for the variable declaration as well, but whatever.
"""
decl_start = data.find(INITIAL_PLAYER_RESPONSE_DECL)
if decl_start < 0:
return
logdebug("Found script element with player response in watch page.")
obj_start = data.find("{", decl_start)
obj_end = data.find("};", obj_start) + 1
if obj_end > obj_start:
self.player_response_text = data[obj_start:obj_end]
# Logging functions;
# ansi sgr 0=reset, 1=bold, while 3x sets the foreground color:
# 0black 1red 2green 3yellow 4blue 5magenta 6cyan 7white
def logerror(msg):
logging.error("\033[31m{0}\033[0m\033[K".format(msg))
def logwarn(msg):
logging.warning("\033[33m{0}\033[0m\033[K".format(msg))
def loginfo(msg):
logging.info("\033[32m{0}\033[0m\033[K".format(msg))
def logdebug(msg):
logging.debug("\033[36m{0}\033[0m\033[K".format(msg))
if WINDOWS:
import ctypes
from ctypes.wintypes import HANDLE, BOOL, DWORD, LPWSTR, LPVOID
from ctypes import WinError, get_last_error
OpenProcess = ctypes.windll.kernel32.OpenProcess
OpenProcess.argtypes = (DWORD, BOOL, DWORD)
OpenProcess.restype = HANDLE
MiniDumpWriteDump = ctypes.windll.DbgHelp.MiniDumpWriteDump
MiniDumpWriteDump.argtypes = (HANDLE, DWORD, HANDLE, DWORD, DWORD, DWORD, DWORD)
MiniDumpWriteDump.restype = BOOL
CreateFile = ctypes.windll.kernel32.CreateFileW
CreateFile.argtypes = (LPWSTR, DWORD, DWORD, LPVOID, DWORD, DWORD, HANDLE)
CreateFile.restype = ctypes.wintypes.HANDLE
FILE_CREATE_ALWAYS = 2
FILE_GENERIC_RW = 0xc0000000
FILE_ATTRIBUTE_NORMAL = 0x80
PROCESS_ALL_ACCESS = 0x1f0fff
COREDUMP_MODE = 2 # 0=normal 2=fullMemory
def winfug(msg):
raise Exception('{} ({})'.format(msg, WinError(get_last_error())))
def windump(fn):
pid = os.getpid()
hproc = OpenProcess(PROCESS_ALL_ACCESS, False, pid)
if not hproc:
winfug('could not openprocess')
hfile = CreateFile(fn, FILE_GENERIC_RW, 0, None, FILE_CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, None)
if not hfile:
winfug('could not createfile')
res = MiniDumpWriteDump(hproc, pid, hfile, COREDUMP_MODE, 0, 0, 0)
if not res:
winfug('could not writedump')
logwarn('wrote coredump to [{}]'.format(fn))
class DoOrDie(object):
def __init__(self):
self.q = queue.Queue(64)
self.deadline = None
self.active_task = None
self.worker_thr = threading.Thread(target=self._worker, daemon=True)
self.worker_thr.start()
t = threading.Thread(target=self._watchdog, daemon=True)
t.start()
def do(self, timeout, fun, *args, **kwargs):
retq = queue.Queue()
self.q.put([timeout, fun, args, kwargs, retq])
ok, ret = retq.get()
if ok:
return ret
raise ret
def shutdown(self):
self.q.put(None)
self.worker_thr.join()
self.worker_thr = None
def _worker(self):
while True:
task = self.q.get()
if task is None:
break
timeout, fun, args, kwargs, ret_q = task
self.active_task = task
self.deadline = time.time() + timeout
try:
ret = self._exec(fun, args, kwargs)
ret_q.put([True, ret])
except Exception as ex:
logwarn("dod-ex: {!r}\n {!r}\n".format(task[:-1], ex))
ret_q.put([False, ex])
self.deadline = None
def _exec(self, fun, args, kwargs):
x = ["dod-exec: " + repr([fun, args, kwargs])]
ret = fun(*args, **kwargs)
del x[0]
def _watchdog(self):
while self.worker_thr:
time.sleep(1)
if not self.deadline:
continue
if time.time() >= self.deadline:
logerror("dod-time: {!r}".format(self.active_task[:-1]))
self._dump()
sys.exit(1)
def _dump(self):
ts = time.time()
fn = "coredump-{:.3f}.txt".format(ts)
with open(fn, "w", encoding="utf-8") as f:
f.write("\n".join([str(x) for x in [
platform.python_implementation(),
sys.version_info,
platform.system(),
sys.platform,
platform.python_compiler(),
platform.version(),
time.time(),
self.deadline,
repr(self.active_task)
]]) + "\n\n")
faulthandler.dump_traceback(file=f)
if WINDOWS:
fn = "coredump-{:.3f}.dmp".format(ts)
cw = windump(fn)
else:
os.kill(os.getpid(), signal.SIGABRT)
def sterilize_filename(fname):
"""
Remove any illegal filename chars
Not robust, but the combination of video title and id should prevent other illegal combinations
:param fname:
"""
for c in BAD_CHARS:
fname = fname.replace(c, "_")
return fname
def format_size(bsize):
"""
Pretty formatting of byte count
:param bsize:
"""
postfixes = ["bytes", "KiB", "MiB", "GiB"] # don't even bother with terabytes
i = 0
while bsize > 1024:
bsize = bsize / 1024
i += 1
return "{0:.2f}{1}".format(bsize, postfixes[i])
def execute(args):
"""
Execute an external process using the given args
Returns the process return code, or -1 on unknown error
:param args:
"""
retcode = 0
logdebug("Executing command: {0}".format(" ".join(shlex.quote(x) for x in args)))
print()
try:
subprocess.run(args, check=True, encoding="utf-8")
except subprocess.CalledProcessError as err:
retcode = err.returncode
except Exception as err:
logerror(err)
retcode = -1
return retcode
def patch_getaddrinfo(inet_family):
"""
Patch socket.getaddrinfo() to allow forcing IPv4 or IPv6
:param inet_family:
"""
orig_getaddrinfo = socket.getaddrinfo
def new_getaddrinfo(host, port, family=0, type=0, proto=0, flags=0):
return orig_getaddrinfo(host=host, port=port, family=inet_family, type=type, proto=proto, flags=flags)
socket.getaddrinfo = new_getaddrinfo
def download_as_text(url):
"""
Download data from the given URL and return it as unicode text
:param url:
"""
data = b""
try:
with urllib.request.urlopen(url, timeout=5) as resp:
data = resp.read()
except Exception as err:
logwarn("Failed to retrieve data from {0}: {1}".format(url, err))
return ""
return data.decode("utf-8")
def download_thumbnail(url, fname):
try:
with urllib.request.urlopen(url, timeout=5) as resp:
with open(fname, "wb") as f:
f.write(resp.read())
except Exception as err:
logwarn("Failed to download thumbnail: {0}".format(err))
return False
return True
def get_player_response(info):
"""
Get the base player response object for the given video id
:param info:
"""
#vinfo = download_as_text(INFO_URL.format(info.vid))
#parsedinfo = None
player_response = None
"""if not vinfo or len(vinfo) == 0:
logwarn("get_video_info failed to return data.")
logwarn("Attempting to get data from watch page.")
"""
watch_html = download_as_text(WATCH_URL.format(info.vid))
if len(watch_html) == 0:
logwarn("Watch page did not return any data. What?")
return None
watch_parser = WatchPageParser()
watch_parser.feed(watch_html)
if len(watch_parser.player_response_text) == 0:
logwarn("Player response not found in the watch page.")
return None
player_response = json.loads(watch_parser.player_response_text)
"""else:
parsedinfo = urllib.parse.parse_qs(vinfo)
player_response = json.loads(parsedinfo["player_response"][0])
"""
return player_response
def make_quality_list(formats):
"""
Make a comma-separated list of available formats
:param formats:
"""
qualities = ""
quarity = ""
for f in formats:
qualities += f + ", "
qualities += "best"
return qualities
def parse_quality_list(formats, quality):
"""
Parse the user-given list of qualities they are willing to accept for download
:param formats:
:param quality:
"""
selected_qualities = []
quality = quality.lower().strip()
selected_quarities = quality.split("/")
for q in selected_quarities:
stripped = q.strip()
if stripped in formats or stripped == "best":
selected_qualities.append(q)
if len(selected_qualities) < 1:
print("No valid qualities selected")
return selected_qualities
def get_quality_from_user(formats, waiting=False):
"""
Prompt the user to select a video quality
:param formats:
:param waiting:
"""
if waiting:
print("Since you are going to wait for the stream, you must pre-emptively select a video quality.")
print(
"There is no way to know which qualities will be available before the stream starts, so a list of all possible stream qualities will be presented.")
print("You can use youtube-dl style selection (slash-delimited first to last preference). Default is 'best'\n")
quarity = ""
selected_qualities = []
qualities = make_quality_list(formats)
print("Available video qualities: {0}".format(qualities))
while len(selected_qualities) < 1:
quarity = better_input("Enter desired video quality: ")
quarity = quarity.lower().strip()
if quarity == "":
quarity = DEFAULT_VIDEO_QUALITY
selected_qualities = parse_quality_list(formats, quarity)
return selected_qualities
def get_yes_no(msg):
yesno = better_input("{0} [y/N]: ".format(msg)).lower().strip()
return yesno.startswith("y")
def ask_wait_for_stream(info):
"""
Ask if the user wants to wait for a scheduled stream to start and then record it
:param info:
"""
print("{0} is probably a future scheduled livestream.".format(info.url))
print("Would you like to wait for the scheduled start time, poll until it starts, or not wait?")
choice = better_input("wait/poll/[no]: ").lower().strip()
if choice.startswith("wait"):
return True
elif choice.startswith("poll"):
secs = better_input("Input poll interval in seconds (15 or more recommended): ").strip()
try:
info.retry_secs = abs(int(secs))
except Exception:
logerror("Poll interval must be a whole number. Given {0}".format(secs))
sys.exit(1)
return True
return False
def get_playable_player_response(info):
"""
Keep retrieving the player response object until the playability status is OK
:param info:
"""
first_wait = True
retry = True
player_response = {}
secs_late = 0
selected_qualities = []
if info.selected_quality:
selected_qualities = parse_quality_list(list(VIDEO_LABEL_ITAGS.keys()), info.selected_quality)
while retry:
player_response = get_player_response(info)
if not player_response:
return {"noPlayerResponse": True}
if not "videoDetails" in player_response:
if info.in_progress:
logwarn("Video details no longer available mid download.")
logwarn("Stream was likely privated after finishing.")
logwarn("We will continue to download, but if it starts to fail, nothing can be done.")
info.print_status()
info.is_live = False
info.is_unavailable = True
else:
print("Video Details not found, video is likely private or does not exist.")
return {}
if not player_response["videoDetails"]["isLiveContent"]:
print("{0} is not a livestream. It would be better to use youtube-dl to download it.".format(info.url))
return {}
playability = player_response["playabilityStatus"]
playability_status = playability["status"]
if playability_status == PLAYABLE_ERROR:
logwarn("Playability status: ERROR. Reason: {0}".format(playability["reason"]))
if info.in_progress:
loginfo("Finishing download")
info.is_live = False
return {}
elif playability_status == PLAYABLE_UNPLAYABLE:
logged_in = not player_response["responseContext"]["mainAppWebResponseContext"]["loggedOut"]
logwarn("Playability status: Unplayable.")
logwarn("Reason: {0}".format(playability["reason"]))
logwarn("Logged in status: {0}".format(logged_in))
logwarn(
"If this is a members only stream, you provided a cookies.txt file, and the above 'logged in' status is not True, please try updating your cookies file.")
logwarn(
"Also check if your cookies file includes '#HttpOnly_' in front of some lines. If it does, delete that part of those lines and try again.")
if info.in_progress:
info.print_status()
info.is_live = False
info.is_unavailable = True
return {}
elif playability_status == PLAYABLE_OFFLINE:
# We've already started downloading, stream might be experiencing issues
if info.in_progress:
logdebug("Livestream status is {0} mid-download".format(PLAYABLE_OFFLINE))
return {}
if info.wait == Action.DO_NOT:
print("Stream appears to be a future scheduled stream, and you opted not to wait.")
return {}
if first_wait and info.wait == Action.ASK and info.retry_secs == 0:
if not ask_wait_for_stream(info):
return {}
if first_wait:
print()
if len(selected_qualities) < 1:
selected_qualities = get_quality_from_user(list(VIDEO_LABEL_ITAGS.keys()), True)
if info.retry_secs > 0:
if first_wait:
try:
poll_delay_ms = playability["liveStreamability"]["liveStreamabilityRenderer"]["pollDelayMs"]
poll_delay = int(int(poll_delay_ms) / 1000)
if info.retry_secs < poll_delay:
info.retry_secs = poll_delay
except:
pass
print("Waiting for stream, retrying every {0} seconds...".format(info.retry_secs))
first_wait = False
time.sleep(info.retry_secs)
continue
# Jesus fuck youtube, embed some more objects why don't you
sched_time = int(playability["liveStreamability"]["liveStreamabilityRenderer"]["offlineSlate"][
"liveStreamOfflineSlateRenderer"]["scheduledStartTime"])
cur_time = int(time.time())
slep_time = sched_time - cur_time
if slep_time > 0:
if not first_wait:
if secs_late > 0:
print()
print("Stream rescheduled")
first_wait = False
secs_late = 0
print("Stream starts in {0} seconds. Waiting for this time to elapse...".format(slep_time))
# Loop it just in case a rogue sleep interrupt happens
while slep_time > 0:
# There must be a better way but whatever
time.sleep(slep_time)
cur_time = int(time.time())
slep_time = sched_time - cur_time
if slep_time > 0:
logdebug("Woke up {0} seconds early. Continuing sleep...".format(slep_time))
# We've waited until the scheduled time
continue
if first_wait:
print("Stream should have started, checking back every {0} seconds".format(RECHECK_TIME))
first_wait = False
# If we get this far, the stream's scheduled time has passed but it's still not started
# Check every 15 seconds
time.sleep(RECHECK_TIME)
secs_late += RECHECK_TIME
print("\rStream is {0} seconds late...".format(secs_late), end="")
continue
elif playability_status != PLAYABLE_OK:
if secs_late > 0:
print()
logwarn("Unknown playability status: {0}".format(playability_status))
if info.in_progress:
info.is_live = False
return {}
if secs_late > 0:
print()
retry = False
return {"player_response": player_response, "selected_qualities": selected_qualities}
def is_fragmented(url):
# Per anon, there will be a noclen parameter if the given URLs
# are meant to be downloaded in fragments. Else it will have a clen
# parameter obviously specifying content length.
return url.lower().find("noclen") >= 0
def get_urls_from_manifest(manifest):
"""
Parse the DASH manifest XML and get the download URLs from it
:param manifest:
:return:
"""
urls = {}
try:
root = ET.fromstring(manifest)
reps = root.findall(".//{*}Representation")
for r in reps:
itag = r.get("id")
url = r.find("{*}BaseURL").text + "sq/{0}"
try:
int(itag)
except Exception:
continue
if itag and url:
urls[int(itag)] = url
except Exception as err:
logwarn("Error parsing DASH manifest: {0}".format(err))
return urls
def get_download_urls(info, formats):
"""
Get download URLs either from the DASH manifest or from the adaptiveFormats
Prioritize DASH manifest if it is available
:param info:
:param formats:
"""
urls = {}
if info.dash_manifest_url:
manifest = download_as_text(info.dash_manifest_url)
if manifest:
urls = get_urls_from_manifest(manifest)
if urls:
return urls
for fmt in formats:
if "url" in fmt:
urls[fmt["itag"]] = fmt["url"] + "&sq={0}"
return urls
def get_video_info(info):
"""
Get necessary video info such as video/audio URLs
Stores them in info
:param info:
"""
with info.lock: # Because I forgot some releases, this is worth the extra indent
if info.gvideo_ddl:
# We have no idea if we can get the video information.
# Don't even bother to avoid complexity. Might change later.
return False
if info.stopping:
return False
# We already know there's no information to be gotten
if info.is_unavailable:
return None
# Almost nothing we care about is likely to change in 15 seconds,
# except maybe whether the livestream is online
update_delta = time.time() - info.last_updated
if update_delta < RECHECK_TIME:
return False
info.last_updated = time.time()
vals = get_playable_player_response(info)
if not vals:
return False
if "noPlayerResponse" in vals:
info.is_live = False
info.is_unavailable = True
return False
player_response = vals["player_response"]
selected_qualities = vals["selected_qualities"]
streaming_data = player_response["streamingData"]
pmfr = player_response["microformat"]["playerMicroformatRenderer"]
live_details = pmfr["liveBroadcastDetails"]
is_live = live_details["isLiveNow"]
if not is_live and not info.in_progress:
# Likely the livestream ended already.
# Check if the stream has been mostly processed.
# If not then download it. Else youtube-dl is a better choice.
if "endTimestamp" in live_details:
# Assume that all formats will be fully processed if one is, and vice versa
if not ("adaptiveFormats" in streaming_data
and "url" in streaming_data["adaptiveFormats"][0]):
print("Livestream has ended and is being processed. Download URLs are not available.")
return False
url = streaming_data["adaptiveFormats"][0]["url"]
if not is_fragmented(url):
print("Livestream has been processed, use youtube-dl instead.")
return False
else:
print("Livestream is offline, should have started, but has no end timestamp.")
print("You could try again, or try youtube-dl.")
return False
if "dashManifestUrl" in streaming_data: # Should be but maybe it isn't sometimes
info.dash_manifest_url = streaming_data["dashManifestUrl"]
formats = streaming_data["adaptiveFormats"]
info.target_duration = formats[0].get("targetDurationSec", info.target_duration)
dl_urls = get_download_urls(info, formats)
if info.quality < 0:
qualities = ["audio_only"]
itags = list(VIDEO_LABEL_ITAGS.keys())
found = False
# Generate a list of available qualities, sorted in order from best to worst
# Assuming if VP9 is available, h264 should be available for that quality too
for fmt in formats:
if fmt["mimeType"].startswith("video/mp4"):
qlabel = fmt["qualityLabel"].lower()
priority = itags.index(qlabel)
idx = 0
for q in qualities:
p = itags.index(q)
if p > priority:
break
idx += 1
qualities.insert(idx, qlabel)
while not found:
if len(selected_qualities) == 0:
selected_qualities = get_quality_from_user(qualities)
for q in selected_qualities:
q = q.strip()
# Get the best quality of those availble.
# This is why we sorted the list as we made it.
if q == "best":
q = qualities[len(qualities) - 1]
video_itag = VIDEO_LABEL_ITAGS[q]
aonly = video_itag == VIDEO_LABEL_ITAGS["audio_only"]
info.mdl_info[DTYPE_AUDIO].download_url = dl_urls[AUDIO_ITAG]
if aonly:
info.quality = video_itag
info.mdl_info[DTYPE_VIDEO].download_url = ""
found = True
break
if info.vp9 and video_itag["vp9"] in dl_urls:
info.mdl_info[DTYPE_VIDEO].download_url = dl_urls[video_itag["vp9"]]
info.quality = video_itag["vp9"]
found = True
print("Selected quality: {0} (VP9)".format(q))
break
elif video_itag["h264"] in dl_urls:
info.mdl_info[DTYPE_VIDEO].download_url = dl_urls[video_itag["h264"]]
info.quality = video_itag["h264"]
found = True
print("Selected quality: {0} (h264)".format(q))
break
# None of the qualities the user gave were available
# Should only be possible if they chose to wait for a stream
# and chose only qualities that the streamer ended up not using
# i.e. 1080p60/720p60 when the stream is only available in 30 FPS
if not found:
print("\nThe qualities you selected ended up unavailble for this stream")
print("You will now have the option to select from the available qualities")
selected_qualities.clear()
else:
aonly = info.quality == VIDEO_LABEL_ITAGS["audio_only"]
# Don't bother with refreshing the URL if it's not the kind we can even use
if AUDIO_ITAG in dl_urls and is_fragmented(dl_urls[AUDIO_ITAG]):
info.mdl_info[DTYPE_AUDIO].download_url = dl_urls[AUDIO_ITAG]
if not aonly:
if info.quality in dl_urls and is_fragmented(dl_urls[info.quality]):
info.mdl_info[DTYPE_VIDEO].download_url = dl_urls[info.quality]
# Grab some extra info on the first run through this function
if not info.in_progress: