当前位置: 首页>>代码示例>>Python>>正文


Python Livestreamer.resolve_url方法代码示例

本文整理汇总了Python中livestreamer.Livestreamer.resolve_url方法的典型用法代码示例。如果您正苦于以下问题:Python Livestreamer.resolve_url方法的具体用法?Python Livestreamer.resolve_url怎么用?Python Livestreamer.resolve_url使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在livestreamer.Livestreamer的用法示例。


在下文中一共展示了Livestreamer.resolve_url方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: TestPluginStream

# 需要导入模块: from livestreamer import Livestreamer [as 别名]
# 或者: from livestreamer.Livestreamer import resolve_url [as 别名]
class TestPluginStream(unittest.TestCase):
    def setUp(self):
        self.session = Livestreamer()

    def assertDictHas(self, a, b):
        for key, value in a.items():
            self.assertEqual(b[key], value)

    def _test_akamaihd(self, surl, host, streamname):
        channel = self.session.resolve_url(surl)
        streams = channel.get_streams()

        self.assertTrue("live" in streams)

        stream = streams["live"]
        self.assertTrue(isinstance(stream, AkamaiHDStream))
        self.assertEqual(stream.host, host)
        self.assertEqual(stream.streamname, streamname)

    def _test_hls(self, surl, url):
        channel = self.session.resolve_url(surl)
        streams = channel.get_streams()

        self.assertTrue("live" in streams)

        stream = streams["live"]
        self.assertTrue(isinstance(stream, HLSStream))
        self.assertEqual(stream.url, url)

    def _test_rtmp(self, surl, url, params):
        channel = self.session.resolve_url(surl)
        streams = channel.get_streams()

        self.assertTrue("live" in streams)

        stream = streams["live"]
        self.assertTrue(isinstance(stream, RTMPStream))
        self.assertEqual(stream.params["rtmp"], url)
        self.assertDictHas(params, stream.params)

    def test_plugin(self):
        self._test_rtmp("rtmp://hostname.se/stream",
                         "rtmp://hostname.se/stream", dict())

        self._test_rtmp("rtmp://hostname.se/stream live=1 num=47",
                        "rtmp://hostname.se/stream", dict(live=True, num=47))

        self._test_rtmp("rtmp://hostname.se/stream live=1 qarg='a \'string' noq=test",
                        "rtmp://hostname.se/stream", dict(live=True, qarg='a \'string', noq="test"))

        self._test_hls("hls://http://hostname.se/playlist.m3u8",
                       "http://hostname.se/playlist.m3u8")

        self._test_akamaihd("akamaihd://http://hostname.se/stream",
                            "http://hostname.se", "stream")
开发者ID:buttsKramer,项目名称:livestreamer,代码行数:57,代码来源:test_plugin_stream.py

示例2: TestSession

# 需要导入模块: from livestreamer import Livestreamer [as 别名]
# 或者: from livestreamer.Livestreamer import resolve_url [as 别名]
class TestSession(unittest.TestCase):
    PluginPath = os.path.join(os.path.dirname(__file__), "plugins")

    def setUp(self):
        self.session = Livestreamer()
        self.session.load_plugins(self.PluginPath)

    def test_exceptions(self):
        try:
            self.session.resolve_url("invalid url")
            self.assertTrue(False)
        except NoPluginError:
            self.assertTrue(True)

    def test_load_plugins(self):
        plugins = self.session.get_plugins()
        self.assertTrue(plugins["testplugin"])

    def test_builtin_plugins(self):
        plugins = self.session.get_plugins()
        self.assertTrue("justintv" in plugins)

    def test_resolve_url(self):
        plugins = self.session.get_plugins()
        channel = self.session.resolve_url("http://test.se/channel")
        self.assertTrue(isinstance(channel, Plugin))
        self.assertTrue(isinstance(channel, plugins["testplugin"]))

    def test_options(self):
        self.session.set_option("test_option", "option")
        self.assertEqual(self.session.get_option("test_option"), "option")
        self.assertEqual(self.session.get_option("non_existing"), None)

        self.assertEqual(self.session.get_plugin_option("testplugin", "a_option"), "default")
        self.session.set_plugin_option("testplugin", "another_option", "test")
        self.assertEqual(self.session.get_plugin_option("testplugin", "another_option"), "test")
        self.assertEqual(self.session.get_plugin_option("non_existing", "non_existing"), None)
        self.assertEqual(self.session.get_plugin_option("testplugin", "non_existing"), None)

    def test_plugin(self):
        channel = self.session.resolve_url("http://test.se/channel")
        streams = channel.get_streams()

        self.assertTrue("best" in streams)
        self.assertTrue(streams["best"] is streams["1080p"])
        self.assertTrue(isinstance(streams["rtmp"], RTMPStream))
        self.assertTrue(isinstance(streams["http"], HTTPStream))
        self.assertTrue(isinstance(streams["hls"], HLSStream))
        self.assertTrue(isinstance(streams["akamaihd"], AkamaiHDStream))
