def _load_media(self, uri, local=True): """Load a new media file/stream, and whatever else is involved therein""" ##FIXME: Handle loading of subtitles as well ## If a .srt or similar is placed with the media file, load that and turn them on by default. (I think VLC does this automatically) ## Otherwise turn them off by default, but search for them automatically at http://thesubdb.com/ ## TV stream telx & similar should be turned off by default as well. # VLC detects local vs. remote URIs by simply checking if there is a ':' character in it, this is insufficient. ## FIXME: Actually automate this using better heuristics rather than just passing that test off to the user ## Used urlparse.urlparse for this test in UPMC if local: ## FIXME: bytes() conversion here not necessary for python-vlc 2.2.* ## Should I instead check version at import time and just error out completely if < 2.2? if not vlc.libvlc_get_version().startswith(b'2.2.'): uri = bytes(uri, sys.getfilesystemencoding()) media = self.instance.media_new_path(uri) else: media = self.instance.media_new(uri) media_em = media.event_manager() media_em.event_attach(vlc.EventType.MediaStateChanged, self._on_state_change) media_em.event_attach(vlc.EventType.MediaParsedChanged, self._on_parsed) self.player.set_media(media)
def getVlcVersion(): import vlc try: ver=vlc.libvlc_get_version() ver=ver.split()[0] except: ver='unknown' return ver
def jouer(self, current=None): try: self.instance.vlm_add_broadcast("test", self.media_name, self.sout, 0, None, True,False) #media=self.instance.media_new(self.media_name) except NameError: print ('NameError: % (%s vs Libvlc %s)' % (sys.exc_info()[1],vlc.__version__, vlc.libvlc_get_version())) sys.exit(1) self.instance.vlm_play_media("test") return 'http://192.168.1.53:8090/'+ str(self.media_name)
def __init__(self, qt_frame, cmdline): self.__speed = 1.0 self.__instance = vlc.Instance(cmdline) self.__mediaplayer = self.__instance.media_player_new() self.__mediaplayer.video_set_mouse_input(False) # disable mouse in player self.__mediaplayer.video_set_key_input(False) # disable keyboard self.__listplayer = self.__instance.media_list_player_new() self.Bind(qt_frame) self.version = vlc.libvlc_get_version()
def jouer(self, current=None): try: self.instance.vlm_add_broadcast("test", self.media_name, self.sout, 0, None, True, False) #media=self.instance.media_new(self.media_name) except NameError: print( 'NameError: % (%s vs Libvlc %s)' % (sys.exc_info()[1], vlc.__version__, vlc.libvlc_get_version())) sys.exit(1) self.instance.vlm_play_media("test") return 'http://192.168.1.53:8090/' + str(self.media_name)
def play(self, path_to_media_file): debug(u"attempting to play file: {0} of type: {1} and repr: {2}".format(path_to_media_file, type(path_to_media_file), repr(path_to_media_file))) encoded_path=path_to_media_file.encode("UTF-8") if not os.path.isfile(path_to_media_file): warn(u"This file: {0} does not exist. Full path: {1}".format(path_to_media_file, os.path.abspath(path_to_media_file))) return try: media = self.instance.media_new(encoded_path) except Exception as e: logger.exception("exception! {0}".format(e)) warn('NameError: %s (LibVLC %s)' % (sys.exc_info()[1],vlc.libvlc_get_version())) self.player.set_media(media) self.player.play()
def print_version(): """Print version of vlc.py and of libvlc""" try: print('%s: %s (%s)' % (basename(vlc.__file__), vlc.__version__, vlc.build_date)) print('LibVLC version: %s (%#x)' % (vlc.bytes_to_str( vlc.libvlc_get_version()), vlc.libvlc_hex_version())) print('LibVLC compiler: %s' % vlc.bytes_to_str(vlc.libvlc_get_compiler())) if vlc.plugin_path: print('Plugin path: %s' % vlc.plugin_path) except Exception: print('Error: %s' % sys.exc_info()[1])
def get_version(): """Get VLC version. VLC version given by the lib is on the form "x.y.z CodeName" in bytes. Returns: packaging.version.Version: Parsed version of VLC. """ match = re.search(r"(\d+\.\d+\.\d+(?:\.\d+)*)", libvlc_get_version().decode()) if match: return parse(match.group(1)) raise VersionNotFoundError("Unable to get VLC version")
def menuInfo_(self, item): try: self.menuPause_(item) # display Python, vlc, libVLC, media info p = self.player m = p.get_media() t = Table(' Name', ' Value:200', ' Alt:300') t.append('PyCocoa', __PyCocoa__, '20' + __version__) t.append('Python', *_Python) t.append('macOS', *_macOS) t.separator() t.append('vlc.py', vlc.__version__, hex(vlc.hex_version())) b = ' '.join(vlc.build_date.split()[:5]) t.append('built', strftime('%x', strptime(b, '%c')), vlc.build_date) t.separator() t.append('libVLC', bytes2str(vlc.libvlc_get_version()), hex(vlc.libvlc_hex_version())) t.append('libVLC', *bytes2str(vlc.libvlc_get_compiler()).split(None, 1)) t.separator() f = bytes2str(m.get_mrl()) t.append('media', os.path.basename(f), f) if f.startswith('file:///'): z = os.path.getsize(f[7:]) t.append('size', z1000str(z), zSIstr(z)) t.append('state', str(p.get_state())) t.append('track/count', z1000str(p.video_get_track()), z1000str(p.video_get_track_count())) t.append('time/duration', z1000str(p.get_time()), z1000str(m.get_duration())) f = max(p.get_position(), 0) t.append('position', '%.2f%%' % (f * 100,), f) t.separator() f = p.get_fps() t.append('fps/mspf', '%.6f' % (f,), '%.3f ms' % (_mspf(f),)) r = p.get_rate() t.append('rate', '%s%%' % (int(r * 100),), r) w, h = p.video_get_size(0) r = aspect_ratio(w, h) or '' if r: r = '%s:%s' % r t.append('video size', '%sx%s' % (w, h)) # num=0 t.append('aspect ratio', str(p.video_get_aspect_ratio()), r) t.append('scale', '%.3f' % (p.video_get_scale(),), '%.3f' % (self.scale,)) t.display('Python, VLC & Media Information', width=600) except Exception as x: printf('%r', x, nl=1, nt=1)
def setup_backend(cls, vlc_opts=['--no-video-title-show']): """ Prepare/check the VLC backend Args: vlc_opts (`list`): the arguments for starting vlc Returns: `str`: the version of VLC used by the backend """ if IS_WINDOWS and vlc.plugin_path: # let python find the DLLs os.environ['PATH'] = vlc.plugin_path + ';' + os.environ['PATH'] VlcOverlay._instance = vlc.Instance(vlc_opts) return 'VLC {}'.format(vlc.libvlc_get_version().decode('ascii'))
def _createAudioStream(self): """ Create the audio stream player for the video using pyvlc. """ if not os.access(self.filename, os.R_OK): raise RuntimeError('Error: %s file not readable' % self.filename) self._vlc_instance = vlc.Instance('--novideo') try: self._audio_stream = self._vlc_instance.media_new(self.filename) except NameError: raise ImportError('NameError: %s vs LibVLC %s' % (vlc.__version__, vlc.libvlc_get_version())) self._audio_stream_player = self._vlc_instance.media_player_new() self._audio_stream_player.set_media(self._audio_stream) self._audio_stream_event_manager = self._audio_stream_player.event_manager() self._audio_stream_event_manager.event_attach(vlc.EventType.MediaPlayerTimeChanged, _audioTimeCallback, weakref.ref(self), self._audio_stream_player) self._audio_stream_event_manager.event_attach(vlc.EventType.MediaPlayerEndReached, _audioEndCallback, weakref.ref(self))
def check_vlc_version(self): """Print the VLC version and perform some parameter adjustements """ # get and log version self.vlc_version = vlc.libvlc_get_version().decode() logger.info("VLC %s", self.vlc_version) # VLC version is on the form "x.y.z CodeName" # so we split the string to have the version number only version_str, _ = self.vlc_version.split() version = parse_version(version_str) # perform action according to VLC version if version >= parse_version("3.0.0"): # starting from version 3, VLC prioritizes subtitle files that are # nearby the media played, not the ones explicitally added; this # option forces VLC to use the explicitally added files only self.media_parameters_text_screen.append("no-sub-autodetect-file")
def __init__(self, streamDialog=None, parent=None): QtGui.QWidget.__init__(self, parent) self.setMinimumSize(160, 120) self.statusPlayer = 0 self.streamDialog = streamDialog self.playerInitialized = 0 vlcVersionString = QtCore.QString(vlc.libvlc_get_version()) vlcVersion, ok = vlcVersionString[0:3].toFloat() if ok: self.vlcVersion = vlcVersion else: print "vlcVersion not recognized" exit() print "vlcVersion: ", self.vlcVersion if self.vlcVersion >= 1: if sys.platform == "win32": currentPath = QtCore.QDir.toNativeSeparators(QtCore.QDir.currentPath ()) sessionPlugin = str(currentPath) + "\plugins" print "sessionPlugin", sessionPlugin self.vlcInstance = vlc.Instance(["--plugin-path", sessionPlugin]) else: self.vlcInstance = vlc.Instance()
def info_(self, notification): try: self.pause_(notification) p = self.player m = p.get_media() # print Python, vlc, libVLC, media info _printf('PyCocoa %s (%s)', __PyCocoa__, __version__, nl=1) _printf('python %s', ' '.join(_Python)) _printf('macOS %s', ' '.join(_macOS)) _printf('vlc.py %s (%#x)', vlc.__version__, vlc.hex_version()) _printf('built: %s', vlc.build_date) _printf('libVLC %s (%#x)', _b2str(vlc.libvlc_get_version()), vlc.libvlc_hex_version()) _printf('libVLC %s', _b2str(vlc.libvlc_get_compiler()), nt=1) _printf('media: %s', _b2str(m.get_mrl())) _printf('state: %s', p.get_state()) _printf('track/count: %s/%s', p.video_get_track(), p.video_get_track_count()) _printf('time/duration: %s/%s ms', p.get_time(), m.get_duration()) _printf('position/length: %.2f%%/%s ms', p.get_position() * 100.0, p.get_length()) f = p.get_fps() _printf('fps: %.3f (%.3f ms)', f, _mspf(f)) _printf('rate: %s', p.get_rate()) w, h = p.video_get_size(0) r = gcd(w, h) or '' if r and w and h: r = ' (%s:%s)' % (w // r, h // r) _printf('video size: %sx%s%s', w, h, r) # num=0 _printf('aspect ratio: %s', p.video_get_aspect_ratio()) _printf('scale: %.3f (%.3f)', p.video_get_scale(), self.scale) _printf('window: %r', p.get_hwnd(), nt=1) except Exception as x: _printf('%r', x, nl=1, nt=1)
def load_media(self, uri, local=True): """Load a new media file/stream, and whatever else is involved therein""" logger.debug('VLDWidget loading media') ##FIXME: Handle loading of subtitles as well ## If a .srt or similar is placed with the media file, load that and turn them on by default. ## Does VLC do that automatically? ## ## Otherwise turn them off by default, but search for them automatically at http://thesubdb.com/ ## TV stream telx & similar should be turned off by default as well. # VLC detects local vs. remote URIs by simply checking if there is a ':' character in it, this is insufficient. ## FIXME: Actually automate this using better heuristics rather than just passing that test off to the user ## Used urlparse.urlparse for this test in UPMC logger.debug('VLCWidget actually loading media') if local: ## FIXME: bytes() conversion here not necessary for python-vlc 2.2.* ## Should I instead check version at import time and just error out completely if < 2.2? if not vlc.libvlc_get_version().startswith(b'2.2.'): uri = bytes(uri, sys.getfilesystemencoding()) media = self.instance.media_new_path(uri) else: media = self.instance.media_new(uri) media_em = media.event_manager() # I now do this in the __init__ #media_em.event_attach(vlc.EventType.MediaStateChanged, self._on_state_change) # FIXME: Move ParsedChanged into __init__? media_em.event_attach(vlc.EventType.MediaParsedChanged, self._on_parsed) # FIXME: Have a self.metadata dictionary that gets updated when this event triggers. # FIXME: The meta keeps changing without this event being triggered! #media_em.event_attach(vlc.EventType.MediaMetaChanged, lambda _: print('meta_changed')) self.player.set_media(media)
def daemon(): if type(VLC_PARAMETERS_INSTANCE) is not str: raise ValueError('VLC instance parameters must be a string') if type(VLC_PARAMETERS_MEDIA) is not str: raise ValueError('VLC media parameters must be a string') instance = vlc.Instance(VLC_PARAMETERS_INSTANCE) player = instance.media_player_new() player.set_fullscreen(FULLSCREEN_MODE) version = vlc.libvlc_get_version() logging.info("VLC " + version.decode()) logging.info("Daemon started") # load loader template and background loader_bg_path = get_loader_bg_path() loader_text_template = get_loader_text_template() loader_text_path = os.path.join( tempdir, LOADER_TEXT_NAME ) playing_id = None previous_request_time = 0 previous_status = Status.START skip = False loader_status = False loader_end = 0 while True: ## # First case # player is playing # if player.get_state() in ( vlc.State.Playing, vlc.State.Opening, vlc.State.Buffering, vlc.State.Paused ): # if we just switched state, or the previous request we # sent was more than DELAY_BETWEEN_REQUEST seconds ago if previous_status not in ( Status.PLAYING, Status.LOADING, ) or \ time.time() - previous_request_time \ > DELAY_BETWEEN_REQUESTS: # if a loader is playing if loader_status: previous_status = Status.LOADING # if loader duration is elapsed if time.time() - loader_end > LOADER_DURATION: # play the preloaded song player.set_media(media) player.play() loader_status = False # no timing for loader timing = 0 # if a song is playing else: previous_status = Status.PLAYING # get timing timing = player.get_time() if timing == -1: timing = 0 # send status to server previous_request_time = time.time() requested_status = send_status( playing_id, timing, player.get_state() == vlc.State.Paused ) # manage pause request if requested_status["pause"] and \ player.get_state() == vlc.State.Playing: player.pause() logging.info("Player is now paused") elif not requested_status["pause"] and \ player.get_state() == vlc.State.Paused: player.play() logging.info("Player resumed play") # manage skip request if requested_status["skip"]: # wanted to do a simple player.stop() but # it closes the window skip = True ## # Second case # player has stopped or a skip request is issued # if skip or player.get_state() in ( vlc.State.Ended, vlc.State.NothingSpecial, vlc.State.Stopped ): if skip: logging.info("Song skipped") skip = False # if we juste switched states, or the last request we # sent was more than DELAY_BETWEEN_REQUEST seconds ago if previous_status != Status.STOPPED or \ time.time() - previous_request_time \ > DELAY_BETWEEN_REQUESTS: previous_request_time = time.time() # request next music to play from server next_song = send_next_song_status() if next_song: file_path = os.path.join( KARA_FOLDER_PATH, next_song["song"]["file_path"] ) logging.info("New song to play: {}".format( file_path )) # don't check file exists: handling any kind of error # (file missing, invalid file...) in the same place; # see third case below # preload media, play loader instead; # the media will be played after, see # first case playing_id = next_song["id"] media = instance.media_new( "file://" + urllib.parse.quote(file_path) ) media.add_options(VLC_PARAMETERS_MEDIA) loader_status = True loader_end = time.time() + LOADER_DURATION loader = instance.media_new_path( loader_bg_path ) # create custom loader text and save it loader_text = loader_text_template.substitute( title=next_song["song"]["title"], artists=", ".join((a["name"] for a in next_song["song"]["artists"])), works=", ".join(( w["work"]["title"] + (" ({})".format(w["work"]["subtitle"]) if w["work"]["subtitle"] else "") + " - " + w["link_type"] + (str(w["link_type_number"]) if w["link_type_number"] else "") for w in next_song["song"]["works"])) \ if next_song["song"]["works"] else "" ) with open(loader_text_path, 'w', encoding='utf8') as file: file.write(loader_text) player.set_media(loader) player.play() # have to set subtitle after the video started playing player.video_set_subtitle_file(loader_text_path) else: logging.info("Player idle") playing_id = None player.stop() send_status( playing_id, 0, False ) previous_status = Status.STOPPED ## # Third case # error while playing (or not) # if player.get_state() == vlc.State.Error: logging.error("Error while playing {}".format( file_path )) error_message = vlc.libvlc_errmsg().decode() or "No detail" player.stop() send_error(playing_id, error_message) playing_id = None previous_status = Status.ERROR # wait between each loop time.sleep(0.1)
_Adjust = vlc.VideoAdjustOption # Enum # <https://Wiki.VideoLan.org/Documentation:Modules/adjust> _Adjust3 = { _Adjust.Brightness: (0, 1, 2), _Adjust.Contrast: (0, 1, 2), _Adjust.Gamma: (0.01, 1, 10), _Adjust.Hue: (-180, 0, 180), _Adjust.Saturation: (0, 1, 3) } _Argv0 = splitext(basename(__file__))[0] _Movies = '.m4v', '.mov', '.mp4' # lower-case file types for movies, videos _Python = sys.version.split()[0], _platform.architecture()[0] # PYCHOK false _Select = 'Select a video file from the panel' _VLC_3_ = vlc.__version__.split('.')[0] > '2' and \ bytes2str(vlc.libvlc_get_version().split(b'.')[0]) > '2' # <https://Wiki.Videolan.org/Documentation:Modules/marq/#appendix_marq-color> class _Color(object): # PYCHOK expected Aqua = 0x00FFFF Black = 0x000000 Blue = 0x0000FF Fuchsia = 0xFF00FF Gray = 0x808080 Green = 0x008000 Lime = 0x00FF00 Maroon = 0x800000 Navy = 0x000080 Olive = 0x808000 Purple = 0x800080
def menuInfo_(self, item): try: self.menuPause_(item) # display Python, vlc, libVLC, media info table p = self.player m = p.get_media() t = Table(' Name:bold', ' Value:200:Center:center', ' Alt:100') t.append(_Argv0, __version__, '20' + __version__) t.append('PyCocoa', _pycocoa_version, '20' + _pycocoa_version) t.append('Python', *_Python) t.append(*_macOS()) x = 'built-in' if self.window.screen.isBuiltIn else 'external' t.append('screen', x, str(self.window.screen.displayID)) t.separator() t.append('vlc.py', vlc.__version__, hex(vlc.hex_version())) b = ' '.join(vlc.build_date.split()[:5]) t.append('built', strftime('%x', strptime(b, '%c')), vlc.build_date) t.separator() t.append('libVLC', bytes2str(vlc.libvlc_get_version()), hex(vlc.libvlc_hex_version())) t.append('libVLC', *bytes2str(vlc.libvlc_get_compiler()).split(None, 1)) t.separator() f = mrl_unquote(bytes2str(m.get_mrl())) t.append('media', basename(f), f) if f.lower().startswith('file://'): z = getsize(f[7:]) t.append('size', z1000str(z), zSIstr(z)) t.append('state', str(p.get_state())) f = max(p.get_position(), 0) t.append('position/length', '%.2f%%' % (f * 100, ), _ms2str(p.get_length())) f = map(_ms2str, (p.get_time(), m.get_duration())) t.append('time/duration', *f) t.append('track/count', z1000str(p.video_get_track()), z1000str(p.video_get_track_count())) t.separator() f = p.get_fps() t.append('fps/mspf', '%.6f' % (f, ), '%.3f ms' % (_mspf(f), )) r = p.get_rate() t.append('rate', '%s%%' % (int(r * 100), ), r) w, h = p.video_get_size(0) t.append('video size', _ratio2str('x', w, h)) # num=0 r = _ratio2str(':', *aspect_ratio(w, h)) # p.video_get_aspect_ratio() t.append('aspect ratio', r, _ratio2str(':', *self.window.ratio)) t.append('scale', '%.3f' % (p.video_get_scale(), ), '%.3f' % (self.scale, )) t.separator() def VLCadjustr2(option): # get option value lo, _, hi = _Adjust3[option] f = self.player.video_get_adjust_float(option) p = max(0, (f - lo)) * 100.0 / (hi - lo) t = '%.2f %.1f%%' % (f, p) # return 2-tuple (value, percentage) as strings return t.replace('.0%', '%').replace('.00', '.0').split() t.append('brightness', *VLCadjustr2(_Adjust.Brightness)) t.append('contrast', *VLCadjustr2(_Adjust.Contrast)) t.append('gamma', *VLCadjustr2(_Adjust.Gamma)) t.append('hue', *VLCadjustr2(_Adjust.Hue)) t.append('saturation', *VLCadjustr2(_Adjust.Saturation)) t.separator() s = vlc.MediaStats() # re-use single MediaStats instance? if m.get_stats(s): def Kops2bpstr2(bitrate): # convert Ko/s to bits/sec # bitrates are conventionally in kilo-octets-per-sec return zSIstr(bitrate * 8000, B='bps', K=1000).split() t.append('media read', *zSIstr(s.read_bytes).split()) t.append('input bitrate', *Kops2bpstr2(s.input_bitrate)) if s.input_bitrate > 0: # XXX approximate caching, based # on <https://GitHub.com/oaubert/python-vlc/issues/61> b = s.read_bytes - s.demux_read_bytes t.append('input caching', _ms2str(b / s.input_bitrate), zSIstr(b)) t.append('demux read', *zSIstr(s.demux_read_bytes).split()) t.append('stream bitrate', *Kops2bpstr2(s.demux_bitrate)) t.append('video decoded', z1000str(s.decoded_video), 'blocks') t.append('video played', z1000str(s.displayed_pictures), 'frames') t.append('video lost', z1000str(s.lost_pictures), 'frames') t.append('audio decoded', z1000str(s.decoded_audio), 'blocks') t.append('audio played', z1000str(s.played_abuffers), 'buffers') t.append('audio lost', z1000str(s.lost_abuffers), 'buffers') t.display('Python, VLC & Media Information', width=500) except Exception as x: if self.raiser: raise printf('%s', x, nl=1, nt=1)
def _vlc_start(self): """ Create the vlc stream player for the video using python-vlc. """ if not os.access(self.filename, os.R_OK): raise RuntimeError('Error: %s file not readable' % self.filename) if self.no_audio: instance = vlc.Instance("--no-audio") else: instance = vlc.Instance() try: stream = instance.media_new(self.filename) except NameError: msg = 'NameError: %s vs LibVLC %s' raise ImportError(msg % (vlc.__version__, vlc.libvlc_get_version())) player = instance.media_player_new() player.set_media(stream) # Load up the file stream.parse() size = player.video_get_size() self.video_width = size[0] self.video_height = size[1] self.frame_rate = player.get_fps() self.frame_counter = 0 # TODO: Why is duration -1 still even after parsing? Newer vlc docs seem to hint this won't work until playback starts duration = player.get_length() logging.warning( "Video is %ix%i, duration %s, fps %s" % (self.video_width, self.video_height, duration, self.frame_rate)) logging.flush() # We assume we can use the RGBA format here player.video_set_format("RGBA", self.video_width, self.video_height, self.video_width << 2) # Configure a lock and a buffer for the pixels coming from VLC self.pixel_lock = threading.Lock() self.pixel_buffer = (ctypes.c_ubyte * self.video_width * self.video_height * 4)() # Once you set these callbacks, you are in complete control of what to do with the video buffer selfref = ctypes.cast(ctypes.pointer(ctypes.py_object(self)), ctypes.c_void_p) player.video_set_callbacks(vlcLockCallback, vlcUnlockCallback, vlcDisplayCallback, selfref) manager = player.event_manager() manager.event_attach(vlc.EventType.MediaPlayerTimeChanged, vlcTimeCallback, weakref.ref(self), player) manager.event_attach(vlc.EventType.MediaPlayerEndReached, vlcEndReached, weakref.ref(self), player) # Keep references self._self_ref = selfref self._instance = instance self._player = player self._stream = stream self._manager = manager logging.info("Initialized VLC...") self._vlc_initialized = True
def do_play(self): return False def do_play_pause(self): return False VideoOverlay._backends['image/gif'] = GifOverlay VideoOverlay._backend_versions.append(_('GtkImage gif player')) try: import vlc vlc_opts = ['--no-video-title-show'] if IS_POSIX: vlc_opts.append('--no-xlib') elif IS_WINDOWS and vlc.plugin_path: # let python find the DLLs os.environ['PATH'] = vlc.plugin_path + ';' + os.environ['PATH'] VLCVideo._instance = vlc.Instance(vlc_opts) # make VLCvideo the fallback VideoOverlay._backends = defaultdict(lambda: VLCVideo, VideoOverlay._backends) VideoOverlay._backend_versions.append('VLC {}'.format( vlc.libvlc_get_version().decode('ascii'))) except: logger.exception(_("Video support using VLC is disabled."))
def record(self): filepath = 'https://rt-news.secure.footprint.net/1103.m3u8' movie = os.path.expanduser(filepath) if 'https://' not in filepath: if not os.access(movie, os.R_OK): msg = 'Error: %s file is not readable' % movie print msg self.logger.error(msg) return recording_duration = self.interval # while (1): filename_record = "records/1103_" + datetime.datetime.now().strftime("%Y-%m-%d-%H-%M-%S") + "_recording.mp3" filename_record_final = "records/1103_" + datetime.datetime.now().strftime("%Y-%m-%d-%H-%M-%S") + ".mp3" msg = "Starting recording to file %s" % filename_record print msg self.logger.info(msg) filename_and_command = "--sout=#transcode{vcodec=none,acodec=mp3,ab=320,channels=2,samplerate=44100}:file{dst=" + filename_record + "}" print filename_and_command # filename_and_command = "--sout=file/ts:example" + str(clipNumber) + ".mp3" instance = vlc.Instance(filename_and_command) try: media = instance.media_new(movie) except NameError: msg = 'NameError: % (%s vs Libvlc %s)' % (sys.exc_info()[1], vlc.__version__, vlc.libvlc_get_version()) print msg self.logger.error(msg) return player = instance.media_player_new() player.set_media(media) player.play() time.sleep(recording_duration) # exit() player.stop() os.rename(filename_record, filename_record_final) msg = "Ending recording to file" print (msg) self.logger.info(msg)
import time #http://streamer64.eboundservices.com/geo/geonews_abr/playlist.m3u8 #http://app.pakistanvision.tv:1935/live/PTVnews/player.m3u8 #http://demo.codesamplez.com/html5/video/sample clipNumber = sys.argv[1] filepath = 'http://app.pakistanvision.tv:1935/live/PTVnews/player.m3u8' movie = os.path.expanduser(filepath) if 'http://' not in filepath: if not os.access(movie, os.R_OK): print('Error: %s file is not readable' % movie) sys.exit(1) while (1): filename_and_command = "--sout=#transcode{vcodec=none,acodec=mp3,ab=320,channels=2,samplerate=44100}:file{dst=example" + str( clipNumber) + ".mp3}" # filename_and_command = "--sout=file/ts:example" + str(clipNumber) + ".mp3" instance = vlc.Instance(filename_and_command) try: media = instance.media_new(movie) except NameError: print('NameError: % (%s vs Libvlc %s)' % (sys.exc_info()[1], vlc.__version__, vlc.libvlc_get_version())) sys.exit(1) player = instance.media_player_new() player.set_media(media) player.play() time.sleep(15) exit()
def _openMedia(self, uri=None): """Internal method that opens a new stream using `filename`. This will close the previous stream. Raises an error if a VLC instance is not available. """ # if None, use `filename` uri = self.filename if uri is None else uri # create a fresh VLC instance self._createVLCInstance() # raise error if there is no VLC instance if self._instance is None: errmsg = "Cannot open a stream without a VLC instance started." logging.fatal(errmsg, obj=self) logging.flush() # check if we have a player, stop it if so if self._player is None: errmsg = "Cannot open a stream without a VLC media player." logging.fatal(errmsg, obj=self) logging.flush() else: self._player.stop() # stop any playback # check if the file is valid and readable if not os.access(uri, os.R_OK): raise RuntimeError('Error: %s file not readable' % uri) # close the previous VLC resources if needed if self._stream is not None: self._stream.release() # open the file and create a new stream try: self._stream = self._instance.media_new(uri) except NameError: raise ImportError('NameError: %s vs LibVLC %s' % ( vlc.__version__, vlc.libvlc_get_version())) # player object self._player.set_media(self._stream) # set media related attributes self._stream.parse() videoWidth, videoHeight = self._player.video_get_size() self._videoWidth = videoWidth self._videoHeight = videoHeight # set the video size if self._useFrameSizeFromVideo: self.size = self._origSize = numpy.array( (self._videoWidth, self._videoHeight), float) self._frameRate = self._player.get_fps() self._frameCounter = self._loopCount = 0 self._streamEnded = False # uncomment if not using direct GPU write, might be more thread-safe self._framePixelBuffer = ( ctypes.c_ubyte * self._videoWidth * self._videoHeight * 4)() # duration unavailable until started duration = self._player.get_length() logging.info("Video is %ix%i, duration %s, fps %s" % ( self._videoWidth, self._videoHeight, duration, self._frameRate)) logging.flush() # We assume we can use the RGBA format here self._player.video_set_format( "RGBA", self._videoWidth, self._videoHeight, self._videoWidth << 2) # setup texture buffers before binding the callbacks self._setupTextureBuffers() # Set callbacks since we have the resources to write to. thisInstance = ctypes.cast( ctypes.pointer(ctypes.py_object(self)), ctypes.c_void_p) self._player.video_set_callbacks( vlcLockCallback, vlcUnlockCallback, vlcDisplayCallback, thisInstance)
def get_vlc_version(): return vlc.libvlc_get_version()
import os import sys import vlc if __name__ == '__main__': filepath = "iwyb.mp3" movie = os.path.expanduser(filepath) if 'http://' not in filepath: if not os.access(movie, os.R_OK): print ( 'Error: %s file is not readable' % movie ) sys.exit(1) instance = vlc.Instance("--aout=alsa", "--alsa-audio-device=default") try: media = instance.media_new(movie) except NameError: print ('NameError: % (%s vs Libvlc %s)' % (sys.exc_info()[1], vlc.__version__, vlc.libvlc_get_version())) sys.exit(1) player = instance.media_player_new() player.set_media(media) player.play() #dont exit! # p = vlc.MediaPlayer("rr.mp3") # p.play() while(1): continue
def test_backends(self): found = 0 try: import gst import pygst found += 1 self.add_success( 'PyGST is available', "PyGST was found and GStreamer should be " "available in TV-Maxe.") except: self.add_warning( 'PyGST cannot be imported', "Seems that GStreamer is either not installed or " "the corresponding Python bindings are not " "available. Please install proper packages from " "your distribution repositories if you want " "GStreamer support in TV-Maxe.") try: import vlc try: v = vlc.libvlc_get_version().split()[0] if int(v.replace('.', '')) < 110: self.add_warning( "Old libVLC", "Your VLC installation is old. At least " "version 1.1.0 is required for TV-Maxe " "to work with VLC backend.") else: found += 1 self.add_success( 'VLC is available', "VLC was found in your system and seems " "to be fully functional.") except: self.add_warning( 'Couldn\'t determine VLC version', "VLC was found, but its version couldn't be " "determined. VLC backend may not work.") except: self.add_warning( 'VLC was not found', "libVLC was not found; playing streams using " "VLC-tvmx backend will not be available.") try: p = subprocess.Popen('mplayer', stdout=subprocess.PIPE, stderr=subprocess.PIPE) p.wait() if not p.poll(): found += 1 self.add_success( 'MPlayer is available', "MPlayer was found and should be available as TV-Maxe " "backend.") else: self.add_warning( 'MPlayer error', "MPlayer was found but doesn't seems to be " "working. Please run mplayer from Terminal " "for more details.") except: self.add_warning( 'MPLayer not found', "MPlayer was not found; playing streams using " "MPlayer as backend will not be available.") if not found: self.add_error('No backend available', "No backend found. Playing streams will not work.") self.do_next_test()
def display(data, id): img = cv2.CreateImage((VIDEO_WIDTH, VIDEO_HEIGHT), IPL_DEPTH_8U, 4) img.imageData = videobuf cv2.ShowImage(vlc.libvlc_get_version(), img) cv2.WaitKey(10) cv2.ReleaseImage(img)
def menuInfo_(self, item): try: self.menuPause_(item) # display Python, vlc, libVLC, media info p = self.player m = p.get_media() t = Table(' Name:bold', ' Value:200:Center:center', ' Alt:300') t.append('cocoavlc', __version__, '20' + __version__) t.append('PyCocoa', __PyCocoa__, '20' + __PyCocoa__) t.append('Python', *_Python) t.append('macOS', *_macOS) t.separator() t.append('vlc.py', vlc.__version__, hex(vlc.hex_version())) b = ' '.join(vlc.build_date.split()[:5]) t.append('built', strftime('%x', strptime(b, '%c')), vlc.build_date) t.separator() t.append('libVLC', bytes2str(vlc.libvlc_get_version()), hex(vlc.libvlc_hex_version())) t.append('libVLC', *bytes2str(vlc.libvlc_get_compiler()).split(None, 1)) t.separator() f = bytes2str(m.get_mrl()) t.append('media', os.path.basename(f), f) if f.startswith('file:///'): z = os.path.getsize(f[7:]) t.append('size', z1000str(z), zSIstr(z)) t.append('state', str(p.get_state())) t.append('track/count', z1000str(p.video_get_track()), z1000str(p.video_get_track_count())) t.append('time/duration', z1000str(p.get_time()), z1000str(m.get_duration())) f = max(p.get_position(), 0) t.append('position', '%.2f%%' % (f * 100,), f) t.separator() f = p.get_fps() t.append('fps/mspf', '%.6f' % (f,), '%.3f ms' % (_mspf(f),)) r = p.get_rate() t.append('rate', '%s%%' % (int(r * 100),), r) w, h = p.video_get_size(0) r = aspect_ratio(w, h) or '' if r: r = '%s:%s' % r t.append('video size', '%sx%s' % (w, h)) # num=0 t.append('aspect ratio', str(p.video_get_aspect_ratio()), r) t.append('scale', '%.3f' % (p.video_get_scale(),), '%.3f' % (self.scale,)) t.separator() def _VLCadjustr2(option): lo, _, hi = _Adjust3[option] f = self.player.video_get_adjust_float(option) p = max(0, (f - lo)) * 100.0 / (hi - lo) t = '%.2f %.1f%%' % (f, p) return t.replace('.0%', '%').replace('.00', '.0').split() t.append('brightness', *_VLCadjustr2(_Adjust.Brightness)) t.append('contrast', *_VLCadjustr2(_Adjust.Contrast)) t.append('gamma', *_VLCadjustr2(_Adjust.Gamma)) t.append('hue', *_VLCadjustr2(_Adjust.Hue)) t.append('saturation', *_VLCadjustr2(_Adjust.Saturation)) t.separator() t.display('Python, VLC & Media Information', width=600) except Exception as x: printf('%r', x, nl=1, nt=1)
args = parser.parse_args() config = "--aout=alsa " if args.test: # when we are testing the url, don't use real output, we don't want extra playback config += " --alsa-audio-device null" elif args.output: alsa_device = args.output config += " --alsa-audio-device {}".format(alsa_device) instance = vlc.Instance(config.split()) try: media = instance.media_new(args.url) except (AttributeError, NameError) as e: print('%s: %s (%s LibVLC %s)' % (e.__class__.__name__, e, sys.argv[0], vlc.libvlc_get_version())) sys.exit(1) player = instance.media_player_new() player.set_media(media) player.play() if args.song_info: try: f = open(args.song_info, "wt") f.write(json.dumps({"state": str(player.get_state())})) f.close() except Exception: print(sys.exc_info()) exit(1) # Allow stream to start playing time.sleep(2)
def test_backends(self): found = 0 try: import gst import pygst found += 1 self.add_success('PyGST is available', "PyGST was found and GStreamer should be " "available in TV-Maxe.") except: self.add_warning('PyGST cannot be imported', "Seems that GStreamer is either not installed or " "the corresponding Python bindings are not " "available. Please install proper packages from " "your distribution repositories if you want " "GStreamer support in TV-Maxe.") try: import vlc try: v = vlc.libvlc_get_version().split()[0] if int(v.replace('.', '')) < 110: self.add_warning("Old libVLC", "Your VLC installation is old. At least " "version 1.1.0 is required for TV-Maxe " "to work with VLC backend.") else: found += 1 self.add_success('VLC is available', "VLC was found in your system and seems " "to be fully functional.") except: self.add_warning('Couldn\'t determine VLC version', "VLC was found, but its version couldn't be " "determined. VLC backend may not work.") except: self.add_warning('VLC was not found', "libVLC was not found; playing streams using " "VLC-tvmx backend will not be available.") try: p = subprocess.Popen( 'mplayer', stdout=subprocess.PIPE, stderr=subprocess.PIPE ) p.wait() if not p.poll(): found += 1 self.add_success( 'MPlayer is available', "MPlayer was found and should be available as TV-Maxe " "backend." ) else: self.add_warning('MPlayer error', "MPlayer was found but doesn't seems to be " "working. Please run mplayer from Terminal " "for more details.") except: self.add_warning('MPLayer not found', "MPlayer was not found; playing streams using " "MPlayer as backend will not be available.") if not found: self.add_error('No backend available', "No backend found. Playing streams will not work.") self.do_next_test()
def testnext(pipes): """ Move to next pipe to test """ global pipe_to_test if pipe_to_test is not None: pipes.append(pipe_to_test) pipe_to_test = pipes.pop(0) attachvlc(pipe_to_test) if __name__ == "__main__": print("HTTP Stream strainer by Markus Vuorio, 2013") print("Using VLC version " + vlc.libvlc_get_version()) if len(sys.argv) < 2: print("Use: " + sys.argv[0] + " http://your/url") sys.exit(1) url = sys.argv[1] pipes = [] runwget(url, pipes) testedpipes = 0 total_corrupted = 0 start_time = time.time() last_time = time.time() testnext(pipes) try:
runtime = time.time() - start_time allstats['decoded_delta'] += runtime - stats.decoded_video def testnext(pipes): """ Move to next pipe to test """ global pipe_to_test if pipe_to_test is not None: pipes.append(pipe_to_test) pipe_to_test = pipes.pop(0) attachvlc(pipe_to_test) if __name__ == "__main__": print("HTTP Stream strainer by Markus Vuorio, 2013") print("Using VLC version " + vlc.libvlc_get_version()) if len(sys.argv) < 2: print("Use: " + sys.argv[0] + " http://your/url") sys.exit(1) url = sys.argv[1] pipes = [] runwget(url, pipes) testedpipes = 0 total_corrupted = 0 start_time = time.time() last_time = time.time() testnext(pipes) try: