def getTS(self, request):
	if "file" in request.args:
		filename = unquote(request.args["file"][0]).decode('utf-8', 'ignore').encode('utf-8')
		if not os.path.exists(filename):
			return "File '%s' not found" % (filename)

#	ServiceReference is not part of filename so look in the '.ts.meta' file
		sRef = ""
		if os.path.exists(filename + '.meta'):
			metafile = open(filename + '.meta', "r")
			line = metafile.readline()
			if line:
				sRef = eServiceReference(line.strip()).toString()
			metafile.close()

		progopt = ''
		if config.OpenWebif.service_name_for_stream.value and sRef != '':
			progopt="#EXTVLCOPT:program=%d\n" % (int(sRef.split(':')[3],16))

		portNumber = config.OpenWebif.port.value
		info = getInfo()
		model = info["model"]
		if model in ("solo2", "duo2", "solose", "vusolo2", "vuduo2", "vusolose", "xpeedlx3", "gbquad", "gbquadplus"):
			if "device" in request.args :
				if request.args["device"][0] == "phone" :
					portNumber = 8002
		if "port" in request.args:
			portNumber = request.args["port"][0]
		response = "#EXTM3U\n#EXTVLCOPT--http-reconnect=true \n%shttp://%s:%s/file?file=%s\n" % (progopt,request.getRequestHostname(), portNumber, quote(filename))
		request.setHeader('Content-Type', 'application/text')
		return response
	else:
		return "Missing file parameter"
def getTS(self, request):
	if "file" in request.args:
		filename = unquote(request.args["file"][0]).decode('utf-8', 'ignore').encode('utf-8')
		if not os.path.exists(filename):
			return "File '%s' not found" % (filename)

#	ServiceReference is not part of filename so look in the '.ts.meta' file
		sRef = ""
		progopt = ''

		if os.path.exists(filename + '.meta'):
			metafile = open(filename + '.meta', "r")
			name = ''
			seconds = -1 				# unknown duration default
			line = metafile.readline()	# service ref
			if line:
				sRef = eServiceReference(line.strip()).toString()
			line2 = metafile.readline()	# name
			if line2:
				name = line2.strip()
			line3 = metafile.readline()	# description
			line4 = metafile.readline() # recording time
			line5 = metafile.readline() # tags
			line6 = metafile.readline() # length

			if line6:
				seconds = float(line6.strip()) / 90000 # In seconds

			if config.OpenWebif.service_name_for_stream.value:
				progopt="%s#EXTINF:%d,%s\n" % (progopt, seconds, name)

			metafile.close()

		portNumber = config.OpenWebif.port.value
		info = getInfo()
		model = info["model"]
		transcoder_port = None
		if model in ("solo2", "duo2", "solose", "vusolo2", "vuduo2", "vusolose", "hd2400", "xpeedlx3", "gbquad", "gbquadplus"):
			try:
				transcoder_port = int(config.plugins.transcodingsetup.port.value)
			except StandardError:
				#Transcoding Plugin is not installed or your STB does not support transcoding
				transcoder_port = None
			if "device" in request.args :
				if request.args["device"][0] == "phone" :
					portNumber = 8002

		if "port" in request.args:
			portNumber = request.args["port"][0]

		# When you use EXTVLCOPT:program in a transcoded stream, VLC does not play stream
		if config.OpenWebif.service_name_for_stream.value and sRef != '' and portNumber != transcoder_port:
			progopt="%s#EXTVLCOPT:program=%d\n" % (progopt, int(sRef.split(':')[3],16))

		response = "#EXTM3U\n#EXTVLCOPT--http-reconnect=true \n%shttp://%s:%s/file?file=%s\n" % (progopt,request.getRequestHostname(), portNumber, quote(filename))
		request.setHeader('Content-Type', 'application/text')
		return response
	else:
		return "Missing file parameter"
def getStream(session, request, m3ufile):
	if "ref" in request.args:
		sRef=unquote(unquote(request.args["ref"][0]).decode('utf-8', 'ignore')).encode('utf-8')
	else:
		sRef = ""

	currentServiceRef = None
	if m3ufile == "streamcurrent.m3u":
		currentServiceRef = session.nav.getCurrentlyPlayingServiceReference()
		sRef = currentServiceRef.toString()

	if sRef.startswith("1:134:"):
		if currentServiceRef is None:
			currentServiceRef = session.nav.getCurrentlyPlayingServiceReference()
		if currentServiceRef is None:
			currentServiceRef = eServiceReference()
		ref = getBestPlayableServiceReference(eServiceReference(sRef), currentServiceRef)
		if ref is None:
			sRef = ""
		else:
			sRef = ref.toString()

	name = "stream"
	# #EXTINF:-1,%s\n adding back to show service name in programs like VLC
	progopt = ''
	if "name" in request.args:
		name = request.args["name"][0]
		if config.OpenWebif.service_name_for_stream.value:
			progopt="#EXTINF:-1,%s\n" % name

	portNumber = config.OpenWebif.streamport.value
	info = getInfo()
	model = info["model"]
	transcoder_port = None
	if model in ("solo2", "duo2", "solose", "vusolo2", "vuduo2", "vusolose", "hd2400", "xpeedlx3", "gbquad", "gbquadplus"):
		try:
			transcoder_port = int(config.plugins.transcodingsetup.port.value)
		except StandardError:
			#Transcoding Plugin is not installed or your STB does not support transcoding
			transcoder_port = None
		if "device" in request.args :
			if request.args["device"][0] == "phone" :
				portNumber = 8002

	if "port" in request.args:
		portNumber = request.args["port"][0]

	# When you use EXTVLCOPT:program in a transcoded stream, VLC does not play stream
	if config.OpenWebif.service_name_for_stream.value and sRef != '' and portNumber != transcoder_port:
		progopt="%s#EXTVLCOPT:program=%d\n" % (progopt, int(sRef.split(':')[3],16))

	response = "#EXTM3U \n#EXTVLCOPT--http-reconnect=true \n%shttp://%s:%s/%s\n" % (progopt,request.getRequestHostname(), portNumber, sRef)
	request.setHeader('Content-Type', 'application/text')
	return response
示例#4
0
def predict_dir(caffemodel, deploy, source_list, IMAGE_SIZE=227, LAYER_NAME="my-fc8", mode=True, BORDER_AGE=18):
    # f = open("predict.log", "w")
    file_list = []
    correct_num = 0
    for source in source_list:
        for root, dirs, files in os.walk(source):
            for file in files:
                file_list.append(os.path.join(root, file))
                # f.write(str(real_age)+" "+str(predict_age)+'\n')
    # f.close()
    images = np.zeros((len(file_list), 3, IMAGE_SIZE, IMAGE_SIZE), dtype=np.float)

    # read age list
    real_ages = []
    for index, dicom_file in enumerate(file_list):
        print dicom_file
        real_age = info.getInfo(dicom_file)
        real_ages.append(real_age)
        images[index, :, :, :] = preprocess.process(dicom_file, IMAGE_SIZE=IMAGE_SIZE)
        # if abs(predict_age - real_age)<=3:
        #     correct_num = correct_num+1
    if mode:
        caffe.set_mode_gpu()
    else:
        caffe.set_mode_cpu()
    net = caffe.Net(deploy, caffemodel, caffe.TEST)
    output = {}
    for x in range(0, len(file_list), 10):
        # net.blobs['data'].reshape(100, 3, IMAGE_SIZE, IMAGE_SIZE)
        if len(file_list) - x < 10:
            net.blobs['data'].reshape(len(file_list) - x, 3, IMAGE_SIZE, IMAGE_SIZE)
            net.blobs['data'].data[...] = images[x:]
        else:
            net.blobs['data'].reshape(10, 3, IMAGE_SIZE, IMAGE_SIZE)
            net.blobs['data'].data[...] = images[x:x+10]
        o = net.forward()
        output = dict(output.items()+o.items())
    for index, result in enumerate(output[LAYER_NAME]):
        predict_age = result[0]
        real_age = real_ages[index]
        '''
        the condition that you think the prediction result is correct
        '''
        # if abs(predict_age - real_age) <= 3:
        #     correct_num = correct_num+1
        if (predict_age > BORDER_AGE and real_age > BORDER_AGE) or (predict_age <= BORDER_AGE and real_age <= BORDER_AGE):
            correct_num = correct_num+1
    return float(correct_num)/len(file_list)
示例#5
0
def userLogin(driver):
    username = driver.find_element_by_name('username')
    user_name, pass_word = getInfo()
    username.send_keys(user_name)
    password = driver.find_element_by_name('password')
    password.send_keys(pass_word)

    login = driver.find_element_by_name('login')
    login.click()

    try:
        element = WebDriverWait(driver, 10).until(
            EC.presence_of_element_located((By.CLASS_NAME, "golinks"))
        )
    except:
        print("error.................")
示例#6
0
def getStream(session, request, m3ufile):

    if "ref" in request.args:
        sRef = unquote(unquote(request.args["ref"][0]).decode("utf-8", "ignore")).encode("utf-8")
    else:
        sRef = ""

    currentServiceRef = None
    if m3ufile == "streamcurrent.m3u":
        currentServiceRef = session.nav.getCurrentlyPlayingServiceReference()
        sRef = currentServiceRef.toString()

    if sRef.startswith("1:134:"):
        if currentServiceRef is None:
            currentServiceRef = session.nav.getCurrentlyPlayingServiceReference()
        if currentServiceRef is None:
            currentServiceRef = eServiceReference()
        ref = getBestPlayableServiceReference(eServiceReference(sRef), currentServiceRef)
        if ref is None:
            sRef = ""
        else:
            sRef = ref.toString()

    name = "stream"
    if "name" in request.args:
        name = request.args["name"][0]
        # #EXTINF:-1,%s\n  remove not compatiple with old api
    progopt = ""
    if config.OpenWebif.service_name_for_stream.value and sRef != "":
        progopt = "#EXTVLCOPT:program=%d\n" % (int(sRef.split(":")[3], 16))
    portNumber = config.OpenWebif.streamport.value
    info = getInfo()
    model = info["model"]
    if model in ("solo2", "duo2", "Sezam Marvel", "Xpeed LX3", "gbquad", "gbquadplus"):
        if "device" in request.args:
            if request.args["device"][0] == "phone":
                portNumber = config.plugins.transcodingsetup.port.value
        if "port" in request.args:
            portNumber = request.args["port"][0]
    response = "#EXTM3U \n#EXTVLCOPT--http-reconnect=true \n%shttp://%s:%s/%s\n" % (
        progopt,
        request.getRequestHostname(),
        portNumber,
        sRef,
    )
    request.setHeader("Content-Type", "application/text")
    return response
示例#7
0
def predict_dir_output_temp_1(caffemodel, deploy, source_list, mode=True, IMAGE_SIZE=227, LAYER_NAME="my-fc8", LOGFILE="predict.log", BORDER_AGE=18):
    # f = open("predict.log", "w")
    file_list = []
    for source in source_list:
        for root, dirs, files in os.walk(source):
            for file in files:
                file_list.append(os.path.join(root, file))
    images = np.zeros((len(file_list), 3, IMAGE_SIZE, IMAGE_SIZE), dtype=np.float)

    # read age list
    real_ages = []
    for index, dicom_file in enumerate(file_list):
        real_age = info.getInfo(dicom_file)
        real_ages.append(real_age)
        images[index, :, :, :] = preprocess.process(dicom_file, IMAGE_SIZE=IMAGE_SIZE)
    if mode:
        caffe.set_mode_gpu()
    else:
        caffe.set_mode_cpu()
    net = caffe.Net(deploy, caffemodel, caffe.TEST)
    net.blobs['data'].reshape(len(file_list), 3, IMAGE_SIZE, IMAGE_SIZE)
    net.blobs['data'].data[...] = images
    output = net.forward()
    f = open(LOGFILE, 'w')
    dic = {}
    for index, result in enumerate(output[LAYER_NAME]):
        predict_age = result[0]
        real_age = real_ages[index]
        file_name = file_list[index]
        ds = dicom.read_file(file_list[index])
        id = ds.PatientID
        birthDate = ds.PatientBirthDate
        studyDate = ds.StudyDate
        # only see the error sample
        # if (predict_age > BORDER_AGE and real_age > BORDER_AGE) or (predict_age <= BORDER_AGE and real_age <= BORDER_AGE):
        #     continue
        line = "%s %s %s %s %s %s %s" % (file_name.split('/')[-1], id, birthDate, studyDate, real_age, predict_age, abs(predict_age-real_age))
        dic[line] = abs(predict_age - real_age)
    dic = sorted(dic.items(), key=lambda d: d[1], reverse=True)
    for key, value in dic:
        f.write("%s\n" % key)
        # print(type(dic[key]))
        # print(key, value)
    f.close()
def getStream(session, request, m3ufile):

	if "ref" in request.args:
		sRef=unquote(unquote(request.args["ref"][0]).decode('utf-8', 'ignore')).encode('utf-8')
	else:
		sRef = ""
	
	currentServiceRef = None
	if m3ufile == "streamcurrent.m3u":
		currentServiceRef = session.nav.getCurrentlyPlayingServiceReference()
		sRef = currentServiceRef.toString() 
	
	if sRef.startswith("1:134:"):
		if currentServiceRef is None:
			currentServiceRef = session.nav.getCurrentlyPlayingServiceReference()
		if currentServiceRef is None:
			currentServiceRef = eServiceReference()
		ref = getBestPlayableServiceReference(eServiceReference(sRef), currentServiceRef)
		if ref is None:
			sRef = ""
		else:
			sRef = ref.toString()

	name = "stream"
	if "name" in request.args:
		name = request.args["name"][0]
	# #EXTINF:-1,%s\n  remove not compatiple with old api
	progopt = ''
	if config.OpenWebif.service_name_for_stream.value and sRef != '':
		progopt="#EXTVLCOPT:program=%d\n" % (int(sRef.split(':')[3],16))
	portNumber = config.OpenWebif.streamport.value
	info = getInfo()
	model = info["model"]
	if model in ("solo2", "duo2", "Sezam Marvel", "Xpeed LX3", "gbquad", "gbquadplus"):
		if "device" in request.args :
			if request.args["device"][0] == "phone" :
				portNumber = config.plugins.transcodingsetup.port.value
		if "port" in request.args:
			portNumber = request.args["port"][0]
	response = "#EXTM3U \n#EXTVLCOPT--http-reconnect=true \n%shttp://%s:%s/%s\n" % (progopt,request.getRequestHostname(), portNumber, sRef)
	request.setHeader('Content-Type', 'application/text')
	return response