开发者ID:buttsKramer,项目名称:livestreamer,代码行数:51,代码来源:test_session.py

示例3: GetYoutubeFullLink

# 需要导入模块: from livestreamer import Livestreamer [as 别名]
# 或者: from livestreamer.Livestreamer import resolve_url [as 别名]
def GetYoutubeFullLink(url):
	from livestreamer import Livestreamer
	livestr = Livestreamer()
	channel = livestr.resolve_url(url)
	streams = channel.get_streams()
	stream = streams["best"]
	return stream.url
开发者ID:aw20x,项目名称:xbmc-pal,代码行数:9,代码来源:myResolver.py

示例4: face_detect

# 需要导入模块: from livestreamer import Livestreamer [as 别名]
# 或者: from livestreamer.Livestreamer import resolve_url [as 别名]
def face_detect(x, y, width, height, stream_url):
    x = x*426/651
    y = y*240/398
    width = width*426/651
    height = height*240/398
    cascade_fn = "haarcascade_frontalface_alt.xml"
    nested_fn = "haarcascade_eye.xml"

    cascade = cv2.CascadeClassifier(cascade_fn)
    nested = cv2.CascadeClassifier(nested_fn)

    FFMPEG_BIN = 'C:/ffmpeg/bin/ffmpeg.exe'

    livestreamer = Livestreamer()
    plugin = livestreamer.resolve_url(stream_url)
    streams = plugin.get_streams()
    stream = streams.get("best")
    VIDEO_URL = stream.url
    print VIDEO_URL
    pipe = sp.Popen([FFMPEG_BIN, "-i", VIDEO_URL,
                     "-loglevel", "quiet",  # no text output
                     "-an",  # disable audio
                     "-f", "image2pipe",
                     "-pix_fmt", "bgr24",
                     "-vcodec", "rawvideo", "-"],
                    stdin=sp.PIPE, stdout=sp.PIPE)
    interval = 0
    while True:
        raw_image = pipe.stdout.read(426 * 240 * 3)  # read 432*240*3 bytes (= 1 frame)
        img = np.fromstring(raw_image, dtype='uint8').reshape((240, 426, 3))
        img = img[y:(y + height), x:(x + width)]
        gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
        gray = cv2.equalizeHist(gray)

        rects = detect(gray, cascade)
        vis = img.copy()
        if rects:
            interval += 1
        draw_rects(vis, rects, (0, 255, 0))
        for x1, y1, x2, y2 in rects:
            roi = gray[y1:y2, x1:x2]
            vis_roi = vis[y1:y2, x1:x2]
            subrects = detect(roi.copy(), nested)
            draw_rects(vis_roi, subrects, (255, 0, 0))

        cv2.imwrite('./media/face', vis)
        if cv2.waitKey(5) == 27:
            break
    cv2.destroyAllWindows()
开发者ID:ramitarora,项目名称:crowdcams,代码行数:51,代码来源:tasks.py

示例5: serveFile

