/*
    This file is part of jellything (https://codeberg.org/metamuffin/jellything)
    which is licensed under the GNU Affero General Public License (version 3); see /COPYING.
    Copyright (C) 2026 metamuffin <metamuffin.org>
*/

use crate::muxers::{FragmentMuxer, matroska::MatroskaFragmentMuxer};
use anyhow::Result;
use std::{
    io::{Cursor, Write, copy},
    process::{Command, Stdio},
    thread::spawn,
};
use winter_matroska::Segment;

pub struct Mpeg4FragmentMuxer;
impl FragmentMuxer for Mpeg4FragmentMuxer {
    fn write_fragment(out: &mut dyn Write, segment: Segment) -> Result<()> {
        let mut mk_frag = Vec::new();
        MatroskaFragmentMuxer::write_fragment(&mut mk_frag, segment)?;

        let mut child = Command::new("ffmpeg")
            .args(
                "-hide_banner -f matroska -i pipe:0 -c copy -f mp4 -movflags frag_keyframe+empty_moov pipe:1"
                    .split(" "),
            )
            .stdin(Stdio::piped())
            .stdout(Stdio::piped())
            .spawn()?;

        let mut stdin = child.stdin.take().unwrap();
        let mut stdout = child.stdout.take().unwrap();
        spawn(move || copy(&mut Cursor::new(mk_frag), &mut stdin));
        copy(&mut stdout, out)?;
        Ok(())
    }
}
