示例#1
0
文件: rtmp.py 项目: ov1d1u/tv-maxe-ng
    def play_url(self):
        self.conn = librtmp.RTMP(self.url, **self.params)
        log.debug('Initializing RTMP connection with {0}'.format(self.url))
        try:
            self.conn.connect()
        except Exception as e:
            log.debug('Failed to initiate RTMP connection: {0}'.format(e))
            self.error.emit(str(e))
            return

        log.debug('Creating RTMP connection stream')
        try:
            self.rtmp_stream = self.conn.create_stream()
        except librtmp.exceptions.RTMPError as e:
            log.debug('Failed to create RTMP connection stream')
            self.error.emit(str(e))
            return

        log.debug('Configuring HTTP server')
        server_address = ('127.0.0.1', get_open_port())
        self.httpd = HTTPServer(server_address, RequestHandler)
        self.httpd.rtmp_stream = self.rtmp_stream
        log.debug('Starting HTTP Server')
        threading.Thread(target=self.httpd.serve_forever).start()
        self.stream_available.emit('http://{0}:{1}'.format(
            server_address[0], server_address[1]))
示例#2
0
def receive_write_stream():
    UDP_IP = "127.0.0.1"
    reconstruct_rtmp = librtmp.RTMP("rtmp://178.62.61.235:1935/show/stream_name", live=True)
    reconstruct_rtmp.connect()
    rtmpwritestream = reconstruct_rtmp.create_stream(True,True)
    sock = socket.socket(socket.AF_INET,socket.SOCK_DGRAM) # UDP
    sock.bind((UDP_IP, 5006))
    get_bytes(sock,rtmpwritestream)
示例#3
0
def connection():
    try:
        conn = librtmp.RTMP(
            "rtmp://evp.mm.uol.com.br/educadora_cps/_definst_/educadora_cps")
        conn.connect()
        stream = conn.create_stream()
        return stream
    except:
        pass
示例#4
0
def get_stream():
    #conn = librtmp.RTMP("rtmp://188.138.17.8:1935/albuk/albuk.stream", live=True)
    conn = librtmp.RTMP("rtmp://84.20.77.50/live/livestream1", live=True)
    rtmpcall = conn.connect()
    print "Transaction ID", rtmpcall.transaction_id, "\n Result of the Call", rtmpcall.result(
    )
    rtmpstream = conn.create_stream()
    write_stream()
    get_bytes(rtmpstream)
示例#5
0
def rtmpvideo(url):
    """Get RTMP using native libraries."""
    conn = librtmp.RTMP(url, live=False)
    conn.connect()
    stream = conn.create_stream()
    data = stream.read(4096)
    while len(data) > 0:
        data += stream.read(4096)
    return data
示例#6
0
def get_stream():
    #conn = librtmp.RTMP("rtmp://188.138.17.8:1935/albuk/albuk.stream", live=True)
    conn = librtmp.RTMP("rtmp://84.20.77.50/live/livestream1", live=True)
    rtmpcall = conn.connect()
    print "Transaction ID", rtmpcall.transaction_id, "\n Result of the Call", rtmpcall.result(
    )
    rtmpstream = conn.create_stream()
    sock = socket(AF_INET, SOCK_DGRAM)
    sock.connect(('127.0.0.1', 5006))  # stream data
    get_bytes(rtmpstream, sock)
示例#7
0
def create_ums_connection(app, media_id, page_url, exception=PluginError):
    params = dict(application=app, media=str(media_id))
    conn = librtmp.RTMP(RTMP_URL, connect_data=params,
                        swfurl=SWF_URL, pageurl=page_url)

    try:
        conn.connect()
    except librtmp.RTMPError:
        raise exception("Failed to connect to RTMP server")

    return conn
示例#8
0
    def __private_connect(self):
        try:
            # Create a connection
            self.__rtmp_conn = librtmp.RTMP(self.__url, live=True, timeout=10)
            # Attempt to connect
            self.__rtmp_conn.connect()
            # Get a file-like object to access to the stream
            self.__rtmp_stream = self.__rtmp_conn.create_stream()

        except:
            self.__logger.error("[RtmpThread] librtmp initialize failed.")
            self.__vaild = False
