# Extract audio from the video
audio_file = "temp_audio.wav"
cmd = [
'ffmpeg',
'-i', input_video,
'-ar', '44100', # Sample rate
'-ac', '1', # Mono audio
'-vn', # No video
'-y', # Overwrite output file
audio_file
]
subprocess.run(cmd, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
status_label.config(text="Analyzing audio...")
root.update_idletasks()
# Get the frame rate and total number of frames
frame_rate = get_frame_rate(input_video)
total_frames = get_total_frames(input_video)
if frame_rate == 0 or total_frames == 0:
messagebox.showerror("Error", "Could not determine frame rate or total frames.")
cleanup([audio_file])
return
# Load the audio file
y, sr = librosa.load(audio_file, sr=None)
frame_duration = 1.0 / frame_rate
frame_length = int(sr * frame_duration)
# Compute loudness (RMS) for each frame
loudness_list = []
for i in range(total_frames):
start = i * frame_length
end = start + frame_length
frame_audio = y[start:end]
if len(frame_audio) == 0:
rms = 0
else:
rms = np.sqrt(np.mean(frame_audio ** 2))
loudness_list.append((i, rms))
# Sort the frames by loudness (from quietest to loudest)
loudness_list.sort(key=lambda x: x[1])
status_label.config(text="Extracting frames from video...")
root.update_idletasks()
# Extract frames from the video
frame_folder = "frames"
if os.path.exists(frame_folder):
shutil.rmtree(frame_folder)
os.makedirs(frame_folder, exist_ok=True)
cmd = [
'ffmpeg',
'-i', input_video,
'-vf', f'fps={frame_rate}',
os.path.join(frame_folder, 'frame%06d.png') # Use 6 digits for frame numbering
]
subprocess.run(cmd, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
# Verify extracted frames
extracted_frames = sorted(glob.glob(os.path.join(frame_folder, 'frame*.png')))
if len(extracted_frames) < total_frames:
messagebox.showerror("Error", f"Expected {total_frames} frames, but extracted {len(extracted_frames)} frames.")
cleanup([audio_file], frame_folder)
return
status_label.config(text="Rearranging audio segments...")
root.update_idletasks()
# Pair frames with their loudness
frames_with_loudness = []
for idx, (frame_index, rms) in enumerate(loudness_list):
frame_filename = os.path.join(frame_folder, f'frame{frame_index+1:06d}.png') # ffmpeg starts at 1
if not os.path.exists(frame_filename):
messagebox.showerror("Error", f"Frame file {frame_filename} does not exist.")
cleanup([audio_file], frame_folder)
return
frames_with_loudness.append((frame_filename, rms, frame_index))
status_label.config(text="Rearranging audio segments...")
root.update_idletasks()
# Rearrange audio segments as per the sorted frames
sorted_audio_segments = []
for (frame_file, rms, original_index) in frames_with_loudness:
start = original_index * frame_length
end = start + frame_length
frame_audio = y[start:end]
sorted_audio_segments.append(frame_audio)
# Concatenate sorted audio segments
if sorted_audio_segments:
sorted_audio = np.concatenate(sorted_audio_segments)
else:
sorted_audio = y # Fallback in case of empty segments
# Save the sorted audio to a file
sorted_audio_file = "sorted_audio.wav"
sf.write(sorted_audio_file, sorted_audio, sr)
status_label.config(text="Rearranging frames...")
root.update_idletasks()
# Create a temporary directory for sorted frames
sorted_frame_folder = 'sorted_frames'
if os.path.exists(sorted_frame_folder):
shutil.rmtree(sorted_frame_folder)
os.makedirs(sorted_frame_folder, exist_ok=True)
for idx, (frame_file, rms, original_index) in enumerate(frames_with_loudness):
new_filename = os.path.join(sorted_frame_folder, f'frame{idx+1:06d}.png')
shutil.copy(frame_file, new_filename)
status_label.config(text="Creating video from frames...")
root.update_idletasks()
# Create a video from sorted frames
sorted_video = 'sorted_video.mp4'
cmd = [
'ffmpeg',
'-framerate', f"{frame_rate}",
'-i', os.path.join(sorted_frame_folder, 'frame%06d.png'),
'-c:v', 'libx264',
'-pix_fmt', 'yuv420p',
'-y',
sorted_video
]
subprocess.run(cmd, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
status_label.config(text="Merging audio and video...")
root.update_idletasks()
# Merge the sorted audio with the video
final_output = 'output_with_audio.mp4'
cmd = [
'ffmpeg',
'-i', sorted_video,
'-i', sorted_audio_file,
'-c:v', 'copy',
'-c:a', 'aac',
'-strict', 'experimental',
'-y',
final_output
]
subprocess.run(cmd, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
status_label.config(text="Cleaning up temporary files...")
root.update_idletasks()
# Clean up temporary files and directories
cleanup(
[audio_file, sorted_audio_file, sorted_video],
[frame_folder, sorted_frame_folder]
)
status_label.config(text=f"Processing completed.\nOutput saved as '{final_output}'")
root.update_idletasks()
import tkinter as tk
from tkinter import filedialog, messagebox
import subprocess
import os
import librosa
import numpy as np
import shutil
import soundfile as sf
import glob
import tempfile
from concurrent.futures import ThreadPoolExecutor
def select_file():
file_path = filedialog.askopenfilename(filetypes=[("Video files", "*.mp4 *.avi *.mov")])
video_path.set(file_path)
def get_video_info(video_file):
"""
Retrieves frame rate, total frames, and duration using a single ffprobe call.
"""
cmd = [
'ffprobe',
'-v', 'error',
'-select_streams', 'v:0',
'-show_entries', 'stream=avg_frame_rate,nb_frames',
'-show_entries', 'format=duration',
'-of', 'default=noprint_wrappers=1:nokey=1',
video_file
]
result = subprocess.run(cmd, capture_output=True, text=True)
output = result.stdout.strip().split('\n')
if len(output) < 3:
raise ValueError("Insufficient video information retrieved.")
# Extract frame rate
rate_str = output[0]
if '/' in rate_str:
num, denom = rate_str.split('/')
frame_rate = float(num) / float(denom) if float(denom) != 0 else 0
else:
frame_rate = float(rate_str)
# Extract total frames
frame_count_str = output[1]
if frame_count_str.isdigit():
total_frames = int(frame_count_str)
else:
# Fallback to duration * fps
duration_str = output[2]
try:
duration = float(duration_str)
total_frames = int(duration * frame_rate)
except ValueError:
total_frames = 0
# Extract duration
try:
duration = float(output[2])
except (IndexError, ValueError):
duration = 0.0
return frame_rate, total_frames, duration
def start_processing():
if video_path.get():
processing_thread = threading.Thread(target=lambda: process_video(video_path.get()))
processing_thread.start()
else:
messagebox.showerror("Error", "Please select a video file.")
def process_video(input_video):
try:
status_label.config(text="Extracting audio...")
root.update_idletasks()
with tempfile.TemporaryDirectory() as temp_dir:
audio_file = os.path.join(temp_dir, "temp_audio.wav")
# Extract audio using FFmpeg
cmd = [
'ffmpeg',
'-i', input_video,
'-ar', '44100', # Sample rate
'-ac', '1', # Mono audio
'-vn', # No video
'-y', # Overwrite output file
audio_file
]
subprocess.run(cmd, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, check=True)
status_label.config(text="Analyzing audio...")
root.update_idletasks()
# Get video information
frame_rate, total_frames, duration = get_video_info(input_video)
if frame_rate == 0 or total_frames == 0:
messagebox.showerror("Error", "Could not determine frame rate or total frames.")
return
# Load audio and compute RMS in a vectorized manner
y, sr = librosa.load(audio_file, sr=44100, mono=True)
frame_length = int(sr / frame_rate)
hop_length = frame_length # Non-overlapping frames
rms = librosa.feature.rms(y=y, frame_length=frame_length, hop_length=hop_length)[0]
# Ensure the RMS array length matches the total frames
if len(rms) < total_frames:
rms = np.pad(rms, (0, total_frames - len(rms)), 'constant')
elif len(rms) > total_frames:
rms = rms[:total_frames]
# Pair frame indices with their RMS values
loudness_list = list(enumerate(rms))
status_label.config(text="Extracting frames from video...")
root.update_idletasks()
frame_folder = os.path.join(temp_dir, "frames")
os.makedirs(frame_folder, exist_ok=True)
# Extract frames using FFmpeg
cmd = [
'ffmpeg',
'-i', input_video,
'-vf', f'fps={frame_rate}',
os.path.join(frame_folder, 'frame%06d.png') # 6-digit frame numbering
]
subprocess.run(cmd, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, check=True)
# Verify extracted frames
extracted_frames = sorted(glob.glob(os.path.join(frame_folder, 'frame*.png')))
if len(extracted_frames) < total_frames:
messagebox.showerror("Error", f"Expected {total_frames} frames, but extracted {len(extracted_frames)} frames.")
return
status_label.config(text="Sorting frames by loudness...")
root.update_idletasks()
# Sort frames based on loudness
sorted_indices = sorted(range(total_frames), key=lambda i: loudness_list[i][1])
sorted_frame_folder = os.path.join(temp_dir, "sorted_frames")
os.makedirs(sorted_frame_folder, exist_ok=True)
# Function to copy frames in parallel
def copy_frame(idx, sorted_idx):
src = os.path.join(frame_folder, f'frame{idx+1:06d}.png')
dst = os.path.join(sorted_frame_folder, f'frame{sorted_idx+1:06d}.png')
shutil.copy(src, dst)
# Copy frames using ThreadPoolExecutor
with ThreadPoolExecutor(max_workers=8) as executor:
for sorted_idx, original_idx in enumerate(sorted_indices):
executor.submit(copy_frame, original_idx, sorted_idx)
status_label.config(text="Rearranging audio segments...")
root.update_idletasks()
# Rearrange audio segments based on sorted frame order
sorted_audio_segments = y[sorted_indices * frame_length : (sorted_indices + 1) * frame_length]
sorted_audio = np.concatenate(sorted_audio_segments) if len(sorted_audio_segments) > 0 else y
sorted_audio_file = os.path.join(temp_dir, "sorted_audio.wav")
sf.write(sorted_audio_file, sorted_audio, sr)
status_label.config(text="Creating video from sorted frames...")
root.update_idletasks()
# Create video from sorted frames
sorted_video = os.path.join(temp_dir, 'sorted_video.mp4')
cmd = [
'ffmpeg',
'-framerate', f"{frame_rate}",
'-i', os.path.join(sorted_frame_folder, 'frame%06d.png'),
'-c:v', 'libx264',
'-pix_fmt', 'yuv420p',
'-y',
sorted_video
]
subprocess.run(cmd, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, check=True)
status_label.config(text="Merging sorted audio with video...")
root.update_idletasks()
# Merge sorted audio with sorted video
final_output = 'output_sorted_video.mp4'
cmd = [
'ffmpeg',
'-i', sorted_video,
'-i', sorted_audio_file,
'-c:v', 'copy',
'-c:a', 'aac',
'-strict', 'experimental',
'-y',
final_output
]
subprocess.run(cmd, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, check=True)
status_label.config(text=f"Processing completed.\nOutput saved as '{final_output}'")
root.update_idletasks()
except subprocess.CalledProcessError as e:
messagebox.showerror("FFmpeg Error", f"An error occurred while running FFmpeg:\n{e}")
except Exception as e:
messagebox.showerror("Error", f"An unexpected error occurred:\n{e}")
def cleanup(files_to_remove=None, dirs_to_remove=None):
if files_to_remove:
for file in files_to_remove:
if os.path.exists(file):
os.remove(file)
if dirs_to_remove:
for dir in dirs_to_remove:
if os.path.exists(dir):
shutil.rmtree(dir)
import threading
# Set up the main application window
root = tk.Tk()
root.title("Video Frame Sorter")
# Create the UI components
frame = tk.Frame(root)
frame.pack(padx=10, pady=10)
video_path = tk.StringVar()
select_button = tk.Button(frame, text="Select Video File", command=select_file)
select_button.pack(pady=5)
video_label = tk.Label(frame, textvariable=video_path, wraplength=400, justify="left")
video_label.pack(pady=5)
start_button = tk.Button(frame, text="Start Processing", command=start_processing)
start_button.pack(pady=5)
status_label = tk.Label(frame, text="", wraplength=400, justify="left")
status_label.pack(pady=5)
# Run the application
root.mainloop()