/*
    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;
use anyhow::Result;
use std::io::Write;
use winter_ebml::{EbmlHeader, EbmlToVec};
use winter_matroska::{MatroskaFile, Segment};

fn write_fragment_shared(out: &mut dyn Write, mut segment: Segment, webm: bool) -> Result<()> {
    segment.info.muxing_app =
        concat!(env!("CARGO_PKG_NAME"), "-", env!("CARGO_PKG_VERSION")).to_string();
    if webm && let Some(tracks) = &mut segment.tracks {
        for track in &mut tracks.entries {
            if let Some(video) = &mut track.video {
                video.colour = None;
                video.projection = None;
                video.display_unit = 0; // pixels
                video.display_width = Some(video.pixel_width);
                video.display_height = Some(video.pixel_height);
            }
        }
    }

    let file = MatroskaFile {
        ebml_header: EbmlHeader {
            ebml_version: 1,
            ebml_read_version: 1,
            ebml_max_id_length: 4,
            ebml_max_size_length: 8,
            doc_type: if webm { "webm" } else { "matroska" }.to_string(),
            doc_type_version: 4,
            doc_type_read_version: 2,
            ..Default::default()
        },
        segment,
    };
    out.write_all(&file.to_vec())?;
    Ok(())
}

pub struct MatroskaFragmentMuxer;
impl FragmentMuxer for MatroskaFragmentMuxer {
    fn write_fragment(out: &mut dyn Write, segment: Segment) -> Result<()> {
        write_fragment_shared(out, segment, false)
    }
}
pub struct WebmFragmentMuxer;
impl FragmentMuxer for WebmFragmentMuxer {
    fn write_fragment(out: &mut dyn Write, segment: Segment) -> Result<()> {
        write_fragment_shared(out, segment, true)
    }
}