# 需要导入模块: from livestreamer import Livestreamer [as 别名]
# 或者: from livestreamer.Livestreamer import resolve_url [as 别名]
    def serveFile(self, fURL, sendData):
        if (sendData):
            fURL, quality = player.GetStreamUrl(unquote(fURL))
            session = Livestreamer()
            if '|' in fURL:
                    sp = fURL.split('|')
                    fURL = sp[0]
                    headers = dict(urlparse.parse_qsl(sp[1]))
                    session.set_option("http-headers", headers)
                    session.set_option("http-ssl-verify",False)
                    session.set_option("hls-segment-threads",3)
                    session.set_option("stream-segment-threads",3)
            try:
                #streams = session.streams(fURL)
                channel = session.resolve_url(fURL)
                streams = channel.get_streams()
            except Exception as ex:
                traceback.print_exc(file=sys.stdout)
                self.send_response(403)
            self.send_response(200)
            #print "XBMCLocalProxy: Sending headers..."
            self.end_headers()

            #print "XBMCLocalProxy: Sending data..."
            fileout = self.wfile
            try:
                stream = streams[quality]
                try:
                    response = stream.open()
                    buf = 'INIT'
                    while (buf != None and len(buf) > 0):
                        buf = response.read(200 * 1024)
                        fileout.write(buf)
                        fileout.flush()
                    response.close()
                    fileout.close()
                    #print time.asctime(), "Closing connection"
                except socket.error, e:
                    #print time.asctime(), "Client Closed the connection."
                    try:
                        response.close()
                        fileout.close()
                    except Exception, e:
                        return
                except Exception, e:
                    traceback.print_exc(file=sys.stdout)
                    response.close()
                    fileout.close()
开发者ID:avigdork,项目名称:xbmc-avigdork,代码行数:50,代码来源:livestreamerXBMCLocalProxy.py

示例6: get_streams

# 需要导入模块: from livestreamer import Livestreamer [as 别名]
# 或者: from livestreamer.Livestreamer import resolve_url [as 别名]
    def get_streams(self):
        live = Livestreamer()
        print self.url
        live.set_option("http-ssl-verify", False)


        streams = None

        live.load_plugins(os.path.join(os.getcwd(), "plugins"))
        try:
            plugin = live.resolve_url(self.url)
            streams = plugin.get_streams()

            self.play_url = stream_to_url(streams.get("best"))
        except NoPluginError:
            print("No plugin can handle URL")
        except PluginError as err:
            print("{0}", err)
开发者ID:AnteWall,项目名称:Twitcherino,代码行数:20,代码来源:TwitchPlayer.py

示例7: get_stream

# 需要导入模块: from livestreamer import Livestreamer [as 别名]
# 或者: from livestreamer.Livestreamer import resolve_url [as 别名]
def get_stream(stream_url):
    # change to a stream that is actually online
    livestreamer = Livestreamer()
    stream = None
    try:
        plugin = livestreamer.resolve_url("http://www.twitch.tv/" + stream_url)
        plugin.set_option('oauth_token', 'xtlhyl6uapy6znsvuhy4zfk0jbt086')
        streams = plugin.get_streams()
        # It seems best isn't necessarily the best, twitch doesn't seem to consider 60
        # streams, so we should search for those first.
        if '1080p60' in streams:
            stream = streams['1080p60']
        elif '720p60' in streams:
            stream = streams['720p60']
        else:
            stream = streams['best']
    except Exception:
        pass
    return stream
开发者ID:atkaiser,项目名称:sc2livescores,代码行数:21,代码来源:update_state.py

示例8: main

# 需要导入模块: from livestreamer import Livestreamer [as 别名]
# 或者: from livestreamer.Livestreamer import resolve_url [as 别名]
def main():
    if len(sys.argv) < 3:
        exit("Usage: {0} <url> <quality>".format(sys.argv[0]))

    # Collect arguments
    url = sys.argv[1]
    quality = sys.argv[2]

    # Create the Livestreamer session
    livestreamer = Livestreamer()

    # Enable logging
    livestreamer.set_loglevel("info")
    livestreamer.set_logoutput(sys.stdout)

    # Attempt to find a plugin for this URL
    try:
        plugin = livestreamer.resolve_url(url)
    except NoPluginError:
        exit("Livestreamer is unable to handle the URL '{0}'".format(url))

    # Attempt to fetch streams
    try:
        streams = plugin.get_streams()
    except PluginError as err:
        exit("Plugin error: {0}".format(err))

    if len(streams) == 0:
        exit("No streams found on URL '{0}'".format(url))

    # Look for specified stream
    if quality not in streams:
        exit("Unable to find '{0}' stream on URL '{1}'".format(quality, url))

    # We found the stream
    stream = streams[quality]

    # Create the player and start playback
    player = LivestreamerPlayer()

    # Blocks until playback is done
    player.play(stream)
