Skip to content

Commit

Permalink
Update tsclient.py
Browse files Browse the repository at this point in the history
  • Loading branch information
Belfagor2005 committed Aug 21, 2024
1 parent e035c4c commit 2d6a6d9
Showing 1 changed file with 22 additions and 137 deletions.
159 changes: 22 additions & 137 deletions usr/lib/enigma2/python/Plugins/Extensions/vavoo/resolver/tsclient.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,20 +23,8 @@
import threading
import time
import os
# import re
# import operator
# import six
from six.moves.urllib.request import urlopen
# from six.moves.urllib.request import Request
# from six.moves.urllib.error import HTTPError, URLError
# from six.moves.urllib.parse import urlparse
# from six.moves.urllib.parse import quote
# from six.moves.urllib.parse import urlencode
# from six.moves.urllib.parse import unquote
# from six.moves.urllib.parse import quote_plus
# from six.moves.urllib.parse import unquote_plus
# from six.moves.urllib.parse import parse_qs
# from six.moves.urllib.request import urlretrieve

import bitstring
PY3 = sys.version_info.major >= 3
try:
Expand All @@ -55,6 +43,7 @@ def log(msg):
SUPPORTED_VERSION = 3
STREAM_PFILE = '/tmp/hls.avi'
defualtype = ""
packet = ''


def getLastPTS(data, rpid, type="video"):
Expand All @@ -79,7 +68,7 @@ def getLastPTS(data, rpid, type="video"):
found = False
while not found:
if len(data) - currentpost >= 188:
bytes = data[currentpost:currentpost+188]
bytes = data[currentpost:currentpost + 188]

bits = bitstring.ConstBitStream(bytes=bytes)
sign = bits.read(8).uint
Expand All @@ -89,7 +78,7 @@ def getLastPTS(data, rpid, type="video"):
pid = bits.read(13).uint
if pid == rpid or rpid == 0:
try:
packet = bits.read((packsize-3)*8)
packet = bits.read((packsize - 3) * 8)
scramblecontrol = packet.read(2).uint
adapt = packet.read(2).uint
concounter = packet.read(4).uint
Expand All @@ -107,23 +96,23 @@ def getLastPTS(data, rpid, type="video"):
splicingpoint = packet.read(1).uint
transportprivate = packet.read(1).uint
adaptation_ext = packet.read(1).uint
restofadapt = (adaptation_size+3) - 1
restofadapt = (adaptation_size + 3) - 1
if pcrpresent == 1:
pcr = packet.read(48)
restofadapt -= 6
if opcrpresent == 1:
opcr = packet.read(48)
restofadapt -= 6
packet.pos += (restofadapt-3) * 8
if ((packet.len - packet.pos)/8) > 5:
if ((packet.len - packet.pos) / 8) > 5:
pesync = packet.read(24) # .hex
if pesync == ('0x000001'):
pestype = packet.read(8).uint
if pestype > 223 and pestype < 240:
av = 'video'
if pestype < 223 and pestype > 191:
av = 'audio'
packet.pos += (3*8)
packet.pos += (3 * 8)
ptspresent = packet.read(1).uint
dtspresent = packet.read(1).uint
if ptspresent:
Expand Down Expand Up @@ -158,7 +147,7 @@ def getLastPTS(data, rpid, type="video"):
splicingpoint = packet.read(1).uint
transportprivate = packet.read(1).uint
adaptation_ext = packet.read(1).uint
restofadapt = (adaptation_size+3) - 1
restofadapt = (adaptation_size + 3) - 1
if pcrpresent == 1:
pcr = packet.read(48)
restofadapt -= 6
Expand Down Expand Up @@ -200,7 +189,7 @@ def getLastPTS(data, rpid, type="video"):
if decodedpts and (type == "" or av == type) and len(av) > 0:
return decodedpts

currentpost = currentpost-packsize
currentpost -= packsize
if currentpost < 10:
found = True
return ret
Expand All @@ -216,7 +205,7 @@ def getFirstPTSFrom(data, rpid, initpts, type="video"):
ff = data.find('\x47', currentpost)
if ff == - 1:
found = True
elif data[ff + packsize] == '\x47' and data[ff + packsize+packsize] == '\x47':
elif data[ff + packsize] == '\x47' and data[ff + packsize + packsize] == '\x47':
spoint = ff
found = True
else:
Expand All @@ -228,7 +217,7 @@ def getFirstPTSFrom(data, rpid, initpts, type="video"):

