async def stream(network, channel, message): req = message.content.split('stream')[1].strip() if not req: return await network.send_message(channel, 'What stream did you want to listen to, {}?'.format(message.author.name)) try: # this actually blocks.. for a while :| streams = livestreamer.streams('twitch.tv/{}'.format(req)) except NoPluginError: # we should/could actually check that this is a twitch streamer in particular return await network.send_message(channel, 'I could not find a streamer named {}, {}'.format(req, message.author.name)) audio_url = streams['audio'].url # uhh.. yeah, fake a player object to work with the request system class Foo(object): pass fake_player = Foo() fake_player._query = audio_url J.requests.append(fake_player) return await network.send_message(channel, "{}'s stream has been added to the queue.".format(req, message.author.name))
def streamredir(url): try: streams = livestreamer.streams(url) best = streams['best'] return redirect(best.url) except: return "No stream found", 404
def GetMediaStream(partner_id, entry_id): livestreamer_url = 'hlsvariant://' + media_url.format(partnerId=partner_id, entryId=entry_id) streams = livestreamer.streams(livestreamer_url) mediaUrl = streams['best'].url Log(mediaUrl) return mediaUrl
def processing_stream(self): reg_twitch = 'http[s]?://www.twitch.tv/(\w+)' reg_link = 'http[s]?://.+' if self.url_link: if re.match(reg_twitch, self.url_link) is not None: chan_name = re.match(reg_twitch, self.url_link).group(1) print(chan_name) try: if self.url_link in self.data['favorit']: self.love_btn.setDisabled(True) except AttributeError: print("Favorits channel not found") self.statusbar.showMessage("Получение адреса стрима...") self.streams = livestreamer.streams(self.url_link) qual = self.quality_cb.currentText() qual = qual.lower() try: stream = self.streams[qual] self.statusbar.showMessage( "Устновка качества видео...") filename = stream.url self.channel = chan_name self.construct_video(filename) self.newThreads(filename, chan_name) except KeyError: self.messageBox("Извените, но данный канал оффлайн") if re.match(reg_link, self.url_link) is not None: # self.construct_video(url_link) pass else: self.messageBox("Пожалуйста введите адрес стрима")
def refresh(self): self.clear_widgets() # for key, val in self.ids.items(): # self.remove_widget(val) x = Qbut(width = 300) x.btype = 0 x.text = self.name y = Qbut(width = 50) y.btype = 1 y.text = "del" self.link = "www.twitch.tv/" + self.name[:-1] self.add_widget(x) self.add_widget(y) links = livestreamer.streams(self.link) if(links): self.qualities = links.keys() self.online = True self.state = "online" for a in self.qualities: b = Qbut(text=a, width = 100) b.link = self.link + " " + a b.btype = 2 self.add_widget(b) else: self.online = False self.state = "offline" self.qualities = [] x.text = self.name + " " + self.state
def processing_stream(self): reg_twitch = 'http[s]?://www.twitch.tv/(\w+)' reg_link = 'http[s]?://.+' if self.url_link: if re.match(reg_twitch, self.url_link) is not None: chan_name = re.match(reg_twitch, self.url_link).group(1) print(chan_name) try: if self.url_link in self.data['favorit']: self.love_btn.setDisabled(True) except AttributeError: print("Favorits channel not found") self.statusbar.showMessage("Получение адреса стрима...") self.streams = livestreamer.streams(self.url_link) qual = self.quality_cb.currentText() qual = qual.lower() try: stream = self.streams[qual] self.statusbar.showMessage("Устновка качества видео...") filename = stream.url self.channel = chan_name self.construct_video(filename) self.newThreads(filename, chan_name) except KeyError: self.messageBox("Извените, но данный канал оффлайн") if re.match(reg_link, self.url_link) is not None: # self.construct_video(url_link) pass else: self.messageBox("Пожалуйста введите адрес стрима")
def getQualities(self, event): stream = event.GetText() streams = livestreamer.streams('https://twitch.tv/'+stream) self.combo.Clear() for quality in streams: self.combo.Append(quality) self.combo.SetValue('best') self.to_change.Enable()
def getQualities(self, event): stream = event.GetText() streams = livestreamer.streams('https://twitch.tv/' + stream) self.combo.Clear() for quality in streams: self.combo.Append(quality) self.combo.SetValue('best') self.to_change.Enable()
def GetYoutubeFullLink(url): #from livestreamer import Livestreamer #livestr = Livestreamer() #channel = livestr.resolve_url(url) #streams = channel.get_streams() import livestreamer streams = livestreamer.streams(url) stream = streams["best"] return stream.url
def collect(info): streams = livestreamer.streams(info['url']) stream = streams[info['stream']] cap = get_capture_from_livestream(stream) succes, img_bgr = cap.read() img_rgb = cv2.cvtColor(img_bgr, cv2.COLOR_BGR2RGB) logger.debug('captured: %s', info) # return numpy array and info return img_rgb, info
def getQualities(url): streams = livestreamer.streams(url) if not streams == {}: qualities = [] for idx, l in enumerate(streams.keys()): qualities.append({"label": str(idx+1) + ": " + l.capitalize(), "quality": l}) return qualities else: raise
def getStream(roomid): streams = livestreamer.streams(roomurl + str(roomid)) if len(streams) > 0: return streams else: logging.info('no streams') time.sleep(10) main() return
def get_available_quality(url): try: streams = livestreamer.streams(url) return streams except livestreamer.NoPluginError as err: raise LivestreamerError("No plugin for this url") except livestreamer.PluginError as err: raise LivestreamerError(str(err)) except Exception as ex: raise LivestreamerError(str(ex))
def run(self): try: streams = livestreamer.streams(self.url) self.streams = streams except livestreamer.NoPluginError as no_plugin_error: self.no_plugin_error = no_plugin_error except livestreamer.PluginError as plugin_error: self.plugin_error = plugin_error self.done = True
def __init__(self, stream_url, stream_read_size=8192, debug=False): self.stream_url = stream_url self.stream_read_size = stream_read_size self.debug = debug self.streams = livestreamer.streams(stream_url) self.active_stream_name = None self.active_stream_fd = None if not self.get_stream_names(): raise ValueError('There are currently no streams being served by the URL, %s !' % (self.stream_url)) self.set_active_stream('source' if 'source' in self.get_stream_names() else self.get_stream_names()[0])
def record(url,format,filename): stream = livestreamer.streams(url)[format] fd = stream.open() totalSize,temp = 0,BytesIO() for piece in fd: temp.write(piece) totalSize += sys.getsizeof(piece) if totalSize >= 1048576: with open(filename,'ab') as output: output.write(temp.getvalue()) totalSize,temp = 0,BytesIO()
def get_media_url(entry_id): hls_url = HLS_URL_FMT.format(entry_id) livestreamer_url = 'hlsvariant://' + hls_url log("Retrieving streams from {}".format(hls_url)) resolution = plugin.get_setting('resolution') streams = livestreamer.streams(livestreamer_url, sorting_excludes=[">{}".format(resolution)]) log("Available streams: {}".format(' '.join(streams))) media_url = streams['best'].url log("Playing URL {}".format(media_url)) return media_url
def __init__(self, twitch, timeout=3, verbose=False): self.twitch = twitch self.url = 'twitch.tv/{}'.format(self.twitch) s = livestreamer.streams(self.url) if len(s) == 0: raise ViewerBotException('Stream offline!?') self.timeout = timeout self.verbose = verbose self.proxies = ProxyList(fun=ProxyList.progress_fun if verbose else None)
def main(): # Parse command line arguments. parser = argparse.ArgumentParser( description="Create graphs for SpaceX's launch videos.") parser.add_argument('-c', '--capture', action='store', dest='capture_path', help='Path (url or local) of the desired video') parser.add_argument('-d', '--destination', action='store', dest='destination_path', default='telemetry.json', help='Path to the file that will contain the output') parser.add_argument('-t', '--templates', action='store', dest='templates_path', default='Images', help='Path to the folder that cotains the template images') parser.add_argument('-T', '--time', action='store', dest='launch_time', default=0, help='Time delay from the beginning of the video to the time of the launch (in seconds)') parser.add_argument('-r', action='store', dest='irl', default='true', help='If true (Or not given) the program will NOT write to a file and ' 'only output json data') args = parser.parse_args() # If no arguments are given show help and exit. if len(argv) == 1: parser.print_help() exit(-1) # Use Livestreamer if the input is a url. if args.capture_path.startswith('www.youtube.com') or args.capture_path.startswith('http'): streams = livestreamer.streams(args.capture_path) capture = streams['1080'].url else: capture = args.capture_path # Notify the user if he/she tries to override a file. if args.irl.lower() == 'false': if isfile(args.destination_path) and input('{} already exists. Are you sure you want to overwrite it? [y/n]: '.format(args.destination_path)) != 'y': exit(1) # Open output files. file = open(args.destination_path, 'wt') else: file = None # Load digits' templates from the disk. templates = [cv2.imread('{}/{}.jpg'.format(args.templates_path, i), 0) for i in range(10)] # Tries to read from video file. if args.capture_path is not None: cap = cv2.VideoCapture(capture) else: exit(2) # Call analysis function. analyze_capture(cap, file, templates, int(args.launch_time))
def collect(meta): utc = dateutil.tz.tzutc() t = datetime.datetime.now(utc).isoformat() meta['t'] = t streams = livestreamer.streams(meta['url']) stream = streams[meta['stream']] cap = get_capture_from_livestream(stream) succes, img_bgr = cap.read() img_rgb = cv2.cvtColor(img_bgr, cv2.COLOR_BGR2RGB) # return numpy array and info filename = generate_filename(meta) meta['filename'] = filename plt.imsave(filename, img_rgb) return meta
def read_config(Config): raw = Config.get('URLs', 'streamList') urlList = list(filter(None, (x.strip() for x in raw.splitlines()))) streamList = [] for url in urlList: try: stream = livestreamer.streams(url)['best'] streamList.append(stream) except: print("Error: couldn't fetch video stream for url " + url) return streamList
def main(args): chunk_size = 16384 url = u"hls://{}".format(args[1]) stream = livestreamer.streams(url)['worst'].open() ############################################################### ffmpeg_args = u"avconv -i pipe:0".split() + args[2:] process = subprocess.Popen(ffmpeg_args, stdin=subprocess.PIPE) ############################################################### data = stream.read(chunk_size) while data: process.stdin.write(data) data = stream.read(chunk_size) process.kill() return
def Qualities(url): """ get streams from url with livestreamer, list the qualities """ oc = ObjectContainer() try: streams = livestreamer.streams(url) except livestreamer.NoPluginError: Log("Livestreamer can't handle the url %s" % url) return oc except livestreamer.PluginError as err: Log("Livestreamer plugin error: %s" % err) return oc for quality in streams: oc.add(VideoClipObject(url="livestreamer://{}|{}".format(stream_type(streams[quality]), streams[quality].url), title=quality)) return oc
def __isStreamLive(self): # Iterate until the queue is empty while True: streamTuple = self.streamQueue.get() # Construct the URL to each stream using the tuple fullStream = self.siteMap[streamTuple[0]] + streamTuple[1] # Check if the stream is live stream = livestreamer.streams(fullStream) # If the stream is live, it will return a non-empty list if stream: # Lock the list on writes self.listOfStreamsLock.acquire() self.listOfStreams.append(streamTuple) self.listOfStreamsLock.release() self.streamQueue.task_done()
def Qualities(url): """ get streams from url with livestreamer, list the qualities """ oc = ObjectContainer() try: streams = livestreamer.streams(url) except livestreamer.NoPluginError: Log("Livestreamer can't handle the url %s" % url) return oc except livestreamer.PluginError as err: Log("Livestreamer plugin error: %s" % err) return oc for quality in streams: stream = "livestreamer://{}|{}".format(stream_type(streams[quality]), streams[quality].url) try: URLService.MetadataObjectForURL(stream) except: Log.Exception(u"Plex Framework error: can't handle '{}'".format(stream)) continue oc.add(VideoClipObject(url=stream, title=quality)) return oc
def parseStreamURL(stream_url): global streams, quality, stream_url_hls stream_url_hls = 'hlsvariant://' + stream_url streams = livestreamer.streams(stream_url_hls) #print '\n' + stream_url_hls print('\nAvailable streams : %s' % str(streams.keys())) quality = raw_input('Enter stream quality <leave empty for default> : ') if quality == '': quality = 'best' stream_url = streams[quality].url print('Using the "best" possible quality...\n') elif quality in streams.keys(): stream_url = streams[quality].url else: print('Incorrect option. Switching to default...\n') quality = 'best' stream_url = streams[quality].url #print stream_url return stream_url
def handler(event, context): if 'url' not in event or not event['url']: print("ERROR: url not found in request") return {"error": "missing url"} url = event["url"] res = { "streamable": False, "streams": {}, "msg": "" } if url.startswith("rtsp") or url.startswith("rtmp"): # URL should be streamable, no further resolution needed. res["streamable"] = True else: # Attempt to get streamable url via livestreamer streams = None try: streams = livestreamer.streams(url) for q,u in streams.items(): try: streams[q] = u.url except Exception as e: streams[q] = u except NoPluginError: res["msg"] = "URL is not yet supported." except PluginError as err: res["msg"] = "Unable to process URL." if streams: res["streamable"] = True res["streams"] = { k:str(v) for k,v in streams.items() } else: res["msg"] = "No streams found on URL" return res
def get_streams_status(self,event=None): """ Getting all qualities for each stream url """ self.refresh_btn['state'] = 'disabled' self.streams_urls = self.read_streamlist() self.streams_box.delete(0,tk.END) self.progbar['value'] = 0 size = len(self.streams_urls) delta = self.progbar['maximum']//size data = [] for url in self.streams_urls: self.root.update() # refresh display try: url = url[:-1] # ignore trailing space options = livestreamer.streams(url) data.append( ["{1} {0}".format(k,url) for k,v in options.items() if k == "medium" or k=="high" or k == "best" or k=="720p" or k =="480p" or k == "680p"]) self.progbar.step(delta) except: print("COULDNT LOAD {}".format(url) ) self.progbar['value'] = self.progbar['maximum'] self.all_statuses = data self.insert_streams() self.refresh_btn['state'] = 'normal'
def GetStreamliveToFullLink(url): stream = livestreamer.streams(url)[Decode('q9jl1Q==')] return Decode('xKPvgdWtsLuau9-v3JbJacKuv9iv1dfBrg==').format( stream.params[Decode('u-ff0Q==')], stream.params[Decode('udTZxrq-tQ==')])
def GetLivestreamerLink(url): return livestreamer.streams(url)[Decode('q9jl1Q==')].url
def GetStreamliveToFullLink(url): stream = livestreamer.streams(url)['best'] return '{0} pageUrl={1} live=true'.format(stream.params['rtmp'], stream.params['pageUrl'])
def advance(self, actual_menu): qualities = livestreamer.streams(self.option['channel']['url']) save_stream_opened(self.option) return Menu(map(Execute, zip(qualities.keys(), qualities.values())), previous=actual_menu)
def GetLivestreamerLink(url): return livestreamer.streams(url)['best'].url
def get_qualities(self, streamer): url = "https://twitch.tv/%s" % (streamer) streams = livestreamer.streams(url) return streams
import livestreamer streams = livestreamer.streams("http://www.twitch.tv/sumaildoto") stream_hlv = streams['source'] stream = stream_hlv.url print stream # f = open('hls_url.txt','w') # f.write(repr(stream)) # f.close()
def GetYoutubeFullLink(url): streams = livestreamer.streams(url) stream = streams["best"] return stream.url
import livestreamer import json import urllib2 url = raw_input('paste the link: ') id = url[url.rindex('/')+1:] HOTSTAR_CDN = "http://getcdn.hotstar.com/AVS/besc?action=GetCDN&asJson=Y&channel=TABLET&type=VOD&id=" + str(id) responsestring = urllib2.urlopen(HOTSTAR_CDN).read() jsonresponse = json.loads(responsestring) dl_url = jsonresponse['resultObj']['src'] the_real_url = "hlsvariant://" + str(dl_url) streams = livestreamer.streams(the_real_url) qualities = streams.keys() print qualities the_qlty = raw_input('?') stream = streams[str(the_qlty)] print stream.url
def GetStreamliveToFullLink(url): import livestreamer streams = livestreamer.streams(url) stream = streams["best"] return "{0} pageUrl={1} live=true".format(stream.params["rtmp"], stream.params["pageUrl"])
import cv2 import numpy as np import time import livestreamer # use live streamer to figure out the stream info streams = livestreamer.streams("http://www.youtube.com/watch?v=-JcaDowz2G8&ab_channel=HopeCollegeAthletics") stream = streams['best'] # open our out file. fname = "test.mpg" vid_file = open(fname,"wb") # dump from the stream into an mpg file -- get a buffer going fd = stream.open() for i in range(0,1048): if i%256==0: print "Buffering..." new_bytes = fd.read(1024) vid_file.write(new_bytes) # open the video file from the begining print "Done buffering." cam = cv2.VideoCapture(fname) while True: ret, img = cam.read() try: if ret: img = 255-img # invert the colors cv2.imshow('live_img',img) except: print "DERP" continue if (0xFF & cv2.waitKey(5) == 27) or img.size == 0:
import livestreamer streams = livestreamer.streams( "http://demo.codesamplez.com/html5/video/sample") stream = streams["source"] fd = stream.open() data = fd.read(1024) fd.close()
import cv2 import numpy as np import time import livestreamer # use live streamer to figure out the stream info streams = livestreamer.streams("http://www.twitch.tv/inostupid") stream = streams['best'] # open our out file. fname = "test.mpg" vid_file = open(fname, "wb") # dump from the stream into an mpg file -- get a buffer going fd = stream.open() for i in range(0, 2 * 2048): if i % 256 == 0: print "Buffering..." new_bytes = fd.read(1024) vid_file.write(new_bytes) # open the video file from the begining print "Done buffering." cam = cv2.VideoCapture(fname) while True: ret, img = cam.read() try: if ret: img = 255 - img # invert the colors cv2.imshow('live_img', img) except: print "DERP" continue if (0xFF & cv2.waitKey(5) == 27) or img.size == 0:
def get_avaible_streams(name): avaible = livestreamer.streams("http://twitch.tv/"+name) return avaible.items()
#!/Users/bes/miniconda3/bin/python #You obviously need to `pip install livestreamer` first #Tested with Python 3.5.1 in Miniconda import sys import livestreamer import re stream = str(sys.argv[1]) quality = "best" if len(sys.argv) >= 3: quality = str(sys.argv[2]) match = re.search(r"twitch\.[a-zA-Z]+\/", stream) if match is None: stream = "twitch.tv/" + stream print (livestreamer.streams(stream)[quality].url)
def create_stream_container(url, quality): cli = get_docker_client() container = None docker_image = None docker_image = options.player_docker_image if url.startswith("rtsp") or (options.rpi_player and url.startswith("rtmp")): # Just pass the url to the player, no checks. pass else: # Attempt to get streamable url via livestreamer streams = None try: streams = livestreamer.streams(url) except NoPluginError: return False, "Livestreamer is unable to handle the URL '{0}'".format( url) except PluginError as err: return False, "Plugin error: {0}".format(err) if not streams: return False, "No streams found on URL '{0}'".format(url) # Look for specified stream if quality not in streams: return False, "Unable to find '{0}' stream on URL '{1}'".format( quality, url) # We found the stream stream = streams[quality] if options.resolve_url: logger.info("Stream URL resolved to: '{0}'".format(stream.url)) try: url = stream.url except Exception as e: return False, "Could not get url from stream, plugin class missing .url method: {0}".format( type(stream)) container = None try: devices = [] if options.rpi_player: for d in ["/dev/vchiq", "/dev/fb0", "/dev/snd"]: devices.append(d + ":" + d + ":rwm") volumes = [] binds = [] if options.rpi_player: for v in ["/opt/vc"]: binds.append(v + ":" + v + ":ro") volumes.append(v) host_config = cli.create_host_config(restart_policy={ "MaximumRetryCount": 0, "Name": "always" }, port_bindings={8000: 8000}, devices=devices, binds=binds) if options.rpi_player: entrypoint = "omxplayer -b -o both" else: entrypoint = None container = cli.create_container(image=docker_image, entrypoint=entrypoint, command=url, ports=[8000], detach=True, name="curr_stream", volumes=volumes, host_config=host_config) except Exception as e: logger.error("Error creating docker container: {0}".format(e)) #TODO: revert to previous stream on error if container: logger.info("Created container with image: '{0}'".format(docker_image)) return container else: return None
def GetStreamliveToFullLink(url): stream = livestreamer.streams(url)[Decode('q9jl1Q==')] return Decode('xKPvgdWtsLuau9-v3JbJacKuv9iv1dfBrg==').format(stream.params[Decode('u-ff0Q==')], stream.params[Decode('udTZxrq-tQ==')])