开发者ID:barretod,项目名称:livestreamer,代码行数:44,代码来源:gst-player.py

示例9: dict

# 需要导入模块: from livestreamer import Livestreamer [as 别名]
# 或者: from livestreamer.Livestreamer import resolve_url [as 别名]
    print help_message
    
    args, video_src = getopt.getopt(sys.argv[1:], '', ['cascade=', 'nested-cascade='])
    try: video_src = video_src[0]
    except: video_src = 0
    args = dict(args)
    cascade_fn = args.get('--cascade', "haarcascade_frontalface_alt.xml")
    nested_fn  = args.get('--nested-cascade', "haarcascade_eye.xml")

    cascade = cv2.CascadeClassifier(cascade_fn)
    nested = cv2.CascadeClassifier(nested_fn)

    FFMPEG_BIN = 'C:/ffmpeg/bin/ffmpeg.exe'

    livestreamer = Livestreamer()
    plugin = livestreamer.resolve_url("http://www.ustream.tv/channel/personal-cam1")
    streams = plugin.get_streams()
    stream = streams.get("best")
    VIDEO_URL = stream.url
    print VIDEO_URL
    pipe = sp.Popen([FFMPEG_BIN, "-i", VIDEO_URL,
           "-loglevel", "quiet", # no text output
           "-an",   # disable audio
           "-f", "image2pipe",
           "-pix_fmt", "bgr24",
           "-vcodec", "rawvideo", "-"],
           stdin = sp.PIPE, stdout = sp.PIPE)

    while True:
        raw_image = pipe.stdout.read(426*240*3) # read 432*240*3 bytes (= 1 frame)
        img = np.fromstring(raw_image, dtype='uint8').reshape((240,426,3))
开发者ID:ramitarora,项目名称:crowdcams,代码行数:33,代码来源:opencvtest2.py

示例10: StreamAnalysis

# 需要导入模块: from livestreamer import Livestreamer [as 别名]
# 或者: from livestreamer.Livestreamer import resolve_url [as 别名]
class StreamAnalysis( Thread ):

  def __init__( self, timeList, eventList, worldmap ):
    Thread.__init__( self )
    self._timeList = timeList
    self._eventList = eventList

    self._timeZero = 1392254560

    # set up templates as private variables for this class
    self._templatesTime = pickle.load( open('timeValues.data', 'rb') )
    self._templatesRed = pickle.load( open('redTemplates.data', 'rb') )
    self._templatesEvent = pickle.load( open('eventTemplates.data', 'rb') )

    self._worldmap = cv2.cvtColor(worldmap.copy(), cv2.COLOR_BGR2GRAY)


  def initStream( self ):
    self._livestreamer = Livestreamer()
    self._plugin = self._livestreamer.resolve_url('http://twitch.tv/twitchplayspokemon')

  def fetchStream( self ):
    streams = self._plugin.get_streams()
    if 'source' in streams:
      return streams.get('source')

    return False

  def run( self ):
    
    self.initStream()
    
    stream = self.fetchStream()
    while stream == False:
      print 'STREAM'
      time.sleep(60)
      print 'rechecking if stream is available'
      stream = self.fetchStream()

    #cap = cv2.VideoCapture( 'http://store22.media22.justin.tv/archives/2014-2-17/live_user_twitchplayspokemon_1392633446.flv' )
    cap = cv2.VideoCapture( stream.url )

    tmpTimeValues = []
    last_position = (-1, -1)

    while True:

      if not overridePosition == (-1, -1) and last_position == (-1, -1):
        last_position = overridePosition

      flag, frame = cap.read()
      
      if not flag:
        stream = self.fetchStream()
        cap = cv2.VideoCapture( stream.url )
        flag, frame = cap.read()

        if not flag:
          break

      gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
      timeValues = self.getTimeValues( gray[81:119, 526:830] )

      if timeValues == tmpTimeValues:
        continue

      tmpTimeValues = timeValues
      date = self.getDateFromTime( timeValues )
      if not 'day' in date or not 'hour' in date or not 'minute' in date or not 'second' in date:
        print 'error parsing date'
        continue

      timeStamp = self._timeZero + int(date['day']) * 24 * 60 * 60 + int(date['hour']) * 60 * 60 + int(date['minute']) * 60 + int(date['second'])

      # crop to gameboy area
      crop = gray[24:457, 24:504]

      # find red (if not found with enough confidence it's "undefined")
      currentDirection = self.getRedDirection( crop[182:230, 194:233] )
      if currentDirection == 'undefined':
        #self.newEntry(timeStamp, date, last_position)
        continue

      # check if there is currently an event open
      events = self.detectEvents( crop )
      if len(events) > 0 and not last_position == (-1, -1):
        #self.newEntry(timeStamp, date, last_position)
        self._eventList.append(events[0])
        continue

      # detect position on map

      # scale to world-map ratio
      # 480px -> 160px
      crop = cv2.resize(crop, (160, 144))

      # crop the worldmap image to a reasonable size, so we do not have to search so excessively
      # we can only do this if we have a starting position
      validationImage = self._worldmap
      left_corner = (0, 0)
