-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathytdash-requests
1839 lines (1804 loc) · 81.9 KB
/
ytdash-requests
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
# -*- coding: utf-8 -*-
from concurrent.futures import ThreadPoolExecutor, TimeoutError
from threading import active_count as active_threads
try:
import xml.etree.cElementTree as ET
except ImportError:
import xml.etree.ElementTree as ET
from urllib.parse import parse_qs, urlparse, urlencode
from io import BytesIO
import certifi
import logging
import os
import signal
import sys
import time
import subprocess
import re
import shlex
import json
import argparse
# import chardet
try:
import gi
gi.require_version('Gdk', '3.0')
from gi.repository import Gdk
w = Gdk.get_default_root_window()
maxwidth, maxheight = w.get_geometry()[2:4]
del gi
except ImportError:
maxwidth, maxheight = 1360, 768
pass
def time_type(string):
# timepattern=re.compile(r"^[0-9]+[h,s,m]{0,1}$")
if not re.match(r"^[+,-]{0,1}[0-9]+[HhMmSs]+$|^$", string):
raise argparse.ArgumentTypeError
return string
def request(url=None, mode='body'):
# HEADERS = ['Connection: Keep-Alive', 'Keep-Alive: 300']
# rawheaders = BytesIO()
# content = BytesIO()
headers = 0
curlobj = pycurl.Curl()
curlobj.setopt(pycurl.VERBOSE, 0)
# curlobj.setopt(pycurl.HEADER, 1)
# curlobj.setopt(pycurl.ACCEPT_ENCODING, 'gzip, deflate')
curlobj.setopt(pycurl.CONNECTTIMEOUT, 15)
curlobj.setopt(pycurl.TIMEOUT, 0)
curlobj.setopt(pycurl.TRANSFER_ENCODING, 1)
# curlobj.setopt_string(CURLOPT_TCP_FASTOPEN, "1L")
# curlobj.setopt(pycurl.RETURN_TRANSFER, True)
curlobj.setopt(pycurl.TCP_KEEPALIVE, 1)
curlobj.setopt(pycurl.PIPEWAIT, 1)
# if live:
# curlobj.setopt(pycurl.BUFFERSIZE, 524288)
# curlobj.setopt(pycurl.NOSIGNAL, 1)
curlobj.setopt(pycurl.HEADER, 0)
# curlobj.setopt(pycurl.KEEP_SENDING_ON_ERROR, 1)
# curlobj.setopt(pycurl.HTTPHEADER, HEADERS)
curlobj.setopt(pycurl.FOLLOWLOCATION, 1)
curlobj.setopt(pycurl.CAINFO, certifi.where())
# curlobj.setopt(pycurl.NOBODY, 0)
if mode == 'head':
curlobj.setopt(pycurl.NOBODY, 1)
# elif mode == 'body':
# content = BytesIO()
# curlobj.setopt(curlobj.WRITEDATA, content)
# curlobj.setopt(pycurl.HEADERFUNCTION, rawheaders.write)
if url:
curlobj.set_url(url)
body = curlobj.get()
status = curlobj.getinfo(pycurl.RESPONSE_CODE)
headers = dict_from_bytes(body)
return curlobj, headers
def dict_from_bytes(byteheaders):
headers = {}
byteheaders.seek(0)
listheaders = byteheaders.read().decode('iso-8859-1').split('\r\n')
for header in listheaders:
if re.match(r'.*: .*', header):
header = header.split(': ')
headers[header[0]] = header[1]
return headers
class Ended(Exception):
pass
def log_(infos):
logging.debug('''---> Going %s, to VID: %s
REMAINING SEGMENTS: %s
MIN DELAY: %s
FFMUX DELAY: %s
DELAY TO UP: %s
TRUE DELAYS: %s
TRUE DELAY AVG: %s
BASE DELAYS: %s
BASE DELAY AVG: %s
DELAYS: %s
DELAY AVG: %s
CURRENT BAND: %s
NEXT BAND: %s
MIN BANDWIDTH AVGS: %s
MIN BANDWIDTH LASTS: %s
BANDWIDTH LASTS AVG: %s
SPEED: %s
NEW VIDEO URL: %s''' % infos)
def get_quality_ids(mediadata, Bandwidths):
minband = min(Bandwidths[1:])[-1]
logging.debug("MINBANDS: %s" % Bandwidths[1:])
mid = len(mediadata) - 1
aid = 1
audioband = 144000
logging.debug('Videodata Attribs: %s' % mediadata[mid][minvid].attrib)
for idv in range(len(mediadata[mid])):
manband = mediadata[mid][idv].attrib.get('bandwidth', 0)
manband = int(manband) + audioband
vid = idv
if manband > minband:
# or manband / 8 > maxband * 1024
break
vid = max(idv - 1, minvid)
logging.debug('VID SELECTED: %s' % vid)
return (aid, vid)
def parse_media_data(downobj, videoquery):
ytdict = parse_qs(videoquery, strict_parsing=False)
if ytdict:
metadata = {}
otf = False
streamtype = ytdict.get('qoe_cat')
if streamtype:
otf = True
metadata['Otf'] = otf
logging.debug('stream type: ' + str(streamtype))
else:
logging.info('Could not get main dictionary...')
return 3
ytpresp = json.loads(ytdict.get('player_response', [0])[0])
if ytpresp:
playable = ytpresp.get('playabilityStatus')
pstatus = playable.get('status')
reason = playable.get('reason')
if pstatus == 'UNPLAYABLE':
logging.info('Video status: UNPLAYABLE')
if reason:
href = re.findall(r'(?<=href=").*?(?=")', reason)
if href:
reco = re.findall(r'(?<=>).*?(?=<)', reason)
if reco:
reco = reco[0] + ' --> ' + href[0]
realreason = re.findall(r'(?<=\n).*$', reason)
if realreason:
reason = realreason[0] + '\n' + reco
logging.info("Reason: %s" % reason)
return 2
else:
logging.info('Could not extract player response data...')
return 3
logging.info("Video id: %s" % videoid)
# Player configs json:
# ytpjs = re.findall(r'ytplayer.config = ({.*?});', r.text)
# if not ytpjs:
# return 1
# ytpjson = json.loads(ytpjs[0])
# ytpargs = ytpjson['args']
liveaheadsecs = ytdict.get('live_readahead_seconds')
liveaheadchunk = ytdict.get('live_chunk_readahead')
latencyclass = ytdict.get('latency_class')
livestream = ytdict.get('livestream')
liveplayback = ytdict.get('live_playback')
# lengthsecs = ytpjson['args']['length_seconds']
# ytpresp = json.loads(ytpjson['args']['player_response'])
ytpconfig = ytpresp.get('playerConfig')
if ytpconfig:
audioconfig = ytpconfig.get('audioConfig')
streamconfig = ytpconfig.get('streamSelectionConfig')
if streamconfig:
maxbitrate = streamconfig.get('maxBitrate')
logging.info('MaxBitrate: ' + maxbitrate)
# Get Video Details:
videodetails = ytpresp.get('videoDetails')
if videodetails:
metadata.update(videodetails)
title = videodetails.get('title')
description = videodetails.get('shortDescription')
author = videodetails.get('author')
isprivate = videodetails.get('isPrivate')
viewcount = videodetails.get('viewCount')
lengthsecs = videodetails['lengthSeconds']
postlivedvr = videodetails.get('isPostLiveDvr')
livecontent = videodetails.get('isLiveContent')
live = videodetails.get('isLive', False)
lowlatency = videodetails.get('isLowLatencyLiveStream')
livedvr = videodetails.get('isLiveDvrEnabled')
# Get streaming Data:
streamingdata = ytpresp.get('streamingData')
if streamingdata:
dashmanurl = streamingdata.get('dashManifestUrl')
hlsmanurl = streamingdata.get('hlsManifestUrl')
manifesturl = dashmanurl
metadata['ManifestUrl'] = manifesturl
formats = streamingdata.get('formats')
adaptivefmts = streamingdata.get('adaptiveFormats')
if adaptivefmts:
# logging.debug('ADAPTIVEFMTS: ' + str(adaptivefmts))
adaptivefmts.sort(key=lambda fmt: fmt.get('bitrate', 0))
nomanaudiodata = []
nomanvideodata = []
for fid in range(len(adaptivefmts)):
mtype = adaptivefmts[fid]['mimeType'].split('; ')
if mtype[0] == 'audio/mp4' and mtype[1][8:11] == 'mp4':
nomanaudiodata.append(adaptivefmts[fid])
elif mtype[0] == 'video/mp4' and mtype[1][8:11] == 'avc':
if not streamtype:
streamtype = adaptivefmts[fid].get('type')
nomanvideodata.append(adaptivefmts[fid])
# logging.debug('Videodata: %s' % nomanvideodata)
if streamtype == 'FORMAT_STREAM_TYPE_OTF':
otf = True
metadata['Otf'] = otf
logging.debug('OTF: ' + str(otf))
else:
manifesturl = None
logging.info('No streaming data found...')
return 3
if not latencyclass:
latencyclass = videodetails.get('latencyClass')
if latencyclass:
latencyclass = re.findall('(?<=LATENCY_).+', latencyclass)
metadata['latencyClass'] = latencyclass[0]
if not livecontent or not manifesturl:
audiodata = nomanaudiodata
videodata = nomanvideodata
# logging Details:
logging.info('View count: ' + viewcount)
logging.debug('postLiveDVR: ' + str(postlivedvr))
logging.debug('reason: ' + str(reason))
logging.debug('liveplayback: ' + str(liveplayback))
logging.debug('livestream: ' + str(livestream))
logging.debug('title: ' + str(title))
logging.debug('description: ' + str(description))
logging.debug('isprivate: ' + str(isprivate))
logging.debug('islive: ' + str(live))
logging.debug('islivecontent: ' + str(livecontent))
logging.debug('islowlatency: ' + str(lowlatency))
logging.debug('islivedvr: ' + str(livedvr))
logging.debug('latencyclass: ' + str(latencyclass))
logging.debug('live readahead secs: ' + str(liveaheadsecs))
logging.debug('live readahead chunks: ' + str(liveaheadchunk))
if manifesturl:
manifesturl += '/keepalive/yes'
logging.debug("Manifest URL: %s" % manifesturl)
rawmanifest, status = Download(downloader, downobj, manifesturl)
if status != 200:
logging.info("Error getting manifest content...")
return 3
# if reason:
if postlivedvr and not args.offset:
return 1
tree = ET.fromstring(rawmanifest)
startnumber = int(tree[0][0].attrib.get('startNumber', 0))
earliestseqnum = int(tree.get('{http://youtube.com/yt/2012/10/10}' +
'earliestMediaSequence', 0))
timescale = float(tree[0][0].get('timescale', 0))
buffersecs = tree.get('timeShiftBufferDepth')
if buffersecs:
buffersecs = float(buffersecs[2:-1])
minuperiod = tree[0].get('minimumUpdatePeriod')
if minuperiod:
segsecs = int(minuperiod[2:-1])
elif timescale:
segsecs = round(float(tree[0][0][0][0].get('d')) / timescale)
logging.debug('minimum Update Period: ' + str(minuperiod))
# Media Metadata:
if otf:
if not lowlatency:
segsecs = 5
ida = 0
idv = 1
else:
ida = 1
idv = 2
audiodata = tree[0][ida].findall("[@mimeType='audio/mp4']/")
videodata = tree[0][idv].findall("[@mimeType='video/mp4']/")
# Sort by bandwidth needed:
for mtype in audiodata, videodata:
mtype.sort(key=lambda mid: int(mid.attrib.get('bandwidth', 0)))
fps_string = 'frameRate'
else:
logging.info('Dash Manifest URL not available...')
if adaptivefmts:
logging.info('Playing manifestless video...')
logging.info('Adaptative video disabled...')
fps_string = 'fps'
segsecs = 5
buffersecs, earliestseqnum, startnumber = 0, 0, 0
else:
logging.info('No adaptive video formats found...')
return 3
logging.info("IS LIVE VIDEO: %s" % live)
logging.info("Total video Qualitys Available: %s" % len(videodata))
# Filter video types by max height, width, fps and badnwidth:
idx = 0
while idx < len(videodata):
# logging.info(videodata[idx].get('bandwidth'))
videofps = int(videodata[idx].get(fps_string, 0))
videoheight = int(videodata[idx].get('height', 0))
videowidth = int(videodata[idx].get('width', 0))
if livecontent and manifesturl:
videoband = int(videodata[idx].attrib.get('bandwidth', 0))
else:
videoband = 0
if(videofps > args.maxfps or videoheight > args.maxheight
or videowidth > args.maxwidth or
videoband / 8 > args.maxband * 1024):
del videodata[idx]
else:
idx += 1
if len(videodata) <= 1:
logging.info('No video found with the requested properties, ' +
'retry with higher values...')
return 3
logging.info("Total video Qualitys Choosen: %s" % len(videodata))
return (latencyclass, audiodata, videodata, buffersecs, earliestseqnum,
startnumber, metadata)
def ffmuxer(ffmpegbin, ffmuxerstdout, apipe, vpipe):
ffmpegargs = '%s -y -v %s -nostdin ' % (ffmpegbin, ffloglevel)
ffmpegargsinputs = (' -blocksize 512 -rtbufsize 10485760 ' +
'-flags +low_delay -thread_queue_size 512 ')
if apipe:
ffmpegargs += ffmpegargsinputs + '-i async:pipe:%s ' % apipe
fds = (apipe, vpipe)
else:
fds = (vpipe,)
ffmpegargs += ffmpegargsinputs + ' -i async:pipe:%s ' % vpipe
ffmpegargs += '-f mpegts -c copy -copyts '
ffmpegargs += '-flags +low_delay -'
ffmpegmuxer = subprocess.Popen(shlex.split(ffmpegargs),
bufsize=10485760,
stdout=ffmuxerstdout,
stderr=None,
close_fds=True,
pass_fds=fds)
fftries = 0
while ffmpegmuxer.poll() is not None:
print("Waiting ffmpeg...")
if fftries < 5:
time.sleep(1)
else:
raise Exception
fftries += 1
return ffmpegmuxer
def get_media(data):
baseurl, segmenturl, fd, downobj, init = data
retries503 = 5
retries40x = 5
conerr = 0
twbytes = 0
acceptranges = None
headnumber = 0
if downloader == 'pycurl':
timeouts = (3.05, 0)
rawheaders = BytesIO()
elif downloader == 'requests':
timeouts = (3.05, max(4, segsecs * 3))
headers = 0
status = 0
response = 0
contentlength = totallength = 0
end = 0
walltimems = 0
headtime = 0
newurl = None
rheaders = {}
speed = 0
initbyte = 0
playerclosed = 0
if not livecontent or not manifesturl:
maxbytes = 524288
# maxbytes = 30000
if downloader == 'pycurl':
downobj.setopt(pycurl.RANGE, '%s-%s' %
(initbyte, initbyte + maxbytes))
elif downloader == 'requests':
rheaders['Range'] = 'bytes=%s-%s' % (initbyte, initbyte + maxbytes)
else:
maxbytes = 0
while True:
columns = os.get_terminal_size().columns
if twbytes:
sbyte = initbyte + int(twbytes)
if maxbytes:
ebyte = sbyte + maxbytes
if totallength and ebyte > totallength:
ebyte = totallength
else:
ebyte = ''
if downloader == 'pycurl':
downobj.setopt(pycurl.RANGE, '%s-%s' % (sbyte, ebyte))
elif downloader == 'requests':
rheaders['Range'] = 'bytes=%s-%s' % (sbyte, ebyte)
logging.debug("Trying to resume from byte: %s to %s" % (sbyte,
ebyte))
url = baseurl + segmenturl
if downloader == 'pycurl':
downobj.setopt(pycurl.URL, url)
downobj.setopt(curlobj.HEADERFUNCTION, rawheaders.write)
if init != 1:
# Write media content to ffmpeg or player pipes:
if otf and not twbytes and init:
iwbytes = fd.write(init)
if downloader == 'pycurl':
downobj.setopt(pycurl.NOBODY, 0)
downobj.setopt(pycurl.HEADER, 0)
downobj.setopt(pycurl.WRITEDATA, fd)
elif downloader == 'requests':
request = downobj.get
else:
if downloader == 'pycurl':
downobj.setopt(pycurl.NOBODY, 1)
elif downloader == 'requests':
request = downobj.head
# curlobj.setopt(CURLOPT_CONNECTTIMEOUT, timeouts[0])
# curlobj.setopt(pycurl.TIMEOUT, timeouts[1])
# curlobj.setopt(pycurl.HTTPHEADER, rheaders)
try:
logging.debug("Getting Media Content...")
# curlobj.setopt(pycurl.WRITEFUNCTION,
# lambda data: onrecv(fd, data) )
if player.poll() is not None:
return 1
if downloader == 'pycurl':
downobj.perform()
elif downloader == 'requests':
gettime = time.time()
res = request(url, stream=True, timeout=timeouts,
allow_redirects=True, headers=rheaders)
# fd.flush()
logging.debug("Saving segment media content to: " + str(fd))
# fd.write(content)
except BrokenPipeError as oserr:
logging.debug("Exception Ocurred: %s %s" % (oserr, str(oserr.args)))
return 1
except requests.exceptions.ConnectionError:
logging.debug("Connection Error, retrying...")
time.sleep(1)
continue
'''except (pycurl.error, requests.exceptions.ReadTimeout) as err:
logging.debug("Pycurl Exception Ocurred: %s Args: %s" %
(err, str(err.args)))
curlerrnum = err.args[0]
if curlerrnum == 18:
logging.debug("Partial content, Transmision ended...")
fd.close()
return 1
if curlerrnum == 23:
logging.debug("Write error and player closed, quitting...")
return 1
if curlerrnum != 28:
time.sleep(segsecs)'''
# Getting metadata from headers:
if downloader == 'pycurl':
headers = dict_from_bytes(rawheaders)
twbytes += int(downobj.getinfo(pycurl.SIZE_DOWNLOAD))
speed = downobj.getinfo(pycurl.SPEED_DOWNLOAD)
totaltime = round(downobj.getinfo(pycurl.TOTAL_TIME), 4)
basedelay = downobj.getinfo(pycurl.APPCONNECT_TIME)
status = downobj.getinfo(pycurl.RESPONSE_CODE)
lasturl = downobj.getinfo(pycurl.EFFECTIVE_URL)
# print('APPCONN TIME: %s ' % (conntime, totaltime))
conntime = round(downobj.getinfo(pycurl.CONNECT_TIME), 4)
print(' ' * columns, end='\r')
ptext = ('\rDownload Speed AVG: %s kB/s' % int(speed / 1024) +
' - Download duration: %s' % totaltime)
print(ptext[0:columns], end='\r')
logging.debug('Download Speed AVG: -> %s kB/s ' % int(speed / 1024))
elif downloader == 'requests':
headers = res.headers
basedelay = round((time.time() - gettime), 4)
status = res.status_code
lasturl = res.url
conntime = 0
speed = 0
headnumber = int(headers.get('X-Head-Seqnum', 0))
sequencenum = int(headers.get('X-Sequence-Num', 0))
headtime = int(headers.get('X-Head-Time-Sec', 0))
walltimems = int(headers.get('X-Walltime-Ms', 0))
if not totallength:
totallength = headers.get('Content-Range', '').split('/')[-1]
if totallength:
if totallength != '*':
totallength = int(totallength)
else:
totallength = ''
contentlength = int(headers.get('Content-Length', 0))
acceptranges = headers.get('Accept-Ranges', 0)
cachecontrol = headers.get('Cache-Control', 0)
headtimems = int(headers.get('X-Head-Time-Millis', 0))
segmentlmt = int(headers.get('X-Segment-Lmt', 0))
contenttype = headers.get('Content-Type', 0)
if contenttype == 'video/mp4':
bandwidthavg = int(headers.get('X-Bandwidth-Avg', 0))
bandwidthest = int(headers.get('X-Bandwidth-Est', 0))
bandwidthest2 = int(headers.get('X-Bandwidth-Est2', 0))
bandwidthest3 = int(headers.get('X-Bandwidth-Est3', 0))
else:
bandwidthavg = 0
bandwidthest = 0
bandwidthest2 = 0
bandwidthest3 = 0
if live or postlivedvr:
# logging.debug('HEADERS: %s' % headers)
# logging.debug('REQ HEADERS: %s' % reqheaders)
# logging.debug("HEADTIMES : %s s %s ms" %
# (headtime, headtimems))
logging.debug('Head Number: %s' % headnumber)
logging.debug('Sequence Number: %s' % sequencenum)
# logging.debug("WALLTIMEMS : %s" % (walltimems))
# logging.debug("SEGMENT LMT: %s" % (segmentlmt))
# logging.debug('ACCEPT-RANGES: %s' % acceptranges)
if contentlength:
logging.debug("Content Length: %s" % contentlength)
if totallength:
logging.debug("Total Length: %s" % totallength)
# Check status codes:
if status == 200 or status == 206:
retries503 = retries40x = 5
# redirurl = curlobj.getinfo(pycurl.REDIRECT_URL)
try:
for chunk in res.iter_content(chunk_size=None):
if player.poll() is not None:
end = 1
break
twbytes += fd.write(chunk)
except requests.exceptions.Timeout:
logging.debug('Timeout Exception')
continue
except Exception as exception:
logging.debug('Exception while downloading :'
' {0}, Args: {1}'.format(str(exception),
str(exception.args)))
time.sleep(1)
pass
'''if not url == lasturl:
rurl = lasturl + "/"
if segmenturl:
baseurl = newurl = rurl.replace(segmenturl + "/", '')
elif not livecontent:
baseurl = rurl[0:-1]
logging.debug('Saving new url: %s' % newurl)'''
if totallength and twbytes < totallength:
continue
elif not manifesturl:
end = 1
if not (otf and contenttype == 'audio/mp4'):
# rawheaders.close()
fd.close()
if conntime:
logging.debug('Connection Delay: %s ' % conntime)
info = (status, basedelay, headnumber, headtimems,
sequencenum, walltimems, segmentlmt, contentlength,
cachecontrol, bandwidthavg, bandwidthest,
bandwidthest2, bandwidthest3, speed,
contenttype, newurl, twbytes, end)
logging.debug('Bytes written: %s' % twbytes)
return info
else:
logging.debug('Status Code: %s' % status)
logging.debug("Target URL: " + url)
# rawheaders.close()
fd.close()
return status
def closefds(totalpipes):
fds = []
if type(totalpipes) is list:
for segmenttuples in totalpipes:
if type(segmenttuples) is list:
for pipetuple in segmenttuples:
if type(pipetuple) is tuple:
for fd in pipetuple:
if type(fd) is int:
fds.append(fd)
elif type(pipetuple) is int:
fds.append(fd)
elif type(segmenttuples) is int:
fds.append(segmenttuples)
elif type(totalpipes) is int:
fds.append(totalpipes)
for fd in fds:
try:
if fd > 2:
if os.close(fd):
logging.debug('fd: %s closed.' % fd)
except OSError:
pass
def Download(downloader, session, url):
if downloader == 'requests':
r = session.get(url)
status = r.status_code
content = r.content.decode('iso-8859-1')
elif downloader == 'pycurl':
session.setopt(pycurl.URL, url)
content = session.perform_rb().decode('iso-8859-1')
status = session.getinfo(pycurl.RESPONSE_CODE)
return (content, status)
if __name__ == '__main__':
# Check platform:
assert ('linux' in sys.platform), "This code runs on Linux only."
# Setting args parser:
parser = argparse.ArgumentParser(prog='ytdash',
description='Youtube DASH video playback.')
parser.add_argument('urls', metavar='URL|QUERY', type=str, nargs='+',
help='URLs or search queries of videos to play')
parser.add_argument('--version', action='version',
version='%(prog)s 0.12-alpha')
parser.add_argument('-quiet', '-q', action='store_true',
help='enable quiet mode (default: %(default)s)')
parser.add_argument('-search', '-s', action='store_true',
help='search mode (default: %(default)s)')
parser.add_argument('-nonlive', '-nl', action='store_true',
help='search also non-live videos ' +
'(default: %(default)s)')
parser.add_argument('-sortby', '-sb', type=str, default='relevance',
choices=['relevance', 'viewCount', 'videoCount', 'date',
'rating', 'title', 'rating'],
help='sorting order for the search results ' +
'(default: %(default)s)')
parser.add_argument('-eventtype', '-et', type=str, default='live',
choices=['live', 'upcoming', 'completed'],
help='filter results by live event type' +
'(default: %(default)s)')
parser.add_argument('-safesearch', '-ss', type=str, default='moderate',
choices=['moderate', 'none', 'strict'],
help='Safe search mode to use if any' +
'(default: %(default)s)')
parser.add_argument('-duration', '-dur', type=str, default='any',
choices=['any', 'long', 'medium', 'short'],
help='filter results by video duration' +
'(default: %(default)s)')
parser.add_argument('-videotype', '-vt', type=str, default='any',
choices=['any', 'episode', 'movie'],
help='filter results by video type ' +
'(default: %(default)s)')
parser.add_argument('-type', type=str, default='video',
choices=['video', 'channel', 'playlist'],
help='filter results by type of resource ' +
'(default: %(default)s)')
parser.add_argument('-definition', '-vd', type=str, default='any',
choices=['hd', 'sd', 'any'],
help='filter results by video definition ' +
'(default: %(default)s)')
parser.add_argument('-license', type=str, default='any',
choices=['creativeCommon', 'youtube', 'any'],
help='filter results by video livense type ' +
'(default: %(default)s)')
parser.add_argument('-playlist', type=str, default='',
help=' Play urls found om filename playlist ' +
'(default: %(default)s)')
parser.add_argument('-maxresults', '-mr', type=int, default=5,
help='search max results (default: %(default)s)')
parser.add_argument('-debug', '-d', action='store_true',
help='enable debug mode (default: %(default)s)')
parser.add_argument('-player', '-p', type=str, default='mpv',
help='player bin name, (default: %(default)s)')
parser.add_argument('-maxfps', '-mf', type=int, default=30,
help='max video fps to allow (default: %(default)s)')
parser.add_argument('-maxband', '-mb', type=int, default=700,
help='max video bandwidth in kB/s to allow when ' +
' possible (default: %(default)s)')
parser.add_argument('-maxheight', '-mh', type=int, default=maxheight,
choices=[144, 240, 360, 480, 720, 1080, 1440, 2160,
4320],
help='max video heigth to allow (default: %(default)s)')
parser.add_argument('-maxwidth', '-mw', type=int, default=maxwidth,
choices=[256, 426, 640, 854, 1280, 1920, 2560, 3840,
7680],
help='max video width to allow (default: %(default)s)')
parser.add_argument('-ffmpeg', '-ff', type=str, default='ffmpeg',
help='ffmpeg location route (default: %(default)s)')
parser.add_argument('-autoplay', action='store_true',
help='Autoplay all results returned by search mode ' +
'(default: %(default)s)')
parser.add_argument('-reallive', '-r', action='store_true',
help='Disable pre buffers, enables true live mode ' +
'(lowest latency possible) on ' +
'all types of live streams. ' +
'(default: %(default)s)')
parser.add_argument('-fixed', '-f', action='store_true',
help='Play a fixed video quality instead of doing' +
' bandwidth adaptive quality change, This is the max' +
' set from options (default: %(default)s)')
parser.add_argument('--offset', '-o', type=time_type, default='',
help='Time offset from where to start ' +
' to play. can be negative or ' +
' positive (i.e: -o 2h, -o 210m, --offset 3000s or' +
' --offset=-3h, -o=-5m, -o=-300s, for hours, minutes,' +
' seconds respectively.) (default: %(default)s)')
args = parser.parse_args()
# Set general variables:
global livecontent, live, otf, lowlatency, manifesturl
global segsecs, videoid, minvid
downloader = 'requests'
vsegoffset = 3
init = None
ffmpegbase = None
player = None
videodata = None
vid = 0
aid = 0
ffmpegmuxer = None
BandwidthsAvgs = [0, 1, 2, 3]
# -
# Setting Logging:
if args.debug:
loglevel = logging.DEBUG
ffloglevel = 'warning'
elif args.quiet:
loglevel = logging.WARN
ffloglevel = 'fatal'
else:
loglevel = logging.INFO
ffloglevel = 'fatal'
logging.basicConfig(
level=loglevel, filename="logfile", filemode="w+",
format="%(asctime)-15s %(levelname)-8s %(message)s")
console = logging.StreamHandler()
console.setLevel(loglevel)
# add the handler to the root logger
logging.getLogger('').addHandler(console)
# -
logging.debug('Resolution detected: %s x %s' % (maxwidth, maxheight))
# Check/Save pid file:
if os.path.isfile('/tmp/dash2.0.pid'):
with open('/tmp/dash2.0.pid', 'r') as fd:
prevpid = fd.read()
if prevpid:
try:
os.killpg(int(prevpid), signal.SIGTERM)
logging.debug("Killed previous instance...")
except ProcessLookupError:
logging.debug("Process does not exist...")
os.setpgrp()
with open('/tmp/dash2.0.pid', 'w') as fd:
fd.write(str(os.getpgrp()))
# -
# Check media player:
if args.player == 'mpv':
# max RAM cached media size downloaded after pause in Mb:
cachesecs = 120 # max cached media downloaded before stop the downloads
backcachesize = 30 # max back and front RAM cache in memory to keep, Mb
playerbaseargs = (' --input-terminal=no ' +
# ' --audio-normalize-downmix=yes '
# ' --rebase-start-time=yes '
'--af=lavfi="[alimiter=limit=0.1:level=enabled]" ' +
'--fullscreen ')
if not args.debug:
playerbaseargs += ' --really-quiet=yes '
elif args.player == 'vlc':
playerbaseargs = ' --file-caching=5000 '
else:
playerbaseargs = ' - '
logging.debug('Player command line opts: ' + args.player + playerbaseargs)
# -
# Start downloader's session:
if downloader == 'requests':
# Requests session:
import requests
session = requests.Session()
session.verify = True
session.mount('https://', requests.adapters.HTTPAdapter(
pool_connections=10,
pool_maxsize=10,
max_retries=0))
session.headers['User-Agent'] += ' ytdash/0.1 (gzip)'
elif downloader == 'pycurl':
# CURL Session:
import pycurl
session = pycurl.Curl()
session.setopt(pycurl.HTTPHEADER, ['User-Agent: ytdash/0.1 (gzip)'])
session.setopt(pycurl.ACCEPT_ENCODING, 'gzip, deflate')
# (X11; Linux x86_64)
if args.playlist:
with open(args.playlist, 'r') as fd:
urls = fd.readlines()
if not urls:
logging.info('No urls found on given file.')
quit()
else:
urls = args.urls
# for urlid in range(len(urls)):
while len(urls):
playerargs = playerbaseargs
url = urlparse(urls[0])
urlquery = url.query
if not args.offset:
args.offset = parse_qs(url.query).get('t', [''])[0]
if args.offset and args.offset[-1:] != 's':
args.offset += 's'
urlhost = url.hostname
urlfolders = url.path.split('/')
idre = re.compile('^[A-z0-9_-]{11}$')
videoid = None
channelid = None
userid = None
if urlhost:
if url.hostname[-8:] == "youtu.be":
videoid = urlfolders[1]
elif url.hostname[-11:] == "youtube.com":
if url.path == '/watch':
videoid = parse_qs(url.query).get('v', [0])[0]
elif url.path == '/embed':
videoid = urlfolders[2]
elif url.path[0:8] == '/channel':
channelid = urlfolders[2]
elif url.path[0:5] == '/user':
userid = urlfolders[2]
if channelid or userid:
if not args.search:
logging.info('Channel URL given but search ' +
'disabled, enable search mode to' +
' list videos found in it or use '
' directly a video url or id instead.')
quit()
elif not args.search:
if url.path and re.match(idre, url.path):
videoid = url.path
else:
logging.info('Could not find a video or channel id' +
' in the given string')
quit()
if videoid:
apitype = 'videos'
else:
apibaseurl = 'https://www.googleapis.com/youtube/v3/'
apiparams = {}
apiparams['part'] = 'snippet'
apiparams['key'] = 'AIzaSyAWOONC01ILGs4dh8vnCJDO4trYbFTH4zQ'
apiurlchecklive = apibaseurl + 'videos?' + urlencode(apiparams)
if userid:
apitype = 'channels'
apiparams['forUsername'] = userid
apiurl = apibaseurl + apitype + '?' + urlencode(apiparams)
if downloader == 'requests':
r = session.get(apiurl)
elif downloader == 'pycurl':
session.setopt(pycurl.URL, apiurl)
r = session.perform_rb()
channelitems = json.loads(r).get('items')
if channelitems:
channelid = channelitems[0].get('id')
else:
logging.info('Could not get user channel id')
quit()
del apiparams['forUsername']
apitype = 'search'
apiparams['type'] = 'video'
apiparams['order'] = args.sortby
if not args.nonlive:
apiparams['eventType'] = args.eventtype
apiparams['videoDimension'] = '2d'
apiparams['regionCode'] = 'AR'
apiparams['safeSearch'] = args.safesearch
apiparams['videoDuration'] = args.duration
apiparams['videoType'] = args.videotype
apiparams['type'] = args.type
apiparams['videoLicense'] = args.license
apiparams['videoDefinition'] = args.definition # high|any
apiparams['maxResults'] = args.maxresults
apiparams['videoEmbeddable'] = 'true'
apiparams['videoSyndicated'] = 'true'
if channelid:
apiparams['channelId'] = channelid
else:
apiparams['q'] = args.urls[0]
apiparams['fields'] = ('items(id,snippet/title,snippet/' +
'channelTitle,snippet/description,' +
'snippet/liveBroadcastContent)')
apiurl = apibaseurl + apitype + '?' + urlencode(apiparams)
try:
if downloader == 'requests':
r = session.get(apiurl)
status = r.status_code
r = r.json()
elif downloader == 'pycurl':
session.setopt(pycurl.URL, apiurl)
r = session.perform_rb().decode('UTF-8')
r = json.loads(r)
status = session.getinfo(pycurl.RESPONSE_CODE)
logging.debug("API URL: " + apiurl)
if status != 200:
if status == 400 or status == 403:
reason = r['error']['message']
logging.info('Bad API request: ' + reason)
else:
logging.info('Error code %s API request ' % str(status))
quit()
# except Exception as err:
except requests.exceptions.ConnectionError as err:
err = tuple(err.args)
if (err[0] == 6 or err[0] == 7 or
err == requests.exceptions.ConnectionError):
logging.warning("Connection Error, Internet is down?")
else:
logging.warning("Http Exception : %s" % str(err))
quit()
# chardet.detect(r)['encoding']
# input()
items = r.get('items')
if items:
print("Videos found:")
else:
print("No videos found.")
quit()
# while True:
answer = None
itemnum = 1
videoids = []
for item in items:
columns = os.get_terminal_size().columns
snippet = item['snippet']
title = snippet['title'].replace('"', "\'")[:columns - 4:]
videoids.append(item['id']['videoId'])
# logging.debug('Title: %s' % title)
channeltitle = snippet["channelTitle"]
description = snippet['description'][:columns - 24:] + '...'
# description = description.replace('"',
# "\'").replace('\\n', "")
# logging.debug('Description: %s' % description)
livebroad = snippet['liveBroadcastContent']
if livebroad == 'none':
livebroad = False
else:
livebroad = True
print('%s) %s\n' % (itemnum, title) +
' * Description: {}\n'.format(repr(description)) +
' * Channel: %s\n' % channeltitle +
' * Live: %s' % livebroad)
itemnum += 1
if args.search and len(items) > 1:
print('Enter nº of video to play, press '
'Enter to play from the first or "q" to exit.')
while True:
if not args.autoplay:
answer = input()
else:
answer = ''
if(re.match(r'^[0-9]+$', answer) and
0 < int(answer) <= len(items)):
answer = int(answer)
if type(answer) is int:
item = items[answer - 1]
break
elif answer == 'q' or answer == 'Q':
quit()
elif answer == '':
urls += videoids[1:]
videoid = videoids[0]
args.search = 0
break
else:
print('Invalid input, only integers from 1 to' +
' %s are accepted...' % len(items))
else:
item = items[0]
# title += ' - ' + channeltitle
if not videoid:
videoid = item['id']['videoId']
# logging.info('Item selected: ' + )
logging.info('Fetching data for video id: %s' % videoid)
# Get the manifest and all its Infos:
# https://www.youtube.com/oembed?url=[Youtubewatchurl]&format=json
url = 'https://www.youtube.com/get_video_info?video_id=' + videoid
logging.debug('URLS: %s ' % str(urls))
logging.debug('Opening URL: %s ' % url)
content, status = Download(downloader, session, url)