import os
import subprocess

def demux_mp4_files(folder_path):
    # Ensure the folder exists
    if not os.path.exists(folder_path):
        print(f"Folder does not exist: {folder_path}")
        return

    # Get a list of all .mp4 files in the folder
    mp4_files = [f for f in os.listdir(folder_path) if f.endswith('.mp4')]

    if not mp4_files:
        print("No MP4 files found in the folder.")
        return

    # Create output folder if it doesn't exist
    output_folder = os.path.join(folder_path, "demuxed")
    os.makedirs(output_folder, exist_ok=True)

    for mp4_file in mp4_files:
        input_path = os.path.join(folder_path, mp4_file)
        file_name = os.path.splitext(mp4_file)[0]

        # Output paths for video and audio
        video_output = os.path.join(output_folder, f"{file_name}_video.mp4")
        audio_output = os.path.join(output_folder, f"{file_name}_audio.aac")

        # FFmpeg command to demux video and audio
        ffmpeg_command = [
            "ffmpeg",
            "-i", input_path,
            "-map", "0:v:0", "-c:v", "copy", video_output,  # Copy video stream
            "-map", "0:a:0", "-c:a", "copy", audio_output   # Copy audio stream
        ]

        try:
            print(f"Demuxing: {mp4_file}")
            subprocess.run(ffmpeg_command, check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
            print(f"Demuxed {mp4_file} into {video_output} and {audio_output}")
        except subprocess.CalledProcessError as e:
            print(f"Error demuxing {mp4_file}: {e.stderr.decode()}\n")

if __name__ == "__main__":
    folder = input("Enter the path to the folder containing MP4 files: ").strip()
    demux_mp4_files(folder)