示例#9
0
def generateHdf5(source, target):
    h5_file = hy.File(target, 'w')
    file_list = []
    for root, dirs, files in os.walk(source):
        for dicom_file in files:
            file_list.append(os.path.join(root, dicom_file))
    random.shuffle(file_list)
    random.shuffle(file_list)
    # change the image size to you want
    data = np.zeros((len(file_list), 3, 227, 227))
    labels = np.zeros(len(file_list), dtype=np.float32)
    for index, dicom_file in enumerate(file_list):
        age = info.getInfo(dicom_file)
        im = preprocess.process(dicom_file)
        data[index, :, :, :] = im
        labels[index] = age
        print(dicom_file)
    h5_file['data'] = data
    h5_file['label'] = labels

    print(labels)
    h5_file.close()
示例#10
0
def move5(source, target):
    for root, dirs, files in os.walk(source):
        for dicom_file in files:
            path = os.path.join(root, dicom_file)
            print path
            age, sex = info.getInfo(path)
            n = int(age)
            if sex == 'F':
                temp = os.path.join(target, 'female')
            elif sex == 'M':
                temp = os.path.join(target, 'male')
            key = "%.2f-%s" % (n, n + 0.99)
            save_path = os.path.join(temp, key)
            if not os.path.exists(save_path):
                os.mkdir(save_path)
            try:
                shutil.move(path, save_path)
            except shutil.Error as e:
                with open("test.txt", "w") as f:
                    f.write(save_path + " " + path + "\n")
                    print e
            print path, save_path
示例#11
0
def predict_dir_output_temp_1(caffemodel, deploy, source_list, mode=True, IMAGE_SIZE=227, LAYER_NAME="my-fc8", LOGFILE="predict.log"):
    images = np.zeros((len(file_list), 3, IMAGE_SIZE, IMAGE_SIZE), dtype=np.float)

    # read age list
    real_ages = []
    for index, dicom_file in enumerate(file_list):
        real_age = info.getInfo(dicom_file)
        real_ages.append(real_age)
        images[index, :, :, :] = preprocess.process(dicom_file, IMAGE_SIZE=IMAGE_SIZE)
    if mode:
        caffe.set_mode_gpu()
    else:
        caffe.set_mode_cpu()
    net = caffe.Net(deploy, caffemodel, caffe.TEST)
    net.blobs['data'].reshape(len(file_list), 3, IMAGE_SIZE, IMAGE_SIZE)
    net.blobs['data'].data[...] = images
    output = net.forward()
    f = open(LOGFILE, 'w')
    dic = {}
    MAE_SUM = 0.0
    for index, result in enumerate(output[LAYER_NAME]):
        predict_age = result[0]
        real_age = real_ages[index]
        file_name = file_list[index]
        ds = dicom.read_file(file_list[index])
        id = ds.PatientID
        birthDate = ds.PatientBirthDate
        studyDate = ds.StudyDate
        line = "%s %s %s %s %s %s %s" % (file_name.split('/')[-1], id, birthDate, studyDate, real_age, predict_age, abs(predict_age-real_age))
        dic[line] = abs(predict_age - real_age)
        MAE_SUM += abs(predict_age - real_age)
        print(abs(predict_age-real_age))
    f.write("%s\n" % str(MAE_SUM/len(file_list)))
    dic = sorted(dic.items(), key=lambda d: d[1], reverse=True)
    for key, value in dic:
        f.write("%s\n" % key)
        print(key)
    f.close()
示例#12
0
def getStream(session, request, m3ufile):
    if "ref" in request.args:
        sRef = unquote(
            unquote(request.args["ref"][0]).decode('utf-8',
                                                   'ignore')).encode('utf-8')
    else:
        sRef = ""

    currentServiceRef = None
    if m3ufile == "streamcurrent.m3u":
        currentServiceRef = session.nav.getCurrentlyPlayingServiceReference()
        sRef = currentServiceRef.toString()

    if sRef.startswith("1:134:"):
        if currentServiceRef is None:
            currentServiceRef = session.nav.getCurrentlyPlayingServiceReference(
            )
        if currentServiceRef is None:
            currentServiceRef = eServiceReference()
        ref = getBestPlayableServiceReference(eServiceReference(sRef),
                                              currentServiceRef)
        if ref is None:
            sRef = ""
        else:
            sRef = ref.toString()

    name = "stream"
    # #EXTINF:-1,%s\n adding back to show service name in programs like VLC
    progopt = ''
    if "name" in request.args:
        name = request.args["name"][0]
        if config.OpenWebif.service_name_for_stream.value:
            progopt = "#EXTINF:-1,%s\n" % name

    portNumber = config.OpenWebif.streamport.value
    info = getInfo()
    model = info["model"]
    machinebuild = info["machinebuild"]
    urlparam = '?'
    if info["imagedistro"] in ('openpli', 'satdreamgr', 'openvision'):
        urlparam = '&'
    transcoder_port = None
    args = ""

    if fileExists("/dev/bcm_enc0"):
        try:
            transcoder_port = int(config.plugins.transcodingsetup.port.value)
        except StandardError:
            # Transcoding Plugin is not installed or your STB does not support transcoding
            transcoder_port = None
        if "device" in request.args:
            if request.args["device"][0] == "phone":
                portNumber = transcoder_port
        if "port" in request.args:
            portNumber = request.args["port"][0]
    elif fileExists("/dev/encoder0") or fileExists(
            "/proc/stb/encoder/0/apply"):
        transcoder_port = portNumber

    if fileExists("/dev/bcm_enc0") or fileExists(
            "/dev/encoder0") or fileExists("/proc/stb/encoder/0/apply"):
        if "device" in request.args:
            if request.args["device"][0] == "phone":
                try:
                    bitrate = config.plugins.transcodingsetup.bitrate.value
                    resolution = config.plugins.transcodingsetup.resolution.value
                    (width, height) = tuple(resolution.split('x'))
                    # framerate = config.plugins.transcodingsetup.framerate.value
                    aspectratio = config.plugins.transcodingsetup.aspectratio.value
                    interlaced = config.plugins.transcodingsetup.interlaced.value
                    if fileExists("/proc/stb/encoder/0/vcodec"):
                        vcodec = config.plugins.transcodingsetup.vcodec.value
                        args = "?bitrate=%s__width=%s__height=%s__vcodec=%s__aspectratio=%s__interlaced=%s" % (
                            bitrate, width, height, vcodec, aspectratio,
                            interlaced)
                    else:
                        args = "?bitrate=%s__width=%s__height=%s__aspectratio=%s__interlaced=%s" % (
                            bitrate, width, height, aspectratio, interlaced)
                    args = args.replace('__', urlparam)
                except Exception:
                    pass

    # When you use EXTVLCOPT:program in a transcoded stream, VLC does not play stream
    if config.OpenWebif.service_name_for_stream.value and sRef != '' and portNumber != transcoder_port:
        progopt = "%s#EXTVLCOPT:program=%d\n" % (progopt,
                                                 int(sRef.split(':')[3], 16))

    if config.OpenWebif.auth_for_streaming.value:
        asession = GetSession()
        if asession.GetAuth(request) is not None:
            auth = ':'.join(asession.GetAuth(request)) + "@"
        else:
            auth = '-sid:' + str(asession.GetSID(request)) + "@"
    else:
        auth = ''

    response = "#EXTM3U \n#EXTVLCOPT--http-reconnect=true \n%shttp://%s%s:%s/%s%s\n" % (
        progopt, auth, request.getRequestHostname(), portNumber, sRef, args)
    request.setHeader('Content-Type', 'application/x-mpegurl')
    # Note: do not rename the m3u file all the time
    if "fname" in request.args:
        request.setHeader(
            'Content-Disposition',
            'inline; filename=%s.%s;' % (request.args["fname"][0], 'm3u8'))
    return response
示例#13
0
def getTS(self, request):
    if "file" in request.args:
        filename = unquote(request.args["file"][0]).decode(
            'utf-8', 'ignore').encode('utf-8')
        if not os.path.exists(filename):
            return "File '%s' not found" % (filename)


# ServiceReference is not part of filename so look in the '.ts.meta' file
        sRef = ""
        progopt = ''

        if os.path.exists(filename + '.meta'):
            metafile = open(filename + '.meta', "r")
            name = ''
            seconds = -1  # unknown duration default
            line = metafile.readline()  # service ref
            if line:
                sRef = eServiceReference(line.strip()).toString()
            line2 = metafile.readline()  # name
            if line2:
                name = line2.strip()
            line6 = metafile.readline()  # description
            line6 = metafile.readline()  # recording time
            line6 = metafile.readline()  # tags
            line6 = metafile.readline()  # length

            if line6:
                seconds = float(line6.strip()) / 90000  # In seconds

            if config.OpenWebif.service_name_for_stream.value:
                progopt = "%s#EXTINF:%d,%s\n" % (progopt, seconds, name)

            metafile.close()

        portNumber = None
        proto = 'http'
        info = getInfo()
        model = info["model"]
        machinebuild = info["machinebuild"]
        transcoder_port = None
        args = ""
        urlparam = '?'
        if info["imagedistro"] in ('openpli', 'satdreamgr', 'openvision'):
            urlparam = '&'

        if fileExists("/dev/bcm_enc0"):
            try:
                transcoder_port = int(
                    config.plugins.transcodingsetup.port.value)
            except StandardError:
                # Transcoding Plugin is not installed or your STB does not support transcoding
                transcoder_port = None
            if "device" in request.args:
                if request.args["device"][0] == "phone":
                    portNumber = transcoder_port
            if "port" in request.args:
                portNumber = request.args["port"][0]
        elif fileExists("/dev/encoder0") or fileExists(
                "/proc/stb/encoder/0/apply"):
            portNumber = config.OpenWebif.streamport.value

        if fileExists("/dev/bcm_enc0") or fileExists(
                "/dev/encoder0") or fileExists("/proc/stb/encoder/0/apply"):
            if "device" in request.args:
                if request.args["device"][0] == "phone":
                    try:
                        bitrate = config.plugins.transcodingsetup.bitrate.value
                        resolution = config.plugins.transcodingsetup.resolution.value
                        (width, height) = tuple(resolution.split('x'))
                        # framerate = config.plugins.transcodingsetup.framerate.value
                        aspectratio = config.plugins.transcodingsetup.aspectratio.value
                        interlaced = config.plugins.transcodingsetup.interlaced.value
                        if fileExists("/proc/stb/encoder/0/vcodec"):
                            vcodec = config.plugins.transcodingsetup.vcodec.value
                            args = "?bitrate=%s__width=%s__height=%s__vcodec=%s__aspectratio=%s__interlaced=%s" % (
                                bitrate, width, height, vcodec, aspectratio,
                                interlaced)
                        else:
                            args = "?bitrate=%s__width=%s__height=%s__aspectratio=%s__interlaced=%s" % (
                                bitrate, width, height, aspectratio,
                                interlaced)
                        args = args.replace('__', urlparam)
                    except Exception:
                        pass

        # When you use EXTVLCOPT:program in a transcoded stream, VLC does not play stream
        if config.OpenWebif.service_name_for_stream.value and sRef != '' and portNumber != transcoder_port:
            progopt = "%s#EXTVLCOPT:program=%d\n" % (
                progopt, int(sRef.split(':')[3], 16))

        if portNumber is None:
            portNumber = config.OpenWebif.port.value
            if request.isSecure():
                portNumber = config.OpenWebif.https_port.value
                proto = 'https'
            ourhost = request.getHeader('host')
            m = re.match('.+\:(\d+)$', ourhost)
            if m is not None:
                portNumber = m.group(1)

        if config.OpenWebif.auth_for_streaming.value:
            asession = GetSession()
            if asession.GetAuth(request) is not None:
                auth = ':'.join(asession.GetAuth(request)) + "@"
            else:
                auth = '-sid:' + str(asession.GetSID(request)) + "@"
        else:
            auth = ''

        response = "#EXTM3U \n#EXTVLCOPT--http-reconnect=true \n%s%s://%s%s:%s/file?file=%s%s\n" % (
            (progopt, proto, auth, request.getRequestHostname(), portNumber,
             quote(filename), args))
        request.setHeader('Content-Type', 'application/x-mpegurl')
        return response
    else:
        return "Missing file parameter"
