diff --git a/deblack/deblack.py b/deblack/deblack.py index 349c040..d50765d 100644 --- a/deblack/deblack.py +++ b/deblack/deblack.py @@ -19,8 +19,39 @@ def delete_back2back(l): return [x[0] for x in groupby(l)] +def get_bitrate(inpath): + cmd = ["ffprobe", "-i", inpath, "-show_entries", "stream=bit_rate", "-of", "default=nw=1", "-v", "quiet"] + output = subprocess.check_output(cmd).decode("utf-8") + video_bitrate = None + audio_bitrate = None + for line in output.split("\n"): + if "bit_rate=" in line: + if "Stream #0:0" in output and "Stream #0:1" in output: + if "Stream #0:0" in line: + video_bitrate = int(line.split("=")[1].strip()) + elif "Stream #0:1" in line: + audio_bitrate = int(line.split("=")[1].strip()) + elif "Stream #0:0" in output: + video_bitrate = int(line.split("=")[1].strip()) + elif "Stream #0:1" in output: + audio_bitrate = int(line.split("=")[1].strip()) + return video_bitrate, audio_bitrate + + def construct_ffmpeg_trim_cmd(timepairs, inpath, outpath, has_audio=True): - cmd = ["ffmpeg", "-i", inpath, "-y", "-filter_complex"] + video_bitrate, audio_bitrate = get_bitrate(inpath) + cmd = ["ffmpeg", "-i", inpath] + + if video_bitrate: + cmd.extend(["-b:v", str(video_bitrate)]) + if has_audio and audio_bitrate: + cmd.extend(["-b:a", str(audio_bitrate)]) + + cmd.extend(["-c:v", "libx264", "-crf", "18"]) + if has_audio: + cmd.extend(["-c:a", "aac"]) + + cmd.extend(["-y", "-filter_complex"]) filter_str = "" for i, (start, end) in enumerate(timepairs): @@ -38,7 +69,8 @@ def construct_ffmpeg_trim_cmd(timepairs, inpath, outpath, has_audio=True): cmd.append(filter_str) cmd.extend(["-map", "[outv]"]) - cmd.extend(["-map", "[outa]"] if has_audio else []) + if has_audio: + cmd.extend(["-map", "[outa]"]) cmd.append(outpath) return cmd @@ -64,7 +96,7 @@ def get_blackdetect(inpath, invert=False): assert len(times), "no black detected" # Handle video ending with black by adding "duration" as last trim if needed - if len(times) % 2 != 0: + if len(times) % 2!= 0: video_length_cmd = ["ffprobe", "-i", inpath, "-show_entries", "format=duration", "-of", "csv=p=0", "-v", "quiet"] video_length_str = subprocess.check_output(video_length_cmd).decode("utf-8") video_length = float(video_length_str) @@ -78,6 +110,7 @@ def get_blackdetect(inpath, invert=False): def main(): + def str2bool(v): if isinstance(v, bool): return v @@ -107,7 +140,7 @@ def str2bool(v): if args.audio == "auto": try: cmd = ["ffprobe", "-i", args.input, "-show_streams", "-select_streams", "a", "-loglevel", "error"] - args.audio = subprocess.check_output(cmd).decode("utf-8").strip() != "" + args.audio = subprocess.check_output(cmd).decode("utf-8").strip()!= "" except Exception as e: print(e, "Failed to detect audio, assuming no audio. Use --audio to override.") else: @@ -123,3 +156,4 @@ def str2bool(v): if __name__ == "__main__": main() + \ No newline at end of file