def get_duration(in_filename: str): ff = FFprobe( executable=os.path.join(settings.AudioTools.DIRECTORY, 'ffprobe'), inputs={in_filename: None}, global_options=['-print_format', 'json', '-show_format'] ) stdout = None # TODO: Use json from stdout if in_filename: stdout, stderr = ff.run(input_data=open(in_filename, 'br').read(), stdout=subprocess.PIPE, stderr=subprocess.PIPE) elif in_content: stdout, stderr = ff.run(input_data=in_content, stdout=subprocess.PIPE, stderr=subprocess.PIPE) duration = None for o in str(stderr).split('\\n'): if 'Duration' in o and 'misdetection' not in o: duration = o.split()[1][:-1].split(':') # here goes magic => time['h', 'm', 's'] break if duration: duration = float(duration[0]) * 3600 + float(duration[1]) * 60 + float(duration[2]) if duration < 1: duration = 1 else: duration = 0 return duration
def is_audio(inputPath): print("THIS ISN'T A VIDEO FILE\n" '¿maybe this is an audio file?') # DO THE SAME AS ABOVE BUT '-select_streams a:0' # ... HOPEFULLY IF v:0 DOESN'T EXIST BUT a:0 DOES, # YOU HAVE AN AUDIO FILE ON YOUR HANDS. WILL HAVE # TO CONFIRM... COULD THIS RETURN TRUE IF v:0 IS BROKEN/CORRUPT? ffprobe = FFprobe(inputs={ inputPath: '-v error -print_format json -show_streams -select_streams a:0' }) try: FR = ffprobe.run(stdout=subprocess.PIPE) output = json.loads(FR[0].decode('utf-8')) try: indexValue = output['streams'][0]['index'] if indexValue == 0: print("This appears to be an audio file!") return True except: print("THIS DOESN'T SMELL LIKE AN AUDIO FILE EITHER") print(output) return False except: print("INVALID FILE INPUT, NOT AUDIO EITHER") return False
def get_duration(in_filename: str): ff = FFprobe(executable=os.path.join(settings.AudioTools.DIRECTORY, 'ffprobe'), inputs={in_filename: None}, global_options=['-print_format', 'json', '-show_format']) stdout = None # TODO: Use json from stdout if in_filename: stdout, stderr = ff.run(input_data=open(in_filename, 'br').read(), stdout=subprocess.PIPE, stderr=subprocess.PIPE) elif in_content: stdout, stderr = ff.run(input_data=in_content, stdout=subprocess.PIPE, stderr=subprocess.PIPE) duration = None for o in str(stderr).split('\\n'): if 'Duration' in o and 'misdetection' not in o: duration = o.split()[1][:-1].split( ':') # here goes magic => time['h', 'm', 's'] break if duration: duration = float(duration[0]) * 3600 + float( duration[1]) * 60 + float(duration[2]) if duration < 1: duration = 1 else: duration = 0 return duration
def get_stream(num, clist, uri): try: ffprobe = FFprobe(inputs={uri: '-v error -show_format -show_streams -print_format json'}) cdata = json.loads(ffprobe.run(stdout=PIPE,stderr=PIPE)[0].decode('utf-8')) return cdata except Exception as e: #traceback.print_exc() print('[{}] {}({}) Error:{}'.format(str(num), clist[0], clist[2], str(e))) return False
def get_info(input_=None, print_=False, **kwargs): _input_opts = Effmpeg._common_ffmpeg_args[:] _inputs = {input_.path: _input_opts} ff = FFprobe(inputs=_inputs) out = ff.run(stdout=subprocess.PIPE, stderr=subprocess.STDOUT)[0].decode('utf-8') if print_: print(out) else: return out
def get_info(input_=None, print_=False, **kwargs): """ Get video Info """ _input_opts = Effmpeg._common_ffmpeg_args[:] _inputs = {input_.path: _input_opts} ffp = FFprobe(inputs=_inputs) out = ffp.run(stdout=subprocess.PIPE, stderr=subprocess.STDOUT)[0].decode('utf-8') if print_: logger.info(out) logger.debug(out) return out
def is_music_file(path: str, ffprobe: str = "ffprobe") -> bool: """Returns True if path is identifiable as a music file.""" if not os.path.exists(path): raise ValueError("No such file or directory: %s" % (repr(path),)) with open(os.devnull, "w") as nullsink: ff = FFprobe( executable = ffprobe, inputs = { path: None }, ) try: ff.run(stdout = nullsink, stderr = nullsink) return True except FFRuntimeError: return False
def get_fps(input_=None, print_=False, **kwargs): _input_opts = '-v error -select_streams v -of ' _input_opts += 'default=noprint_wrappers=1:nokey=1 ' _input_opts += '-show_entries stream=r_frame_rate' if type(input_) == str: _inputs = {input_: _input_opts} else: _inputs = {input_.path: _input_opts} ff = FFprobe(inputs=_inputs) _fps = ff.run(stdout=subprocess.PIPE)[0].decode("utf-8") _fps = _fps.strip() if print_: print("Video fps:", _fps) else: return _fps
def get_fps(input_=None, print_=False, **kwargs): """ Get Frames per Second """ _input_opts = '-v error -select_streams v -of ' _input_opts += 'default=noprint_wrappers=1:nokey=1 ' _input_opts += '-show_entries stream=r_frame_rate' if isinstance(input_, str): _inputs = {input_: _input_opts} else: _inputs = {input_.path: _input_opts} ffp = FFprobe(inputs=_inputs) _fps = ffp.run(stdout=subprocess.PIPE)[0].decode("utf-8") _fps = _fps.strip() if print_: logger.info("Video fps: %s", _fps) logger.debug(_fps) return _fps
def get_tag(self, tag): assert tag in self.__tags, '"%s" tag is not supported' % tag if tag not in self.__gets: result = [] for file in self.videofiles: ff = FFprobe( inputs={ file: [ '-v', 'error', '-show_entries', 'format_tags={}'.format(tag), '-of', 'default=noprint_wrappers=1:nokey=1' ] }) with Popen(ff.cmd, stderr=PIPE, stdout=PIPE, shell=True) as proc: file_tag = proc.communicate()[0].decode()[:-1] result.append(file_tag if file_tag else None) if result and len(result) == 1: self.__gets[tag] = result[0] # single file tag elif result: self.__gets[tag] = result # list of tags else: self.__gets[tag] = None # no tag was found return self.__gets[tag]
def check_channel(channel, verbose=False): title = channel.title def print_failed(): print('\r{}{:22} {}'.format(ERASE_LINE, title, colored('FAILED', 'red', attrs=['bold']))) try: print('{:22} checking'.format(title), end='') stdout.flush() channel_uri = channel.absolute_uri try: channel_playlist = m3u8.load(channel_uri) except HTTPError as error: print_failed() if verbose: print(colored(channel_uri, 'red')) print(error) print() return False segment_uri = channel_playlist.segments[-1].absolute_uri ffprobe = FFprobe(inputs={segment_uri: '-v warning'}) errors = tuple( filter( lambda line: not (line in ('', RESET) or any( regex.search(line) for regex in SKIP_FFPROBE_MESSAGES)), ffprobe.run(stderr=PIPE)[1].decode('utf-8').split('\n'))) if errors: print_failed() if verbose: print(colored(channel_uri, 'green')) print(colored(segment_uri, 'red')) print('\n'.join(errors)) print('' if os.getenv('ANSI_COLORS_DISABLED') else RESET) return False except KeyboardInterrupt as interrupt: raise interrupt except: print_failed() if verbose: traceback.print_exc() return False print('\r{}{:22} {}'.format(ERASE_LINE, title, colored('OK', 'green', attrs=['bold']))) return True
def read_metadata(self): """ Obtain metadata of the video file in JSON format using FFprobe from FFMPEG. :Example of equivalent of FFprobe command and its output: > ffprobe.exe -v quiet -of json -show_format -show_private_data -i video.mp4 { "format": { "filename": "drive:\\path\\to\\video.mp4", "nb_streams": 2, "nb_programs": 0, "format_name": "mov,mp4,m4a,3gp,3g2,mj2", "format_long_name": "QuickTime / MOV", "start_time": "0.000000", "duration": "7.531000", "size": "5164288", "bit_rate": "5485898", "probe_score": 100, "tags": { "major_brand": "isom", "minor_version": "512", "compatible_brands": "isomiso2avc1mp41", "title": "nice title", "album": "52.3005585,4.67532055295702,hoofddorp,the netherlands", "encoder": "Lavf58.17.101", "comment": "some comment", "copyright": "2017-01-29 21:29:29", "grouping": "tag1 tag2", "description": "some description" } } } """ ffprobe = FFprobe(self.ffprobe, global_options=['-v', 'quiet', '-print_format', 'json', '-show_format', '-show_private_data'], inputs={self.path: None}) logging.debug('Running FFprobe command "%s".' % ffprobe.cmd) stdout = '{}' try: stdout = ffprobe.run(stdout=subprocess.PIPE)[0] except FFRuntimeError as err: logging.error('FFprobe command failed due to: %s.' % err) except FFExecutableNotFoundError as err: logging.error('FFprobe command "%s" failed due to: %s.' % (ffprobe.cmd, err)) return json.loads(stdout)
def get_fps(input_=None, print_=False, **kwargs): """ Get Frames per Second """ _input_opts = '-v error -select_streams v -of ' _input_opts += 'default=noprint_wrappers=1:nokey=1 ' _input_opts += '-show_entries stream=r_frame_rate' if isinstance(input_, str): _inputs = {input_: _input_opts} else: _inputs = {input_.path: _input_opts} logger.debug(_inputs) ffp = FFprobe(inputs=_inputs) _fps = ffp.run(stdout=subprocess.PIPE)[0].decode("utf-8") _fps = _fps.strip() if "/" in _fps: _fps = _fps.split("/") _fps = str(round(int(_fps[0])/int(_fps[1]), 2)) if print_: logger.info("Video fps: %s", _fps) logger.debug(_fps) return _fps
def duration(self): ff = FFprobe( inputs={ self.pathname: [ '-v', 'error', '-show_entries', 'format=duration', '-of', 'default=noprint_wrappers=1:nokey=1' ] }) with Popen(ff.cmd, stderr=PIPE, stdout=PIPE, shell=True) as proc: mili_dur = round(float(proc.communicate()[0].decode())) * 1000 return mili_dur
def is_video(inputPath): # THIS WILL RETURN TRUE IF FILE IS VIDEO BECAUSE # YOU ARE TELLING FFPROBE TO LOOK FOR VIDEO STREAM # WITH INDEX=0, AND IF v:0 DOES NOT EXIST, # ISPO FACTO, YOU DON'T HAVE A RECOGNIZED VIDEO FILE. ffprobe = FFprobe(inputs={ inputPath: '-v error -print_format json -show_streams -select_streams v:0' }) try: FR = ffprobe.run(stdout=subprocess.PIPE) output = json.loads(FR[0].decode('utf-8')) # print(output) try: indexValue = output['streams'][0]['index'] if indexValue == 0: return True except: return False except: return False
def num_of_subs(self): # How many streams of subtitles the video has ff = FFprobe( inputs={ self.pathname: [ '-v', 'error', '-select_streams', 's', '-show_entries', 'stream=index', '-of', 'default=noprint_wrappers=1:nokey=1' ] }) with Popen(ff.cmd, stderr=PIPE, stdout=PIPE, shell=True) as proc: sub_streams = proc.communicate()[0].decode().split( ) # list of subtitles streams return len(sub_streams)
def video_duration(vid_path): """ Get duration of video in seconds """ # Build ffprobe command inputs = {vid_path: None} options = '-show_entries stream=r_frame_rate,nb_read_frames -select_streams v -count_frames -of compact=p=0:nk=1 -v 0' ff = FFprobe(global_options=options, inputs=inputs) get_dur = ff.cmd # Run the ffprobe command in a subprocess result = subprocess.check_output(get_dur.split()) result = result.rstrip() # Strip newline character from output num_frames = float( result.split('|')[1]) # Since output of command is like "25/1|69" frame_rate = result.split('|')[0].split('/') vid_duration = num_frames / (float(frame_rate[0]) / float(frame_rate[1])) return vid_duration
def get_info(self): ff = FFprobe(inputs={self.filename: None}) info = ff.run(stderr=subprocess.PIPE) ## Parse Info self.bitrate = re.search(".?bitrate:\s([0-9]*)\skb/s", str(info)).group().strip()