示例#14
0
def getStream(session, request, m3ufile):
	if "ref" in request.args:
		sRef = unquote(unquote(request.args["ref"][0]).decode('utf-8', 'ignore')).encode('utf-8')
	else:
		sRef = ""

	currentServiceRef = None
	if m3ufile == "streamcurrent.m3u":
		currentServiceRef = session.nav.getCurrentlyPlayingServiceReference()
		sRef = currentServiceRef.toString()

	if sRef.startswith("1:134:"):
		if currentServiceRef is None:
			currentServiceRef = session.nav.getCurrentlyPlayingServiceReference()
		if currentServiceRef is None:
			currentServiceRef = eServiceReference()
		ref = getBestPlayableServiceReference(eServiceReference(sRef), currentServiceRef)
		if ref is None:
			sRef = ""
		else:
			sRef = ref.toString()

	name = "stream"
	# #EXTINF:-1,%s\n adding back to show service name in programs like VLC
	progopt = ''
	if "name" in request.args:
		name = request.args["name"][0]
		if config.OpenWebif.service_name_for_stream.value:
			progopt = "#EXTINF:-1,%s\n" % name

	portNumber = config.OpenWebif.streamport.value
	info = getInfo()
	model = info["model"]
	machinebuild = info["machinebuild"]
	transcoder_port = None
	args = ""
	if model in ("Duo4K", "Uno4K", "Uno4K SE", "Ultimo4K", "Solo4K", "Solo²", "Duo²", "Solo SE", "Quad", "Quad Plus", "UHD Quad 4k", "UHD UE 4k") or machinebuild in ('dags7356', 'dags7252', 'gb7252', 'gb7356'):
		try:
			transcoder_port = int(config.plugins.transcodingsetup.port.value)
		except StandardError:
			# Transcoding Plugin is not installed or your STB does not support transcoding
			transcoder_port = None
		if "device" in request.args:
			if request.args["device"][0] == "phone":
				portNumber = transcoder_port
		if "port" in request.args:
			portNumber = request.args["port"][0]

	# INI use dynamic encoder allocation, and each stream can have diffrent parameters
	elif machinebuild in ('ew7356', 'formuler1tc', 'tiviaraplus'):
		transcoder_port = 8001
		if "device" in request.args:
			if request.args["device"][0] == "phone":
				bitrate = config.plugins.transcodingsetup.bitrate.value
				# framerate = config.plugins.transcodingsetup.framerate.value
				args = "?bitrate=%s" % (bitrate)
	elif fileExists("/proc/stb/encoder/0/apply"):
		transcoder_port = 8001
		if "device" in request.args:
			if request.args["device"][0] == "phone":
				bitrate = config.plugins.transcodingsetup.bitrate.value
				resolution = config.plugins.transcodingsetup.resolution.value
				(width, height) = tuple(resolution.split('x'))
				# framerate = config.plugins.transcodingsetup.framerate.value
				aspectratio = config.plugins.transcodingsetup.aspectratio.value
				interlaced = config.plugins.transcodingsetup.interlaced.value
				if fileExists("/proc/stb/encoder/0/vcodec"):
					vcodec = config.plugins.transcodingsetup.vcodec.value
					args = "?bitrate=%s?width=%s?height=%s?vcodec=%s?aspectratio=%s?interlaced=%s" % (bitrate, width, height, vcodec, aspectratio, interlaced)
				else:
					args = "?bitrate=%s?width=%s?height=%s?aspectratio=%s?interlaced=%s" % (bitrate, width, height, aspectratio, interlaced)

	# When you use EXTVLCOPT:program in a transcoded stream, VLC does not play stream
	if config.OpenWebif.service_name_for_stream.value and sRef != '' and portNumber != transcoder_port:
		progopt = "%s#EXTVLCOPT:program=%d\n" % (progopt, int(sRef.split(':')[3], 16))

	if config.OpenWebif.auth_for_streaming.value:
		asession = GetSession()
		if asession.GetAuth(request) is not None:
			auth = ':'.join(asession.GetAuth(request)) + "@"
		else:
			auth = '-sid:' + str(asession.GetSID(request)) + "@"
	else:
		auth = ''

	response = "#EXTM3U \n#EXTVLCOPT--http-reconnect=true \n%shttp://%s%s:%s/%s%s\n" % (progopt, auth, request.getRequestHostname(), portNumber, sRef, args)
	request.setHeader('Content-Type', 'application/x-mpegurl')
	# Note: do not rename the m3u file all the time
	if "fname" in request.args:
		request.setHeader('Content-Disposition', 'inline; filename=%s.%s;' % (request.args["fname"][0], 'm3u8'))
	return response
示例#15
0
def getTS(self, request):
	if "file" in request.args:
		filename = unquote(request.args["file"][0]).decode('utf-8', 'ignore').encode('utf-8')
		if not os.path.exists(filename):
			return "File '%s' not found" % (filename)

# ServiceReference is not part of filename so look in the '.ts.meta' file
		sRef = ""
		progopt = ''

		if os.path.exists(filename + '.meta'):
			metafile = open(filename + '.meta', "r")
			name = ''
			seconds = -1  # unknown duration default
			line = metafile.readline()  # service ref
			if line:
				sRef = eServiceReference(line.strip()).toString()
			line2 = metafile.readline()  # name
			if line2:
				name = line2.strip()
			line6 = metafile.readline()  # description
			line6 = metafile.readline()  # recording time
			line6 = metafile.readline()  # tags
			line6 = metafile.readline()  # length

			if line6:
				seconds = float(line6.strip()) / 90000  # In seconds

			if config.OpenWebif.service_name_for_stream.value:
				progopt = "%s#EXTINF:%d,%s\n" % (progopt, seconds, name)

			metafile.close()

		portNumber = None
		proto = 'http'
		info = getInfo()
		model = info["model"]
		machinebuild = info["machinebuild"]
		transcoder_port = None
		args = ""
		if model in ("Duo4K", "Uno4K", "Uno4K SE", "Ultimo4K", "Solo4K", "Solo²", "Duo²", "Solo SE", "Quad", "Quad Plus") or machinebuild in ('gb7252', 'gb7356'):
			try:
				transcoder_port = int(config.plugins.transcodingsetup.port.value)
			except StandardError:
				# Transcoding Plugin is not installed or your STB does not support transcoding
				transcoder_port = None
			if "device" in request.args:
				if request.args["device"][0] == "phone":
					portNumber = transcoder_port
			if "port" in request.args:
				portNumber = request.args["port"][0]

		# INI use dynamic encoder allocation, and each stream can have diffrent parameters
		elif machinebuild in ('ew7356', 'formuler1tc', 'tiviaraplus'):
			if "device" in request.args:
				if request.args["device"][0] == "phone":
					portNumber = config.OpenWebif.streamport.value
					bitrate = config.plugins.transcodingsetup.bitrate.value
					# framerate = config.plugins.transcodingsetup.framerate.value
					args = "?bitrate=%s" % (bitrate)
		elif fileExists("/proc/stb/encoder/0/apply"):
			if "device" in request.args:
				if request.args["device"][0] == "phone":
					portNumber = config.OpenWebif.streamport.value
					bitrate = config.plugins.transcodingsetup.bitrate.value
					resolution = config.plugins.transcodingsetup.resolution.value
					(width, height) = tuple(resolution.split('x'))
					# framerate = config.plugins.transcodingsetup.framerate.value
					aspectratio = config.plugins.transcodingsetup.aspectratio.value
					interlaced = config.plugins.transcodingsetup.interlaced.value
					if fileExists("/proc/stb/encoder/0/vcodec"):
						vcodec = config.plugins.transcodingsetup.vcodec.value
						args = "?bitrate=%s?width=%s?height=%s?vcodec=%s?aspectratio=%s?interlaced=%s" % (bitrate, width, height, vcodec, aspectratio, interlaced)
					else:
						args = "?bitrate=%s?width=%s?height=%s?aspectratio=%s?interlaced=%s" % (bitrate, width, height, aspectratio, interlaced)

		# When you use EXTVLCOPT:program in a transcoded stream, VLC does not play stream
		if config.OpenWebif.service_name_for_stream.value and sRef != '' and portNumber != transcoder_port:
			progopt = "%s#EXTVLCOPT:program=%d\n" % (progopt, int(sRef.split(':')[3], 16))

		if portNumber is None:
			portNumber = config.OpenWebif.port.value
			if request.isSecure():
				portNumber = config.OpenWebif.https_port.value
				proto = 'https'
			ourhost = request.getHeader('host')
			m = re.match('.+\:(\d+)$', ourhost)
			if m is not None:
				portNumber = m.group(1)

		response = "#EXTM3U \n#EXTVLCOPT--http-reconnect=true \n%s%s://%s:%s/file?file=%s%s\n" % ((progopt, proto, request.getRequestHostname(), portNumber, quote(filename), args))
		request.setHeader('Content-Type', 'application/x-mpegurl')
		return response
	else:
		return "Missing file parameter"
示例#16
0
def create_file_m3u(request):
    """
    Create M3U contents for file streaming.

    Args:
        request (twisted.web.server.Request): HTTP request object

    Returns:
        M3U contents
    """
    try:
        filename = require_valid_file_parameter(request, "file")
    except ValueError as verr:
        request.setResponseCode(http.BAD_REQUEST)
        SLOG.error(verr)
        return ''
    except IOError as ioerr:
        SLOG.error(ioerr)
        request.setResponseCode(http.NOT_FOUND)
        return ''

    for_phone = False
    if "device" in request.args:
        for_phone = request.args["device"][0] == "phone"

    # ServiceReference is not part of filename so look in
    # the '.ts.meta' file
    sRef = ""
    m3u_content = [
        '#EXTM3U',
        '#EXTVLCOPT--http-reconnect=true',
    ]

    if config.OpenWebif.service_name_for_stream.value:
        metafilename = filename + '.meta'
        try:
            with open(metafilename, "rb") as src:
                lines = [x.strip() for x in src.readlines()]
                name = ''
                seconds = -1  # unknown duration default
                if lines[0]:  # service ref
                    sRef = eServiceReference(lines[0]).toString()
                if lines[1]:  # name
                    name = lines[1]
                if lines[5]:  # length
                    seconds = float(lines[5]) / 90000  # In seconds
                m3u_content.append("#EXTINF:%d,%s" % (seconds, name))
        except (IOError, ValueError, IndexError):
            pass

    portNumber = None
    info = getInfo()
    model = info["model"]
    machinebuild = info["machinebuild"]
    transcoder_port = None

    # INI use dynamic encoder allocation, and each stream can have
    # different parameters
    args = create_transcoding_args(machinebuild, for_phone)

    if model in MODEL_TRANSCODING or machinebuild in MACHINEBUILD_TRANSCODING:
        try:
            transcoder_port = int(config.plugins.transcodingsetup.port.value)
        except Exception:
            # Transcoding Plugin is not installed or your STB does not
            # support transcoding
            pass

        if for_phone:
            portNumber = transcoder_port

    if "port" in request.args:
        portNumber = request.args["port"][0]

    if for_phone:
        if machinebuild in MACHINEBUILD_TRANSCODING_ANY:
            portNumber = config.OpenWebif.streamport.value

    # When you use EXTVLCOPT:program in a transcoded stream, VLC does not
    # play stream
    use_s_name = config.OpenWebif.service_name_for_stream.value
    if use_s_name and sRef != '' and portNumber != transcoder_port:
        m3u_content.append("#EXTVLCOPT:program=%d" %
                           (int(sRef.split(':')[3], 16)))

    mangled = mangle_host_header_port(
        request.getHeader('host'), fallback_port=config.OpenWebif.port.value)

    if portNumber is None:
        portNumber = mangled['port']

    args['file'] = filename
    source_url = build_url(hostname=mangled['hostname'],
                           port=portNumber,
                           path="/file",
                           args=args)
    m3u_content.append(source_url)
    request.setHeader('Content-Type', 'application/x-mpegurl')
    return "\n".join(m3u_content)
示例#17
0
def getTS(self, request):
    if "file" in request.args:
        filename = unquote(request.args["file"][0]).decode(
            'utf-8', 'ignore').encode('utf-8')
        if not os.path.exists(filename):
            return "File '%s' not found" % (filename)


#	ServiceReference is not part of filename so look in the '.ts.meta' file
        sRef = ""
        progopt = ''

        if os.path.exists(filename + '.meta'):
            metafile = open(filename + '.meta', "r")
            name = ''
            seconds = -1  # unknown duration default
            line = metafile.readline()  # service ref
            if line:
                sRef = eServiceReference(line.strip()).toString()
            line2 = metafile.readline()  # name
            if line2:
                name = line2.strip()
            line3 = metafile.readline()  # description
            line4 = metafile.readline()  # recording time
            line5 = metafile.readline()  # tags
            line6 = metafile.readline()  # length

            if line6:
                seconds = float(line6.strip()) / 90000  # In seconds

            if config.ModernWebif.service_name_for_stream.value:
                progopt = "%s#EXTINF:%d,%s\n" % (progopt, seconds, name)

            metafile.close()

        portNumber = None
        proto = 'http'
        info = getInfo()
        model = info["model"]
        machinebuild = info["machinebuild"]
        transcoder_port = None
        args = ""
        if model in ("Solo4K", "Solo²", "Duo²", "Solo SE", "Quad",
                     "Quad Plus"):
            try:
                transcoder_port = int(
                    config.plugins.transcodingsetup.port.value)
            except StandardError:
                #Transcoding Plugin is not installed or your STB does not support transcoding
                transcoder_port = None
            if "device" in request.args:
                if request.args["device"][0] == "phone":
                    portNumber = transcoder_port
        if "port" in request.args:
            portNumber = request.args["port"][0]

        # INI use dynamic encoder allocation, and each stream can have diffrent parameters
        if machinebuild in ('inihdp', 'hd2400', 'et10000'):
            if "device" in request.args:
                if request.args["device"][0] == "phone":
                    portNumber = config.ModernWebif.streamport.value
                    bitrate = config.plugins.transcodingsetup.bitrate.value
                    resolution = config.plugins.transcodingsetup.resolution.value
                    (width, height) = tuple(resolution.split('x'))
                    framrate = config.plugins.transcodingsetup.framerate.value
                    aspectratio = config.plugins.transcodingsetup.aspectratio.value
                    interlaced = config.plugins.transcodingsetup.interlaced.value
                    args = "?bitrate=%s?width=%s?height=%s?aspectratio=%s?interlaced=%s" % (
                        bitrate, width, height, aspectratio, interlaced)
        elif machinebuild in ('ew7356'):
            if "device" in request.args:
                if request.args["device"][0] == "phone":
                    portNumber = config.ModernWebif.streamport.value
                    bitrate = config.plugins.transcodingsetup.bitrate.value
                    framrate = config.plugins.transcodingsetup.framerate.value
                    args = "?bitrate=%s" % (bitrate)

        # When you use EXTVLCOPT:program in a transcoded stream, VLC does not play stream
        if config.ModernWebif.service_name_for_stream.value and sRef != '' and portNumber != transcoder_port:
            progopt = "%s#EXTVLCOPT:program=%d\n" % (
                progopt, int(sRef.split(':')[3], 16))

        if portNumber is None:
            portNumber = config.ModernWebif.port.value
            if request.isSecure():
                portNumber = config.ModernWebif.https_port.value
                proto = 'https'
            ourhost = request.getHeader('host')
            m = re.match('.+\:(\d+)$', ourhost)
            if m is not None:
                portNumber = m.group(1)

        response = "#EXTM3U \n#EXTVLCOPT--http-reconnect=true \n%s%s://%s:%s/file?file=%s%s\n" % (
            (progopt, proto, request.getRequestHostname(), portNumber,
             quote(filename), args))
        request.setHeader('Content-Type', 'application/text')
        return response
    else:
        return "Missing file parameter"