while not found:
if len(data) - currentpost >= 188:
bytes = data[currentpost:currentpost+188]
bytes = data[currentpost:currentpost + 188]
bits = bitstring.ConstBitStream(bytes=bytes)
sign = bits.read(8).uint
tei = bits.read(1).uint
Expand All @@ -237,7 +226,7 @@ def getFirstPTSFrom(data, rpid, initpts, type="video"):
pid = bits.read(13).uint
if rpid == pid or rpid == 0:
try:
packet = bits.read((packsize-3)*8)
packet = bits.read((packsize - 3) * 8)
scramblecontrol = packet.read(2).uint
adapt = packet.read(2).uint
concounter = packet.read(4).uint
Expand All @@ -247,31 +236,23 @@ def getFirstPTSFrom(data, rpid, initpts, type="video"):
av = ""
if adapt == 3:
adaptation_size = packet.read(8).uint
discontinuity = packet.read(1).uint
random = packet.read(1).uint
espriority = packet.read(1).uint
pcrpresent = packet.read(1).uint
opcrpresent = packet.read(1).uint
splicingpoint = packet.read(1).uint
transportprivate = packet.read(1).uint
adaptation_ext = packet.read(1).uint
restofadapt = (adaptation_size+3) - 1
restofadapt = (adaptation_size + 3) - 1
if pcrpresent == 1:
pcr = packet.read(48)
restofadapt -= 6
if opcrpresent == 1:
opcr = packet.read(48)
restofadapt -= 6
packet.pos += (restofadapt-3) * 8
if ((packet.len - packet.pos)/8) > 5:
packet.pos += (restofadapt - 3) * 8
if ((packet.len - packet.pos) / 8) > 5:
pesync = packet.read(24) # .hex
if pesync == ('0x000001'):
pestype = packet.read(8).uint
if pestype > 223 and pestype < 240:
av = 'video'
if pestype < 223 and pestype > 191:
av = 'audio'
packet.pos += (3*8)
packet.pos += (3 * 8)
ptspresent = packet.read(1).uint
dtspresent = packet.read(1).uint
if ptspresent:
Expand All @@ -283,7 +264,6 @@ def getFirstPTSFrom(data, rpid, initpts, type="video"):
secondpartpts = pts.read(15)
pts.pos += 1
thirdpartpts = pts.read(15)
# decodedpts = bitstring.ConstBitArray().join([firstpartpts.bin, secondpartpts.bin, thirdpartpts.bin]).uint
decodedpts = int(''.join([firstpartpts.bin, secondpartpts.bin, thirdpartpts.bin]), 2)
if dtspresent:
dts = packet.read(40)
Expand All @@ -293,25 +273,14 @@ def getFirstPTSFrom(data, rpid, initpts, type="video"):
secondpartdts = dts.read(15)
dts.pos += 1
thirdpartdts = dts.read(15)
# decodeddts = bitstring.ConstBitArray().join([firstpartdts.bin, secondpartdts.bin, thirdpartdts.bin]).uint
decodeddts = int(''.join([firstpartdts.bin, secondpartdts.bin, thirdpartdts.bin]), 2)
elif adapt == 2:
# if adapt is 2 the packet is only an adaptation field
adaptation_size = packet.read(8).uint
discontinuity = packet.read(1).uint
random = packet.read(1).uint
espriority = packet.read(1).uint

pcrpresent = packet.read(1).uint
opcrpresent = packet.read(1).uint
splicingpoint = packet.read(1).uint
transportprivate = packet.read(1).uint
adaptation_ext = packet.read(1).uint
restofadapt = (adaptation_size+3) - 1
if pcrpresent == 1:
pcr = packet.read(48)
restofadapt -= 6
if opcrpresent == 1:
opcr = packet.read(48)
restofadapt -= 6
elif adapt == 1:
pesync = packet.read(24) # .hex
Expand All @@ -333,24 +302,18 @@ def getFirstPTSFrom(data, rpid, initpts, type="video"):
secondpartpts = pts.read(15)
pts.pos += 1
thirdpartpts = pts.read(15)
# decodedpts = bitstring.ConstBitArray().join([firstpartpts.bin, secondpartpts.bin, thirdpartpts.bin]).uint
decodedpts = int(''.join([firstpartpts.bin, secondpartpts.bin, thirdpartpts.bin]), 2)
if dtspresent:
dts = packet.read(40)
dts.pos = 4
firstpartdts = dts.read(3)
dts.pos += 1
secondpartdts = dts.read(15)
dts.pos += 1
thirdpartdts = dts.read(15)
# decodeddts = bitstring.ConstBitArray().join([firstpartdts.bin, secondpartdts.bin, thirdpartdts.bin]).uint
decodeddts = int(''.join([firstpartdts.bin, secondpartdts.bin, thirdpartdts.bin]), 2)
if decodedpts and (type == "" or av == type) and len(av) > 0:
if decodedpts > initpts:
return decodedpts, currentpost
else:
found = True
currentpost = currentpost+188
currentpost += 188
if currentpost >= len(data):
found = True
return ret
Expand All @@ -375,7 +338,6 @@ def isDownloading(self):