#.........这里部分代码省略.........
开发者ID:angryfruitsalad,项目名称:TwitchPlaysPokemonMapper,代码行数:103,代码来源:streamAnalysis.py

示例11: TestPluginStream

# 需要导入模块: from livestreamer import Livestreamer [as 别名]
# 或者: from livestreamer.Livestreamer import resolve_url [as 别名]
class TestPluginStream(unittest.TestCase):
    def setUp(self):
        self.session = Livestreamer()

    def assertDictHas(self, a, b):
        for key, value in a.items():
            self.assertEqual(b[key], value)

    def _test_akamaihd(self, surl, url):
        channel = self.session.resolve_url(surl)
        streams = channel.get_streams()

        self.assertTrue("live" in streams)

        stream = streams["live"]
        self.assertTrue(isinstance(stream, AkamaiHDStream))
        self.assertEqual(stream.url, url)

    def _test_hls(self, surl, url):
        channel = self.session.resolve_url(surl)
        streams = channel.get_streams()

        self.assertTrue("live" in streams)

        stream = streams["live"]
        self.assertTrue(isinstance(stream, HLSStream))
        self.assertEqual(stream.url, url)

    def _test_rtmp(self, surl, url, params):
        channel = self.session.resolve_url(surl)
        streams = channel.get_streams()

        self.assertTrue("live" in streams)

        stream = streams["live"]
        self.assertTrue(isinstance(stream, RTMPStream))
        self.assertEqual(stream.params["rtmp"], url)
        self.assertDictHas(params, stream.params)

    def _test_http(self, surl, url, params):
        channel = self.session.resolve_url(surl)
        streams = channel.get_streams()

        self.assertTrue("live" in streams)

        stream = streams["live"]
        self.assertTrue(isinstance(stream, HTTPStream))
        self.assertEqual(stream.url, url)
        self.assertDictHas(params, stream.args)

    def test_plugin(self):
        self._test_rtmp("rtmp://hostname.se/stream",
                         "rtmp://hostname.se/stream", dict())

        self._test_rtmp("rtmp://hostname.se/stream live=1 num=47",
                        "rtmp://hostname.se/stream", dict(live=True, num=47))

        self._test_rtmp("rtmp://hostname.se/stream live=1 qarg='a \\'string' noq=test",
                        "rtmp://hostname.se/stream", dict(live=True, qarg='a \'string', noq="test"))

        self._test_hls("hls://https://hostname.se/playlist.m3u8",
                       "https://hostname.se/playlist.m3u8")

        self._test_hls("hls://hostname.se/playlist.m3u8",
                       "http://hostname.se/playlist.m3u8")

        self._test_akamaihd("akamaihd://http://hostname.se/stream",
                            "http://hostname.se/stream")

        self._test_akamaihd("akamaihd://hostname.se/stream",
                            "http://hostname.se/stream")

        self._test_http("httpstream://http://hostname.se/auth.php auth=('test','test2')",
                        "http://hostname.se/auth.php", dict(auth=("test", "test2")))

        self._test_http("httpstream://hostname.se/auth.php auth=('test','test2')",
                        "http://hostname.se/auth.php", dict(auth=("test", "test2")))

        self._test_http("httpstream://https://hostname.se/auth.php verify=False params={'key': 'a value'}",
                       "https://hostname.se/auth.php?key=a+value", dict(verify=False, params=dict(key='a value')))