示例#18
0
def getStream(session, request, m3ufile):
    if "ref" in request.args:
        sRef = unquote(
            unquote(request.args["ref"][0]).decode('utf-8',
                                                   'ignore')).encode('utf-8')
    else:
        sRef = ""

    currentServiceRef = None
    if m3ufile == "streamcurrent.m3u":
        currentServiceRef = session.nav.getCurrentlyPlayingServiceReference()
        sRef = currentServiceRef.toString()

    if sRef.startswith("1:134:"):
        if currentServiceRef is None:
            currentServiceRef = session.nav.getCurrentlyPlayingServiceReference(
            )
        if currentServiceRef is None:
            currentServiceRef = eServiceReference()
        ref = getBestPlayableServiceReference(eServiceReference(sRef),
                                              currentServiceRef)
        if ref is None:
            sRef = ""
        else:
            sRef = ref.toString()

    name = "stream"
    # #EXTINF:-1,%s\n adding back to show service name in programs like VLC
    progopt = ''
    if "name" in request.args:
        name = request.args["name"][0]
        if config.OpenWebif.service_name_for_stream.value:
            progopt = "#EXTINF:-1,%s\n" % name

    portNumber = config.OpenWebif.streamport.value
    info = getInfo()
    model = info["model"]
    transcoder_port = None
    if model in ("solo2", "duo2", "solose", "vusolo2", "vuduo2", "vusolose",
                 "hd2400", "xpeedlx3", "gbquad", "gbquadplus"):
        try:
            transcoder_port = int(config.plugins.transcodingsetup.port.value)
        except StandardError:
            #Transcoding Plugin is not installed or your STB does not support transcoding
            transcoder_port = None
        if "device" in request.args:
            if request.args["device"][0] == "phone":
                portNumber = 8002

    if "port" in request.args:
        portNumber = request.args["port"][0]

    # When you use EXTVLCOPT:program in a transcoded stream, VLC does not play stream
    if config.OpenWebif.service_name_for_stream.value and sRef != '' and portNumber != transcoder_port:
        progopt = "%s#EXTVLCOPT:program=%d\n" % (progopt,
                                                 int(sRef.split(':')[3], 16))

    response = "#EXTM3U \n#EXTVLCOPT--http-reconnect=true \n%shttp://%s:%s/%s\n" % (
        progopt, request.getRequestHostname(), portNumber, sRef)
    request.setHeader('Content-Type', 'application/text')
    return response
def getStream(session, request, m3ufile):
	if "ref" in request.args:
		sRef = unquote(unquote(request.args["ref"][0]).decode('utf-8', 'ignore')).encode('utf-8')
	else:
		sRef = ""

	currentServiceRef = None
	if m3ufile == "streamcurrent.m3u":
		currentServiceRef = session.nav.getCurrentlyPlayingServiceReference()
		sRef = currentServiceRef.toString()

	if sRef.startswith("1:134:"):
		if currentServiceRef is None:
			currentServiceRef = session.nav.getCurrentlyPlayingServiceReference()
		if currentServiceRef is None:
			currentServiceRef = eServiceReference()
		ref = getBestPlayableServiceReference(eServiceReference(sRef), currentServiceRef)
		if ref is None:
			sRef = ""
		else:
			sRef = ref.toString()

	name = "stream"
	# #EXTINF:-1,%s\n adding back to show service name in programs like VLC
	progopt = ''
	if "name" in request.args:
		name = request.args["name"][0]
		if config.OpenWebif.service_name_for_stream.value:
			progopt = "#EXTINF:-1,%s\n" % name

	portNumber = config.OpenWebif.streamport.value
	info = getInfo()
	model = info["model"]
	machinebuild = info["machinebuild"]
	urlparam = '?'
	if info["imagedistro"] in ('openpli', 'satdreamgr', 'openvision'):
		urlparam = '&'
	transcoder_port = None
	args = ""

	if fileExists("/dev/bcm_enc0"):
		try:
			transcoder_port = int(config.plugins.transcodingsetup.port.value)
		except StandardError:
			# Transcoding Plugin is not installed or your STB does not support transcoding
			transcoder_port = None
		if "device" in request.args:
			if request.args["device"][0] == "phone":
				portNumber = transcoder_port
		if "port" in request.args:
			portNumber = request.args["port"][0]
	elif fileExists("/dev/encoder0") or fileExists("/proc/stb/encoder/0/apply"):
		transcoder_port = portNumber

	if fileExists("/dev/bcm_enc0") or fileExists("/dev/encoder0") or fileExists("/proc/stb/encoder/0/apply"):
		if "device" in request.args:
			if request.args["device"][0] == "phone":
				try:
					bitrate = config.plugins.transcodingsetup.bitrate.value
					resolution = config.plugins.transcodingsetup.resolution.value
					(width, height) = tuple(resolution.split('x'))
					# framerate = config.plugins.transcodingsetup.framerate.value
					aspectratio = config.plugins.transcodingsetup.aspectratio.value
					interlaced = config.plugins.transcodingsetup.interlaced.value
					if fileExists("/proc/stb/encoder/0/vcodec"):
						vcodec = config.plugins.transcodingsetup.vcodec.value
						args = "?bitrate=%s__width=%s__height=%s__vcodec=%s__aspectratio=%s__interlaced=%s" % (bitrate, width, height, vcodec, aspectratio, interlaced)
					else:
						args = "?bitrate=%s__width=%s__height=%s__aspectratio=%s__interlaced=%s" % (bitrate, width, height, aspectratio, interlaced)
					args = args.replace('__', urlparam)
				except Exception:
					pass

	# When you use EXTVLCOPT:program in a transcoded stream, VLC does not play stream
	if config.OpenWebif.service_name_for_stream.value and sRef != '' and portNumber != transcoder_port:
		progopt = "%s#EXTVLCOPT:program=%d\n" % (progopt, int(sRef.split(':')[3], 16))

	if config.OpenWebif.auth_for_streaming.value:
		asession = GetSession()
		if asession.GetAuth(request) is not None:
			auth = ':'.join(asession.GetAuth(request)) + "@"
		else:
			auth = '-sid:' + str(asession.GetSID(request)) + "@"
	else:
		auth = ''

	response = "#EXTM3U \n#EXTVLCOPT--http-reconnect=true \n%shttp://%s%s:%s/%s%s\n" % (progopt, auth, request.getRequestHostname(), portNumber, sRef, args)
	request.setHeader('Content-Type', 'application/x-mpegurl')
	# Note: do not rename the m3u file all the time
	if "fname" in request.args:
		request.setHeader('Content-Disposition', 'inline; filename=%s.%s;' % (request.args["fname"][0], 'm3u8'))
	return response