示例#9
0
    def __init__(self, data_in=None, step_length=1, channel=None, start_chunk_id='-0x1', delay_seconds = 0, enable_backswing=0):
        """
        @data_in: Data source.
        @step_length: The max length of time slices can play.
        @channel: The name of the data source.
        @start_chunk_id: Number of the starting chunk, starting from the current time by default.
        """
        if not channel:
            raise FragmentError('Channenl is required.')
        self._channel = channel
        if not data_in:
            data_in = sys.stdin
        elif data_in.startswith("rtmp://"):
            import librtmp
            conn = librtmp.RTMP(data_in, live=True)
            # Attempt to connect
            conn.connect()
            # Get a file-like object to access to the stream
            stream = conn.create_stream()
            # Read 1024 bytes of data
            data_in = stream

        self._buf = [] #store tag temporary.
        self._id_generator = id_generator(int(start_chunk_id, 16))

        self._stream = RtmpStreamReader(data_in) #data source reader.
        self._step_length = step_length

        self.delay_seconds = delay_seconds

        self._seq = 0 #sequence number of tag.
        self._chunk_seq = 0 #sequence number of chunk.
        self._skip_meta = self._skip_head = self._skip_magic_head = False
        self._flv_head_no = 0

        self._swing = 0 # swing
        self._head  = None
        
        self._skip_audio_tag = self._skip_video_tag = False
        self._enable_backswing = enable_backswing

        self._do_sleep = False

        self._has_head = False
        self._meta_tag = None
示例#10
0
def create_ums_connection(app,
                          media_id,
                          page_url,
                          password,
                          exception=PluginError):
    url = RTMP_URL.format(randint(0, 0xffffff), media_id)
    params = {"application": app, "media": str(media_id), "password": password}
    conn = librtmp.RTMP(url,
                        swfurl=SWF_URL,
                        pageurl=page_url,
                        connect_data=params)

    try:
        conn.connect()
    except librtmp.RTMPError:
        raise exception("Failed to connect to RTMP server")

    return conn
示例#11
0
 def start(self):
     self.laststart = time.monotonic()
     if self.activeConfig.isValid():
         if self.readThread == None :
             self.threadLocked = False
             self.statelog=[]
             self.rtmplog=[]
             self.rtmpConnection = librtmp.RTMP(urllib.parse.urlunsplit(('rtmp', self.activeConfig.band.getDomain(), '', '', '')), app=self.activeConfig.band.getApp(), playpath=self.activeConfig.streamname.getValue(), live=True, timeout=1)
             self.rtmpConnection.set_option('timeout', '1')
             self.readThread = threading.Thread(target=self._readThreadLoop, args=(self.rtmpConnection, self.stdoutWritefd, self.sendSockEvent, self.rtmpReadEventQueue, self.rtmpReadCommandQueue, self.activeConfig.band.getNetworkTimeout(), self.activeConfig.band.getNetworkTimeoutInit()))
             self.readThread.start()
             self.lastState['locked'] = self.threadLocked
             if self.lastState != self.changeRefState : # if the signal parameters have changed
                 self.stateMonotonic += 1
                 self.changeRefState = copy.deepcopy(self.lastState)
         else:
             print("RTMP connection already open")
     else:
         print("Can't start, config invalid")
 def __init__(self, ip, port, stream_id, auth_options, chunk_size=2097152):
     """Create a rtmp url using parameters, then connect to rtmp url"""
     self.stream_id = stream_id
     # Create a rtmp url using ip, port, and stream_id
     connection_string = "rtmp://{0}:{1}/view/{2}".format(
         ip, port, stream_id)
     # Add authorization parameters to connection string
     self.connection_string = self._auth_RTMP(
         connection_string, auth_options["loginUrl"],
         auth_options["rtmpRequestUrl"], auth_options["username"],
         auth_options["password"])
     # Create a stream connection to rtmp url
     self.connection = librtmp.RTMP(self.connection_string, live=True)
     self.connection.connect()
     self.stream = self.connection.create_stream()
     self.chunk_size = chunk_size
     self.bytes_read = 0
     self.previous_read = 0
     self.data = b''
     self.is_reading = True
示例#13
0
    def GetBroadcastStatus(self):

        #currentStatus = Nothing # Current status of the broadcast

        # Create a connection
        conn = librtmp.RTMP("rtmp://1.live.phonelivestreaming.com:1935/live/",
                            timeout=5,
                            live=True)
        # Attempt to connect
        conn.connect()
        testConnection = conn.connected
        testPacket = conn.read_packet()
        print(testPacket)

        # Get a file-like object to access to the stream
        stream = conn.create_stream()

        # Read 1024 bytes of data
        data = stream.read(1024)

        return OnAir.broadcastStatus.BroadcastStatus.OffAir