开发者ID:3cky,项目名称:livestreamer,代码行数:82,代码来源:test_plugin_stream.py

示例12: __init__

# 需要导入模块: from livestreamer import Livestreamer [as 别名]
# 或者: from livestreamer.Livestreamer import resolve_url [as 别名]
class Main:
    def __init__(self):    
        self.gchoice = -1
        self.cchoice = -1    
        self.exit_now = False
        self.state = 'none'
        self.keybingings = {
            ord('q'):       self.quit,
            ord('f'):       self.get_favorites,
            ord('s'):       self.get_fav_games,
            ord('g'):       self.get_games,
            ord('n'):       self.get_next,
            ord('r'):       self.refresh,
            ord('p'):       self.get_previous            
        }
        
        self.games = []
        self.favs = []
        self.channels = []        
        self.twitch = Twitch(config.get('settings', 'twitchapiurl'), config.get('settings', 'channel'), config.get('settings', 'game'))
        self.livestreamer = Livestreamer()
        
        try:
            self.run()
        except Exception as e:
            print e.message
        
    def run(self):
        
        while True:            
            self.display_message()                                            
            if self.exit_now:
                return
    
    def quit(self, c):
        self.exit_now = True
        
    def display_message(self):
                               
        if self.state == 'none':
            clear_screen()                      
            self.handle_user_input('Escoge una opcion : Favoritos(F), Juegos(G), Salir(Q)')            
        
        if self.state == 'favs':
            clear_screen()            
            print 'Mostrando transmisiones favoritas en linea :'
            print '-' * 40
            if(len(self.favs) > 0):                            
                self.show_content(self.favs)            
                self.handle_user_input('Escoge un canal por numero (r para refrescar, g para enlistar juegos y q para salir', range(len(self.favs) + 1))
                clear_screen()
            else:
                self.handle_user_input('No hay canales favoritos en linea (r para refrescar, g para enlistar juegos y q para salir', range(len(self.favs) + 1))
                clear_screen()            
                
        if self.state == 'games':
            clear_screen()            
            print 'Mostrando %d juegos destacados:' % config.getint('settings', 'game')
            print '-' * 40
            if(len(self.games) > 0):                            
                self.show_content(self.games)            
                self.gchoice = self.handle_user_input('Escoge un juego por numero (r para refrescar, f para revisar tus canales favoritos y q para salir', range(len(self.games) + 1))
                if self.gchoice != -1:
                    self.state = 'channels'
                    clear_screen()                                                 
                    
        if self.state == 'favgames':
            clear_screen()            
            print 'Mostrando juegos favoritos:'
            print '-' * 40
            if(len(self.games) > 0):                        
                self.show_content(self.games)            
                self.gchoice = self.handle_user_input('Escoge un juego por numero (r para refrescar, f para revisar tus canales favoritos y q para salir', range(len(self.games) + 1))
                if self.gchoice != -1:
                    self.state = 'channels'
                    clear_screen()
        
        if self.state == 'channels':
            clear_screen()            
            print 'Mostrando %d canales destacados para %s:' % (config.getint('settings', 'channel'), self.games[self.gchoice - 1])
            print '-' * 40            
            self.get_channels(self.gchoice)
            if(len(self.channels) > 0):                            
                self.show_content(self.channels)            
                self.cchoice = self.handle_user_input('Escoge un canal por numero (r para refrescar, f para revisar tus canales favoritos, g para enlistar juegos y q para salir', range(len(self.channels) + 1))
                if self.cchoice != -1:
                    self.play_stream(self.channels[self.cchoice - 1])
                    self.state = 'channels'
                    clear_screen()
       
    def play_stream(self, channel):
        clear_screen()
        
        try:
            plugin = self.livestreamer.resolve_url(("twitch.tv/{0}").format(channel))
        except Exception as e:
            print e.message                   
        
        try:
            streams = plugin.get_streams()