示例#20
0
def main():
    dirPath = os.path.dirname(os.path.realpath(__file__))
    # Fixes pip not able to find other included modules.
    sys.path.append(os.path.abspath(dirPath))

    # Print the version if only the -v option is added.
    if (sys.argv[1:] == ['-v'] or sys.argv[1:] == ['-V']):
        print(f'Auto-Editor version {version}\nPlease use --version instead.')
        sys.exit()

    # If the users just runs: $ auto-editor
    if (sys.argv[1:] == []):
        # Print
        print(
            '\nAuto-Editor is an automatic video/audio creator and editor.\n')
        print(
            'By default, it will detect silence and create a new video with ')
        print(
            'those sections cut out. By changing some of the options, you can')
        print(
            'export to a traditional editor like Premiere Pro and adjust the')
        print(
            'edits there, adjust the pacing of the cuts, and change the method'
        )
        print('of editing like using audio loudness and video motion to judge')
        print('making cuts.')
        print(
            '\nRun:\n    auto-editor --help\n\nTo get the list of options.\n')
        sys.exit()

    from vanparse import ParseOptions
    from usefulFunctions import Log, Timer

    if (len(sys.argv) > 1 and sys.argv[1] == 'generate_test'):
        option_data = generate_options()
        args = ParseOptions(sys.argv[2:], Log(), 'generate_test', option_data)

        if (args.help):
            genHelp(option_data)
            sys.exit()

        from generateTestMedia import generateTestMedia
        from usefulFunctions import FFmpeg

        ffmpeg = FFmpeg(dirPath, args.my_ffmpeg, Log())
        generateTestMedia(ffmpeg, args.output_file, args.fps, args.duration,
                          args.width, args.height)
        sys.exit()

    elif (len(sys.argv) > 1 and sys.argv[1] == 'test'):

        from testAutoEditor import testAutoEditor
        testAutoEditor()
        sys.exit()

    elif (len(sys.argv) > 1 and sys.argv[1] == 'info'):
        option_data = info_options()
        args = ParseOptions(sys.argv[2:], Log(), 'info', option_data)

        if (args.help):
            genHelp(option_data)
            sys.exit()

        from info import getInfo
        from usefulFunctions import FFmpeg, FFprobe

        log = Log()
        ffmpeg = FFmpeg(dirPath, args.my_ffmpeg, log)
        ffprobe = FFprobe(dirPath, args.my_ffmpeg, log)

        getInfo(args.input, ffmpeg, ffprobe, log)
        sys.exit()
    else:
        option_data = main_options()
        args = ParseOptions(sys.argv[1:], Log(True), 'auto-editor',
                            option_data)

    timer = Timer(args.quiet)

    # Print the help screen for the entire program.
    if (args.help):
        print('\n  Have an issue? Make an issue. '\
            'Visit https://github.com/wyattblue/auto-editor/issues\n')
        print('  The help option can also be used on a specific option:')
        print('      auto-editor --frame_margin --help\n')
        genHelp(option_data)
        sys.exit()

    del option_data

    from usefulFunctions import FFmpeg, FFprobe, sep
    ffmpeg = FFmpeg(dirPath, args.my_ffmpeg, Log())
    ffprobe = FFprobe(dirPath, args.my_ffmpeg, Log())

    makingDataFile = (args.export_to_premiere or args.export_to_resolve
                      or args.export_to_final_cut_pro or args.export_as_json)
    is64bit = '64-bit' if sys.maxsize > 2**32 else '32-bit'

    if (args.debug and args.input == []):
        import platform

        print('Python Version:', platform.python_version(), is64bit)
        print('Platform:', platform.system(), platform.release())
        print('Config File path:', dirPath + sep() + 'config.txt')
        print('FFmpeg path:', ffmpeg.getPath())
        ffmpegVersion = ffmpeg.pipe(['-version']).split('\n')[0]
        ffmpegVersion = ffmpegVersion.replace('ffmpeg version', '').strip()
        ffmpegVersion = ffmpegVersion.split(' ')[0]
        print('FFmpeg version:', ffmpegVersion)
        print('Auto-Editor version', version)
        sys.exit()

    if (is64bit == '32-bit'):
        log.warning('You have the 32-bit version of Python, which may lead to' \
            'memory crashes.')

    if (args.version):
        print('Auto-Editor version', version)
        sys.exit()

    TEMP = tempfile.mkdtemp()
    log = Log(args.debug, args.show_ffmpeg_debug, args.quiet, temp=TEMP)
    log.debug(f'\n   - Temp Directory: {TEMP}')

    ffmpeg.updateLog(log)
    ffprobe.updateLog(log)

    from wavfile import read
    from usefulFunctions import isLatestVersion

    if (not args.quiet and isLatestVersion(version, log)):
        log.print('\nAuto-Editor is out of date. Run:\n')
        log.print('    pip3 install -U auto-editor')
        log.print('\nto upgrade to the latest version.\n')

    from argsCheck import hardArgsCheck, softArgsCheck
    hardArgsCheck(args, log)
    args = softArgsCheck(args, log)

    from validateInput import validInput
    inputList = validInput(args.input, ffmpeg, args, log)

    # Figure out the output file names.
    def newOutputName(oldFile: str, exa=False, data=False, exc=False) -> str:
        dotIndex = oldFile.rfind('.')
        if (exc):
            return oldFile[:dotIndex] + '.json'
        elif (data):
            return oldFile[:dotIndex] + '.xml'
        ext = oldFile[dotIndex:]
        if (exa):
            ext = '.wav'
        return oldFile[:dotIndex] + '_ALTERED' + ext

    if (len(args.output_file) < len(inputList)):
        for i in range(len(inputList) - len(args.output_file)):
            args.output_file.append(
                newOutputName(inputList[i], args.export_as_audio,
                              makingDataFile, args.export_as_json))

    if (args.combine_files):
        # Combine video files, then set input to 'combined.mp4'.
        cmd = []
        for fileref in inputList:
            cmd.extend(['-i', fileref])
        cmd.extend([
            '-filter_complex', f'[0:v]concat=n={len(inputList)}:v=1:a=1',
            '-codec:v', 'h264', '-pix_fmt', 'yuv420p', '-strict', '-2',
            f'{TEMP}{sep()}combined.mp4'
        ])
        ffmpeg.run(cmd)
        del cmd
        inputList = [f'{TEMP}{sep()}combined.mp4']

    speeds = [args.silent_speed, args.video_speed]
    log.debug(f'   - Speeds: {speeds}')

    audioExtensions = [
        '.wav', '.mp3', '.m4a', '.aiff', '.flac', '.ogg', '.oga', '.acc',
        '.nfa', '.mka'
    ]

    # videoExtensions = ['.mp4', '.mkv', '.mov', '.webm', '.ogv']

    for i, INPUT_FILE in enumerate(inputList):
        fileFormat = INPUT_FILE[INPUT_FILE.rfind('.'):]

        chunks = None
        if (fileFormat == '.json'):
            log.debug('Reading .json file')
            from makeCutList import readCutList
            INPUT_FILE, chunks, speeds = readCutList(INPUT_FILE, version, log)

            newOutput = newOutputName(INPUT_FILE, args.export_as_audio,
                                      makingDataFile, False)

            fileFormat = INPUT_FILE[INPUT_FILE.rfind('.'):]
        else:
            newOutput = args.output_file[i]

        log.debug(f'   - INPUT_FILE: {INPUT_FILE}')
        log.debug(f'   - newOutput: {newOutput}')

        if (os.path.isfile(newOutput) and INPUT_FILE != newOutput):
            log.debug(f'  Removing already existing file: {newOutput}')
            os.remove(newOutput)

        if (args.sample_rate is None):
            sampleRate = ffprobe.getSampleRate(INPUT_FILE)
            if (sampleRate == 'N/A'):
                sampleRate = '48000'
                log.warning(
                    f"Samplerate couldn't be detected, using {sampleRate}.")
        else:
            sampleRate = str(args.sample_rate)
        log.debug(f'   - sampleRate: {sampleRate}')

        if (args.audio_bitrate is None):
            if (INPUT_FILE.endswith('.mkv')):
                # audio bitrate not supported in the mkv container.
                audioBitrate = None
            else:
                audioBitrate = ffprobe.getPrettyABitrate(INPUT_FILE)
                if (audioBitrate == 'N/A'):
                    log.warning("Couldn't automatically detect audio bitrate.")
                    audioBitrate = None
        else:
            audioBitrate = args.audio_bitrate

        log.debug(f'   - audioBitrate: {audioBitrate}')

        audioFile = fileFormat in audioExtensions
        if (audioFile):
            if (args.force_fps_to is None):
                fps = 30  # Audio files don't have frames, so give fps a dummy value.
            else:
                fps = args.force_fps_to
            if (args.force_tracks_to is None):
                tracks = 1
            else:
                tracks = args.force_tracks_to
            cmd = ['-i', INPUT_FILE]
            if (audioBitrate is not None):
                cmd.extend(['-b:a', audioBitrate])
            cmd.extend([
                '-ac', '2', '-ar', sampleRate, '-vn',
                f'{TEMP}{sep()}fastAud.wav'
            ])
            ffmpeg.run(cmd)
            del cmd

            sampleRate, audioData = read(f'{TEMP}{sep()}fastAud.wav')
        else:
            if (args.force_fps_to is not None):
                fps = args.force_fps_to
            elif (args.export_to_premiere or args.export_to_final_cut_pro
                  or args.export_to_resolve):
                # Based on timebase.
                fps = int(ffprobe.getFrameRate(INPUT_FILE))
            else:
                fps = ffprobe.getFrameRate(INPUT_FILE)
            log.debug(f'Frame rate: {fps}')

            tracks = args.force_tracks_to
            if (tracks is None):
                tracks = ffprobe.getAudioTracks(INPUT_FILE)

            if (args.cut_by_this_track >= tracks):
                allTracks = ''
                for trackNum in range(tracks):
                    allTracks += f'Track {trackNum}\n'

                if (tracks == 1):
                    message = f'is only {tracks} track'
                else:
                    message = f'are only {tracks} tracks'
                log.error("You choose a track that doesn't exist.\n" \
                    f'There {message}.\n {allTracks}')

            # Split audio tracks into: 0.wav, 1.wav, etc.
            for trackNum in range(tracks):
                cmd = ['-i', INPUT_FILE]
                if (audioBitrate is not None):
                    cmd.extend(['-ab', audioBitrate])
                cmd.extend([
                    '-ac', '2', '-ar', sampleRate, '-map', f'0:a:{trackNum}',
                    f'{TEMP}{sep()}{trackNum}.wav'
                ])
                ffmpeg.run(cmd)
                del cmd

            # Check if the `--cut_by_all_tracks` flag has been set or not.
            if (args.cut_by_all_tracks):
                # Combine all audio tracks into one audio file, then read.
                cmd = [
                    '-i', INPUT_FILE, '-filter_complex',
                    f'[0:a]amix=inputs={tracks}:duration=longest', '-ar',
                    sampleRate, '-ac', '2', '-f', 'wav',
                    f'{TEMP}{sep()}combined.wav'
                ]
                ffmpeg.run(cmd)
                sampleRate, audioData = read(f'{TEMP}{sep()}combined.wav')
                del cmd
            else:
                # Read only one audio file.
                if (os.path.isfile(
                        f'{TEMP}{sep()}{args.cut_by_this_track}.wav')):
                    sampleRate, audioData = read(
                        f'{TEMP}{sep()}{args.cut_by_this_track}.wav')
                else:
                    log.bug('Audio track not found!')

        log.debug(f'   - Frame Rate: {fps}')
        if (chunks is None):
            from cutting import audioToHasLoud, motionDetection

            audioList = None
            motionList = None
            if ('audio' in args.edit_based_on):
                log.debug('Analyzing audio volume.')
                audioList = audioToHasLoud(audioData, sampleRate,
                                           args.silent_threshold, fps, log)

            if ('motion' in args.edit_based_on):
                log.debug('Analyzing video motion.')
                motionList = motionDetection(INPUT_FILE,
                                             ffprobe,
                                             args.motion_threshold,
                                             log,
                                             width=args.width,
                                             dilates=args.dilates,
                                             blur=args.blur)

                if (audioList is not None):
                    if (len(audioList) != len(motionList)):
                        log.debug(f'audioList Length:  {len(audioList)}')
                        log.debug(f'motionList Length: {len(motionList)}')
                    if (len(audioList) > len(motionList)):
                        log.debug(
                            'Reducing the size of audioList to match motionList.'
                        )
                        audioList = audioList[:len(motionList)]
                    elif (len(motionList) > len(audioList)):
                        log.debug(
                            'Reducing the size of motionList to match audioList.'
                        )
                        motionList = motionList[:len(audioList)]

            from cutting import combineArrs, applySpacingRules

            hasLoud = combineArrs(audioList, motionList, args.edit_based_on,
                                  log)
            del audioList, motionList

            chunks = applySpacingRules(hasLoud, fps, args.frame_margin,
                                       args.min_clip_length,
                                       args.min_cut_length, args.ignore,
                                       args.cut_out, log)
            del hasLoud

        clips = []
        numCuts = len(chunks)
        for chunk in chunks:
            if (speeds[chunk[2]] != 99999):
                clips.append([chunk[0], chunk[1], speeds[chunk[2]] * 100])

        if (fps is None and not audioFile):
            if (makingDataFile):
                dotIndex = INPUT_FILE.rfind('.')
                end = '_constantFPS' + INPUT_FILE[dotIndex:]
                constantLoc = INPUT_FILE[:dotIndex] + end
            else:
                constantLoc = f'{TEMP}{sep()}constantVid{fileFormat}'
            ffmpeg.run(
                ['-i', INPUT_FILE, '-filter:v', 'fps=fps=30', constantLoc])
            INPUT_FILE = constantLoc

        if (args.export_as_json):
            from makeCutList import makeCutList
            makeCutList(INPUT_FILE, newOutput, version, chunks, speeds, log)
            continue

        if (args.preview):
            newOutput = None
            from preview import preview
            preview(INPUT_FILE, chunks, speeds, fps, audioFile, log)
            continue

        if (args.export_to_premiere or args.export_to_resolve):
            from editor import editorXML
            editorXML(INPUT_FILE, TEMP, newOutput, clips, chunks, tracks,
                      sampleRate, audioFile, args.export_to_resolve, fps, log)
            continue

        if (audioFile):
            from fastAudio import fastAudio, handleAudio, convertAudio
            theFile = handleAudio(ffmpeg, INPUT_FILE, audioBitrate,
                                  str(sampleRate), TEMP, log)
            fastAudio(theFile, f'{TEMP}{sep()}convert.wav', chunks, speeds,
                      log, fps, args.machine_readable_progress,
                      args.no_progress)
            convertAudio(ffmpeg, ffprobe, f'{TEMP}{sep()}convert.wav',
                         INPUT_FILE, newOutput, args, log)
            continue

        from videoUtils import handleAudioTracks, muxVideo

        continueVid = handleAudioTracks(ffmpeg, newOutput, args, tracks,
                                        chunks, speeds, fps, TEMP, log)
        if (continueVid):

            if (args.render == 'auto'):
                try:
                    import av
                    args.render = 'av'
                except ImportError:
                    args.render = 'opencv'

            log.debug(f'Using {args.render} method')
            if (args.render == 'av'):
                from renderVideo import renderAv
                renderAv(ffmpeg, INPUT_FILE, args, chunks, speeds, TEMP, log)

            if (args.render == 'opencv'):
                from renderVideo import renderOpencv
                renderOpencv(ffmpeg, INPUT_FILE, args, chunks, speeds, fps,
                             TEMP, log)

            # Now mix new audio(s) and the new video.
            muxVideo(ffmpeg, newOutput, args, tracks, TEMP, log)

    if (newOutput is not None and not os.path.isfile(newOutput)):
        log.bug(f'The file {newOutput} was not created.')

    if (not args.preview and not makingDataFile):
        timer.stop()

    if (not args.preview and makingDataFile):
        from usefulFunctions import humanReadableTime
        # Assume making each cut takes about 30 seconds.
        timeSave = humanReadableTime(numCuts * 30)

        s = 's' if numCuts != 1 else ''
        log.print(f'Auto-Editor made {numCuts} cut{s}', end='')
        log.print(
            f', which would have taken about {timeSave} if edited manually.')

    if (not args.no_open):
        from usefulFunctions import smartOpen
        smartOpen(newOutput, log)

    log.debug('Deleting temp dir')
    rmtree(TEMP)
示例#21
0
def x3(caffemodel,
       deploy,
       source,
       mode=True,
       IMAGE_SIZE=227,
       LAYER_NAME="my-fc8"):
    # f = open("predict.log", "w")
    file_list = []
    for root, dirs, files in os.walk(source):
        for file in files:
            file_list.append(os.path.join(root, file))
    images = np.zeros((len(file_list), 3, IMAGE_SIZE, IMAGE_SIZE),
                      dtype=np.float)

    # read age list
    real_ages = []
    for index, dicom_file in enumerate(file_list):
        real_age = info.getInfo(dicom_file)
        real_ages.append(real_age)
        images[index, :, :, :] = preprocess.process(dicom_file)
    if mode:
        caffe.set_mode_gpu()
    else:
        caffe.set_mode_cpu()
    net = caffe.Net(deploy, caffemodel, caffe.TEST)
    net.blobs['data'].reshape(len(file_list), 3, IMAGE_SIZE, IMAGE_SIZE)
    net.blobs['data'].data[...] = images
    output = net.forward()
    dic = {}
    for index, result in enumerate(output[LAYER_NAME]):
        predict_age = result[0]
        real_age = real_ages[index]
        file_name = file_list[index]
        id = dicom.read_file(file_list[index]).PatientID
        # only see the error sample
        # if (predict_age > BORDER_AGE and real_age > BORDER_AGE) or (predict_age <= BORDER_AGE and real_age <= BORDER_AGE):
        #     continue
        line = "%s %s %s %s %s" % (file_name, id, real_age, predict_age,
                                   abs(predict_age - real_age))
        dic[line] = abs(predict_age - real_age)
    dic = sorted(dic.items(), key=lambda d: d[1], reverse=False)
    test = {
        '25.00-25.99': 58,
        '16.00-16.99': 27,
        '22.00-22.99': 47,
        '26.00-26.99': 39,
        '18.00-18.99': 27,
        '24.00-24.99': 48,
        '19.00-19.99': 30,
        '20.00-20.99': 34,
        '21.00-21.99': 53,
        '23.00-23.99': 49,
        '27.00-27.99': 3,
        '15.00-15.99': 16,
        '17.00-17.99': 25,
        '14.00-14.99': 18
    }
    val = {
        '25.00-25.99': 0,
        '22.00-22.99': 0,
        '26.00-26.99': 0,
        '18.00-18.99': 0,
        '24.00-24.99': 0,
        '19.00-19.99': 0,
        '27.00-27.99': 0,
        '20.00-20.99': 0,
        '21.00-21.99': 0,
        '23.00-23.99': 0,
        '16.00-16.99': 0,
        '17.00-17.99': 0,
        '14.00-14.99': 0,
        '15.00-15.99': 0
    }
    temp = []
    for key, value in dic:
        # print key, value
        a = key.split(" ")
        n = int(float(a[2]))
        k = "%.2f-%s" % (n, n + 0.99)
        if val[k] < test[k]:
            print key
            val[k] += 1
            temp.append(a[0])

    t1 = set(temp)
    t2 = set(file_list)
    t = t2 - t1
    for x in t:
        os.remove(x)
示例#22
0
def x2():
    data = xlrd.open_workbook('/Users/HZzone/Desktop/female.xlsx')
    table = data.sheets()[0]
    c = table.col_values(0)
    #     test = {'25.00-25.99': 5,
    # '22.00-22.99': 11,
    # '26.00-26.99': 5,
    # '18.00-18.99': 8,
    # '24.00-24.99': 6,
    # '19.00-19.99': 4,
    # '20.00-20.99': 6,
    # '21.00-21.99': 8,
    # '23.00-23.99': 6,
    # '17.00-17.99': 3,
    # '14.00-14.99': 2,
    # '15.00-15.99': 4}
    #     val = {'25.00-25.99': 0,
    #             '22.00-22.99': 0,
    #             '26.00-26.99': 0,
    #             '18.00-18.99': 0,
    #             '24.00-24.99': 0,
    #             '19.00-19.99': 0,
    #             '20.00-20.99': 0,
    #             '21.00-21.99': 0,
    #             '23.00-23.99': 0,
    #             '16.00-16.99': 0,
    #             '17.00-17.99': 0,
    #             '14.00-14.99': 0,
    #             '15.00-15.99': 0}
    test = {
        '25.00-25.99': 6,
        '16.00-16.99': 2,
        '22.00-22.99': 5,
        '26.00-26.99': 4,
        '18.00-18.99': 3,
        '24.00-24.99': 8,
        '19.00-19.99': 4,
        '20.00-20.99': 3,
        '21.00-21.99': 4,
        '23.00-23.99': 5,
        '17.00-17.99': 1,
        '14.00-14.99': 1
    }
    val = {
        '25.00-25.99': 0,
        '22.00-22.99': 0,
        '26.00-26.99': 0,
        '18.00-18.99': 0,
        '24.00-24.99': 0,
        '19.00-19.99': 0,
        '20.00-20.99': 0,
        '21.00-21.99': 0,
        '23.00-23.99': 0,
        '16.00-16.99': 0,
        '17.00-17.99': 0,
        '14.00-14.99': 0,
        '15.00-15.99': 0
    }
    print c
    for root, dirs, files in os.walk("/Volumes/Hzzone/processed/female"):
        for dicom_file in files:
            path = os.path.join(root, dicom_file)
            age = info.getInfo(path)
            print age
            n = int(age)
            key = "%.2f-%s" % (n, n + 0.99)
            print key
            for i in c:
                if abs(age - i) <= 0.0000000001:
                    print(age - i)
                    try:
                        if val[key] >= test[key]:
                            continue
                        shutil.move(path,
                                    "/Volumes/Hzzone/processed/female/test")
                        val[key] = val[key] + 1
                    except:
                        pass