示例#14
0
 def init_rtmp(self):
     conn = librtmp.RTMP(
         "rtmp://%s:1935/live/livestream" % HOST,  # 推流地址
         live=True)
     librtmp.librtmp.RTMP_EnableWrite(conn.rtmp)
     conn.connect()
     # 拼装视频格式的数据包
     meta_body_array = [
         python_push_rtmp.get_meta_string('@setDataFrame'),
         python_push_rtmp.get_meta_string('onMetaData'),
         bytes(bytearray([0x08, 0x00, 0x00, 0x00, 0x06])),
         # 两个字符串和ECMA array头,共计6个元素,注释掉了音频相关数据
         python_push_rtmp.get_property_string('width'),
         python_push_rtmp.get_meta_double(640.0),
         python_push_rtmp.get_property_string('height'),
         python_push_rtmp.get_meta_double(480.0),
         python_push_rtmp.get_property_string('videodatarate'),
         python_push_rtmp.get_meta_double(0.0),
         python_push_rtmp.get_property_string('framerate'),
         python_push_rtmp.get_meta_double(25.0),
         python_push_rtmp.get_property_string('videocodecid'),
         python_push_rtmp.get_meta_double(7.0),
         # get_property_string('audiodatarate'), get_meta_double(125.0),
         # get_property_string('audiosamplerate'), get_meta_double(44100.0),
         # get_property_string('audiosamplesize'), get_meta_double(16.0),
         # get_property_string('stereo'), get_meta_boolean(True),
         # get_property_string('audiocodecid'), get_meta_double(10.0),
         python_push_rtmp.get_property_string('encoder'),
         python_push_rtmp.get_meta_string('Lavf57.56.101'),
         bytes(bytearray([0x00, 0x00, 0x09]))
     ]
     meta_body = ''.join(meta_body_array)
     meta_packet = librtmp.RTMPPacket(type=librtmp.PACKET_TYPE_INFO,
                                      format=librtmp.PACKET_SIZE_LARGE,
                                      channel=0x04,
                                      timestamp=0,
                                      body=meta_body)
     meta_packet.packet.m_nInfoField2 = 1  # 修改stream id
     stream = conn.create_stream(writeable=True)
     return (conn, meta_packet, stream)
示例#15
0
    def connect(self):
        """ Attempts to make a RTMP connection with the given connection parameters. """
        tinychat.recaptcha(proxy=self._proxy)
        cauth_cookie = tinychat.get_cauth_cookie(self._roomname,
                                                 proxy=self._proxy)
        data = {
            'account': self.account,
            'type': self._room_type,
            'prefix': self._prefix,
            'room': self._roomname,
            'version': self._desktop_version,
            'cookie': cauth_cookie
        }
        log.info('connect data: %s' % data)

        self.connection = librtmp.RTMP(url=self._tc_url,
                                       tcurl=self._tc_url,
                                       app=self._app,
                                       pageurl=self._embed_url,
                                       swfurl=self._swf_url,
                                       flashver=u'WIN 22.0.0.209',
                                       connect_data=data,
                                       timeout=20 * 1000,
                                       live=True)
        try:
            if SETTINGS['reset_time']:
                self._init_time = time.time()
            self.connection.connect()
            if self.connection.connected:
                self.is_connected = True
            self.__callback()
        except Exception as ex:
            log.error('Connect error: %s' % ex, exc_info=True)
            if SETTINGS['debug_mode']:
                traceback.print_exc()
            self.reconnect()
示例#16
0
def write_stream():
    global rtmpwritestream
    reconstruct_rtmp = librtmp.RTMP(
        "rtmp://178.62.61.235:1935/show/stream_name", live=True)
    reconstruct_rtmp.connect()
    rtmpwritestream = reconstruct_rtmp.create_stream(True, True)
示例#17
0
import os
import librtmp, time

conn = librtmp.RTMP(
    "rtmp://10.0.0.174:1935/",
    "A0 - 0 - 0 - 0 - 6DF129EE266348B3A758145C4C58D9E2 - admin - 888888",
    live=True)
youtube = librtmp.RTMP("rtmp://a.rtmp.youtube.com/live2/",
                       "dkqx-5w8b-6tby-akrp",
                       subscribe="test123",
                       live=True)
conn.connect()
youtube.connect()
stream = conn.create_stream()
youtube_push = youtube.create_stream(writeable=True)
for y in range(0, 300000):
    data = stream.read(1024000)
    youtube_push.write(data)