#.........这里部分代码省略.........
开发者ID:parurope,项目名称:twitchscript,代码行数:103,代码来源:twitchscript_Serialloser.py

示例13: Livestreamer

# 需要导入模块: from livestreamer import Livestreamer [as 别名]
# 或者: from livestreamer.Livestreamer import resolve_url [as 别名]
from livestreamer import Livestreamer
import cv2
import subprocess as sp
FFMPEG_BIN = 'C:/ffmpeg/bin/ffmpeg.exe'
import numpy

livestreamer = Livestreamer()
plugin = livestreamer.resolve_url("http://www.ustream.tv/channel/jamthehype")
streams = plugin.get_streams()
print streams
stream = streams.get("best")
cv2.namedWindow("GoPro",cv2.CV_WINDOW_AUTOSIZE)
VIDEO_URL = stream.url
print VIDEO_URL
pipe = sp.Popen([FFMPEG_BIN, "-i", VIDEO_URL,
           "-loglevel", "quiet", # no text output
           "-an",   # disable audio
           "-f", "image2pipe",
           "-pix_fmt", "bgr24",
           "-vcodec", "rawvideo", "-"],
           stdin = sp.PIPE, stdout = sp.PIPE)
while True:
    raw_image = pipe.stdout.read(426*240*3) # read 432*240*3 bytes (= 1 frame)
    image =  numpy.fromstring(raw_image, dtype='uint8').reshape((240,426,3))
    cv2.imshow("GoPro",image)
    if cv2.waitKey(5) == 27:
        break
cv2.destroyAllWindows()
开发者ID:ramitarora,项目名称:crowdcams,代码行数:30,代码来源:opencvustream.py

示例14: TestSession

# 需要导入模块: from livestreamer import Livestreamer [as 别名]
# 或者: from livestreamer.Livestreamer import resolve_url [as 别名]
class TestSession(unittest.TestCase):
    PluginPath = os.path.join(os.path.dirname(__file__), "plugins")

    def setUp(self):
        self.session = Livestreamer()
        self.session.load_plugins(self.PluginPath)

    def test_exceptions(self):
        try:
            self.session.resolve_url("invalid url")
            self.assertTrue(False)
        except NoPluginError:
            self.assertTrue(True)

    def test_load_plugins(self):
        plugins = self.session.get_plugins()
        self.assertTrue(plugins["testplugin"])

    def test_builtin_plugins(self):
        plugins = self.session.get_plugins()
        self.assertTrue("twitch" in plugins)

    def test_resolve_url(self):
        plugins = self.session.get_plugins()
        channel = self.session.resolve_url("http://test.se/channel")
        self.assertTrue(isinstance(channel, Plugin))
        self.assertTrue(isinstance(channel, plugins["testplugin"]))

    def test_options(self):
        self.session.set_option("test_option", "option")
        self.assertEqual(self.session.get_option("test_option"), "option")
        self.assertEqual(self.session.get_option("non_existing"), None)

        self.assertEqual(self.session.get_plugin_option("testplugin", "a_option"), "default")
        self.session.set_plugin_option("testplugin", "another_option", "test")
        self.assertEqual(self.session.get_plugin_option("testplugin", "another_option"), "test")
        self.assertEqual(self.session.get_plugin_option("non_existing", "non_existing"), None)
        self.assertEqual(self.session.get_plugin_option("testplugin", "non_existing"), None)

    def test_plugin(self):
        channel = self.session.resolve_url("http://test.se/channel")
        streams = channel.get_streams()

        self.assertTrue("best" in streams)
        self.assertTrue("worst" in streams)
        self.assertTrue(streams["best"] is streams["1080p"])
        self.assertTrue(streams["worst"] is streams["350k"])
        self.assertTrue(isinstance(streams["rtmp"], RTMPStream))
        self.assertTrue(isinstance(streams["http"], HTTPStream))
        self.assertTrue(isinstance(streams["hls"], HLSStream))
        self.assertTrue(isinstance(streams["akamaihd"], AkamaiHDStream))

    def test_plugin_stream_types(self):
        channel = self.session.resolve_url("http://test.se/channel")
        streams = channel.get_streams(stream_types=["http", "rtmp"])

        self.assertTrue(isinstance(streams["480p"], HTTPStream))
        self.assertTrue(isinstance(streams["480p_rtmp"], RTMPStream))

        streams = channel.get_streams(stream_types=["rtmp", "http"])

        self.assertTrue(isinstance(streams["480p"], RTMPStream))
        self.assertTrue(isinstance(streams["480p_http"], HTTPStream))

    def test_plugin_stream_sorted_excludes(self):
        channel = self.session.resolve_url("http://test.se/channel")
        streams = channel.get_streams(sorting_excludes=["1080p", "3000k"])

        self.assertTrue("best" in streams)
        self.assertTrue("worst" in streams)
        self.assertTrue(streams["best"] is streams["1500k"])

        streams = channel.get_streams(sorting_excludes=[">=1080p", ">1500k"])
        self.assertTrue(streams["best"] is streams["1500k"])

        streams = channel.get_streams(sorting_excludes=lambda q: not q.endswith("p"))
        self.assertTrue(streams["best"] is streams["3000k"])

    def test_plugin_support(self):
        channel = self.session.resolve_url("http://test.se/channel")
        streams = channel.get_streams()

        self.assertTrue("support" in streams)
        self.assertTrue(isinstance(streams["support"], HTTPStream))