示例#23
0
def getStream(session, request, m3ufile):
    if "ref" in request.args:
        sRef = unquote(
            unquote(request.args["ref"][0]).decode('utf-8',
                                                   'ignore')).encode('utf-8')
    else:
        sRef = ""

    currentServiceRef = None
    if m3ufile == "streamcurrent.m3u":
        currentServiceRef = session.nav.getCurrentlyPlayingServiceReference()
        sRef = currentServiceRef.toString()

    if sRef.startswith("1:134:"):
        if currentServiceRef is None:
            currentServiceRef = session.nav.getCurrentlyPlayingServiceReference(
            )
        if currentServiceRef is None:
            currentServiceRef = eServiceReference()
        ref = getBestPlayableServiceReference(eServiceReference(sRef),
                                              currentServiceRef)
        if ref is None:
            sRef = ""
        else:
            sRef = ref.toString()

    name = "stream"
    # #EXTINF:-1,%s\n adding back to show service name in programs like VLC
    progopt = ''
    if "name" in request.args:
        name = request.args["name"][0]
        if config.OpenWebif.service_name_for_stream.value:
            progopt = "#EXTINF:-1,%s\n" % name

    portNumber = config.OpenWebif.streamport.value
    info = getInfo()
    model = info["model"]
    machinebuild = info["machinebuild"]
    transcoder_port = None
    args = ""
    if model in ("Uno4K", "Uno4K SE", "Ultimo4K", "Solo4K", "Solo²", "Duo²",
                 "Solo SE", "Quad", "Quad Plus",
                 "UHD Quad 4k") or machinebuild in ('dags7356', 'dags7252',
                                                    'gb7252', 'gb7356'):
        try:
            transcoder_port = int(config.plugins.transcodingsetup.port.value)
        except StandardError:
            # Transcoding Plugin is not installed or your STB does not support transcoding
            transcoder_port = None
        if "device" in request.args:
            if request.args["device"][0] == "phone":
                portNumber = transcoder_port
        if "port" in request.args:
            portNumber = request.args["port"][0]

    # INI use dynamic encoder allocation, and each stream can have diffrent parameters
    elif machinebuild in ('ew7356', 'formuler1tc', 'tiviaraplus'):
        transcoder_port = 8001
        if "device" in request.args:
            if request.args["device"][0] == "phone":
                bitrate = config.plugins.transcodingsetup.bitrate.value
                # framerate = config.plugins.transcodingsetup.framerate.value
                args = "?bitrate=%s" % (bitrate)
    elif fileExists("/proc/stb/encoder/0/apply"):
        transcoder_port = 8001
        if "device" in request.args:
            if request.args["device"][0] == "phone":
                bitrate = config.plugins.transcodingsetup.bitrate.value
                resolution = config.plugins.transcodingsetup.resolution.value
                (width, height) = tuple(resolution.split('x'))
                # framerate = config.plugins.transcodingsetup.framerate.value
                aspectratio = config.plugins.transcodingsetup.aspectratio.value
                interlaced = config.plugins.transcodingsetup.interlaced.value
                if fileExists("/proc/stb/encoder/0/vcodec"):
                    vcodec = config.plugins.transcodingsetup.vcodec.value
                    args = "?bitrate=%s?width=%s?height=%s?vcodec=%s?aspectratio=%s?interlaced=%s" % (
                        bitrate, width, height, vcodec, aspectratio,
                        interlaced)
                else:
                    args = "?bitrate=%s?width=%s?height=%s?aspectratio=%s?interlaced=%s" % (
                        bitrate, width, height, aspectratio, interlaced)

    # When you use EXTVLCOPT:program in a transcoded stream, VLC does not play stream
    if config.OpenWebif.service_name_for_stream.value and sRef != '' and portNumber != transcoder_port:
        progopt = "%s#EXTVLCOPT:program=%d\n" % (progopt,
                                                 int(sRef.split(':')[3], 16))

    if config.OpenWebif.auth_for_streaming.value:
        asession = GetSession()
        if asession.GetAuth(request) is not None:
            auth = ':'.join(asession.GetAuth(request)) + "@"
        else:
            auth = '-sid:' + str(asession.GetSID(request)) + "@"
    else:
        auth = ''

    response = "#EXTM3U \n#EXTVLCOPT--http-reconnect=true \n%shttp://%s%s:%s/%s%s\n" % (
        progopt, auth, request.getRequestHostname(), portNumber, sRef, args)
    request.setHeader('Content-Type', 'application/x-mpegurl')
    return response
示例#24
0
def create_stream_m3u(session, request, m3ufile):
    """
    Create M3U contents for service streaming.

    Args:
        session: enigma session object
        request (twisted.web.server.Request): HTTP request object
        m3ufile: M3U filename

    Returns:
        M3U contents
    """
    m3u_content = [
        '#EXTM3U',
        '#EXTVLCOPT--http-reconnect=true',
    ]
    sRef = ""
    currentServiceRef = None

    if "ref" in request.args:
        sRef = request.args["ref"][0].decode('utf-8', 'ignore').encode('utf-8')

    for_phone = False
    if "device" in request.args:
        for_phone = request.args["device"][0] == "phone"

    if m3ufile == "streamcurrent.m3u":
        currentServiceRef = session.nav.getCurrentlyPlayingServiceReference()
        sRef = currentServiceRef.toString()

    if sRef.startswith("1:134:"):
        if currentServiceRef is None:
            currentServiceRef = session.nav.getCurrentlyPlayingServiceReference(
            )  # NOQA
        if currentServiceRef is None:
            currentServiceRef = eServiceReference()
        ref = getBestPlayableServiceReference(eServiceReference(sRef),
                                              currentServiceRef)
        if ref is None:
            sRef = ""
        else:
            sRef = ref.toString()

    portNumber = config.OpenWebif.streamport.value
    info = getInfo()
    model = info["model"]
    machinebuild = info["machinebuild"]
    transcoder_port = None
    args = create_transcoding_args(machinebuild, for_phone)

    if model in MODEL_TRANSCODING or machinebuild in MACHINEBUILD_TRANSCODING:
        try:
            transcoder_port = int(config.plugins.transcodingsetup.port.value)
        except Exception:
            # Transcoding Plugin is not installed or your STB does not support
            # transcoding
            pass
        if for_phone:
            portNumber = transcoder_port
        if "port" in request.args:
            portNumber = request.args["port"][0]

    # INI use dynamic encoder allocation, and each stream can have diffrent
    # parameters
    if machinebuild in MACHINEBUILD_TRANSCODING_ANY:
        transcoder_port = 8001

    if config.OpenWebif.service_name_for_stream.value:
        if "name" in request.args:
            name = request.args["name"][0]
            m3u_content.append("#EXTINF:-1,%s" % name)

        # When you use EXTVLCOPT:program in a transcoded stream, VLC does
        # not play stream
        if sRef != '' and portNumber != transcoder_port:
            m3u_content.append("#EXTVLCOPT:program=%d" %
                               (int(sRef.split(':')[3], 16)))

    mangled = mangle_host_header_port(request.getHeader('host'))
    source_url = build_url(hostname=mangled['hostname'],
                           port=portNumber,
                           path=sRef,
                           args=args)
    m3u_content.append(source_url)
    request.setHeader('Content-Type', 'application/x-mpegurl')
    return "\n".join(m3u_content)
