def _probe(video_file): if hasattr(video_file, 'read'): out = ffprobe("pipe:0", _in=video_file.read(), _in_bufsize=1024).stderr video_file.seek(0) else: out = ffprobe(video_file) if len(out) > 0: return out return out.stderr
def get_video_duration(file): """ Returns the duration of a video file in timedelta. """ time = None try: if arch in ('armv6l', 'armv7l'): run_player = omxplayer(file, info=True, _err_to_out=True, _ok_code=[0, 1], _decode_errors='ignore') else: run_player = ffprobe('-i', file, _err_to_out=True) except sh.ErrorReturnCode_1: raise Exception('Bad video format') for line in run_player.split('\n'): if 'Duration' in line: match = re.search(r'[0-9]+:[0-9]+:[0-9]+\.[0-9]+', line) if match: time_input = match.group() time_split = time_input.split(':') hours = int(time_split[0]) minutes = int(time_split[1]) seconds = float(time_split[2]) time = timedelta(hours=hours, minutes=minutes, seconds=seconds) break return time
def media_duration(path): re_duration = re.compile('^ *Duration: (\d+):(\d+):(\d+)(\.\d+),') output = sh.ffprobe('-hide_banner', path).stderr.decode('utf-8') lines = list(filter(lambda l: re_duration.match(l), output.split('\n'))) if len(lines) == 1: m = re_duration.match(lines[0]) return (float(m[1])*60*60) + \ (float(m[2])*60) + \ (float(m[3])) + float(m[4]) else: raise Exception('Unexpected output from ffprobe: %s' % output)
def probe(input_fname): """Use ffprobe to get video file metadata.""" try: probe = sh.ffprobe('-print_format', 'json', '-show_format', '-show_streams', input_fname) except sh.ErrorReturnCode_1 as e: print('error running ffprobe:\n' f'RUN:\n{e.full_cmd}\n\n' f'STDOUT:\n{e.stdout}\n\n' f'STDERR:\n{e.stderr}') sys.exit(1) probe_meta = json.loads(probe.stdout) metadata = {} # Copy video metadata. video_meta = probe_meta['streams'][0] if video_meta['codec_type'] != 'video': print('stream 0 is not video') sys.exit(1) vmeta = {} common_meta = ['codec_name', 'bit_rate', 'duration'] # Not sure how to specify chroma location in encoding. # But X-T3 HEVC output video have chroma_location unspecified, maybe this # is not important. for k in common_meta + [ 'avg_frame_rate', 'pix_fmt', 'color_range', 'color_space', 'color_transfer', 'color_primaries', 'chroma_location' ]: vmeta[k] = video_meta.get(k, None) metadata['video'] = vmeta audio_meta = probe_meta['streams'][1] if audio_meta['codec_type'] != 'audio': print('stream 1 is not audio') sys.exit(1) ameta = {} for k in common_meta + ['sample_rate']: ameta[k] = audio_meta[k] metadata['audio'] = ameta return metadata
# boucle sur les fichiers récupérés for filename in os.listdir(temp_dir): if filename.endswith(".mp3"): cnt_f = cnt_f + 1 # reencode pour prendre moins de place subprocess.call([ 'lame', '--mp3input', '-b', '32', temp_dir + "/" + filename, temp_dir + "/B_" + filename ], shell=False) os.rename(temp_dir + "/B_" + filename, temp_dir + "/" + filename) # construction des items à ajouter dans le feed.xml titre = sh.cut( sh.grep( sh.ffprobe("-v", "error", "-show_format", temp_dir + "/" + filename), "title"), "-d", "=", "-f2") titre = str(titre) titre = titre.replace('\n', '') fichier = open(temp_dir + "/" + "items.xml", "a") fichier.write("<item>\n") fichier.write("<title><![CDATA[" + titre + "]]></title>\n") fichier.write( "<link>https://raw.githubusercontent.com/tcaenen/tt_pod/master/media/" + filename + "</link>\n") fichier.write( '<enclosure url="https://raw.githubusercontent.com/tcaenen/tt_pod/master/media/' + filename + '" length="30066338" type="audio/mpeg"></enclosure>\n') fichier.write( "<guid>https://raw.githubusercontent.com/tcaenen/tt_pod/master/media/"
def burst_frames_to_shm(vid_path, temp_burst_dir, frame_size=-1, frame_rate=-1, frame_uniform=-1): """ - To burst frames in a temporary directory in shared memory. - Directory name is chosen as random 128 bits so as to avoid clash during parallelization - Returns path to directory containing frames for the specific video """ target_mask = os.path.join(temp_burst_dir, '%06d.bmp') if not os.system('ffmpeg -version > /dev/null') == 0: raise FFMPEGNotFound() try: if frame_size > 0 or frame_uniform > 0: ffprobe_args = [ '-v', 'error', '-count_frames', '-of', 'default=nokey=1:noprint_wrappers=1', '-select_streams', 'v:0', '-show_entries', 'stream=width,height,nb_read_frames', vid_path ] output = sh.ffprobe(ffprobe_args) [width_src, height_src, total_frames] = [int(o) for o in output.split()[-3:]] vf_param = [] if frame_size > 0: if height_src < width_src: vf_param.append('scale=-1:{}'.format(int(frame_size))) else: vf_param.append('scale={}:-1'.format(int(frame_size))) if frame_uniform > 0: if frame_uniform == 1: # select the middle frame frames_to_sample = [(total_frames + 1) // 2] else: frames_to_sample = np.linspace( 1, total_frames - 1, frame_uniform).round().astype(int) select_param = '+'.join( ['eq(n\,{})'.format(n) for n in frames_to_sample]) vf_param.append('select=' + select_param) ffmpeg_args = [ '-i', vid_path, '-q:v', str(1), '-f', 'image2', target_mask, ] if frame_size > 0 or frame_uniform > 0: ffmpeg_args.insert(2, '-vf') ffmpeg_args.insert(3, ','.join(vf_param)) if frame_uniform > 0: ffmpeg_args.insert(4, '-vsync') ffmpeg_args.insert(5, 'vfr') if frame_rate > 0: ffmpeg_args.insert(2, '-r') ffmpeg_args.insert(3, str(frame_rate)) sh.ffmpeg(*ffmpeg_args) except Exception as e: pass