def return_duration(vid): meta = ffprobe3.FFProbe(vid) duration = None for petitmeta in meta.streams: duration = int((float(petitmeta.duration)) * 1000) return duration
def videoSetup(self, video_path): self.video_path = video_path self.label_info = wx.StaticText(self, label="Video properties:") self.label_info.SetFont(self.font) self.label_info.SetForegroundColour((255, 255, 255)) self.panel_sizer.Add(self.label_info, 0, wx.ALL | wx.EXPAND, 5) metadata = ffprobe3.FFProbe(video_path) audio_stream = None video_stream = None for stream in metadata.streams: if stream.is_video(): video_stream = stream if stream.is_audio(): audio_stream = stream if video_stream is None: return self.resolution = InfoLabel( self, "Resolution:", video_stream.__dict__["width"] + "x" + video_stream.__dict__["height"]) self.panel_sizer.Add(self.resolution, 0, wx.ALL | wx.EXPAND, 5) self.length = InfoLabel(self, "Length:", video_stream.__dict__["duration"] + " s") self.panel_sizer.Add(self.length, 0, wx.ALL | wx.EXPAND, 5) self.fps = InfoLabel( self, "Frame rate:", video_stream.__dict__["r_frame_rate"].split("/")[0] + " fps") self.panel_sizer.Add(self.fps, 0, wx.ALL | wx.EXPAND, 5) self.video_codec = InfoLabel(self, "Video codec:", video_stream.codec()) self.panel_sizer.Add(self.video_codec, 0, wx.ALL | wx.EXPAND, 5) self.video_bitrate = InfoLabel( self, "Video bitrate:", video_stream.__dict__["bit_rate"] + " bps") self.panel_sizer.Add(self.video_bitrate, 0, wx.ALL | wx.EXPAND, 5) if audio_stream is None: return self.audio_codec = InfoLabel(self, "Audio codec:", audio_stream.codec()) self.panel_sizer.Add(self.audio_codec, 0, wx.ALL | wx.EXPAND, 5) self.audio_bitrate = InfoLabel( self, "Audio bitrate:", audio_stream.__dict__["bit_rate"] + " bps") self.panel_sizer.Add(self.audio_bitrate, 0, wx.ALL | wx.EXPAND, 5) self.line0 = wx.StaticLine(self, -1, style=wx.LI_HORIZONTAL) self.line0.SetBackgroundColour((255, 255, 255)) self.panel_sizer.Add(self.line0, 0, wx.ALL | wx.EXPAND, 10) self.label_cut = wx.StaticText(self, label="Cut section:") self.label_cut.SetFont(self.font) self.label_cut.SetForegroundColour((255, 255, 255)) self.panel_sizer.Add(self.label_cut, 0, wx.ALL | wx.EXPAND, 5) self.edit_panel = EditPanel(self, float(video_stream.__dict__["duration"])) self.panel_sizer.Add(self.edit_panel, 0, wx.ALL | wx.EXPAND, 5) self.button = wx.Button(self, label="Render") self.panel_sizer.Add(self.button, 0, wx.ALL | wx.EXPAND, 30) self.button.Bind(wx.EVT_BUTTON, self.onButton)
def sfp(reel, partitions=None): '''Standard frames per partition''' probe = ffprobe3.FFProbe(str(reel)) num_frames = int(probe.streams[0].nb_frames) if not partitions: return num_frames partitions[-1] = (partitions[-1][0], num_frames) norm_partitions = [(partition[1] - partition[0]) / num_frames for partition in partitions] entropy = stats.entropy(norm_partitions, base=len(partitions)) return num_frames / (1 + ((len(partitions) - 1) * entropy**2))
def main(): args = parse_args() styutils.start_logging() probe = ffprobe3.FFProbe(str(args.reel)) num_frames = int(probe.streams[0].nb_frames) if args.read_from: partitions = read_cuts(args.read_from, num_frames) else: partitions = divide(args.reel, num_frames, args.write_to) logging.info(partitions) logging.info('SFP: {}'.format(sfp(args.reel, partitions)))
def handle_client(self, client): ''' Trata as requisições TCP de um determinado cliente ''' cli = self.clients[client][0] print('conectado') while True: data = cli.recv(self.buffersize) if data: request = pickle.loads(data) if request[0] == globals.FILE_REQUEST: start = time.time() cli.send(b'0' * self.buffersize) cli.recv(self.buffersize) rtt = self.buffersize / ( (time.time() - start) / 2) # quantos bytes por segundo metadata = ffprobe3.FFProbe(request[2]).video[0] bit_rate = int( metadata.bit_rate) / 8 # em bytes por segundo tamanho_do_pacote = max(min(int(bit_rate // 700), 1500), 200) # tamanho do pacote atraso = 0 if ((rtt - tamanho_do_pacote) <= 0) else ( (rtt - tamanho_do_pacote) / rtt / 1000) buffer_leitura = int(bit_rate // tamanho_do_pacote) buffer_inicial = buffer_leitura * 2 cli.send( pickle.dumps((tamanho_do_pacote, buffer_inicial, buffer_leitura, bit_rate))) t = threading.Thread(target=self.sendto_client, args=(client, request[1], request[2], tamanho_do_pacote, atraso)) t.start() if request[0] == globals.STOP_TRANSMISSION: # para a transmissão do vídeo pass
def main(): args = parse_args() styutils.start_logging() if args.mode == 'n': probe = ffprobe3.FFProbe(str(args.target)) num_frames = str(probe.streams[0].nb_frames) print(num_frames) return dst = pathlib.Path('out') / os.path.splitext(os.path.basename( args.target))[0] styutils.makedirs(dst) if args.mode == 's': split_frames(args.target, dst, args.extension) elif args.mode == 'c': if not args.src: sys.exit('Please specify a source directory.') combine_frames(args.target, pathlib.Path(args.src), format=args.format)
def combine_frames(target, src, dst=pathlib.Path('out'), format=None): check_deps() styutils.makedirs(dst) if not format: format = OUTPUT_FORMAT basename = os.path.splitext(os.path.basename(str(target)))[0] no_audio = str(src / ('{}_no_audio.mp4'.format(basename))) audio = str(dst / ('{}_stylized.mp4'.format(basename))) # Don't try to combine frames if the destination already exists. # FFMPEG checks for this, but if we should preemptively avoid it if we can. if os.path.exists(no_audio): logging.info('{} already exists -- quitting'.format(no_audio)) return if os.path.exists(audio): logging.info('{} already exists -- quitting'.format(audio)) return # Get the original video's length. This will be necessary to properly reconstruct it. # TODO: Check to see if a video contains audio before attempting to add audio. probe = ffprobe3.FFProbe(str(target)) duration = probe.streams[-1].duration num_frames = str(probe.streams[0].nb_frames) # Combine stylized frames into a video. subprocess.run([ 'ffmpeg', '-i', str(src / format), '-c:v', 'libx264', '-preset', 'veryslow', '-pix_fmt', 'yuv420p', '-filter:v', 'setpts={}/{}*N/TB'.format(duration, num_frames), '-r', '{}/{}'.format(num_frames, duration), no_audio ]) # Add audio to that video. subprocess.run([ 'ffmpeg', '-i', no_audio, '-i', str(target), '-c', 'copy', '-map', '0:0', '-map', '1:1', audio ]) # Remove the version without audio. os.remove(no_audio)
def split_frames(target, dst, extension='ppm'): check_deps() styutils.makedirs(dst) # Split video into a collection of frames. # Don't split the video if we've already done so. probe = ffprobe3.FFProbe(str(target)) num_frames = int(probe.streams[0].nb_frames) files_present = styutils.count_files(dst, '.{}'.format(extension)) if num_frames <= files_present: logging.info( 'Video is already split into {} frames'.format(num_frames)) return num_frames logging.info( '{} frames in video != {} frames on disk; splitting frames...'.format( num_frames, files_present)) # This line is to account for extensions other than the default. frame_name = '{}.{}'.format(os.path.splitext(FRAME_NAME)[0], extension) subprocess.run(['ffmpeg', '-i', str(target), str(dst / frame_name)])
def split_by_seconds(filename, split_length=None, vcodec="h264", acodec="copy", extra="", **kwargs): if not split_length: split_length = 15 #if split_length and split_length <= 0: #print("Split length can't be 0") #raise SystemExit meta = ffprobe3.FFProbe(filename) video_length = None for something in meta.streams: video_length = float(something.duration) #split_length = int(video_length/4) # print('{} min et {} sec'.format(int(math.modf(float(something.duration)/60)[1]), (math.modf(float(something.duration)/60)[0]))) ''' output = subprocess.Popen("ffmpeg -i \""+filename+"\" 2>&1 | findstr 'Duration'", shell = True, stdout = subprocess.PIPE ).stdout.read() print(output) matches = re_length.search(meta) if matches: video_length = int(matches.group(1)) * 3600 + \ int(matches.group(2)) * 60 + \ int(matches.group(3)) else: print("Can't determine video length.") raise SystemExit ''' print("Video length in seconds: " + str(video_length)) split_count = int(math.ceil(video_length / float(split_length))) if (split_count == 1): print("Video length is less then the target split length.") raise SystemExit filepath = os.path.join( r'C:\\Users\CARBON\Desktop\internet work\PY project work\Instagram API\Test files', 'test.mp4') split_cmd = "ffmpeg -i \"%s\" -vcodec %s -acodec %s %s" % ( filepath, vcodec, acodec, extra) resize_cmd = 'ffmpeg -i \"{}\" -vf scale=1080:1920 \"{}\"' list_splitted_filenames = [] print('about to run {}'.format(resize_cmd.format(filename, filepath))) resize = subprocess.Popen(resize_cmd.format(filename, filepath), shell=True, stdout=subprocess.PIPE).stdout.read() justname = os.path.splitext(filepath)[0] justextension = os.path.splitext(filepath)[1] for n in range(0, split_count): split_str = "" if n == 0: split_start = 0 else: split_start = split_length * n split_str += " -ss " + str(split_start) + " -t " + str(split_length) + \ " \"" + justname + "-" + str(n) + justextension # Splitting files here print("About to run: " + split_cmd + split_str) output = subprocess.Popen(split_cmd + split_str, shell=True, stdout=subprocess.PIPE).stdout.read() # Resizing files to 1080, 1920 for stories: splitted_filename = justname + '-' + str(n) + justextension list_splitted_filenames.append(splitted_filename) return list_splitted_filenames
def run(event, context): try: logger.info("start", event=event, context=context) body = json.loads(event['Records'][0]['body']) logger.info("body", body=body) stream_id = body['stream_id'] receipt_handle = event['Records'][0].get('receiptHandle') try: stream = ts_aws.rds.stream.get_stream(stream_id) except ts_model.Exception as e: if e.code == ts_model.Exception.STREAM__NOT_EXIST: logger.error("warn", _module=f"{e.__class__.__module__}", _class=f"{e.__class__.__name__}", _message=str(e), traceback=''.join(traceback.format_exc())) stream = ts_model.Stream( stream_id=stream_id, ) if stream._status_initialize == ts_model.Status.DONE: raise ts_model.Exception(ts_model.Exception.STREAM__STATUS_INITIALIZE_DONE) if stream._status_initialize < ts_model.Status.WORKING: stream._status_initialize = ts_model.Status.WORKING ts_aws.rds.stream.save_stream(stream) try: twitch_url = f"https://twitch.tv/videos/{stream_id}" twitch_streams = streamlink.streams(twitch_url) logger.info("twitch_streams", twitch_streams=twitch_streams) twitch_stream = twitch_streams['best'] twitch_stream_url_prefix = "/".join(twitch_stream.url.split("/")[:-1]) except Exception as e: logger.error("warn", _module=f"{e.__class__.__module__}", _class=f"{e.__class__.__name__}", _message=str(e), traceback=''.join(traceback.format_exc())) stream._status_initialize = ts_model.Status.ERROR ts_aws.rds.stream.save_stream(stream) raise ts_model.Exception(ts_model.Exception.STREAM_ID__NOT_VALID) from None playlist_filename = f"/tmp/playlist-raw.m3u8" ts_http.download_file(twitch_stream.url, playlist_filename) timestamp = 0 stream_segments = [] ss_duration = None ss = None with open(playlist_filename, 'r') as f: for line in f: if ss is None: ss = ts_model.StreamSegment( stream_id=stream_id, ) if "EXTINF" in line: ss_duration_raw = line.strip() ss_duration = float(re.findall("\d+\.\d+", ss_duration_raw)[0]) if ".ts" in line: ss_segment_raw = line.strip() ss.segment = int(''.join(filter(str.isdigit, ss_segment_raw))) ss.media_url = f"{twitch_stream_url_prefix}/{ss_segment_raw}" if ss.segment is not None and ss_duration is not None: ss.stream_time_in = timestamp timestamp += ss_duration ss.stream_time_out = timestamp stream_segments.append(ss) ss = None ss_duration = None ts_file.delete(playlist_filename) width = 0 height = 0 fps_numerator = 0 fps_denominator = 0 first_stream_segment = stream_segments[0] segment_padded = str(first_stream_segment.segment).zfill(6) media_filename = f"/tmp/{segment_padded}.ts" ts_http.download_file(first_stream_segment.media_url, media_filename) metadata = ffprobe3.FFProbe(media_filename) for s in metadata.streams: if s.is_video(): width = s.width height = s.height [fps_numerator, fps_denominator] = s.r_frame_rate.split("/") ts_file.delete(media_filename) ts_aws.rds.stream_segment.save_stream_segments(stream_segments) stream.streamer = "_".join(twitch_stream.url.split("/")[3].split("_")[1:-2]) stream.playlist_url = twitch_stream.url stream.duration = timestamp stream.fps_numerator = int(fps_numerator) stream.fps_denominator = int(fps_denominator) stream.width = width stream.height = height stream._status_initialize = ts_model.Status.DONE ts_aws.rds.stream.save_stream(stream) logger.info("success") return True except Exception as e: logger.error("error", _module=f"{e.__class__.__module__}", _class=f"{e.__class__.__name__}", _message=str(e), traceback=''.join(traceback.format_exc())) if type(e) == ts_model.Exception and e.code in [ ts_model.Exception.STREAM__STATUS_INITIALIZE_DONE, ts_model.Exception.STREAM_ID__NOT_VALID, ]: return True else: ts_aws.sqs.stream__initialize.change_visibility(receipt_handle) raise Exception(e) from None