示例#18
0
import librtmp
from pylonghair import fec_encode, fec_decode
# Create a connection
conn = librtmp.RTMP("rtmp://188.138.17.8:1935/albuk/albuk.stream", live=True)
# Attempt to connect
conn.connect()
# Get a file-like object to access to the stream
stream = conn.create_stream()
k = 8
m = 4
block_size = 128
parity = bytearray(m * block_size)
data = 0
count = 0
# Read 1024 bytes of data
while (count < 1):
    data = stream.read(1024)
    #print len(data)
    #cauchy_256_encode(k, m, data_ptrs, recovery_blocks, bytes)
    #_fec_encode(int k, int m, int block_size, unsigned char* data, unsigned char* parity)
    #
    print fec_encode(k, m, block_size, data, parity)
    #for par in parity:
    #    print par
    count += 1
#print len(parity)
blocks = []
# artifica=ially removed the first byte
blocks.append((0, bytearray(parity[0:block_size])))
# add the remaining blocks to the transfer
for row in range(k - 1):
import librtmp

# Create a connection
#conn = librtmp.RTMP("rtmp://rtmp.live.tudou.com/flv/mcountdown", live=True)
conn = librtmp.RTMP("rtmp://www.scbtv.cn/live/new", live=True)
# Attempt to connect
conn.connect()
# Get a file-like object to access to the stream
stream = conn.create_stream()
# Read 1024 bytes of data
data = stream.read(1)
print(data)
if(data == 'F'):
    c = stream.read(1)
    print(c)
    c = stream.read(1)
    print(c)
    c = stream.read(1)
    print("@")
import os
import librtmp, time
import cv2
import numpy as np

fileOutput = "./test.flv"
if os.path.isfile(fileOutput):
    os.remove(fileOutput)
videoFile = open(fileOutput, "wb")

conn = librtmp.RTMP(
    "rtmp://10.0.0.174:1935/",
    "A0 - 0 - 0 - 0 - 6DF129EE266348B3A758145C4C58D9E2 - admin - 888888",
    live=True)
conn.connect()
stream = conn.create_stream()
for y in range(0, 300000):
    print(y)
    data = stream.read(1024)
    videoFile.write(data)
videoFile.close()
示例#21
0
import base64

import librtmp

# Create a connection
conn = librtmp.RTMP("rtmp://20.46.44.246:1935/stream/ashustream")
conn.connect()

stream = conn.create_stream()

data = stream.read(1024)

# with open('test.flv', 'wb') as f:
#     stream.write(data)
示例#22
0
import librtmp

# Create a connection
conn = librtmp.RTMP("rtmp://192.168.153.128:1935/stream/rtmptest", live=True)
# Attempt to connect
conn.connect()
# Get a file-like object to access to the stream
stream = conn.create_stream()
# Read 1024 bytes of data
data = stream.read(1024)
示例#23
0
import subprocess as sp
import cv2
import time
import mmap
import os
import signal
import librtmp

rtmpUrl = "rtmp://send3a.douyu.com/live/976948rcHoxLK9jM?wsSecret=b0f7a5396f6246db14a2492ae1705021&wsTime=5d6f69b8&wsSeek=off&wm=0&tw=0&roirecognition=0"
conn = librtmp.RTMP(rtmpUrl,live =True)
conn.connect()
stream = conn.create_stream(writeable = True)

#rtmpUrl = "rtmp://send3a.douyu.com/live/976948rsDWcEbFyY?wsSecret=61d5a86470678bd04cb3a86557f6926e&wsTime=5d6c9f66&wsSeek=off&wm=0&tw=0&roirecognition=0"
#rtmpUrl = "rtmp://livepush.binyx.vip/live/m600?txSecret=3c2ac4fd2c7c135b00986ca3dee2b798&txTime=5D6E8DFF"

#myMmap = None
#mmapPath = "/home/dji/DJI_Onboard_Sdk/src/Onboard-SDK-ROS/dji_sdk/scripts/mmap_info.txt"

#def init_mymmap():
#  global myMmap
#  global mmapPath
#  myMmap = mmap.mmap(os.open(mmapPath,os.O_RDWR),os.path.getsize(mmapPath))
    	
 
#def getVauleFromMmap():
#  global myMmap
#  myMmap.seek(myMmap.find('onlive',0)+len("onlive")+1)
#  temp = myMmap.read(1)
#  return int(temp)