def run(self):
self.play()
# def download_chunks(self, downloadUrl, chunk_size=4096):

def download_chunks(self, downloadUrl, chunk_size=192512):
conn = urlopen(downloadUrl)
Expand All @@ -394,99 +356,24 @@ def player_pipe(self, queue, videopipe):
if block is None:
return
videopipe.write(block)
# videopipe.flush()
if not self._downLoading:
self._downLoading = True

def play(self):
# check if pipe exists
# if os.access(STREAM_PFILE, os.W_OK):
if os.path.exists(STREAM_PFILE):
os.remove(STREAM_PFILE)
# os.mkfifo(STREAM_PFILE)
cmd = "/usr/bin/mkfifo " + STREAM_PFILE
os.system(cmd)
videopipe = open(STREAM_PFILE, "w+b")
variants = []
variant = None
"""
for line in self.gen_m3u(self.url):
if line.startswith('#EXT'):
tag, attribs = self.parse_m3u_tag(line)
if tag == '#EXT-X-STREAM-INF':
variant = attribs
elif variant:
variants.append((line, variant))
variant = None
pass#print "Here in hlsclient-py variants =", variants
if len(variants) == 1:
self.url = urlparse.urljoin(self.url, variants[0][0])
elif len(variants) >= 2:
pass#print '[hlsclient::play] More than one variant of the stream was provided.'
autoChoice = {}
for i, (vurl, vattrs) in enumerate(variants):
pass#print "i, vurl =", i, vurl
pass#print "i, vattrs =", i, vattrs
for attr in vattrs:
key, value = attr.split('=')
key = key.strip()
value = value.strip().strip('"')
if key == 'BANDWIDTH':
#Limit bandwidth?
#if int(value) < 1000000:
# autoChoice[i] = int(value)
autoChoice[i] = int(value)
pass#print 'bitrate %.2f kbps' % (int(value)/1024.0)
elif key == 'PROGRAM-ID':
pass#print 'program %s' % value,
elif key == 'CODECS':
pass#print 'codec %s' % value,
elif key == 'RESOLUTION':
pass#print 'resolution %s' % value,
else:
pass
# raise ValueError('[hlsclient::play] unknown STREAM-INF attribute %s' % key)
## pass#print "Here in hls-py into stop 1"
## os.remove(STREAM_PFILE)
## self.stop()
# print
choice = max(autoChoice.iteritems(), key=operator.itemgetter(1))[0]
pass#print '[hlsclient::play] Autoselecting %s' % choice
#Use the first choice for testing
## choice = 0
self.url = urlparse.urljoin(self.url, variants[choice][0])
"""
queue = queue.Queue(1024) # 1024 blocks of 4K each ~ 4MB buffer
self.thread = threading.Thread(target=self.player_pipe, args=(queue, videopipe))
queuex = queue(1024) # 1024 blocks of 4K each ~ 4MB buffer
self.thread = threading.Thread(target=self.player_pipe, args=(queuex, videopipe))
self.thread.start()
# try:
fpts = 0
while self.thread.isAlive():
if self._stop:
self.hread._Thread__stop()
"""
medialist = list(self.handle_basic_m3u(self.url))
pass#print 'Here in [hlsclient::play] medialist A=', medialist
if None in medialist:
# choose to start playback at the start, since this is a VOD stream
pass
else:
# choose to start playback three files from the end, since this is a live stream
medialist = medialist[-3:]
pass#print 'Here in [hlsclient::play] medialist =', medialist
for media in medialist:
try:
if media is None:
queue.put(None, block=True)
return
seq, enc, duration, targetduration, media_url = media
pass#print 'Here in [hlsclient::play] media_url =', media_url
if seq > last_seq:
"""
lastpts = 0
fixpid = 256
lastchunk = ""
# fpts = 0
i = 0
starttime = time.time()
for chunk in self.download_chunks(self.url):
Expand All @@ -497,17 +384,15 @@ def play(self):
firstpts, pos = getFirstPTSFrom(chunk, fixpid, lastpts)
except:
continue
i = i+1
i += 1
queue.put(chunk, block=True)
else:
continue
lc = len(lastchunk)
fpts = firstpts
lastpts = getLastPTS(lastchunk, fixpid, defualtype)
if (lastpts is None) or (lastpts == "None"):
lastpts = 0
videotime = lastpts - firstpts
videotime = videotime/90000
videotime = videotime / 90000
starttime = int(float(starttime))
endtime = time.time()
endtime = int(float(endtime))
Expand Down

0 comments on commit 2d6a6d9

Please sign in to comment.