示例#25
0
def main():
    dirPath = os.path.dirname(os.path.realpath(__file__))
    # Fixes pip not able to find other included modules.
    sys.path.append(os.path.abspath(dirPath))

    # Print the version if only the -v option is added.
    if(sys.argv[1:] == ['-v'] or sys.argv[1:] == ['-V']):
        print(f'Auto-Editor version {version}\nPlease use --version instead.')
        sys.exit()

    if(sys.argv[1:] == []):
        print('\nAuto-Editor is an automatic video/audio creator and editor.\n')
        print('By default, it will detect silence and create a new video with ')
        print('those sections cut out. By changing some of the options, you can')
        print('export to a traditional editor like Premiere Pro and adjust the')
        print('edits there, adjust the pacing of the cuts, and change the method')
        print('of editing like using audio loudness and video motion to judge')
        print('making cuts.')
        print('\nRun:\n    auto-editor --help\n\nTo get the list of options.\n')
        sys.exit()

    from vanparse import ParseOptions
    from usefulFunctions import Log, Timer

    subcommands = ['create', 'test', 'info', 'levels']

    if(len(sys.argv) > 1 and sys.argv[1] in subcommands):
        if(sys.argv[1] == 'create'):
            from create import create, create_options
            from usefulFunctions import FFmpeg
            args = ParseOptions(sys.argv[2:], Log(), 'create', create_options())

            ffmpeg = FFmpeg(dirPath, args.my_ffmpeg, True, Log())
            create(ffmpeg, args.input, args.output_file, args.frame_rate, args.duration,
                args.width, args.height, Log())

        if(sys.argv[1] == 'test'):
            from testAutoEditor import testAutoEditor
            testAutoEditor()

        if(sys.argv[1] == 'info'):
            from info import getInfo, info_options
            from usefulFunctions import FFmpeg, FFprobe

            args = ParseOptions(sys.argv[2:], Log(), 'info', info_options())

            log = Log()
            ffmpeg = FFmpeg(dirPath, args.my_ffmpeg, False, log)
            ffprobe = FFprobe(dirPath, args.my_ffmpeg, False, log)
            getInfo(args.input, ffmpeg, ffprobe, args.fast, log)
        if(sys.argv[1] == 'levels'):
            from levels import levels, levels_options
            from usefulFunctions import FFmpeg, FFprobe
            args = ParseOptions(sys.argv[2:], Log(), 'levels', levels_options())

            TEMP = tempfile.mkdtemp()
            log = Log(temp=TEMP)
            ffmpeg = FFmpeg(dirPath, args.my_ffmpeg, False, log)
            ffprobe = FFprobe(dirPath, args.my_ffmpeg, False, log)
            levels(args.input, args.track, args.output_file, ffmpeg, ffprobe, TEMP, log)
        sys.exit()
    else:
        option_data = main_options()
        args = ParseOptions(sys.argv[1:], Log(True), 'auto-editor', option_data)

    timer = Timer(args.quiet)

    del option_data

    from usefulFunctions import FFmpeg, FFprobe, sep
    ffmpeg = FFmpeg(dirPath, args.my_ffmpeg, args.show_ffmpeg_debug, Log())
    ffprobe = FFprobe(dirPath, args.my_ffmpeg, args.show_ffmpeg_debug, Log())

    # Stops "The file {file} does not exist." from showing.
    if(args.export_as_clip_sequence):
        args.no_open = True

    makingDataFile = (args.export_to_premiere or args.export_to_resolve or
        args.export_to_final_cut_pro or args.export_as_json)
    is64bit = '64-bit' if sys.maxsize > 2**32 else '32-bit'

    if(args.debug and args.input == []):
        import platform

        print('Python Version:', platform.python_version(), is64bit)
        print('Platform:', platform.system(), platform.release())
        print('Config File path:', dirPath + sep() + 'config.txt')
        print('FFmpeg path:', ffmpeg.getPath())
        print('FFmpeg version:', ffmpeg.getVersion())
        print('Auto-Editor version', version)
        sys.exit()

    TEMP = tempfile.mkdtemp()
    log = Log(args.debug, args.quiet, temp=TEMP)
    log.debug(f'\n   - Temp Directory: {TEMP}')

    if(is64bit == '32-bit'):
        log.warning('You have the 32-bit version of Python, which may lead to' \
            'memory crashes.')

    if(args.version):
        print('Auto-Editor version', version)
        sys.exit()

    ffmpeg.updateLog(log)
    ffprobe.updateLog(log)

    from usefulFunctions import isLatestVersion

    if(not args.quiet and not isLatestVersion(version, log)):
        log.print('\nAuto-Editor is out of date. Run:\n')
        log.print('    pip3 install -U auto-editor')
        log.print('\nto upgrade to the latest version.\n')

    from argsCheck import hardArgsCheck, softArgsCheck
    hardArgsCheck(args, log)
    args = softArgsCheck(args, log)

    from validateInput import validInput
    inputList = validInput(args.input, ffmpeg, args, log)

    # Figure out the output file names.
    def newOutputName(oldFile: str, audio, final_cut_pro, data, json) -> str:
        dotIndex = oldFile.rfind('.')
        print(oldFile)
        if(json):
            return oldFile[:dotIndex] + '.json'
        if(final_cut_pro):
            return oldFile[:dotIndex] + '.fcpxml'
        if(data):
            return oldFile[:dotIndex] + '.xml'
        if(audio):
            return oldFile[:dotIndex] + '_ALTERED.wav'
        return oldFile[:dotIndex] + '_ALTERED' + oldFile[dotIndex:]

    if(len(args.output_file) < len(inputList)):
        for i in range(len(inputList) - len(args.output_file)):
            args.output_file.append(newOutputName(inputList[i],
                args.export_as_audio, args.export_to_final_cut_pro, makingDataFile,
                args.export_as_json))

    if(args.combine_files):
        # Combine video files, then set input to 'combined.mp4'.
        cmd = []
        for fileref in inputList:
            cmd.extend(['-i', fileref])
        cmd.extend(['-filter_complex', f'[0:v]concat=n={len(inputList)}:v=1:a=1',
            '-codec:v', 'h264', '-pix_fmt', 'yuv420p', '-strict', '-2',
            f'{TEMP}{sep()}combined.mp4'])
        ffmpeg.run(cmd)
        del cmd
        inputList = [f'{TEMP}{sep()}combined.mp4']

    speeds = [args.silent_speed, args.video_speed]
    if(args.cut_out != [] and 99999 not in speeds):
        speeds.append(99999)

    for item in args.set_speed_for_range:
        if(item[0] not in speeds):
            speeds.append(float(item[0]))

    log.debug(f'   - Speeds: {speeds}')

    from wavfile import read
    audioExtensions = ['.wav', '.mp3', '.m4a', '.aiff', '.flac', '.ogg', '.oga',
        '.acc', '.nfa', '.mka']
    sampleRate = None

    for i, INPUT_FILE in enumerate(inputList):

        if(len(inputList) > 1):
            log.conwrite(f'Working on {INPUT_FILE}')

        fileFormat = INPUT_FILE[INPUT_FILE.rfind('.'):]

        chunks = None
        if(fileFormat == '.json'):
            log.debug('Reading .json file')
            from makeCutList import readCutList
            INPUT_FILE, chunks, speeds = readCutList(INPUT_FILE, version, log)
            newOutput = newOutputName(INPUT_FILE, args.export_as_audio,
                args.export_to_final_cut_pro, makingDataFile, False)

            fileFormat = INPUT_FILE[INPUT_FILE.rfind('.'):]
        else:
            newOutput = args.output_file[i]
            if(not os.path.isdir(INPUT_FILE) and '.' not in newOutput):
                newOutput += INPUT_FILE[INPUT_FILE.rfind('.'):]

        log.debug(f'   - INPUT_FILE: {INPUT_FILE}')
        log.debug(f'   - newOutput: {newOutput}')

        if(os.path.isfile(newOutput) and INPUT_FILE != newOutput):
            log.debug(f'  Removing already existing file: {newOutput}')
            os.remove(newOutput)

        if(args.sample_rate is None):
            sampleRate = ffprobe.getSampleRate(INPUT_FILE)
            if(sampleRate == 'N/A'):
                sampleRate = '48000'
                log.warning(f"Samplerate wasn't detected, so it will be set to {sampleRate}.")
        else:
            sampleRate = str(args.sample_rate)
        log.debug(f'   - sampleRate: {sampleRate}')

        if(args.audio_bitrate is None):
            if(INPUT_FILE.endswith('.mkv')):
                # audio bitrate not supported in the mkv container.
                audioBitrate = None
            else:
                audioBitrate = ffprobe.getPrettyBitrate(INPUT_FILE, 'a')
                if(audioBitrate == 'N/A'):
                    log.warning("Couldn't automatically detect audio bitrate.")
                    audioBitrate = None
        else:
            audioBitrate = args.audio_bitrate

        log.debug(f'   - audioBitrate: {audioBitrate}')

        audioData = None
        audioFile = fileFormat in audioExtensions
        if(audioFile):
            if(args.force_fps_to is None):
                fps = 30 # Audio files don't have frames, so give fps a dummy value.
            else:
                fps = args.force_fps_to
            if(args.force_tracks_to is None):
                tracks = 1
            else:
                tracks = args.force_tracks_to
            cmd = ['-i', INPUT_FILE]
            if(audioBitrate is not None):
                cmd.extend(['-b:a', audioBitrate])
            cmd.extend(['-ac', '2', '-ar', sampleRate, '-vn', f'{TEMP}{sep()}fastAud.wav'])
            ffmpeg.run(cmd)
            del cmd

            sampleRate, audioData = read(f'{TEMP}{sep()}fastAud.wav')
        else:
            if(args.force_fps_to is not None):
                fps = args.force_fps_to
            elif(args.export_to_premiere or args.export_to_final_cut_pro or
                args.export_to_resolve):
                # Based on timebase.
                fps = int(ffprobe.getFrameRate(INPUT_FILE))
            else:
                fps = ffprobe.getFrameRate(INPUT_FILE)

            if(fps < 1):
                log.error(f"{INPUT_FILE}: Frame rate cannot be below 1. fps: {fps}")

            tracks = args.force_tracks_to
            if(tracks is None):
                tracks = ffprobe.getAudioTracks(INPUT_FILE)

            if(args.cut_by_this_track >= tracks):
                allTracks = ''
                for trackNum in range(tracks):
                    allTracks += f'Track {trackNum}\n'

                if(tracks == 1):
                    message = f'is only {tracks} track'
                else:
                    message = f'are only {tracks} tracks'
                log.error("You choose a track that doesn't exist.\n" \
                    f'There {message}.\n {allTracks}')

            # Split audio tracks into: 0.wav, 1.wav, etc.
            for trackNum in range(tracks):
                cmd = ['-i', INPUT_FILE]
                if(audioBitrate is not None):
                    cmd.extend(['-ab', audioBitrate])
                cmd.extend(['-ac', '2', '-ar', sampleRate, '-map',
                    f'0:a:{trackNum}', f'{TEMP}{sep()}{trackNum}.wav'])
                ffmpeg.run(cmd)
                del cmd

            # Check if the `--cut_by_all_tracks` flag has been set or not.
            if(args.cut_by_all_tracks):
                # Combine all audio tracks into one audio file, then read.
                cmd = ['-i', INPUT_FILE, '-filter_complex',
                    f'[0:a]amix=inputs={tracks}:duration=longest', '-ar',
                    sampleRate, '-ac', '2', '-f', 'wav', f'{TEMP}{sep()}combined.wav']
                ffmpeg.run(cmd)
                sampleRate, audioData = read(f'{TEMP}{sep()}combined.wav')
                del cmd
            else:
                # Read only one audio file.
                if(os.path.isfile(f'{TEMP}{sep()}{args.cut_by_this_track}.wav')):
                    sampleRate, audioData = read(f'{TEMP}{sep()}{args.cut_by_this_track}.wav')
                else:
                    log.bug('Audio track not found!')

        log.debug(f'   - Frame Rate: {fps}')
        if(chunks is None):
            from cutting import audioToHasLoud, motionDetection

            audioList = None
            motionList = None
            if('audio' in args.edit_based_on):
                log.debug('Analyzing audio volume.')
                audioList = audioToHasLoud(audioData, sampleRate,
                    args.silent_threshold,  fps, log)

            if('motion' in args.edit_based_on):
                log.debug('Analyzing video motion.')
                motionList = motionDetection(INPUT_FILE, ffprobe,
                    args.motion_threshold, log, width=args.width,
                    dilates=args.dilates, blur=args.blur)

                if(audioList is not None):
                    if(len(audioList) != len(motionList)):
                        log.debug(f'audioList Length:  {len(audioList)}')
                        log.debug(f'motionList Length: {len(motionList)}')
                    if(len(audioList) > len(motionList)):
                        log.debug('Reducing the size of audioList to match motionList.')
                        audioList = audioList[:len(motionList)]
                    elif(len(motionList) > len(audioList)):
                        log.debug('Reducing the size of motionList to match audioList.')
                        motionList = motionList[:len(audioList)]

            from cutting import combineArrs, applySpacingRules

            hasLoud = combineArrs(audioList, motionList, args.edit_based_on, log)
            del audioList, motionList

            effects = []
            if(args.zoom != []):
                from cutting import applyZooms
                effects += applyZooms(args.zoom, audioData, sampleRate, fps, log)
            if(args.rectangle != []):
                from cutting import applyRects
                effects += applyRects(args.rectangle, audioData, sampleRate, fps, log)

            chunks = applySpacingRules(hasLoud, speeds, fps, args, log)
            del hasLoud


        def isClip(chunk):
            nonlocal speeds
            return speeds[chunk[2]] != 99999

        def getNumberOfCuts(chunks, speeds):
            return len(list(filter(isClip, chunks)))

        def getClips(chunks, speeds):
            clips = []
            for chunk in chunks:
                if(isClip(chunk)):
                    clips.append([chunk[0], chunk[1], speeds[chunk[2]] * 100])
            return clips

        numCuts = getNumberOfCuts(chunks, speeds)
        clips = getClips(chunks, speeds)

        if(fps is None and not audioFile):
            if(makingDataFile):
                constantLoc = appendFileName(INPUT_FILE, '_constantFPS')
            else:
                constantLoc = f'{TEMP}{sep()}constantVid{fileFormat}'
            ffmpeg.run(['-i', INPUT_FILE, '-filter:v', 'fps=fps=30', constantLoc])
            INPUT_FILE = constantLoc

        if(args.export_as_json):
            from makeCutList import makeCutList
            makeCutList(INPUT_FILE, newOutput, version, chunks, speeds, log)
            continue

        if(args.preview):
            newOutput = None
            from preview import preview
            preview(INPUT_FILE, chunks, speeds, fps, audioFile, log)
            continue

        if(args.export_to_premiere or args.export_to_resolve):
            from editor import editorXML
            editorXML(INPUT_FILE, TEMP, newOutput, ffprobe, clips, chunks, tracks,
                sampleRate, audioFile, args.export_to_resolve, fps, log)
            continue

        if(args.export_to_final_cut_pro):
            from editor import fcpXML
            fcpXML(INPUT_FILE, TEMP, newOutput, ffprobe, clips, chunks, tracks,
                sampleRate, audioFile, fps, log)
            continue

        def makeAudioFile(input_, chunks, output):
            from fastAudio import fastAudio, handleAudio, convertAudio
            theFile = handleAudio(ffmpeg, input_, audioBitrate, str(sampleRate),
                TEMP, log)

            TEMP_FILE = f'{TEMP}{sep()}convert.wav'
            fastAudio(theFile, TEMP_FILE, chunks, speeds, log, fps,
                args.machine_readable_progress, args.no_progress)
            convertAudio(ffmpeg, ffprobe, TEMP_FILE, input_, output, args, log)

        if(audioFile):
            if(args.export_as_clip_sequence):
                i = 1
                for item in chunks:
                    if(speeds[item[2]] == 99999):
                        continue
                    makeAudioFile(INPUT_FILE, [item], appendFileName(newOutput, f'-{i}'))
                    i += 1
            else:
                makeAudioFile(INPUT_FILE, chunks, newOutput)
            continue

        def makeVideoFile(input_, chunks, output):
            from videoUtils import handleAudioTracks, muxVideo
            continueVid = handleAudioTracks(ffmpeg, output, args, tracks, chunks, speeds,
                fps, TEMP, log)
            if(continueVid):
                if(args.render == 'auto'):
                    if(args.zoom != [] or args.rectangle != []):
                        args.render = 'opencv'
                    else:
                        try:
                            import av
                            args.render = 'av'
                        except ImportError:
                            args.render = 'opencv'

                log.debug(f'Using {args.render} method')
                if(args.render == 'av'):
                    if(args.zoom != []):
                        log.error('Zoom effect is not supported on the av render method.')

                    if(args.rectangle != []):
                        log.error('Rectangle effect is not supported on the av render method.')

                    from renderVideo import renderAv
                    renderAv(ffmpeg, ffprobe, input_, args, chunks, speeds, fps,
                    TEMP, log)

                if(args.render == 'opencv'):
                    from renderVideo import renderOpencv
                    renderOpencv(ffmpeg, ffprobe, input_, args, chunks, speeds, fps,
                        effects, TEMP, log)

                # Now mix new audio(s) and the new video.
                muxVideo(ffmpeg, output, args, tracks, TEMP, log)
                if(output is not None and not os.path.isfile(output)):
                    log.bug(f'The file {output} was not created.')

        if(args.export_as_clip_sequence):
            i = 1
            totalFrames = chunks[len(chunks) - 1][1]
            speeds.append(99999) # guarantee we have a cut speed to work with.
            for item in chunks:
                if(speeds[item[2]] == 99999):
                    continue

                makeVideoFile(INPUT_FILE, padChunk(item, totalFrames),
                    appendFileName(newOutput, f'-{i}'))
                i += 1
        else:
            makeVideoFile(INPUT_FILE, chunks, newOutput)

    if(not args.preview and not makingDataFile):
        timer.stop()

    if(not args.preview and makingDataFile):
        from usefulFunctions import humanReadableTime
        # Assume making each cut takes about 30 seconds.
        timeSave = humanReadableTime(numCuts * 30)

        s = 's' if numCuts != 1 else ''
        log.print(f'Auto-Editor made {numCuts} cut{s}', end='')
        log.print(f', which would have taken about {timeSave} if edited manually.')

    if(not args.no_open):
        from usefulFunctions import openWithSystemDefault
        openWithSystemDefault(newOutput, log)

    log.debug('Deleting temp dir')

    try:
        rmtree(TEMP)
    except PermissionError:
        from time import sleep
        sleep(1)
        try:
            rmtree(TEMP)
        except PermissionError:
            log.debug('Failed to delete temp dir.')
示例#26
0
def test(source):
    for root, dirs, files in os.walk(source):
        for dicom_file in files:
            path = os.path.join(root, dicom_file)
            age = info.getInfo(path)
            print root, age
示例#27
0
def getTS(self, request):
    if "file" in request.args:
        filename = unquote(request.args["file"][0]).decode(
            'utf-8', 'ignore').encode('utf-8')
        if not os.path.exists(filename):
            return "File '%s' not found" % (filename)