开发者ID:492580195,项目名称:livestreamer,代码行数:86,代码来源:test_session.py

示例15: StreamList

# 需要导入模块: from livestreamer import Livestreamer [as 别名]
# 或者: from livestreamer.Livestreamer import resolve_url [as 别名]

#.........这里部分代码省略.........

    def redraw_status(self):
        self.s.move(self.max_y, 0)
        self.overwrite_line(self.status[:self.max_x], curses.A_NORMAL)
        self.s.refresh()

    def redraw_stream_footer(self):
        if not self.no_stream_shown:
            row = self.pads[self.current_pad].getyx()[0]
            s = self.filtered_streams[row]
            self.set_footer('{0}/{1} {2} {3}'.format(row+1, len(self.filtered_streams), s['url'], s['res']))
            self.s.refresh()

    def check_stopped_streams(self):
        finished = self.q.get_finished()
        for f in finished:
            for s in self.streams:
                try:
                    i = self.filtered_streams.index(s)
                except ValueError:
                    continue
                if f == s['id']:
                    self.set_footer('Stream {0} has stopped'.format(s['name']))
                    if i == self.pads[self.current_pad].getyx()[0]:
                        attr = curses.A_REVERSE
                    else:
                        attr = curses.A_NORMAL
                    self.pads['streams'].addstr(i, PLAYING_FIELD_OFFSET,
                                                INDICATORS[s['online']], attr)
                    self.refresh_current_pad()

    def _check_stream(self, url):
        try:
            plugin = self.livestreamer.resolve_url(url)
            avail_streams = plugin.get_streams()
            if avail_streams:
                return 1
            return 0
        except:
            return 3

    def check_online_streams(self):
        self.all_streams_offline = True
        self.set_status(' Checking online streams...')

        done_queue   = queue.Queue()

        def check_stream_managed(args):
            url, queue = args
            status = self._check_stream(url)
            done_queue.put(url)
            return status

        pool = Pool(CHECK_ONLINE_THREADS)
        args = [(s['url'], done_queue) for s in self.streams]
        statuses = pool.map_async(check_stream_managed, args)
        n_streams = len(self.streams)

        while not statuses.ready():
            sleep(0.1)
            self.set_status(' Checked {0}/{1} streams...'.format(done_queue.qsize(), n_streams))
            self.s.refresh()

        statuses = statuses.get()
        for i, s in enumerate(self.streams):
            s['online'] = statuses[i]
开发者ID:fletom,项目名称:livestreamer-curses,代码行数:70,代码来源:main.py


注:本文中的livestreamer.Livestreamer.resolve_url方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。