#	ServiceReference is not part of filename so look in the '.ts.meta' file
        sRef = ""
        progopt = ''

        if os.path.exists(filename + '.meta'):
            metafile = open(filename + '.meta', "r")
            name = ''
            seconds = -1  # unknown duration default
            line = metafile.readline()  # service ref
            if line:
                sRef = eServiceReference(line.strip()).toString()
            line2 = metafile.readline()  # name
            if line2:
                name = line2.strip()
            line3 = metafile.readline()  # description
            line4 = metafile.readline()  # recording time
            line5 = metafile.readline()  # tags
            line6 = metafile.readline()  # length

            if line6:
                seconds = float(line6.strip()) / 90000  # In seconds

            if config.OpenWebif.service_name_for_stream.value:
                progopt = "%s#EXTINF:%d,%s\n" % (progopt, seconds, name)

            metafile.close()

        portNumber = config.OpenWebif.port.value
        info = getInfo()
        model = info["model"]
        transcoder_port = None
        if model in ("solo2", "duo2", "solose", "vusolo2", "vuduo2",
                     "vusolose", "hd2400", "xpeedlx3", "gbquad", "gbquadplus"):
            try:
                transcoder_port = int(
                    config.plugins.transcodingsetup.port.value)
            except StandardError:
                #Transcoding Plugin is not installed or your STB does not support transcoding
                transcoder_port = None
            if "device" in request.args:
                if request.args["device"][0] == "phone":
                    portNumber = 8002

        if "port" in request.args:
            portNumber = request.args["port"][0]

        # When you use EXTVLCOPT:program in a transcoded stream, VLC does not play stream
        if config.OpenWebif.service_name_for_stream.value and sRef != '' and portNumber != transcoder_port:
            progopt = "%s#EXTVLCOPT:program=%d\n" % (
                progopt, int(sRef.split(':')[3], 16))

        response = "#EXTM3U\n#EXTVLCOPT--http-reconnect=true \n%shttp://%s:%s/file?file=%s\n" % (
            progopt, request.getRequestHostname(), portNumber, quote(filename))
        request.setHeader('Content-Type', 'application/text')
        return response
    else:
        return "Missing file parameter"
示例#28
0
def getStream(session, request, m3ufile):
	if "ref" in request.args:
		sRef=unquote(unquote(request.args["ref"][0]).decode('utf-8', 'ignore')).encode('utf-8')
	else:
		sRef = ""

	currentServiceRef = None
	if m3ufile == "streamcurrent.m3u":
		currentServiceRef = session.nav.getCurrentlyPlayingServiceReference()
		sRef = currentServiceRef.toString() 

	if sRef.startswith("1:134:"):
		if currentServiceRef is None:
			currentServiceRef = session.nav.getCurrentlyPlayingServiceReference()
		if currentServiceRef is None:
			currentServiceRef = eServiceReference()
		ref = getBestPlayableServiceReference(eServiceReference(sRef), currentServiceRef)
		if ref is None:
			sRef = ""
		else:
			sRef = ref.toString()

	name = "stream"
	# #EXTINF:-1,%s\n adding back to show service name in programs like VLC
	progopt = ''
	if "name" in request.args:
		name = request.args["name"][0]
		if config.ModernWebif.service_name_for_stream.value:
			progopt="#EXTINF:-1,%s\n" % name
	
	portNumber = config.ModernWebif.streamport.value
	info = getInfo()
	model = info["model"]
	machinebuild = info["machinebuild"]
	transcoder_port = None
	args = ""
	if model in ("Solo4K", "Solo²", "Duo²", "Solo SE", "Quad", "Quad Plus") or machinebuild in ('dags3', 'dags4'):
		try:
			transcoder_port = int(config.plugins.transcodingsetup.port.value)
		except StandardError:
			#Transcoding Plugin is not installed or your STB does not support transcoding
			transcoder_port = None
		if "device" in request.args :
			if request.args["device"][0] == "phone" :
				portNumber = transcoder_port
		if "port" in request.args:
			portNumber = request.args["port"][0]
			
	# INI use dynamic encoder allocation, and each stream can have diffrent parameters 
	if machinebuild in ('inihdp', 'hd2400', 'et10000'):
		transcoder_port = 8001
		if "device" in request.args :
			if request.args["device"][0] == "phone" :
				bitrate = config.plugins.transcodingsetup.bitrate.value
				resolution = config.plugins.transcodingsetup.resolution.value
				(width, height) = tuple(resolution.split('x'))
				framrate = config.plugins.transcodingsetup.framerate.value
				aspectratio = config.plugins.transcodingsetup.aspectratio.value
				interlaced = config.plugins.transcodingsetup.interlaced.value
				args = "?bitrate=%s?width=%s?height=%s?aspectratio=%s?interlaced=%s" % (bitrate, width, height, aspectratio, interlaced)
	if machinebuild in ('ew7356'):
		transcoder_port = 8001
		if "device" in request.args :
			if request.args["device"][0] == "phone" :
				bitrate = config.plugins.transcodingsetup.bitrate.value
				framrate = config.plugins.transcodingsetup.framerate.value
				args = "?bitrate=%s" % (bitrate)

	# When you use EXTVLCOPT:program in a transcoded stream, VLC does not play stream
	if config.ModernWebif.service_name_for_stream.value and sRef != '' and portNumber != transcoder_port:
		progopt="%s#EXTVLCOPT:program=%d\n" % (progopt, int(sRef.split(':')[3],16))

	response = "#EXTM3U \n#EXTVLCOPT--http-reconnect=true \n%shttp://%s:%s/%s%s\n" % (progopt,request.getRequestHostname(), portNumber, sRef, args)
	request.setHeader('Content-Type', 'application/text')
	return response
示例#29
0
def getStream(session, request, m3ufile):
    if "ref" in request.args:
        sRef = unquote(
            unquote(request.args["ref"][0]).decode('utf-8',
                                                   'ignore')).encode('utf-8')
    else:
        sRef = ""

    currentServiceRef = None
    if m3ufile == "streamcurrent.m3u":
        currentServiceRef = session.nav.getCurrentlyPlayingServiceReference()
        sRef = currentServiceRef.toString()

    if sRef.startswith("1:134:"):
        if currentServiceRef is None:
            currentServiceRef = session.nav.getCurrentlyPlayingServiceReference(
            )
        if currentServiceRef is None:
            currentServiceRef = eServiceReference()
        ref = getBestPlayableServiceReference(eServiceReference(sRef),
                                              currentServiceRef)
        if ref is None:
            sRef = ""
        else:
            sRef = ref.toString()

    name = "stream"
    # #EXTINF:-1,%s\n adding back to show service name in programs like VLC
    progopt = ''
    if "name" in request.args:
        name = request.args["name"][0]
        if config.ModernWebif.service_name_for_stream.value:
            progopt = "#EXTINF:-1,%s\n" % name

    portNumber = config.ModernWebif.streamport.value
    info = getInfo()
    model = info["model"]
    machinebuild = info["machinebuild"]
    transcoder_port = None
    args = ""
    if model in ("Solo4K", "Solo²", "Duo²", "Solo SE", "Quad",
                 "Quad Plus") or machinebuild in ('dags3', 'dags4'):
        try:
            transcoder_port = int(config.plugins.transcodingsetup.port.value)
        except StandardError:
            #Transcoding Plugin is not installed or your STB does not support transcoding
            transcoder_port = None
        if "device" in request.args:
            if request.args["device"][0] == "phone":
                portNumber = transcoder_port
        if "port" in request.args:
            portNumber = request.args["port"][0]

    # INI use dynamic encoder allocation, and each stream can have diffrent parameters
    if machinebuild in ('inihdp', 'hd2400', 'et10000'):
        transcoder_port = 8001
        if "device" in request.args:
            if request.args["device"][0] == "phone":
                bitrate = config.plugins.transcodingsetup.bitrate.value
                resolution = config.plugins.transcodingsetup.resolution.value
                (width, height) = tuple(resolution.split('x'))
                framrate = config.plugins.transcodingsetup.framerate.value
                aspectratio = config.plugins.transcodingsetup.aspectratio.value
                interlaced = config.plugins.transcodingsetup.interlaced.value
                args = "?bitrate=%s?width=%s?height=%s?aspectratio=%s?interlaced=%s" % (
                    bitrate, width, height, aspectratio, interlaced)
    if machinebuild in ('ew7356'):
        transcoder_port = 8001
        if "device" in request.args:
            if request.args["device"][0] == "phone":
                bitrate = config.plugins.transcodingsetup.bitrate.value
                framrate = config.plugins.transcodingsetup.framerate.value
                args = "?bitrate=%s" % (bitrate)

    # When you use EXTVLCOPT:program in a transcoded stream, VLC does not play stream
    if config.ModernWebif.service_name_for_stream.value and sRef != '' and portNumber != transcoder_port:
        progopt = "%s#EXTVLCOPT:program=%d\n" % (progopt,
                                                 int(sRef.split(':')[3], 16))

    response = "#EXTM3U \n#EXTVLCOPT--http-reconnect=true \n%shttp://%s:%s/%s%s\n" % (
        progopt, request.getRequestHostname(), portNumber, sRef, args)
    request.setHeader('Content-Type', 'application/text')
    return response
示例#30
0
def index():
    return jsonify(info.getInfo())
team.append("Miami Heat")
team.append("Orlando Magic")
team.append("Washington Wizards")
team.append("Denver Nuggets")
team.append("Minnesota Timberwolves")
team.append("Oklahoma City Thunder")
team.append("Portland Trail Blazers")
team.append("Utah Jazz")
team.append("Golden State Warriors")
team.append("Los Angeles Clippers")
team.append("Los Angeles Lakers")
team.append("Phoenix Suns")
team.append("Sacramento Kings")
team.append("Dallas Mavericks")
team.append("Houston Rockets")
team.append("Memphis Grizzlies")
team.append("New Orleans Pelicans")
team.append("San Antonio Spurs")

year = 2010
while(year<=2015):
	temp = '%d' %year
	tem1 = temp[2:]
	tem2 = '%d' %(year-1)
	season = tem2+"-"+tem1
	for i in range(0,30):
		url = prefix+season+mid+teamid[i]
		print url
		info.getInfo(url,team[i],season)
		i+=1
	year+=1
def getTS(self, request):
	if "file" in request.args:
		filename = unquote(request.args["file"][0]).decode('utf-8', 'ignore').encode('utf-8')
		if not os.path.exists(filename):
			return "File '%s' not found" % (filename)

# ServiceReference is not part of filename so look in the '.ts.meta' file
		sRef = ""
		progopt = ''

		if os.path.exists(filename + '.meta'):
			metafile = open(filename + '.meta', "r")
			name = ''
			seconds = -1  # unknown duration default
			line = metafile.readline()  # service ref
			if line:
				sRef = eServiceReference(line.strip()).toString()
			line2 = metafile.readline()  # name
			if line2:
				name = line2.strip()
			line6 = metafile.readline()  # description
			line6 = metafile.readline()  # recording time
			line6 = metafile.readline()  # tags
			line6 = metafile.readline()  # length

			if line6:
				seconds = float(line6.strip()) / 90000  # In seconds

			if config.OpenWebif.service_name_for_stream.value:
				progopt = "%s#EXTINF:%d,%s\n" % (progopt, seconds, name)

			metafile.close()

		portNumber = None
		proto = 'http'
		info = getInfo()
		model = info["model"]
		machinebuild = info["machinebuild"]
		transcoder_port = None
		args = ""
		urlparam = '?'
		if info["imagedistro"] in ('openpli', 'satdreamgr', 'openvision'):
			urlparam = '&'
		
		if fileExists("/dev/bcm_enc0"):
			try:
				transcoder_port = int(config.plugins.transcodingsetup.port.value)
			except StandardError:
				# Transcoding Plugin is not installed or your STB does not support transcoding
				transcoder_port = None
			if "device" in request.args:
				if request.args["device"][0] == "phone":
					portNumber = transcoder_port
			if "port" in request.args:
				portNumber = request.args["port"][0]
		elif fileExists("/dev/encoder0") or fileExists("/proc/stb/encoder/0/apply"):
			portNumber = config.OpenWebif.streamport.value

		if fileExists("/dev/bcm_enc0") or fileExists("/dev/encoder0") or fileExists("/proc/stb/encoder/0/apply"):
			if "device" in request.args:
				if request.args["device"][0] == "phone":
					try:
						bitrate = config.plugins.transcodingsetup.bitrate.value
						resolution = config.plugins.transcodingsetup.resolution.value
						(width, height) = tuple(resolution.split('x'))
						# framerate = config.plugins.transcodingsetup.framerate.value
						aspectratio = config.plugins.transcodingsetup.aspectratio.value
						interlaced = config.plugins.transcodingsetup.interlaced.value
						if fileExists("/proc/stb/encoder/0/vcodec"):
							vcodec = config.plugins.transcodingsetup.vcodec.value
							args = "?bitrate=%s__width=%s__height=%s__vcodec=%s__aspectratio=%s__interlaced=%s" % (bitrate, width, height, vcodec, aspectratio, interlaced)
						else:
							args = "?bitrate=%s__width=%s__height=%s__aspectratio=%s__interlaced=%s" % (bitrate, width, height, aspectratio, interlaced)
						args = args.replace('__', urlparam)
					except Exception:
						pass

		# When you use EXTVLCOPT:program in a transcoded stream, VLC does not play stream
		if config.OpenWebif.service_name_for_stream.value and sRef != '' and portNumber != transcoder_port:
			progopt = "%s#EXTVLCOPT:program=%d\n" % (progopt, int(sRef.split(':')[3], 16))

		if portNumber is None:
			portNumber = config.OpenWebif.port.value
			if request.isSecure():
				portNumber = config.OpenWebif.https_port.value
				proto = 'https'
			ourhost = request.getHeader('host')
			m = re.match('.+\:(\d+)$', ourhost)
			if m is not None:
				portNumber = m.group(1)

		if config.OpenWebif.auth_for_streaming.value:
			asession = GetSession()
			if asession.GetAuth(request) is not None:
				auth = ':'.join(asession.GetAuth(request)) + "@"
			else:
				auth = '-sid:' + str(asession.GetSID(request)) + "@"
		else:
			auth = ''

		response = "#EXTM3U \n#EXTVLCOPT--http-reconnect=true \n%s%s://%s%s:%s/file?file=%s%s\n" % ((progopt, proto, auth, request.getRequestHostname(), portNumber, quote(filename), args))
		request.setHeader('Content-Type', 'application/x-mpegurl')
		return response
	else:
		return "Missing file parameter"